text:
package org.drools.examples.banking;

public class BankingExample2 {
    public static void main(String[] args) {
        Number[] numbers = new Number[] {wrap(3), wrap(1), wrap(4), wrap(1), wrap(5)};
        new RuleRunner().runRules( new String[] { "Example2.drl" },
                                   numbers );
    }

    private static Integer wrap(int i) {
        return Integer.valueOf(i);
    }
}


text:
var searchData=
[
  ['fonctionsdehashage',['fonctionsDeHashage',['../classfonctions_de_hashage.html',1,'']]]
];

redpajama_set_name: RedPajamaGithub


text:
@interface ABI43_0_0EXUpdatesDatabaseTests : XCTestCase

@property (nonatomic, strong) ABI43_0_0EXUpdatesDatabase *db;
@property (nonatomic, strong) NSURL *testDatabaseDir;
@property (nonatomic, strong) ABI43_0_0EXManifestsNewManifest *manifest;
@property (nonatomic, strong) ABI43_0_0EXUpdatesConfig *config;

@end

@implementation ABI43_0_0EXUpdatesDatabaseTests

- (void)setUp
{
  NSURL *applicationSupportDir = [NSFileManager.defaultManager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask].lastObject;
  _testDatabaseDir = [applicationSupportDir URLByAppendingPathComponent:@"ABI43_0_0EXUpdatesDatabaseTests"];
  if (![NSFileManager.defaultManager fileExistsAtPath:_testDatabaseDir.path]) {
    NSError *error;
    [NSFileManager.defaultManager createDirectoryAtPath:_testDatabaseDir.path withIntermediateDirectories:YES attributes:nil error:&error];
    XCTAssertNil(error);
  }

  _db = [[ABI43_0_0EXUpdatesDatabase alloc] init];
  dispatch_sync(_db.databaseQueue, ^{
    NSError *dbOpenError;
    [_db openDatabaseInDirectory:_testDatabaseDir withError:&dbOpenError];
    XCTAssertNil(dbOpenError);
  });

  _manifest = [[ABI43_0_0EXManifestsNewManifest alloc] initWithRawManifestJSON:@{
    @"runtimeVersion": @"1",
    @"id": @"0eef8214-4833-4089-9dff-b4138a14f196",
    @"createdAt": @"2020-11-11T00:17:54.797Z",
    @"launchAsset": @{@"url": @"https://url.to/bundle.js", @"contentType": @"application/javascript"}
  }];
  _config = [ABI43_0_0EXUpdatesConfig configWithDictionary:@{
    @"ABI43_0_0EXUpdatesURL": @"https://exp.host/@test/test",
    @"ABI43_0_0EXUpdatesUsesLegacyManifest": @(NO)
  }];
}

- (void)tearDown
{
  dispatch_sync(_db.databaseQueue, ^{
    [_db closeDatabase];
  });
  NSError *error;
  [NSFileManager.defaultManager removeItemAtPath:_testDatabaseDir.path error:&error];
  XCTAssertNil(error);
}

- (void)testForeignKeys
{
  __block NSError *expectedError;
  ABI43_0_0EXUpdatesUpdate *update = [ABI43_0_0EXUpdatesNewUpdate updateWithNewManifest:_manifest response:nil config:_config database:_db];
  dispatch_sync(_db.databaseQueue, ^{
    NSError *updatesError;
    [_db addUpdate:update error:&updatesError];
    if (updatesError) {
      return;
    }

    NSError *updatesAssetsError;
    [_db _executeSql:@"INSERT OR REPLACE INTO updates_assets (\"update_id\", \"asset_id\") VALUES (?1, ?2)" withArgs:@[update.updateId, @(47)] error:&updatesAssetsError];
    expectedError = updatesAssetsError;
  });
  XCTAssertNotNil(expectedError);
  XCTAssertEqual(787, expectedError.code); // SQLITE_CONSTRAINT_FOREIGNKEY
}

- (void)testSetMetadata_OverwriteAllFields
{
  NSHTTPURLResponse *response1 = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://exp.host/"] statusCode:200 HTTPVersion:@"HTTP/2" headerFields:@{
    @"expo-manifest-filters": @"branch-name=\"rollout-1\",test=\"value\""
  }];
  ABI43_0_0EXUpdatesUpdate *update1 = [ABI43_0_0EXUpdatesNewUpdate updateWithNewManifest:_manifest response:response1 config:_config database:_db];
  __block NSError *error1;
  dispatch_sync(_db.databaseQueue, ^{
    [_db setMetadataWithManifest:update1 error:&error1];
  });
  XCTAssertNil(error1);

  NSHTTPURLResponse *response2 = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://exp.host/"] statusCode:200 HTTPVersion:@"HTTP/2" headerFields:@{
    @"expo-manifest-filters": @"branch-name=\"rollout-2\""
  }];
  ABI43_0_0EXUpdatesUpdate *update2 = [ABI43_0_0EXUpdatesNewUpdate updateWithNewManifest:_manifest response:response2 config:_config database:_db];
  __block NSError *error2;
  dispatch_sync(_db.databaseQueue, ^{
    [_db setMetadataWithManifest:update2 error:&error2];
  });
  XCTAssertNil(error2);

  NSDictionary *expected = @{@"branch-name": @"rollout-2"};
  __block NSDictionary *actual;
  __block NSError *readError;
  dispatch_sync(_db.databaseQueue, ^{
    actual = [_db manifestFiltersWithScopeKey:update2.scopeKey error:&readError];
  });
  XCTAssertNil(readError);
  XCTAssertNotNil(actual);
  XCTAssertEqualObjects(expected, actual);
}

- (void)testSetMetadata_OverwriteEmpty
{
  NSHTTPURLResponse *response1 = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://exp.host/"] statusCode:200 HTTPVersion:@"HTTP/2" headerFields:@{
    @"expo-manifest-filters": @"branch-name=\"rollout-1\""
  }];
  ABI43_0_0EXUpdatesUpdate *update1 = [ABI43_0_0EXUpdatesNewUpdate updateWithNewManifest:_manifest response:response1 config:_config database:_db];
  __block NSError *error1;
  dispatch_sync(_db.databaseQueue, ^{
    [_db setMetadataWithManifest:update1 error:&error1];
  });
  XCTAssertNil(error1);

  NSHTTPURLResponse *response2 = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://exp.host/"] statusCode:200 HTTPVersion:@"HTTP/2" headerFields:@{
    @"expo-manifest-filters": @""
  }];
  ABI43_0_0EXUpdatesUpdate *update2 = [ABI43_0_0EXUpdatesNewUpdate updateWithNewManifest:_manifest response:response2 config:_config database:_db];
  __block NSError *error2;
  dispatch_sync(_db.databaseQueue, ^{
    [_db setMetadataWithManifest:update2 error:&error2];
  });
  XCTAssertNil(error2);

  NSDictionary *expected = @{};
  __block NSDictionary *actual;
  __block NSError *readError;
  dispatch_sync(_db.databaseQueue, ^{
    actual = [_db manifestFiltersWithScopeKey:update2.scopeKey error:&readError];
  });
  XCTAssertNil(readError);
  XCTAssertNotNil(actual);
  XCTAssertEqualObjects(expected, actual);
}

- (void)testSetMetadata_OverwriteNull
{
  NSHTTPURLResponse *response1 = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://exp.host/"] statusCode:200 HTTPVersion:@"HTTP/2" headerFields:@{
    @"expo-manifest-filters": @"branch-name=\"rollout-1\""
  }];
  ABI43_0_0EXUpdatesUpdate *update1 = [ABI43_0_0EXUpdatesNewUpdate updateWithNewManifest:_manifest response:response1 config:_config database:_db];
  __block NSError *error1;
  dispatch_sync(_db.databaseQueue, ^{
    [_db setMetadataWithManifest:update1 error:&error1];
  });
  XCTAssertNil(error1);

  NSHTTPURLResponse *response2 = [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://exp.host/"] statusCode:200 HTTPVersion:@"HTTP/2" headerFields:@{}];
  ABI43_0_0EXUpdatesUpdate *update2 = [ABI43_0_0EXUpdatesNewUpdate updateWithNewManifest:_manifest response:response2 config:_config database:_db];
  __block NSError *error2;
  dispatch_sync(_db.databaseQueue, ^{
    [_db setMetadataWithManifest:update2 error:&error2];
  });
  XCTAssertNil(error2);

  NSDictionary *expected = @{@"branch-name": @"rollout-1"};
  __block NSDictionary *actual;
  __block NSError *readError;
  dispatch_sync(_db.databaseQueue, ^{
    actual = [_db manifestFiltersWithScopeKey:update2.scopeKey error:&readError];
  });
  XCTAssertNil(readError);
  XCTAssertNotNil(actual);
  XCTAssertEqualObjects(expected, actual);
}

@end


text:
from setuptools import setup, find_packages

setup(
    name="libcdmi-python",
    version='1.0alpha',
    description="""CDMI client library""",
    author="Ilja Livenson and Co",
    author_email="ilja.livenson@gmail.com",
    packages=find_packages(),
    entry_points={'console_scripts': ['cdmiclient = libcdmi.cli:run']},
    install_requires=[
        "setuptools",  # Redundant but removes a warning
        ],
)


text:
//  See http://www.boost.org for most recent version.

//
// Options common to all edg based compilers.
//
// This is included from within the individual compiler mini-configs.

#ifndef  __EDG_VERSION__
#  error This file requires that __EDG_VERSION__ be defined.
#endif

#if (__EDG_VERSION__ <= 238)
#   define BOOST_NO_INTEGRAL_INT64_T
#   define BOOST_NO_SFINAE
#endif

#if (__EDG_VERSION__ <= 240)
#   define BOOST_NO_VOID_RETURNS
#endif

#if (__EDG_VERSION__ <= 241) && !defined(BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP)
#   define BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
#endif

#if (__EDG_VERSION__ <= 244) && !defined(BOOST_NO_TEMPLATE_TEMPLATES)
#   define BOOST_NO_TEMPLATE_TEMPLATES
#endif

#if (__EDG_VERSION__ < 300) && !defined(BOOST_NO_IS_ABSTRACT)
#   define BOOST_NO_IS_ABSTRACT
#endif

#if (__EDG_VERSION__ <= 303) && !defined(BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL)
#   define BOOST_FUNCTION_SCOPE_USING_DECLARATION_BREAKS_ADL
#endif

// See also kai.hpp which checks a Kai-specific symbol for EH
# if !defined(__KCC) && !defined(__EXCEPTIONS)
#     define BOOST_NO_EXCEPTIONS
# endif

# if !defined(__NO_LONG_LONG)
#     define BOOST_HAS_LONG_LONG
# else
#     define BOOST_NO_LONG_LONG
# endif

//
// C++0x features
//
//   See above for BOOST_NO_LONG_LONG
//
#if (__EDG_VERSION__ <= 310) || !defined(BOOST_STRICT_CONFIG)
// No support for initializer lists
#  define BOOST_NO_INITIALIZER_LISTS
#endif

#define BOOST_NO_AUTO_DECLARATIONS
#define BOOST_NO_AUTO_MULTIDECLARATIONS
#define BOOST_NO_CHAR16_T
#define BOOST_NO_CHAR32_T
#define BOOST_NO_CONCEPTS
#define BOOST_NO_CONSTEXPR
#define BOOST_NO_DECLTYPE
#define BOOST_NO_DEFAULTED_FUNCTIONS
#define BOOST_NO_DELETED_FUNCTIONS
#define BOOST_NO_EXPLICIT_CONVERSION_OPERATORS
#define BOOST_NO_EXTERN_TEMPLATE
#define BOOST_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define BOOST_NO_LAMBDAS
#define BOOST_NO_NULLPTR
#define BOOST_NO_RAW_LITERALS
#define BOOST_NO_RVALUE_REFERENCES
#define BOOST_NO_SCOPED_ENUMS
#define BOOST_NO_SFINAE_EXPR
#define BOOST_NO_STATIC_ASSERT
#define BOOST_NO_TEMPLATE_ALIASES
#define BOOST_NO_UNICODE_LITERALS
#define BOOST_NO_VARIADIC_TEMPLATES

#ifdef c_plusplus
// EDG has "long long" in non-strict mode
// However, some libraries have insufficient "long long" support
// #define BOOST_HAS_LONG_LONG
#endif


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class top_model extends CI_Model {

}


text:
This repo was used for computational experiments for this article: https://journals.agh.edu.pl/dmms/article/view/2502. The algorithm described runs in O(n^2), but I found a way simpler solution in O(n), which coauthor of the article Szymon Duraj used in MSc thesis. I did not find a public link to it though. I regard this repo as obsolete because of improved algorithm complexity, but I am leaving it as a souvenir.

## Description
This repository will include implementation of algorithms for scheduling of unit-length jobs with incompatibility graphs of bounded degree.
Cubic scheduling algorithms are based on article "Scheduling of unit-length jobs with cubic incompatibility graphs on three uniform machines" written by Hanna Furmańczyk and Marek Kubale. Article is available under a link:

http://eti.pg.edu.pl/documents/174618/23783336/Scheduling%20of%20unit-length%20jobs%20with%20cubic%20incompatibility%20graphs%20on%20three%20uniform%20machines.pdf

## Scheduling problem
We are given n unit-length jobs and processing speeds of 3 or 4 machines working in parallel. Each job is in conflict with 3, 4 or less other jobs, depending on the particular problem. The goal is to find such a division of those jobs between machines that:
  1. No 2 jobs that are in conflict will be processed on the same machine.
  2. Processing time will be minimal.

This problem can be presented as finding an appropriate 3-coloring of cubic incompatibility graph. All the details are provided in the above mentioned article.

## Status
No sense in using. Algorithm got better.


text:
bernie - to do
==============

* Twitter
  * Tweet:
    * Entry (and re-entry) into market
    * Threshold crossings / sells

* Bernie accepts commands!
  * Use Twitter
    *
  * Alternative:
    * Set up http server
  * Commands:
    * ?

{
  "btc": 469.1194,
  "cash": 339642.48,
  "originalPrice": 724.00,
  "status": 0,
  "lossThreshold": -1.5,
  "gainThreshold": 3.0
}
    /*
      Bid is the most someone is willing to pay for something
      Ask is the least that someone is asking for when they are selling something.
      Market is just a sale at whatever the highest bid or lowest ask is
      Limit is when you specify the most you are going to pay or the least you are going to sell for.
    */
    //           btc: 1
    //          cash: 580.11
    // originalPrice: 580.1100
    //     sellPrice: 592.00000 (market.ask)
    //     gain/loss: +2.0496%

    // calculate # of btc; add / subtract
    // x = 580.11 /

  /*
  that.sell = function(market) {
    var value = _data.btc / market.ask;

    console.log('sell: market: ' + util.inspect(market));
    console.log('value (cash): ' + value);
    _data.cash = value;
    _data.status = -1;
    console.log('_data: ' + util.inspect(_data));
  }

  that.buy = function(market) {
  }
  */


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.flume (Apache Flume 1.7.0 API)</title>
<meta name="date" content="2016-10-12">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.apache.flume

Interfaces

Channel

ChannelFactory

ChannelSelector

Clock

Event

EventDrivenSource

NamedComponent

PollableSource

Sink

SinkFactory

SinkProcessor

Source

SourceFactory

Transaction

Classes

Constants

Context

CounterGroup

Dummy

SinkRunner

SinkRunner.PollingRunner

SourceRunner

SystemClock

Enums

PollableSource.Status

Sink.Status

Transaction.TransactionState

Exceptions

ChannelException

ChannelFullException

EventDeliveryException

FlumeException

Annotation Types

VersionAnnotation


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='ReceiptLog',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('status', models.PositiveIntegerField(default=0, choices=[(0, b'Error'), (1, b'Completed')])),
                ('started', models.DateTimeField(help_text=b'The time the script started processing', auto_now=True)),
                ('run_time', models.PositiveIntegerField(help_text=b'Time the script took to complete in seconds', null=True, blank=True)),
                ('query_from', models.DateTimeField(null=True, blank=True)),
                ('query_to', models.DateTimeField(null=True, blank=True)),
                ('total_emails', models.PositiveIntegerField(default=0, help_text=b'Number of entries received from the API')),
                ('total_errors', models.PositiveIntegerField(default=0, help_text=b'Number of entries that were not processable')),
                ('total_failed', models.PositiveIntegerField(default=0, help_text=b'Number of entries recorded as failed by the PA')),
                ('total_success', models.PositiveIntegerField(default=0, help_text=b'Number of entries that the PA indicated were successfully processed')),
                ('status_detail', models.TextField(null=True, blank=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
package db

import "github.com/stretchr/testify/mock"

// MockBatch mocks Batch.
type MockBatch struct {
	mock.Mock
}

// NewMockBatch creates a new MockBatch.
func NewMockBatch() *MockBatch {
	return &MockBatch{}
}

// Query adds the query to the batch operation
func (m *MockBatch) Query(stmt string, values ...interface{}) {
	var all []interface{}
	all = append(all, stmt)
	all = append(all, values...)

	m.Called(all...)
}

// Execute executes the batch operation.
func (m *MockBatch) Execute() error {
	args := m.Called()
	return args.Error(0)
}


text:
This is a very simple way to deploy CachetHD on to Openshift or Kubernetes.  I have only tested this on OpenShift 3.3 at this time 01/29/2017.

## Motivation

This was someting I did a work as we needed a dashboard to see that status of the services in our OpenShift.

## Installation

To get this all work you need to have a DB you can access.

Deploy the DC using `oc create -f cachethd-dc.yaml` while logged in to the project you want to deploy to.

You will need to change the env values to your setup.

You will then need to setup service and then a route so you can get to Cachet URL.

## Contributors

Andy del Hierro
andelhie@cisco.com


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;

namespace ReportProcessingService.Models
{
    [DataContract]
    internal class ReportStatus
    {
        public ReportStatus(int step, int remaining, string status, string result)
        {
            this.Step = step;
            this.Remaining = remaining;
            this.Status = status;
            this.Result = result;
        }

        [DataMember]
        public int Step { get; private set; }

        [DataMember]
        public int Remaining { get; private set; }

        [DataMember]
        public string Status { get; private set; }

        [DataMember]
        public string Result { get; private set; }
    }
}


text:
%% Colony Diameter - measures the major axis length of the colony
% Matlab Colony Analyzer Toolkit
% Gordon Bean, June 2013

classdef ColonyDiameter < ColonyQuantifier
    methods
        function this = ColonyDiameter()
            this = this@ColonyQuantifier('diameter');
        end

        function colsize = quantify(this, varargin)
            [box, bbox] = this.parse_box(varargin{:});

            % Clear adjacent colonies
            [~, bbox] = clear_adjacent_colonies(box, bbox);

            % Get colony properties
            stats = regionprops(bbox, 'Centroid', 'MajorAxisLength');

            % Identify the center colony
            cents = cat(1, stats.Centroid);
            w = (size(box,1)-1)/2+1;
            tmp = sum((cents - w).^2,2);

            % Return the diameter, or major axis length of the colony
            if isempty(stats)
                % Box is empty
                colsize = nan;
            else
                colsize = stats(argmin(tmp)).MajorAxisLength;
            end
        end
    end
end


text:
import {Rx} from '@cycle/core';
import intent from './intent';
import model from './model';
import view from './view';
import deserialize from './source';
import serialize from './sink';
import ecoItem from './item';
import mapValues from 'lodash.mapvalues';

function amendStateWithChildren(DOM) {
  return function (ecosData) {
    return {
      list: ecosData.list.map(data => {
        const props$ = Rx.Observable.just(data);
        return {
          id: data.id,
          title: data.title,
          ecoItem: ecoItem({DOM, props$}, `.oz-eco-item${data.id}`)
        }
      }),
      filter: ecosData.filter,
      filterFn: ecosData.filterFn,
      spin: ecosData.spin,
    }
  };
}

function makeItemActions(typeItemActions, amendedState$) {
  return mapValues(typeItemActions, (irrelevant, actionKey) =>
    amendedState$
    .filter(ecosData => ecosData.list.length)
    .flatMapLatest(ecosData =>
      Rx.Observable.merge(ecosData.list.map(i => i.ecoItem[actionKey]))
    )
  );
}

function replicateAll(objectStructure, realStreams, proxyStreams) {
  mapValues(objectStructure, (irrelevant, key) => {
    realStreams[key]
  });
}

function ecos({DOM, falcorSource}) {
  console.log("eco falcorSource:", falcorSource);
  let sourceEcosData$ = deserialize(falcorSource);
  let typeItemActions = {toggle$: null, edit$: null, delete$: null};
  let proxyItemActions = mapValues(typeItemActions, () => new Rx.Subject());
  let actions = intent(DOM, proxyItemActions);
  let state$ = model(actions, sourceEcosData$).shareReplay(1);
  let amendedState$ = state$.map(amendStateWithChildren(DOM)).shareReplay(1);
  let itemActions = makeItemActions(typeItemActions, amendedState$);
  replicateAll(typeItemActions, itemActions, proxyItemActions);
  return {
    DOM: view(amendedState$),
    falcorSink: serialize(state$)
  };
}

export default ecos;


text:
package com.nasageek.utexasutilities.adapters;

import android.support.v4.app.FragmentManager;

import com.actionbarsherlock.app.SherlockFragment;

import java.util.List;

public class MultiPanePagerAdapter extends MyFragmentPagerAdapter {

    /**
     * number of pages we want to display at once
     */
    private int mPanesDisplayed;

    public MultiPanePagerAdapter(FragmentManager fm, List<SherlockFragment> fragments) {
        super(fm, fragments);
        mPanesDisplayed = 1;
    }

    public void setPagesDisplayed(int panes) {
        mPanesDisplayed = panes;
    }

    @Override
    public float getPageWidth(int position) {
        return (float) (1.0 / mPanesDisplayed);
    }
}


text:
package rest;

import java.util.List;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import entities.Project;
import entities.ProjectManager;
import services.DevelopersService;
import services.ProjectManagersService;
import services.ProjectsService;

@Path("/projects")
public class ProjectRest {
	private final ProjectsService projectsService;
	private final ProjectManagersService projectManagersService;
	private final DevelopersService developersService;

	@Inject
	public ProjectRest(ProjectsService projectsService, DevelopersService developersService, ProjectManagersService projectManagersService){
		this.projectsService = projectsService;
		this.developersService = developersService;
		this.projectManagersService = projectManagersService;
	}

	@GET
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public List<Project> getProjects(){
		return projectsService.getProjects();
	}

	@GET
	@Path("/{projectId}")
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public Project getProject(@PathParam("projectId") long projectId){
		return projectsService.getProject(projectId);
	}

	@POST
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	@Consumes({MediaType.APPLICATION_JSON})
	public Project createProject(Project project){
		final List<ProjectManager> members = projectManagersService.getProjectManagers();
		project.setProjectManager(members.iterator().next());
		return projectsService.createProject(project);
	}

	@DELETE
	@Path("/{projectId}")
	public void deleteProject(@PathParam("projectId") long projectId){
		projectsService.deleteProject(projectId);
	}

	@PUT
	@Path("/{projectId}")
	@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public Project updateProject(@PathParam("projectId") long projectId, Project project){
		final Project fromDb = projectsService.getProject(projectId);
		fromDb.setName(project.getName());
		fromDb.setDevelopers(developersService.getDevelopersByProject(project));
		fromDb.setProjectManager(project.getProjectManager());
		fromDb.setStatus(project.getStatus());

		return projectsService.updateProject(fromDb);
	}
}


text:
from Queue import PriorityQueue, Empty
from simdesim.action import *

class DESNode:

    def __init__(self, node_id):
        """
        Initialize the node class.

        :param node_id: unique identifier for the node
        """

        self.node_id = node_id
        self.inbox = PriorityQueue()
        self.outbox = []
        self.process_act_ct = 0
        self.outbox_act_ct = 0

    def process_timestep(self, timestep):
        """
        Takes a timestep and processes all messages up
        to and including that timestep
        """

        while True:
            # if theres nothin' in the queue move along
            try:
                cur_msg = self.inbox.get(block=False)
            except Empty:
                break

            # if we've gone past the time step, put it back and break out
            # of the loop
            if cur_msg[ACT_TIMESTEP] > timestep:
                self.inbox.put(cur_msg)
                break

            # otherwise we process the msg
            self.process_action(cur_msg)

    def process_outbox(self):
        """
        Process outgoing actions, meant to be overridden
        """

        self.outbox_act_ct += 1
        for action in self.outbox:
            print action

    def process_action(self, cur_action):
        """
        process incoming actions, meant to be overridden
        """

        self.process_act_ct += 1
        print cur_action


text:
<?php

namespace Emonkak\Waf\Tests\Controller;

class TemplateRenderingHelperTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->templateEngine = $this->getMock('Symfony\Component\Templating\EngineInterface');
        $this->controller = $this->getMockForTrait('Emonkak\Waf\Controller\TemplateRenderingHelper');
        $this->controller->setTemplateEngine($this->templateEngine);
    }

    public function testSetTemplateEngine()
    {
        \Closure::bind(function() {
            $templateEngine = $this->getMock('Symfony\Component\Templating\EngineInterface');
            $this->controller->setTemplateEngine($templateEngine);
            $this->assertSame($templateEngine, $this->controller->templateEngine);
        }, $this, get_class($this->controller))->__invoke();
    }

    public function testRender()
    {
        \Closure::bind(function() {
            $name = 'path/to/template.php';
            $parameters = ['foo' => 'bar'];
            $expected = 'hello world';

            $this->templateEngine
                ->expects($this->once())
                ->method('render')
                ->with($this->identicalTo($name), $this->identicalTo($parameters))
                ->willReturn($expected);

            $this->assertSame($expected, $this->controller->render($name, $parameters));
        }, $this, get_class($this->controller))->__invoke();
    }

    public function testRenderResponse()
    {
        \Closure::bind(function() {
            $name = 'path/to/template.php';
            $parameters = ['foo' => 'bar'];
            $expected = 'hello world';

            $this->templateEngine
                ->expects($this->once())
                ->method('render')
                ->with($this->identicalTo($name), $this->identicalTo($parameters))
                ->willReturn($expected);

            $response = $this->controller->renderResponse($name, $parameters);

            $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
            $this->assertSame($expected, $response->getContent());
        }, $this, get_class($this->controller))->__invoke();
    }
}


text:
#pragma once

#include <aws/core/Core_EXPORTS.h>
#include <mutex>
#include <condition_variable>

namespace Aws
{
    namespace Utils
    {
        namespace Threading
        {
            class AWS_CORE_API Semaphore {
                public:
                    /**
                     * Initializes a new instance of Semaphore class specifying the initial number of entries and
                     * the maximum number of concurrent entries.
                     */
                    Semaphore(size_t initialCount, size_t maxCount);
                    /**
                     * Blocks the current thread until it receives a signal.
                     */
                    void WaitOne();
                    /**
                     * Exits the semaphore once.
                     */
                    void Release();
                    /**
                     * Exit the semaphore up to the maximum number of entries available.
                     */
                    void ReleaseAll();
                private:
                    size_t m_count;
                    const size_t m_maxCount;
                    std::mutex m_mutex;
                    std::condition_variable m_syncPoint;
            };
        }
    }
}


text:
/*****************************************************************************
 * Includes
 ****************************************************************************/
#include "tcp_generator.h"

/*****************************************************************************
 * Definitions
 ****************************************************************************/
static int kni_change_mtu(uint8_t port, unsigned mtu);
static int kni_config_network_if(uint8_t port, uint8_t if_state);

/*****************************************************************************
 * Globals
 ****************************************************************************/
static uint32_t         kni_interfaces;
static struct rte_kni **kni_if;

/*****************************************************************************
 * kni_if_get_count()
 ****************************************************************************/
uint32_t kni_if_get_count(void)
{
    return kni_interfaces;
}

/*****************************************************************************
 * kni_get_first_kni_interface()
 ****************************************************************************/
uint32_t kni_get_first_kni_interface(void)
{
    return rte_eth_dev_count() - kni_if_get_count();
}

/*****************************************************************************
 * kni_handle_kernel_status_requests()
 ****************************************************************************/
void kni_handle_kernel_status_requests(void)
{
    uint32_t kni_port;

    for (kni_port = 0; kni_port < kni_if_get_count(); kni_port++)
        rte_kni_handle_request(kni_if[kni_port]);
}

/*****************************************************************************
 * kni_cores_in_mask()
 ****************************************************************************/
static unsigned int kni_cores_in_mask(uint64_t mask)
{
    int          x;
    unsigned int bits_set = 0;

    for (x = 0; x < 64; x++) {
        if (((1LL << x) & mask) != 0)
            bits_set++;
    }
    return bits_set;
}

/*****************************************************************************
 * kni_if_handle_cmdline_opt()
 ****************************************************************************/
bool kni_if_handle_cmdline_opt(const char *opt_name, char *opt_arg)
{
    if (strcmp(opt_name, "kni-ifs"))
        return false;

#if !defined(TPG_KNI_IF)
    TPG_ERROR_EXIT(EXIT_FAILURE,
                   "ERROR: Recompile with TPG_KNI_IF set for Kernel Networking Interface support!\n");
    return false;
#endif /* !defined(TPG_KNI_IF) */

    errno = 0;
    kni_interfaces = strtol(opt_arg, NULL, 10);
    if (errno != 0)
        TPG_ERROR_EXIT(EXIT_FAILURE, "ERROR: Invalid Ketnel Networking Interface count!\n");

    opt_arg = opt_arg;

    return true;
}

/*****************************************************************************
 * kni_if_init()
 ****************************************************************************/
bool kni_if_init(void)
{
    uint32_t         kni_port;
    global_config_t *cfg;

    if (kni_if_get_count() == 0)
        return true;

    cfg = cfg_get_config();
    if (cfg == NULL)
        return false;

    RTE_LOG(WARNING, USER1,
            "WARNING: Changing the MTU for KNI ports MUST be done trough WARP17!\n");

    /*
     * This check we can not do at command line verification, as we do not
     * know how many ring interfaces we are going to create!
     *
     * NOTE: It's missing the ring_if_get_count() below, as it's init function
     *       has been called at this stage, so they are included in the
     *       rte_eth_dev_count()!
     */
    if ((rte_eth_dev_count() + kni_if_get_count()) > TPG_ETH_DEV_MAX)
        TPG_ERROR_EXIT(EXIT_FAILURE,
                       "ERROR: Total number of virtual interfaces and ethernet ports must be less than (or equal to) %u!\n",
                       TPG_ETH_DEV_MAX);

    /*
     * Allocate memory to store kni pointers
     */

    kni_if = rte_zmalloc("kni_port",
                         sizeof(void *) * kni_if_get_count(), 0);

    if (kni_if == NULL) {
        RTE_LOG(ERR, USER1,
                "ERROR: Failed allocating memory for KNI interfaces!\n");
        return false;
    }

    /*
     * Initialize the KNI dpdk subsystem, no return codes :(
     * It will panic if the kernel module is not loaded...
     */
    rte_kni_init(kni_if_get_count());

    /*
     * Create the individual kernel interfaces
     */

    for (kni_port = 0; kni_port < kni_if_get_count(); kni_port++) {

        struct rte_kni         *kni;
        struct rte_kni_conf     conf;
        struct rte_kni_ops      ops;
        struct rte_eth_dev_info dev_info;
        uint32_t                port = rte_eth_dev_count();

        if (port_port_cfg[port].ppc_q_cnt != kni_cores_in_mask(port_port_cfg[port].ppc_core_mask))
            TPG_ERROR_ABORT("ERROR: Assigned lcores should be the same as number of queues!");

        if (kni_cores_in_mask(port_port_cfg[port].ppc_core_mask) != 1) {
            RTE_LOG(ERR, USER1,
                    "ERROR: Kernel Network Interfaces (warp%u), can only be assigned to a single core!\n",
                    port);
            return false;
        }

        memset(&conf, 0, sizeof(conf));

        conf.core_id = 0;     /* Currently don't bind kernel side to a core */
        conf.force_bind = 0;

        snprintf(conf.name, RTE_KNI_NAMESIZE,
                 "warp%u", port);
        conf.group_id = (uint16_t) port;

        /*
         * We subtract the RTE_PKTMBUF_HEADROOM from the size here,
         * as the KNI kernel driver does not look a the mbuf fields
         * to determine the bytes it can write. Passing the full size
         * of the mbuf will overwrite/trash memory.
         */
        conf.mbuf_size = cfg->gcfg_mbuf_size - RTE_PKTMBUF_HEADROOM;

        memset(&dev_info, 0, sizeof(dev_info));
        memset(&ops, 0, sizeof(ops));
        ops.port_id = port;
        ops.change_mtu = kni_change_mtu;
        ops.config_network_if = kni_config_network_if;

        kni = rte_kni_alloc(mem_get_mbuf_pool(port, 0), &conf, &ops);

        if (kni == NULL) {
            RTE_LOG(ERR, USER1,
                    "ERROR: Failed to create Kernel Networking Interface %u!\n",
                    port);
            return false;
        }

        kni_if[kni_port] = kni;

        if (!kni_eth_from_kni(conf.name, kni, port_get_socket(port, 0))) {
            RTE_LOG(ERR, USER1,
                    "ERROR: Failed to create Kernel Networking Interface %u's ethernet interface!\n",
                    port);
            return false;
        }

        rte_eth_dev_info_get(port, &port_dev_info[port].pi_dev_info);
        port_dev_info[port].pi_numa_node = port_get_socket(port, 0);
        port_dev_info[port].pi_adjusted_reta_size = PORT_QCNT(port);
        port_dev_info[port].pi_ring_if = false;
        port_dev_info[port].pi_kni_if = true;
    }

    return true;
}

/*****************************************************************************
 * kni_change_mtu()
 ****************************************************************************/
static int kni_change_mtu(uint8_t port, unsigned mtu)
{
    global_config_t *cfg;

    if (test_mgmt_get_port_env(port)->te_test_running) {
        RTE_LOG(ERR, USER1,
                "ERROR: Can't change MTU for port %u as test is running!\n",
                port);

        /*
         * Although we report the error here, its not propagated to the user/
         * kernel who tried to change the MTU. So the kernel sets the MTU just
         * fine, so we hope the error above is enough for now ;)
         */
        return -EINVAL;
    }

    cfg = cfg_get_config();
    if (cfg == NULL || mtu > (cfg->gcfg_mbuf_size - RTE_PKTMBUF_HEADROOM)) {

        RTE_LOG(ERR, USER1,
                "ERROR: Requested MTU, %u, for port %u higher than mbuf size, %u!\n",
                mtu,
                port,
                cfg->gcfg_mbuf_size - RTE_PKTMBUF_HEADROOM);

        return -EINVAL;
    }

    if (mtu < ETHER_MIN_LEN) {
        RTE_LOG(ERR, USER1,
                "ERROR: Requested MTU, %u, for port %u smaller than minimal ethernet size, %u!\n",
                mtu,
                port,
                ETHER_MIN_LEN);
        return -EINVAL;
    }

    /*
     * Copy new MTU to global structure, ports will get a copy on test
     * start in pktloop.
     */
    port_dev_info[port].pi_mtu = mtu;

    return 0;
}

/*****************************************************************************
 * kni_config_network_if()
 ****************************************************************************/
static int kni_config_network_if(uint8_t port, uint8_t if_state)
{
    RTE_LOG(DEBUG, USER1, "KNI: Configure network interface of %d %s\n",
            port, if_state ? "up" : "down");
    /*
     * Nothing needs to be done here, as we will call the internals from
     * DPDK to make the PMD port to be up.
     */
    return 0;
}


text:
class Scraper
  def self.scrape_hfict #Hardcover Fiction
    hfict = Nokogiri::HTML(open("http://www.barnesandnoble.com/b/new-york-times-bestsellers-hardcover-fiction/_/N-1p3r", :allow_redirections => :all))
    count = 1
    while count < 16
      book_array = []
      hfict.css("div.product-info").collect do |book|
        book_info = {
          :url => "http://www.barnesandnoble.com#{hfict.css("#listView > li:nth-child(#{count}) > ul > li > div.product-image > a:nth-child(1)").attribute("href").value}"
        }

        book_page = Nokogiri::HTML (open(book_info[:url], :allow_redirections => :all))
        book_info[:title] = book_page.css("h1").text
        book_info[:author] = book_page.css("span > a").first.text
        book_info[:summary] = book_page.css(".flexColumn").text.strip

        book_array << book_info
        count += 1
      end
    end
    book_array
  end

  def self.scrape_hnonfict #Hardcover Nonfiction
    hnonfict = Nokogiri::HTML(open("http://www.barnesandnoble.com/b/new-york-times-bestsellers-hardcover-nonfiction/_/N-1p5q", :allow_redirections => :all))
    count = 1
    while count < 16
      book_array = []
      hnonfict.css("div.product-info").collect do |book|
        book_info = {
          :url => "http://www.barnesandnoble.com#{hnonfict.css("#listView > li:nth-child(#{count}) > ul > li > div.product-image > a:nth-child(1)").attribute("href").value}"
        }

        book_page = Nokogiri::HTML (open(book_info[:url], :allow_redirections => :all))
        book_info[:title] = book_page.css("h1").text
        book_info[:author] = book_page.css("span > a").first.text
        book_info[:summary] = book_page.css(".flexColumn").text.strip

        book_array << book_info
        count += 1
      end
    end
    book_array
  end

  def self.scrape_pfict #Paperback Fiction
    pfict = Nokogiri::HTML(open("http://www.barnesandnoble.com/b/new-york-times-bestsellers-trade-paperback-fiction/_/N-1p3v", :allow_redirections => :all))
    count = 1
    while count < 11
      book_array = []
      pfict.css("div.product-info").collect do |book|
        book_info = {
          :url => "http://www.barnesandnoble.com#{pfict.css("#listView > li:nth-child(#{count}) > ul > li > div.product-image > a:nth-child(1)").attribute("href").value}"
        }

        book_page = Nokogiri::HTML (open(book_info[:url], :allow_redirections => :all))
        book_info[:title] = book_page.css("h1").text
        book_info[:author] = book_page.css("span > a").first.text
        book_info[:summary] = book_page.css(".flexColumn").text.strip

        book_array << book_info
        count += 1
      end
    end
    book_array
  end

  def self.scrape_pnonfict #Paperback Nonfiction
    pnonfict = Nokogiri::HTML(open("http://www.barnesandnoble.com/b/new-york-times-bestsellers-paperback-nonfiction/_/N-1p3u", :allow_redirections => :all))
    count = 1
    while count < 11
      book_array = []
      pnonfict.css("div.product-info").collect do |book|
        book_info = {
          :url => "http://www.barnesandnoble.com#{pnonfict.css("#listView > li:nth-child(#{count}) > ul > li > div.product-image > a:nth-child(1)").attribute("href").value}"
        }

        book_page = Nokogiri::HTML (open(book_info[:url], :allow_redirections => :all))
        book_info[:title] = book_page.css("h1").text
        book_info[:author] = book_page.css("span > a").first.text
        book_info[:summary] = book_page.css(".flexColumn").text.strip

        book_array << book_info
        count += 1
      end
    end
    book_array
  end

  def self.scrape_advice #Advice and How-To
    advice = Nokogiri::HTML(open("http://www.barnesandnoble.com/b/new-york-times-bestsellers-advice-how-to-miscellaneous/_/N-1p3o", :allow_redirections => :all))
    count = 1
    while count < 11
      book_array = []
      advice.css("div.product-info").collect do |book|
        book_info = {
          :url => "http://www.barnesandnoble.com#{advice.css("#listView > li:nth-child(#{count}) > ul > li > div.product-image > a:nth-child(1)").attribute("href").value}"
        }

        book_page = Nokogiri::HTML (open(book_info[:url], :allow_redirections => :all))
        book_info[:title] = book_page.css("h1").text
        book_info[:author] = book_page.css("span > a").first.text
        book_info[:summary] = book_page.css(".flexColumn").text.strip

        book_array << book_info
        count += 1
      end
    end
    book_array
  end
end


text:
var testGenerator = testSteps();

function testSteps()
{
  const name = this.window ? window.location.pathname : "Splendid Test";

  let request = indexedDB.open(name, 1);
  request.onerror = errorHandler;
  request.onupgradeneeded = grabEventAndContinueHandler;
  let event = yield;

  let db = event.target.result;
  db.addEventListener("error", function(event) {
    event.preventDefault();
  }, false);

  let objectStore = db.createObjectStore("foo", { autoIncrement: true });

  request = objectStore.add({});
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  let key1 = event.target.result;

  request = objectStore.put({}, key1);
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key1, "put gave the same key back");

  let key2 = 10;

  request = objectStore.put({}, key2);
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key2, "put gave the same key back");

  key2 = 100;

  request = objectStore.add({}, key2);
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key2, "put gave the same key back");

  try {
    objectStore.put({});
    ok(true, "put with no key should not throw with autoIncrement!");
  }
  catch (e) {
    ok(false, "put with no key threw with autoIncrement");
  }

  try {
    objectStore.put({});
    ok(true, "put with no key should not throw with autoIncrement!");
  }
  catch (e) {
    ok(false, "put with no key threw with autoIncrement");
  }

  try {
    objectStore.delete();
    ok(false, "remove with no key should throw!");
  }
  catch (e) {
    ok(true, "remove with no key threw");
  }

  objectStore = db.createObjectStore("bar");

  try {
    objectStore.add({});
    ok(false, "add with no key should throw!");
  }
  catch (e) {
    ok(true, "add with no key threw");
  }

  try {
    objectStore.put({});
    ok(false, "put with no key should throw!");
  }
  catch (e) {
    ok(true, "put with no key threw");
  }

  try {
    objectStore.put({});
    ok(false, "put with no key should throw!");
  }
  catch (e) {
    ok(true, "put with no key threw");
  }

  try {
    objectStore.delete();
    ok(false, "remove with no key should throw!");
  }
  catch (e) {
    ok(true, "remove with no key threw");
  }

  objectStore = db.createObjectStore("baz", { keyPath: "id" });

  try {
    objectStore.add({});
    ok(false, "add with no key should throw!");
  }
  catch (e) {
    ok(true, "add with no key threw");
  }

  try {
    objectStore.add({id:5}, 5);
    ok(false, "add with inline key and passed key should throw!");
  }
  catch (e) {
    ok(true, "add with inline key and passed key threw");
  }

  try {
    objectStore.put({});
    ok(false, "put with no key should throw!");
  }
  catch (e) {
    ok(true, "put with no key threw");
  }

  try {
    objectStore.put({});
    ok(false, "put with no key should throw!");
  }
  catch (e) {
    ok(true, "put with no key threw");
  }

  try {
    objectStore.delete();
    ok(false, "remove with no key should throw!");
  }
  catch (e) {
    ok(true, "remove with no key threw");
  }

  key1 = 10;

  request = objectStore.add({id:key1});
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key1, "add gave back the same key");

  request = objectStore.put({id:10});
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key1, "put gave back the same key");

  request = objectStore.put({id:10});
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key1, "put gave back the same key");

  request = objectStore.add({id:10});
  request.addEventListener("error", new ExpectError("ConstraintError", true));
  request.onsuccess = unexpectedSuccessHandler;
  event = yield;

  try {
    objectStore.add({}, null);
    ok(false, "add with null key should throw!");
  }
  catch (e) {
    ok(true, "add with null key threw");
  }

  try {
    objectStore.put({}, null);
    ok(false, "put with null key should throw!");
  }
  catch (e) {
    ok(true, "put with null key threw");
  }

  try {
    objectStore.put({}, null);
    ok(false, "put with null key should throw!");
  }
  catch (e) {
    ok(true, "put with null key threw");
  }

  try {
    objectStore.delete({}, null);
    ok(false, "remove with null key should throw!");
  }
  catch (e) {
    ok(true, "remove with null key threw");
  }

  objectStore = db.createObjectStore("bazing", { keyPath: "id",
                                                 autoIncrement: true });

  request = objectStore.add({});
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  key1 = event.target.result;

  request = objectStore.put({id:key1});
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key1, "put gave the same key back");

  key2 = 10;

  request = objectStore.put({id:key2});
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  is(event.target.result, key2, "put gave the same key back");

  try {
    objectStore.put({});
    ok(true, "put with no key should not throw with autoIncrement!");
  }
  catch (e) {
    ok(false, "put with no key threw with autoIncrement");
  }

  try {
    objectStore.put({});
    ok(true, "put with no key should not throw with autoIncrement!");
  }
  catch (e) {
    ok(false, "put with no key threw with autoIncrement");
  }

  try {
    objectStore.delete();
    ok(false, "remove with no key should throw!");
  }
  catch (e) {
    ok(true, "remove with no key threw");
  }

  try {
    objectStore.add({id:5}, 5);
    ok(false, "add with inline key and passed key should throw!");
  }
  catch (e) {
    ok(true, "add with inline key and passed key threw");
  }

  request = objectStore.delete(key2);
  request.onerror = errorHandler;
  request.onsuccess = grabEventAndContinueHandler;
  event = yield;

  finishTest();
  yield;
}


text:
namespace COMISO {

//== IMPLEMENTATION ==========================================================

// solve
int
NewtonSolver::
solve(NProblemGmmInterface* _problem)
{
#if COMISO_SUITESPARSE_AVAILABLE

  // get problem size
  int n = _problem->n_unknowns();

  // hesse matrix
  NProblemGmmInterface::SMatrixNP H;
  // gradient
  std::vector<double> x(n), x_new(n), dx(n), g(n);

  // get initial x, initial grad and initial f
  _problem->initial_x(P(x));
  double f = _problem->eval_f(P(x));

  double reg = 1e-3;
  COMISO::CholmodSolver chol;

  for(int i=0; i<max_iter_; ++i)
  {
    _problem->eval_gradient(P(x), P(g));
    // check for convergence
    if( gmm::vect_norm2(g) < convergence_eps_)
    {
      std::cerr << "Newton Solver converged after "
                << i << " iterations" << std::endl;
      _problem->store_result(P(x));
      return true;
    }

    // get current hessian
    _problem->eval_hessian(P(x), H);

    // regularize
    double reg_comp = reg*gmm::mat_trace(H)/double(n);
    for(int j=0; j<n; ++j)
      H(j,j) += reg_comp;

    // solve linear system
    bool factorization_ok = false;
    if(constant_hessian_structure_ && i != 0)
      factorization_ok = chol.update_system_gmm(H);
    else
      factorization_ok = chol.calc_system_gmm(H);

    bool improvement = false;
    if(factorization_ok)
      if(chol.solve( dx, g))
      {
        gmm::add(x, gmm::scaled(dx,-1.0),x_new);
        double f_new = _problem->eval_f(P(x_new));

        if( f_new < f)
        {
          // swap x and x_new (and f and f_new)
          x_new.swap(x);
          f = f_new;
          improvement = true;

          std::cerr << "energy improved to " << f << std::endl;
        }
      }

    // adapt regularization
    if(improvement)
    {
      if(reg > 1e-9)
        reg *= 0.1;
    }
    else
    {
      if(reg < 1e4)
        reg *= 10.0;
      else
      {
        _problem->store_result(P(x));
        std::cerr << "Newton solver reached max regularization but did not converge ... " << std::endl;
        return false;
      }
    }
  }
  _problem->store_result(P(x));
  std::cerr << "Newton Solver did not converge!!! after "
            << max_iter_ << " iterations." << std::endl;
  return false;

#else
  std::cerr << "Warning: NewtonSolver requires not-available CholmodSolver...\n";
  return false;
#endif
}

//-----------------------------------------------------------------------------

//=============================================================================
} // namespace COMISO
//=============================================================================


text:
// Note: this file is written using commonjs instead of import/export to
// simplify consumption by those less familiar with the current state of
// JavaScript modularization

/* eslint camelcase: [0] */

require(`@ciscospark/plugin-authorization`);
require(`@ciscospark/plugin-phone`);
// explicitly load wdm, since we're relying on preDiscoveryServices and the
// url interceptor
require(`@ciscospark/internal-plugin-wdm`);
require(`@ciscospark/plugin-logger`);
require(`@ciscospark/plugin-people`);

const {merge} = require(`lodash`);
const {registerPlugin} = require(`@ciscospark/spark-core`);
const SparkCore = require(`@ciscospark/spark-core`).default;
const Memberships = require(`./plugins/memberships`).default;
const Messages = require(`./plugins/messages`).default;
const Rooms = require(`./plugins/rooms`).default;
const Teams = require(`./plugins/teams`).default;
const TeamMemberships = require(`./plugins/team-memberships`).default;
const Webhooks = require(`./plugins/webhooks`).default;
const config = require(`./config`);

registerPlugin(`memberships`, Memberships);
registerPlugin(`messages`, Messages);
registerPlugin(`rooms`, Rooms);
registerPlugin(`teams`, Teams);
registerPlugin(`teamMemberships`, TeamMemberships);
registerPlugin(`webhooks`, Webhooks);

// documentation.js puts hashes in relative urls, so need to specify full urls
// here
/**
 * See {@link https://ciscospark.github.io/spark-js-sdk/example/browsers|Browser Guide} and
 * {@link https://ciscospark.github.io/spark-js-sdk/example/servers|Server Guide}
 * @see {@link /example/browsers|Browser Guide}
 * @see {@link /example/servers|Server Guide}
 * @class CiscoSpark
 */
const CiscoSpark = SparkCore.extend({
  ciscospark: true,
  version: PACKAGE_VERSION
});

CiscoSpark.version = PACKAGE_VERSION;

/**
 * Create a new ciscospark instance
 *
 * @example
 *
Create a new CiscoSpark instance configured for your OAuth client

 * const ciscospark = CiscoSpark.init({
 *   config: {
 *     credentials: {
 *       authorizationString: `<AUTHORIZATION URL FROM DEVELOPER PORTAL>`
 *     }
 *   }
 * });
 *
 * @example
 *
Create a new CiscoSpark instance configured for a Bot

 * const ciscospark = CiscoSpark.init({
 *   config: {
 *     credentials: `<BOT TOKEN FROM DEVELOPER PORTAL>`
 *   }
 * });
 *
 *
 * @param {Object} attrs
 * @param {Object} attrs.config (optional)
 * @memberof CiscoSpark
 * @returns {CiscoSpark}
 */
CiscoSpark.init = function init(attrs = {}) {
  attrs.config = merge({}, config, attrs.config);
  return new CiscoSpark(attrs);
};

module.exports = CiscoSpark;


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

//Validation functions

var validateRequired = function(property) {
	if(property === 0)
		return property.toString().length;

	return (property && property.toString().length);
};

/**
 * Event Schema
 */
var EventSchema = new Schema({
	name: {
		type: String,
		trim: true,
		required: true,
		validate: [validateRequired, 'Name is required.']
	},
	start_date: {
		type: Number,
		required: true,
		validate: [validateRequired, 'Start date is required.']
	},
	end_date: {
		type: Number,
		required: true,
		validate: [validateRequired, 'End date is required.']
	},
	location: {
		type: String,
		trim: true,
		required: true,
		validate: [validateRequired, 'Location is required.']
	},
	schedule: {
		type: String,
		trim: true,
		default: 'No schedule specified'
	},
	capacity: {
		type: Number,
		min: 0,
		required: true,
		validate: [validateRequired, 'Capacity is required.']
	},
	attending: {
		type: Number,
		min: 0,
		default: 0,
		required: true
	},
	invited: {
		type: Number,
		min: 0,
		default: 0,
		required: true
	},
	active: {
		type: Boolean,
		default: true,
		required: true
	}
});

EventSchema.index({name:1}, {unique:true});

EventSchema.pre('validate', function(next) {
	if(this.start_date > this.end_date){
		this.invalidate('end_date','end date must be after start date');
	}
	if(this.end_date < new Date().getTime()){
		this.invalidate('end_date','end date must not be in the past');
	}
	if(this.start_date < new Date().getTime()) {
		this.invalidate('start_date', 'Event must start later than now.');
	}
	if(isNaN(new Date(this.end_date).getDate()) || isNaN(new Date(this.start_date).getDate())) {
		this.invalidate('contents', 'Dates must be valid.');
	}
	next();
});

mongoose.model('Event', EventSchema);

exports = EventSchema;


text:
package sword.java.class_analyzer.pool;

import java.io.IOException;
import java.io.InputStream;

import sword.java.class_analyzer.FileError;
import sword.java.class_analyzer.Utils;
import sword.java.class_analyzer.java_type.ExtendedTypeFactory;
import sword.java.class_analyzer.ref.MemberReference;

public abstract class AbstractMemberEntry extends ConstantPoolEntry {

    private final int mClassReferenceIndex;
    private final int mVarReferenceIndex;

    ClassReferenceEntry mClassEntry;
    VariableEntry mVariableEntry;

    AbstractMemberEntry(InputStream inStream) throws IOException, FileError {
        mClassReferenceIndex = Utils.getBigEndian2Int(inStream);
        mVarReferenceIndex = Utils.getBigEndian2Int(inStream);
    }

    @Override
    boolean resolve(ConstantPool pool, ExtendedTypeFactory factory) throws FileError {
        mClassEntry = pool.get(mClassReferenceIndex, ClassReferenceEntry.class);
        mVariableEntry = pool.get(mVarReferenceIndex, VariableEntry.class);

        boolean resolved = mClassEntry.mResolved && mVariableEntry.mResolved;
        if (resolved) {
            mResolved = true;
        }

        return resolved;
    }

    abstract MemberReference getReference();

    public String getName() {
        return getReference().getQualifiedName();
    }

    public String getType() {
        return mVariableEntry.getType();
    }

    @Override
    public String toString() {
        final MemberReference reference = getReference();
        return reference.getQualifiedName() + ' '
                + reference.getTypeSignature();
    }
}


text:
namespace GPS {

    /// Die Klasse Trackpoint verwaltet von GPS-Geräten aufgezeichnete Trackpunkte.
    class Trackpoint : public Waypoint
    {
    protected:
        /// Entfernung vom Start in Metern.
        double _Distance;

        /// Anstieg zum nächsten Trackpunkt in Prozent.
        double _Slope;

        /// Herzfrequenz in Schlägen pro Minute.
        UnsignedIntValue _Heartrate;

        /// Temperatur in °C.
        DoubleValue _Temperature;

        /// Verstrichene Zeit seit dem Start in Sekunden.
        time_t _Duration;

        /// Flag, das angibt, ob dieser Trackpunkt nach dem Ausdünnen via
        /// Track::smoothDouglasPeucker(), Track::weed2D() oder Track::weed3D()
        /// beibehalten wurde.
        bool _Keep;

    public:
        /// Default-Konstruktor.
        Trackpoint(void);

        /// Konstruktor.
        Trackpoint(double lon, double lat, DoubleValue ele = DoubleValue(), Timestamp timestamp = Timestamp());

        /// Copy-Konstruktor.
        /// Der Copy-Konstruktor überträgt alle Membervariablen bis auf _Keep.
        /// _Keep wird auf false gesetzt.
        /// @param other Trackpunkt, von dem die Kopie erstellt werden soll.
        Trackpoint(const Trackpoint& other);

        /// Abstand des Trackpunktes zu einer gedachten berechnen, die durch die beiden übergebenen Trackpunkten verläuft.
        /// Die Berechnung erfolgt in zwei Dimensionen, und zwar nur unter Einbeziehung der Entfernung vom Start und der Höhe.
        /// @param p1 Erster Punkt, durch den die gedachte Linie verlaufen soll.
        /// @param p2 Zweiter Punkt, durch den die gedachte Linie verlaufen soll.
        /// @return (Senkrechter) Abstand.
        double perpendicularDistanceElevation(const Trackpoint* p1, const Trackpoint* p2);

        /// Abstand des Trackpunktes zu einer gedachten berechnen, die durch die beiden übergebenen Trackpunkten verläuft.
        /// Die Berechnung erfolgt in zwei Dimensionen, und zwar nur unter Einbeziehung der Entfernung vom Start und der Höhe.
        /// @param p1 Erster Punkt, durch den die gedachte Linie verlaufen soll.
        /// @param p2 Zweiter Punkt, durch den die gedachte Linie verlaufen soll.
        /// @return (Senkrechter) Abstand.
        double perpendicularDistanceElevation(const Trackpoint& p1, const Trackpoint& p2);

        /// Abstand des Trackpunktes zu einer gedachten berechnen, die durch die beiden übergebenen Trackpunkten verläuft.
        /// Die Berechnung erfolgt in zwei Dimensionen, und zwar ausschließlich unter Einbeziehung von Längen- und Breitengrad. Die Höhe wird ignoriert.
        /// @param p1 Erster Punkt, durch den die gedachte Linie verlaufen soll.
        /// @param p2 Zweiter Punkt, durch den die gedachte Linie verlaufen soll.
        /// @return (Senkrechter) Abstand.
        double perpendicularDistance2D(Trackpoint* p1, Trackpoint* p2);

        /// Abstand des Trackpunktes zu einer gedachten berechnen, die durch die beiden übergebenen Trackpunkten verläuft.
        /// Die Berechnung erfolgt in zwei Dimensionen, und zwar ausschließlich unter Einbeziehung von Längen- und Breitengrad. Die Höhe wird ignoriert.
        /// @param p1 Erster Punkt, durch den die gedachte Linie verlaufen soll.
        /// @param p2 Zweiter Punkt, durch den die gedachte Linie verlaufen soll.
        /// @return (Senkrechter) Abstand.
        double perpendicularDistance2D(Trackpoint& p1, Trackpoint& p2);

        /// Abstand des Trackpunktes zu einer gedachten berechnen, die durch die beiden übergebenen Trackpunkten verläuft.
        /// Die Berechnung erfolgt in drei Dimensionen, also unter Einbeziehung von Längen- und Breitengrad sowie der Höhe.
        /// @param p1 Erster Punkt, durch den die gedachte Linie verlaufen soll.
        /// @param p2 Zweiter Punkt, durch den die gedachte Linie verlaufen soll.
        /// @return (Senkrechter) Abstand.
        double perpendicularDistance3D(Trackpoint* p1, Trackpoint* p2);

        /// Abstand des Trackpunktes zu einer gedachten berechnen, die durch die beiden übergebenen Trackpunkten verläuft.
        /// Die Berechnung erfolgt in drei Dimensionen, also unter Einbeziehung von Längen- und Breitengrad sowie der Höhe.
        /// @param p1 Erster Punkt, durch den die gedachte Linie verlaufen soll.
        /// @param p2 Zweiter Punkt, durch den die gedachte Linie verlaufen soll.
        /// @return (Senkrechter) Abstand.
        double perpendicularDistance3D(Trackpoint& p1, Trackpoint& p2);

        /// Alle relevanten Daten in einer vom Menschen lesbaren Weise ausgeben.
        /// @param os Stream, in den die Daten ausgegeben werden sollen.
        void dump(std::ostream& os);

        /// Entfernung vom Start in Metern zurückgeben.
        /// @return Entfernung in Metern
        /// @see _Distance
        inline double distance(void) const { return _Distance; }

        /// Anstieg in Prozent zum nächsten Trackpunkt zurückgeben.
        /// @return Anstieg in Prozent
        /// @see _Slope
        inline double slope(void) const { return _Slope; }

        /// Herzfrequenz in Schlägen pro Minute zurückgeben.
        /// @see _Heartrate
        /// @return HF (1/min)
        inline const UnsignedIntValue& heartrate(void) const { return _Heartrate; }

        /// Temperatur in °C zurückgeben.
        /// @see _Temperature
        /// @return Temperatur in °C
        inline const DoubleValue& temperature(void) const { return _Temperature; }

        /// Seit dem Start verstrichene Zeit in Sekunden zurückgeben.
        /// @return Seit dem Start verstrichene Zeit in Sekunden
        /// @see _Duration
        inline time_t duration(void) const { return _Duration; }

        /// Den Wert der Membervariablen _Keep zurückliefern.
        /// @see _Keep
        inline bool kept(void) const { return _Keep; }

        /// Setzen der Entfernung (Meter).
        /// @see _Distance
        inline void setDistance(double distance) { _Distance = distance; }

        /// Setzen der Hearzfrequenz (Schläge pro Minute).
        /// @see _Heartrate
        inline void setHeartrate(UnsignedIntValue heartrate) { _Heartrate = heartrate; }

        /// Setzen der Temperatur (° Celsius).
        /// @see _Temperature
        inline void setTemperature(DoubleValue temperature) { _Temperature = temperature; }

        /// Setzen der Höhe (Meter üNN).
        /// @see _Elevation
        inline void setElevation(DoubleValue elevation) { _Elevation = elevation; }

        /// Setzen des Anstiegs (Prozent)
        /// @see _Slope
        inline void setSlope(double slope) { _Slope = slope; }

        /// Setzen der Dauer seit Start (Sekunden)
        /// @see _Duration
        inline void setDuration(time_t duration) { _Duration = duration; }

        /// Setzen des Flags _Keep.
        /// @see _Keep
        inline void keep(bool flag = true) { _Keep = flag; }

        /// Umwandeln der geografischen Koordinaten des Trackpunkts in UTM-Koordinaten.
        inline operator UTMCoord() { return toUTM(); }

    };

};

#endif // __TRACKPOINT_H_


text:
from webob import exc

from nova.api.openstack import extensions
from nova import exception
from nova.openstack.common.gettextutils import _
from nova import utils

ALIAS = "os-multiple-create"
MIN_ATTRIBUTE_NAME = "%s:min_count" % ALIAS
MAX_ATTRIBUTE_NAME = "%s:max_count" % ALIAS
RRID_ATTRIBUTE_NAME = "%s:return_reservation_id" % ALIAS

class MultipleCreate(extensions.V3APIExtensionBase):
    """Allow multiple create in the Create Server v3 API."""

    name = "MultipleCreate"
    alias = ALIAS
    version = 1

    def get_resources(self):
        return []

    def get_controller_extensions(self):
        return []

    # use nova.api.extensions.server.extensions entry point to modify
    # server create kwargs
    def server_create(self, server_dict, create_kwargs):
        # min_count and max_count are optional.  If they exist, they may come
        # in as strings.  Verify that they are valid integers and > 0.
        # Also, we want to default 'min_count' to 1, and default
        # 'max_count' to be 'min_count'.
        min_count = server_dict.get(MIN_ATTRIBUTE_NAME, 1)
        max_count = server_dict.get(MAX_ATTRIBUTE_NAME, min_count)

        try:
            min_count = utils.validate_integer(min_count,
                                               "min_count", min_value=1)
            max_count = utils.validate_integer(max_count,
                                               "max_count", min_value=1)
        except exception.InvalidInput as e:
            raise exc.HTTPBadRequest(explanation=e.format_message())

        if min_count > max_count:
            msg = _('min_count must be <= max_count')
            raise exc.HTTPBadRequest(explanation=msg)

        create_kwargs['min_count'] = min_count
        create_kwargs['max_count'] = max_count
        create_kwargs['return_reservation_id'] = server_dict.get(
            RRID_ATTRIBUTE_NAME, False)


text:
package org.pentaho.di.trans;

import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.StepPartitioningMeta;

public abstract class BasePartitioner implements Partitioner {

	protected StepPartitioningMeta meta;
	protected int nrPartitions = -1;
	protected String id;
	protected String description;

	public BasePartitioner( ) {
	}

	public Partitioner clone() {
		Partitioner partitioner = getInstance();
		partitioner.setId( id );
		partitioner.setDescription(description);
		partitioner.setMeta(meta);
		return partitioner;
	}

	public int getNrPartitions() {
		return nrPartitions;
	}

	public void setNrPartitions(int nrPartitions) {
		this.nrPartitions = nrPartitions;
	}

	public void init(RowMetaInterface rowMeta ) throws KettleException
	{

        if( nrPartitions < 0 ) {
        	nrPartitions = meta.getPartitionSchema().getPartitionIDs().size();
        }

	}

	public StepPartitioningMeta getMeta() {
		return meta;
	}

	public void setMeta(StepPartitioningMeta meta) {
		this.meta = meta;
	}

	public abstract Partitioner getInstance();

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}


text:
require File.expand_path '../../../../test_config', __FILE__

describe FeatureCollection::Section do
  before do
    @city = City.new(name: 'Some city',
                        start_year: 2017,
                        url_name: 'city',
                        country: 'Argentina')

    @city.coords = Sequel.lit("ST_GeomFromText('POINT(-71.064544 42.28787)',4326)")
    @city.save

    @system = System.create(city_id: @city.id, name: 'A system')

    @line = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line', url_name:'test-line')

    @section = Section.new(buildstart: 1980, opening:1985, closure: 1999, osm_id: 555, osm_tags: 'tags', osm_metadata: 'metadata', city_id: @city.id)
    @section.geometry = Sequel.lit("ST_GeomFromText('LINESTRING(-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932)',4326)")
    @section.save

    @section_line = SectionLine.create(section_id: @section.id, line_id: @line.id, city_id: @city.id)

    @city.reload
  end

  it "should return a feature collection of raw features" do
    feature_collection = JSON.parse(FeatureCollection::Section.by_city(@city.id), symbolize_names: true)
    assert_equal "FeatureCollection", feature_collection[:type]
    assert_equal 1, feature_collection[:features].count
  end

  it "should return a feature collection of formatted features" do
    feature_collection = JSON.parse(FeatureCollection::Section.by_city(@city.id, formatted: true), symbolize_names: true)
    assert_equal "FeatureCollection", feature_collection[:type]
    assert_equal 1, feature_collection[:features].count
  end

  it "should return an empty set of features collection" do
    @section.destroy

    feature_collection = JSON.parse(FeatureCollection::Section.by_city(@city.id), symbolize_names: true)
    assert_equal "FeatureCollection", feature_collection[:type]
    assert_empty feature_collection[:features]

    feature_collection = JSON.parse(FeatureCollection::Section.by_city(@city.id, formatted: true), symbolize_names: true)
    assert_equal "FeatureCollection", feature_collection[:type]
    assert_empty feature_collection[:features]
  end

  it "should return empty lines if no lines data is available" do
    SectionLine.where(line_id: @line.id).destroy
    @line.destroy

    feature = FeatureCollection::Section.by_feature(@section.id).first
    assert_empty feature[:properties][:lines]
  end

  describe "raw_feature" do
    it "should return the right feature" do
      feature = FeatureCollection::Section.by_feature(@section.id).first

      assert_equal 'Feature', feature[:type]
      assert feature[:geometry]

      expected_lines = [{
          line: @line.name,
          line_url_name: @line.url_name,
          system: @system.name,
      }]

      expected_properties = {id: @section.id,
                             klass: "Section",
                             length: @section.length,
                             lines: expected_lines,
                             opening: @section.opening,
                             buildstart: @section.buildstart,
                             osm_id: @section.osm_id,
                             osm_tags: @section.osm_tags,
                             osm_metadata: @section.osm_metadata,
                             closure: @section.closure}

      assert_equal expected_properties, feature[:properties]
    end

    it "should contain feature_line years if present" do
      @section_line.fromyear = 1956
      @section_line.toyear = 1999
      @section_line.save

      feature = FeatureCollection::Section.by_feature(@section.id).first

      assert_equal 'Feature', feature[:type]
      assert feature[:geometry]

      expected_lines = [{
          line: @line.name,
          line_url_name: @line.url_name,
          system: @system.name,
          from: 1956,
          to: 1999
      }]

      expected_properties = {id: @section.id,
                             klass: "Section",
                             length: @section.length,
                             lines: expected_lines,
                             opening: @section.opening,
                             buildstart: @section.buildstart,
                             osm_id: @section.osm_id,
                             osm_tags: @section.osm_tags,
                             osm_metadata: @section.osm_metadata,
                             closure: @section.closure}

      assert_equal expected_properties, feature[:properties]
    end

    it "should set system name to an empty string if it is null" do
      system = System.create(city_id: @city.id)

      @line.system_id = system.id
      @line.save

      feature = FeatureCollection::Section.by_feature(@section.id).first

      assert_equal '', feature[:properties][:lines].first[:system]
    end
  end

  describe "formatted_feature" do
    it "should handle one line" do
      features = FeatureCollection::Section.by_feature(@section.id, formatted: true)

      assert 1, features.count
      feature = features.first

      assert_equal 'Feature', feature[:type]
      assert feature[:geometry]

      expected_properties = {id: "#{@section.id}-#{@line.url_name}",
                             klass: "Section",
                             line_url_name: @line.url_name,
                             width: @line.width,
                             offset: 0,
                             opening: @section.opening,
                             buildstart: @section.buildstart,
                             buildstart_end: @section.opening,
                             closure: @section.closure}

      assert_equal expected_properties, feature[:properties]
    end

    it "should handle multiple simultaneous lines" do
      @line2 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 2', url_name:'test-line-2')
      SectionLine.create(line_id: @line2.id, section_id: @section.id, city_id: @city.id)

      features = FeatureCollection::Section.by_feature(@section.id, formatted: true)

      assert 2, features.count

      assert_equal 'Feature', features.first[:type]
      assert features.first[:geometry]

      assert_equal 'Feature', features.last[:type]
      assert features.last[:geometry]

      expected_properties1 = {id: "#{@section.id}-#{@line.url_name}",
                             klass: "Section",
                             line_url_name: @line.url_name,
                             width: @line.width * 0.75,
                             offset: -2.25,
                             opening: @section.opening,
                             buildstart: @section.buildstart,
                             buildstart_end: @section.opening,
                             closure: @section.closure}

      assert_equal expected_properties1, features.first[:properties]

      expected_properties2 = {id: "#{@section.id}-#{@line2.url_name}",
                             klass: "Section",
                             line_url_name: @line2.url_name,
                             width: @line2.width * 0.75,
                             offset: 2.25,
                             opening: @section.opening,
                             buildstart: @section.buildstart,
                             buildstart_end: @section.opening,
                             closure: @section.closure}

      assert_equal expected_properties2, features.last[:properties]
    end

    it "should handle two simultaneous lines first, and a single line after" do
      # Two simulataneous lines until 1995
      # ##################################
      # Original line
      @section_line.toyear = 1995
      @section_line.save
      # default line_group is zero

      # New line before 1995
      @line2 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 2', url_name:'test-line-2')
      SectionLine.create(line_id: @line2.id, section_id: @section.id, city_id: @city.id, toyear: 1995)
      # default line_group is zero

      # One single line after 1995
      # ##########################
      # This line has another line_group, in order to show it with another offset
      # The line_group is set when updating the feature (see EditorHelpers).
      @line3 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 3', url_name:'test-line-3')
      SectionLine.create(line_id: @line3.id, section_id: @section.id, city_id: @city.id, fromyear: 1995, line_group: 1)

      features = FeatureCollection::Section.by_feature(@section.id, formatted: true)

      assert 3, features.count

      expected_properties = [
        {
          id: "#{@section.id}-#{@line.url_name}",
          klass: "Section",
          line_url_name: @line.url_name,
          width: @line.width * 0.75,
          offset: -2.25,
          opening: @section.opening,
          buildstart: @section.buildstart,
          buildstart_end: @section.opening,
          closure: 1995
        },
        {
          id: "#{@section.id}-#{@line2.url_name}",
          klass: "Section",
          line_url_name: @line2.url_name,
          width: @line2.width * 0.75,
          offset: 2.25,
          opening: @section.opening,
          buildstart: @section.buildstart,
          buildstart_end: @section.opening,
          closure: 1995
        },
        {
          id: "#{@section.id}-#{@line3.url_name}",
          klass: "Section",
          line_url_name: @line3.url_name,
          width: @line3.width,
          offset: 0,
          opening: 1995,
          buildstart: 0,
          buildstart_end: 0,
          closure: @section.closure
        }
      ]

      features.each_with_index do |feature, idx|
        assert_equal 'Feature', feature[:type]
        assert feature[:geometry]
        assert_equal expected_properties[idx], feature[:properties]
      end
    end

    describe "width" do
	    it "should return the right width when the section has 1 line" do
        features = FeatureCollection::Section.by_feature(@section.id, formatted: true)
        feature = features.first
	      assert_equal 1, @section.lines.count
	      assert_equal @section.lines.first.width, feature[:properties][:width]
	    end

      it "should return the right width when the section has 2 lines" do
	      line2 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 2', url_name:'test-line-2')
	      SectionLine.create(line_id: line2.id, section_id: @section.id, city_id: @city.id)

	      assert_equal 2, @section.lines.count

        features = FeatureCollection::Section.by_feature(@section.id, formatted: true)
        features.map do |feature|
	        assert_equal @section.lines.first.width * 0.75, feature[:properties][:width]
        end
	    end

      it "should return the right width when the section has 3 or more lines" do
	      line2 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 2', url_name:'test-line-2')
	      SectionLine.create(line_id: line2.id, section_id: @section.id, city_id: @city.id)

	      line3 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 3', url_name:'test-line-3')
	      SectionLine.create(line_id: line3.id, section_id: @section.id, city_id: @city.id)

	      assert_equal 3, @section.lines.count

        features = FeatureCollection::Section.by_feature(@section.id, formatted: true)
        features.map do |feature|
	        assert_equal @section.lines.first.width * 0.66, feature[:properties][:width]
        end
	    end

      it "should use the wider line if lines belong to different transport modes" do
        line2 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 2', url_name:'test-line-2', transport_mode_id: 1)
        SectionLine.create(line_id: line2.id, section_id: @section.id, city_id: @city.id)

        assert_equal 2, @section.lines.count

        features = FeatureCollection::Section.by_feature(@section.id, formatted: true)
        features.map do |feature|
          assert_equal line2.width * 0.75, feature[:properties][:width]
        end
      end

      it "should use the min_width" do
        # transport mode 8 is bus, with width = 1 and min_width = 1
        @line.transport_mode_id = 8
        @line.save

        line2 = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line 2', url_name:'test-line-2', transport_mode_id: 8)
        SectionLine.create(line_id: line2.id, section_id: @section.id, city_id: @city.id)

        assert_equal 2, @section.lines.count

        features = FeatureCollection::Section.by_feature(@section.id, formatted: true)
        features.map do |feature|
          assert_equal 1, feature[:properties][:width]
        end
      end
    end
  end
end


text:
from __future__ import unicode_literals

from django.db import models, migrations
import smart_selects.db_fields
from django.conf import settings
import ckeditor.fields

class Migration(migrations.Migration):

    dependencies = [
        ('fadcanic', '0002_auto_20150701_1539'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('lugar', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Monitoreo',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('fecha', models.DateField()),
                ('resultados', ckeditor.fields.RichTextField(verbose_name=b'Resultados y/o logros de la actividad')),
                ('masculino', models.IntegerField(default=b'0')),
                ('femenino', models.IntegerField(default=b'0')),
                ('menor_12', models.IntegerField(default=b'0', verbose_name=b'Menor a 12 a\xc3\xb1os')),
                ('mayor_12', models.IntegerField(default=b'0', verbose_name=b'12 a 18 a\xc3\xb1os')),
                ('mayor_18', models.IntegerField(default=b'0', verbose_name=b'18 a 30 a\xc3\xb1os')),
                ('mayor_30', models.IntegerField(default=b'0', verbose_name=b'30 a m\xc3\xa1s a\xc3\xb1os')),
                ('creole', models.IntegerField(default=b'0')),
                ('miskito', models.IntegerField(default=b'0')),
                ('ulwa', models.IntegerField(default=b'0')),
                ('rama', models.IntegerField(default=b'0')),
                ('mestizo', models.IntegerField(default=b'0')),
                ('mayagna', models.IntegerField(default=b'0')),
                ('garifuna', models.IntegerField(default=b'0')),
                ('extranjero', models.IntegerField(default=b'0')),
                ('estudiante', models.IntegerField(default=b'0')),
                ('docente', models.IntegerField(default=b'0')),
                ('periodista', models.IntegerField(default=b'0', verbose_name=b'Periodista/comunicador')),
                ('lideres', models.IntegerField(default=b'0', verbose_name=b'L\xc3\xadderes comunitarios')),
                ('representantes', models.IntegerField(default=b'0', verbose_name=b'Representantes de Organizaciones')),
                ('autoridades', models.IntegerField(default=b'0', verbose_name=b'Autoridades comunitarias')),
                ('comunitarios', models.IntegerField(default=b'0', verbose_name=b'Comunitarios/Pobladores')),
                ('actividad', models.ForeignKey(to='fadcanic.TipoActividad')),
                ('comunidad', smart_selects.db_fields.ChainedForeignKey(chained_model_field=b'municipio', chained_field=b'municipio', blank=True, auto_choose=True, to='lugar.Comunidad', null=True)),
                ('eje', models.ForeignKey(to='fadcanic.EjeTransversal')),
                ('municipio', models.ForeignKey(to='lugar.Municipio')),
            ],
            options={
                'verbose_name': 'Monitoreo Actividad',
                'verbose_name_plural': 'Monitoreo Actividades',
            },
        ),
        migrations.CreateModel(
            name='Recolector',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
                ('cargo', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Recolector Datos',
                'verbose_name_plural': 'Recolectores Datos',
            },
        ),
        migrations.AddField(
            model_name='monitoreo',
            name='recolector',
            field=models.ForeignKey(to='comunidad.Recolector'),
        ),
        migrations.AddField(
            model_name='monitoreo',
            name='resultado',
            field=models.ForeignKey(to='fadcanic.ResultadoPrograma'),
        ),
        migrations.AddField(
            model_name='monitoreo',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
#import <Foundation/Foundation.h>

#import "MWLuaLanguage.h"

@interface MWSubstitutedScriptWriter : NSObject {
  NSMutableString *result;
  NSMutableString *partialExpr;
}

- (void)inputLiteral:(NSString *)s;
- (void)inputCode:(NSString *)s;
- (void)inputExpr:(NSString *)s;

- (void)finish;

- (NSString *)result;

@end

@interface MWSubstitutedLuaScriptWriter : MWSubstitutedScriptWriter
@end

@interface MWSubstitutedLuaLanguage : NSObject <MWScriptLanguage>

@end


text:
package com.yanzhenjie.album;

/**
 *
Filter.

 * Created by YanZhenjie on 2017/10/15.
 */
public interface Filter<T> {

    /**
     * Filter the file.
     *
     * @param attributes attributes of file.
     * @return filter returns true, otherwise false.
     */
    boolean filter(T attributes);

}


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

<title>com.gigya.socialize.android.event</title>
<meta name="date" content="2014-06-11">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.gigya.socialize.android.event

Interface Summary

Interface
Description

GSAccountsEventListener

Listener for handling Accounts namespace events.

GSConnectUIListener

Listener for events generated by GSAPI.showAddConnectionsUI

GSDialogListener

Listener for the dismissal of a plugin dialog, displayed by GSAPI.showPluginDialog

GSEventListener
Deprecated

use GSSocializeEventListener instead.

GSLoginUIListener

Listener for events generated by GSAPI.showLoginUI

GSPluginListener

A listener interface for receiving Gigya plugin events.

GSSocializeEventListener

Listener for handling Socialize namespace events.

GSUIListener

Listener for events generated by GSAPI.showLoginUI and GSAPI.showAddConnectionsUI

Class Summary

Class
Description

GSWebBridgeListener

A listener interface for receiving GSWebBridge events.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
namespace termcolor {
// Forward declaration of the `_internal` namespace.
// All comments are below.
namespace _internal {
// An index to be used to access a private storage of I/O streams. See
// colorize / nocolorize I/O manipulators for details.
static int colorize_index = std::ios_base::xalloc();

inline FILE *get_standard_stream(const std::ostream &stream);
inline bool is_colorized(std::ostream &stream);
inline bool is_atty(const std::ostream &stream);

#if defined(TERMCOLOR_OS_WINDOWS)
inline void win_change_attributes(std::ostream &stream, int foreground, int background = -1);
#endif
} // namespace _internal

inline std::ostream &colorize(std::ostream &stream) {
  stream.iword(_internal::colorize_index) = 1L;
  return stream;
}

inline std::ostream &nocolorize(std::ostream &stream) {
  stream.iword(_internal::colorize_index) = 0L;
  return stream;
}

inline std::ostream &reset(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[00m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1, -1);
#endif
  }
  return stream;
}

inline std::ostream &bold(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[1m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &dark(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[2m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &italic(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[3m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &underline(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[4m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &blink(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[5m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &reverse(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[7m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &concealed(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[8m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &crossed(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[9m";
#elif defined(TERMCOLOR_OS_WINDOWS)
#endif
  }
  return stream;
}

inline std::ostream &grey(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[30m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream,
                                     0 // grey (black)
    );
#endif
  }
  return stream;
}

inline std::ostream &red(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[31m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, FOREGROUND_RED);
#endif
  }
  return stream;
}

inline std::ostream &green(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[32m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, FOREGROUND_GREEN);
#endif
  }
  return stream;
}

inline std::ostream &yellow(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[33m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, FOREGROUND_GREEN | FOREGROUND_RED);
#endif
  }
  return stream;
}

inline std::ostream &blue(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[34m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, FOREGROUND_BLUE);
#endif
  }
  return stream;
}

inline std::ostream &magenta(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[35m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, FOREGROUND_BLUE | FOREGROUND_RED);
#endif
  }
  return stream;
}

inline std::ostream &cyan(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[36m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, FOREGROUND_BLUE | FOREGROUND_GREEN);
#endif
  }
  return stream;
}

inline std::ostream &white(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[37m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
#endif
  }
  return stream;
}

inline std::ostream &on_grey(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[40m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1,
                                     0 // grey (black)
    );
#endif
  }
  return stream;
}

inline std::ostream &on_red(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[41m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1, BACKGROUND_RED);
#endif
  }
  return stream;
}

inline std::ostream &on_green(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[42m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1, BACKGROUND_GREEN);
#endif
  }
  return stream;
}

inline std::ostream &on_yellow(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[43m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1, BACKGROUND_GREEN | BACKGROUND_RED);
#endif
  }
  return stream;
}

inline std::ostream &on_blue(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[44m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1, BACKGROUND_BLUE);
#endif
  }
  return stream;
}

inline std::ostream &on_magenta(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[45m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1, BACKGROUND_BLUE | BACKGROUND_RED);
#endif
  }
  return stream;
}

inline std::ostream &on_cyan(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[46m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1, BACKGROUND_GREEN | BACKGROUND_BLUE);
#endif
  }
  return stream;
}

inline std::ostream &on_white(std::ostream &stream) {
  if (_internal::is_colorized(stream)) {
#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
    stream << "\033[47m";
#elif defined(TERMCOLOR_OS_WINDOWS)
    _internal::win_change_attributes(stream, -1,
                                     BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED);
#endif
  }

  return stream;
}

//! Since C++ hasn't a way to hide something in the header from
//! the outer access, I have to introduce this namespace which
//! is used for internal purpose and should't be access from
//! the user code.
namespace _internal {
//! Since C++ hasn't a true way to extract stream handler
//! from the a given `std::ostream` object, I have to write
//! this kind of hack.
inline FILE *get_standard_stream(const std::ostream &stream) {
  if (&stream == &std::cout)
    return stdout;
  else if ((&stream == &std::cerr) || (&stream == &std::clog))
    return stderr;

  return 0;
}

// Say whether a given stream should be colorized or not. It's always
// true for ATTY streams and may be true for streams marked with
// colorize flag.
inline bool is_colorized(std::ostream &stream) {
  return is_atty(stream) || static_cast<bool>(stream.iword(colorize_index));
}

//! Test whether a given `std::ostream` object refers to
//! a terminal.
inline bool is_atty(const std::ostream &stream) {
  FILE *std_stream = get_standard_stream(stream);

  // Unfortunately, fileno() ends with segmentation fault
  // if invalid file descriptor is passed. So we need to
  // handle this case gracefully and assume it's not a tty
  // if standard stream is not detected, and 0 is returned.
  if (!std_stream)
    return false;

#if defined(TERMCOLOR_OS_MACOS) || defined(TERMCOLOR_OS_LINUX)
  return ::isatty(fileno(std_stream));
#elif defined(TERMCOLOR_OS_WINDOWS)
  return ::_isatty(_fileno(std_stream));
#endif
}

#if defined(TERMCOLOR_OS_WINDOWS)
//! Change Windows Terminal colors attribute. If some
//! parameter is `-1` then attribute won't changed.
inline void win_change_attributes(std::ostream &stream, int foreground, int background) {
  // yeah, i know.. it's ugly, it's windows.
  static WORD defaultAttributes = 0;

  // Windows doesn't have ANSI escape sequences and so we use special
  // API to change Terminal output color. That means we can't
  // manipulate colors by means of "std::stringstream" and hence
  // should do nothing in this case.
  if (!_internal::is_atty(stream))
    return;

  // get terminal handle
  HANDLE hTerminal = INVALID_HANDLE_VALUE;
  if (&stream == &std::cout)
    hTerminal = GetStdHandle(STD_OUTPUT_HANDLE);
  else if (&stream == &std::cerr)
    hTerminal = GetStdHandle(STD_ERROR_HANDLE);

  // save default terminal attributes if it unsaved
  if (!defaultAttributes) {
    CONSOLE_SCREEN_BUFFER_INFO info;
    if (!GetConsoleScreenBufferInfo(hTerminal, &info))
      return;
    defaultAttributes = info.wAttributes;
  }

  // restore all default settings
  if (foreground == -1 && background == -1) {
    SetConsoleTextAttribute(hTerminal, defaultAttributes);
    return;
  }

  // get current settings
  CONSOLE_SCREEN_BUFFER_INFO info;
  if (!GetConsoleScreenBufferInfo(hTerminal, &info))
    return;

  if (foreground != -1) {
    info.wAttributes &= ~(info.wAttributes & 0x0F);
    info.wAttributes |= static_cast<WORD>(foreground);
  }

  if (background != -1) {
    info.wAttributes &= ~(info.wAttributes & 0xF0);
    info.wAttributes |= static_cast<WORD>(background);
  }

  SetConsoleTextAttribute(hTerminal, info.wAttributes);
}
#endif // TERMCOLOR_OS_WINDOWS

} // namespace _internal

} // namespace termcolor

#undef TERMCOLOR_OS_WINDOWS
#undef TERMCOLOR_OS_MACOS
#undef TERMCOLOR_OS_LINUX

#endif // TERMCOLOR_HPP_