text:
package org.intellij.lang.regexp;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.ClassExtension;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.intellij.lang.regexp.psi.*;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

/**
 * @author yole
 */
public final class RegExpLanguageHosts extends ClassExtension<RegExpLanguageHost> {
  private static final RegExpLanguageHosts INSTANCE = new RegExpLanguageHosts();
  private final DefaultRegExpPropertiesProvider myDefaultProvider;
  private static RegExpLanguageHost myHost;

  public static RegExpLanguageHosts getInstance() {
    return INSTANCE;
  }

  private RegExpLanguageHosts() {
    super("com.intellij.regExpLanguageHost");
    myDefaultProvider = DefaultRegExpPropertiesProvider.getInstance();
  }

  @TestOnly
  public static void setRegExpHost(@Nullable RegExpLanguageHost host) {
    myHost = host;
  }

  @Contract("null -> null")
  @Nullable
  private static RegExpLanguageHost findRegExpHost(@Nullable final PsiElement element) {
    if (element == null) {
      return null;
    }
    if (ApplicationManager.getApplication().isUnitTestMode() && myHost != null) {
      return myHost;
    }
    final PsiFile file = element.getContainingFile();
    final PsiElement context = file.getContext();
    if (context instanceof RegExpLanguageHost) {
      return (RegExpLanguageHost)context;
    }
    if (context != null) {
      return INSTANCE.forClass(context.getClass());
    }
    return null;
  }

  public boolean isRedundantEscape(@NotNull final RegExpChar ch, @NotNull final String text) {
    if (text.length() <= 1) {
      return false;
    }
    final RegExpLanguageHost host = findRegExpHost(ch);
    if (host != null) {
      final char c = text.charAt(1);
      return !host.characterNeedsEscaping(c);
    }
    else {
      return !("\\]".equals(text) || "\\}".equals(text));
    }
  }

  public boolean supportsInlineOptionFlag(char flag, PsiElement context) {
    final RegExpLanguageHost host = findRegExpHost(context);
    return host == null || host.supportsInlineOptionFlag(flag, context);
  }

  public boolean supportsExtendedHexCharacter(@Nullable RegExpChar regExpChar) {
    final RegExpLanguageHost host = findRegExpHost(regExpChar);
    try {
      return host != null && host.supportsExtendedHexCharacter(regExpChar);
    } catch (AbstractMethodError e) {
      // supportsExtendedHexCharacter not present
      return false;
    }
  }

  public boolean supportsLiteralBackspace(@Nullable RegExpChar regExpChar) {
    final RegExpLanguageHost host = findRegExpHost(regExpChar);
    return host != null && host.supportsLiteralBackspace(regExpChar);
  }

  public boolean supportsNamedGroupSyntax(@Nullable final RegExpGroup group) {
    final RegExpLanguageHost host = findRegExpHost(group);
    return host != null && host.supportsNamedGroupSyntax(group);
  }

  public boolean supportsNamedGroupRefSyntax(@Nullable final RegExpNamedGroupRef ref) {
    final RegExpLanguageHost host = findRegExpHost(ref);
    try {
      return host != null && host.supportsNamedGroupRefSyntax(ref);
    } catch (AbstractMethodError e) {
      // supportsNamedGroupRefSyntax() not present
      return false;
    }
  }

  public boolean isValidGroupName(String name, @Nullable final PsiElement context) {
    final RegExpLanguageHost host = findRegExpHost(context);
    return host != null && host.isValidGroupName(name, context);
  }

  public boolean supportsPerl5EmbeddedComments(@Nullable final PsiComment comment) {
    final RegExpLanguageHost host = findRegExpHost(comment);
    return host != null && host.supportsPerl5EmbeddedComments();
  }

  public boolean supportsPythonConditionalRefs(@Nullable final RegExpPyCondRef condRef) {
    final RegExpLanguageHost host = findRegExpHost(condRef);
    return host != null && host.supportsPythonConditionalRefs();
  }

  public boolean supportsPossessiveQuantifiers(@Nullable final RegExpQuantifier quantifier) {
    final RegExpLanguageHost host = findRegExpHost(quantifier);
    return host == null || host.supportsPossessiveQuantifiers();
  }

  public boolean supportsBoundary(@Nullable final RegExpBoundary boundary) {
    final RegExpLanguageHost host = findRegExpHost(boundary);
    return host == null || host.supportsBoundary(boundary);
  }

  public boolean supportsSimpleClass(@Nullable final RegExpSimpleClass simpleClass) {
    final RegExpLanguageHost host = findRegExpHost(simpleClass);
    return host == null || host.supportsSimpleClass(simpleClass);
  }

  public boolean isValidCategory(@NotNull final PsiElement element, @NotNull String category) {
    final RegExpLanguageHost host = findRegExpHost(element);
    return host != null ? host.isValidCategory(category) : myDefaultProvider.isValidCategory(category);
  }

  public boolean supportsNamedCharacters(@NotNull final RegExpNamedCharacter namedCharacter) {
    final RegExpLanguageHost host = findRegExpHost(namedCharacter);
    return host != null && host.supportsNamedCharacters(namedCharacter);
  }

  public boolean isValidNamedCharacter(@NotNull final RegExpNamedCharacter namedCharacter) {
    final RegExpLanguageHost host = findRegExpHost(namedCharacter);
    return host != null && host.isValidNamedCharacter(namedCharacter);
  }

  @NotNull
  public String[][] getAllKnownProperties(@NotNull final PsiElement element) {
    final RegExpLanguageHost host = findRegExpHost(element);
    return host != null ? host.getAllKnownProperties() : myDefaultProvider.getAllKnownProperties();
  }

  @Nullable
  String getPropertyDescription(@NotNull final PsiElement element, @Nullable final String name) {
    final RegExpLanguageHost host = findRegExpHost(element);
    return host != null ?  host.getPropertyDescription(name) : myDefaultProvider.getPropertyDescription(name);
  }

  @NotNull
  String[][] getKnownCharacterClasses(@NotNull final PsiElement element) {
    final RegExpLanguageHost host = findRegExpHost(element);
    return host != null ? host.getKnownCharacterClasses() : myDefaultProvider.getKnownCharacterClasses();
  }

  String[][] getPosixCharacterClasses(@NotNull final PsiElement element) {
    return myDefaultProvider.getPosixCharacterClasses();
  }
}


text:
require 'spec_helper'

describe AOP do
  context 'block filters, simple param filter' do

    context 'single param' do
      before do
        class_under_test.new_method :main1 do | a |
          a.succ
        end
        class_under_test.param_filter :main1 do | a |
          2 * a
        end
      end
      it{ expect( subject.main1 1 ).to eq 3 }
    end # context 'single param'

    context 'multiple params' do
      before do
        class_under_test.new_method :main2 do | *a |
          a.join
        end
        class_under_test.param_filter :main2 do | *a |
          @a = true
          a.reverse
        end
      end
      it{ expect( subject.main2 2, 3, 4 ).to eq "432" }
      it 'does not allow for side effects' do
        expect( subject.instance_variable_get :@a ).to be_nil
      end
    end # context 'multiple params'

    context 'mixture of params (kwds too)' do
      before do
        class_under_test.new_method :main3 do | *a, required:, optional: false |
          optional ? a : a.map(&:succ)
        end
        class_under_test.param_filter :main3 do | *a |
          kwds, pos = a.partition{|e| Hash === e }
          pos.reverse + kwds
        end
      end
      it{ expect( subject.main3 1, 2, 3, required: nil ).to eq [4,3,2] }
      it{ expect( subject.main3 1, 2, 3, required: nil, optional: true ).to eq [3,2,1] }
    end # context 'mixture of params (kwds too)'

    context 'blox are not touched, geometry can be changed' do
      before do
        class_under_test.new_method :main4 do | a, &blk |
          blk.( a )
        end
        class_under_test.param_filter :main4 do | a, b |
          a + b
        end
      end
      it{ expect( subject.main4( 1, 2 ){|x| 10*x } ).to eq 30  }
    end # context 'blox are not touched'
  end # context 'block filters, simple param filter'
end # describe AOP

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by Labtec on 27.01.2017.
 */
'use strict';

//noinspection JSUnresolvedVariable
import uiTpl from './ui.tpl.html';
//import './ui.scss';

class UiCtrl {

    constructor($element) {
        'ngInject';

        this.$element = $element;

        console.log('Ui');
    }
}

const COMPONENT = {
    template: uiTpl,
    bindings: {
        name: '@'
    },
    controller: UiCtrl,
    controllerAs: 'vm'
};

export default COMPONENT;


text:
<!DOCTYPE html>

        <title>Pothole service requests</title>

Open pot hole service requests

            Service Request Number:

            Status:


text:
/**
 * Created by nateTheAverage on 4/23/2015.
 */

// BossPOS Object Editing initializations bosspos.js
// =================================================================
// Require bootbox.js
// -----------------------------------------------------------------
//
// =================================================================

/*
 * A method to initiate edit buttons on editable objects
 */
function open_edit_window(object)
{
    var interfaceObject = object['id'];
    bootbox.dialog({
        className: "modal-primary",
        title: "Editor",
        message: '
  ' +
        '
 ' +
        'Your browser does not support frames.' +
        '

'
    });
}

window.closeModal = function(){
    $('.modal-primary').modal('hide');
};


text:
package testing

import (
	"k8s.io/apimachinery/pkg/runtime/schema"
)

// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
type TestType struct {
}

func (t TestType) GetObjectKind() schema.ObjectKind {
	return t
}

func (t TestType) SetGroupVersionKind(kind schema.GroupVersionKind) {
}

func (t TestType) GroupVersionKind() schema.GroupVersionKind {
	return schema.GroupVersionKind{
		Group:   "test",
		Version: "v1",
		Kind:    "TestType",
	}
}


text:
The RealTimeSamples table is an aid for possible (more or less) real time monitoring of EMA weather stations.

Real time status messages are stored in this table. If the service runs in the background long enough, this table will be periodically purged approximately at 00:00:00 UTC to delete last days samples.

## Data Model

The data model follows the [dimensional modelling approach by Ralph Kimball]
(https://en.wikipedia.org/wiki/Dimensional_modeling).

### Dimension Tables

* `Date` : preloaded for 10 years)
* `Time` : preloaded, minute resolution)
* `Station`: registered weather stations where to collect data
* `Type` : measurement types (`Minima`, `Maxima`, `Samples`, 'Averages', MinMax' )
* `Units`: an assorted collection of unit labels for reports

The Ùnits` table is what Dr. Kimball denotes as a *junk dimension*.

### Fact Tables

* `MinMaxHistory` : fact table contaning hourly minima and maxima measurements ffrom EMA weather stations.

* `RealTimeSamples` : fact table containing current EMA status messages.

## A.3 Sample queries

## A.4 data mode listing

            CREATE TABLE IF NOT EXISTS Date
            (
            date_id        INTEGER PRIMARY KEY,
            sql_date       TEXT,
            date           TEXT,
            day            INTEGER,
            day_year       INTEGER,
            julian_day     REAL,
            weekday        TEXT,
            weekday_abbr   TEXT,
            weekday_num    INTEGER,
            month_num      INTEGER,
            month          TEXT,
            month_abbr     TEXT,
            year           INTEGER
            );

            CREATE TABLE IF NOT EXISTS Time
            (
            time_id        INTEGER PRIMARY KEY,
            time           TEXT,
            hour           INTEGER,
            minute         INTEGER,
            day_fraction   REAL
            );

            CREATE TABLE IF NOT EXISTS Station
            (
            station_id     INTEGER PRIMARY KEY,
            mqtt_id        TEXT,
            name           TEXT,
            owner          TEXT,
            location       TEXT,
            province       TEXT,
            longitude      REAL,
            longitude_text TEXT,
            latitude       REAL,
            latitude_text  TEXT,
            elevation      REAL
            );

	    CREATE TABLE IF NOT EXISTS Type
            (
            type_id        INTEGER PRIMARY KEY,
            type           TEXT
            );

	    CREATE TABLE IF NOT EXISTS Units
            (
            units_id             INTEGER PRIMARY KEY,
            roof_relay           TEXT,
            aux_relay            TEXT,
            voltage_units        TEXT,
            wet_units            TEXT,
            cloudy_units         TEXT,
            cal_pressure_units   TEXT,
            abs_pressure_units   TEXT,
            rain_units           TEXT,
            irradiation_units    TEXT,
            magnitude_units      TEXT,
            frequency_units      TEXT,
            temperature_units    TEXT,
            rel_humidity_units   TEXT,
            dew_point_units      TEXT,
            wind_speed_units     TEXT,
            wind_speed10m_units  TEXT,
            wind_direction_units TEXT
            );

	    CREATE TABLE IF NOT EXISTS MinMaxHistory
            (
            date_id            INTEGER NOT NULL REFERENCES Date(date_id),
            time_id            INTEGER NOT NULL REFERENCES Time(time_id),
            station_id         INTEGER NOT NULL REFERENCES Station(station_id),
            type_id            INTEGER NOT NULL REFERENCES Type(type_id),
            units_id           INTEGER NOT NULL REFERENCES Units(units_id),
            voltage            REAL,
            wet                REAL,
            cloudy             REAL,
            cal_pressure       REAL,
            abs_pressure       REAL,
            rain               REAL,
            irradiation        REAL,
            vis_magnitude      REAL,
            frequency          REAL,
            temperature        REAL,
            rel_humidity       REAL,
            dew_point          REAL,
            wind_speed         REAL,
            wind_speed10m      REAL,
            wind_direction     INTEGER,
            timestamp          TEXT,
            PRIMARY KEY (date_id, time_id, station_id, type_id)
            );

	    CREATE TABLE IF NOT EXISTS RealTimeSamples
            (
            date_id            INTEGER NOT NULL REFERENCES Date(date_id),
            time_id            INTEGER NOT NULL REFERENCES Time(time_id),
            station_id         INTEGER NOT NULL REFERENCES Station(station_id),
            type_id            INTEGER NOT NULL REFERENCES Type(type_id),
            units_id           INTEGER NOT NULL REFERENCES Units(units_id),
            voltage            REAL,
            wet                REAL,
            cloudy             REAL,
            cal_pressure       REAL,
            abs_pressure       REAL,
            rain               REAL,
            irradiation        REAL,
            vis_magnitude      REAL,
            frequency          REAL,
            temperature        REAL,
            rel_humidity       REAL,
            dew_point          REAL,
            wind_speed         REAL,
            wind_speed10m      REAL,
            wind_direction     INTEGER,
            timestamp          TEXT,
            PRIMARY KEY (date_id, time_id, station_id, type_id)
            );

	    CREATE TABLE IF NOT EXISTS AveragesHistory
            (
            date_id            INTEGER NOT NULL REFERENCES Date(date_id),
            time_id            INTEGER NOT NULL REFERENCES Time(time_id),
            station_id         INTEGER NOT NULL REFERENCES Station(station_id),
            units_id           INTEGER NOT NULL REFERENCES Units(units_id),
            voltage            REAL,
            wet                REAL,
            cloudy             REAL,
            cal_pressure       REAL,
            abs_pressure       REAL,
            rain               REAL,
            irradiation        REAL,
            vis_magnitude      REAL,
            frequency          REAL,
            temperature        REAL,
            rel_humidity       REAL,
            dew_point          REAL,
            wind_speed         REAL,
            wind_speed10m      REAL,
            wind_direction     INTEGER,
            timestamp          TEXT,
            PRIMARY KEY (date_id, time_id, station_id)
            );

            CREATE TABLE IF NOT EXISTS HistoryStats
            (
            date_id            INTEGER NOT NULL REFERENCES Date(date_id),
            time_id            INTEGER NOT NULL REFERENCES Time(time_id),
            station_id         INTEGER NOT NULL REFERENCES Station(station_id),
            type_id            INTEGER NOT NULL REFERENCES Type(type_id),
            records_submitted  INTEGER,
            records_committed  INTEGER,
            timestamp          TEXT DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (date_id, time_id, station_id, type_id)
            );

	    CREATE TABLE IF NOT EXISTS RealTimeStats
            (
            date_id            INTEGER NOT NULL REFERENCES Date(date_id),
            time_id            INTEGER NOT NULL REFERENCES Time(time_id),
            station_id         INTEGER NOT NULL REFERENCES Station(station_id),
            type_id            INTEGER NOT NULL REFERENCES Type(type_id),
            timestamp          TEXT,
            window_size        INTEGER,
            num_samples        INTEGER,
            num_bytes          INTEGER,
            lag                INTEGER,
            PRIMARY KEY (date_id, time_id, station_id, type_id)
            );


text:
using Aurora.Settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Aurora.Profiles.CSGO.Layers
{
    /// <summary>
    /// Interaction logic for Control_CSGOBurningLayer.xaml
    /// </summary>
    public partial class Control_CSGOBurningLayer : UserControl
    {
        private bool settingsset = false;
        private bool profileset = false;

        public Control_CSGOBurningLayer()
        {
            InitializeComponent();
        }

        public Control_CSGOBurningLayer(CSGOBurningLayerHandler datacontext)
        {
            InitializeComponent();

            this.DataContext = datacontext;
        }

        public void SetSettings()
        {
            if (this.DataContext is CSGOBurningLayerHandler && !settingsset)
            {
                this.ColorPicker_Burning.SelectedColor = Utils.ColorUtils.DrawingColorToMediaColor((this.DataContext as CSGOBurningLayerHandler).Properties._BurningColor ?? System.Drawing.Color.Empty);
                this.checkBox_Animated.IsChecked = (this.DataContext as CSGOBurningLayerHandler).Properties._Animated;

                settingsset = true;
            }
        }

        internal void SetProfile(ProfileManager profile)
        {
            if (profile != null && !profileset)
            {
                var var_types_numerical = profile.ParameterLookup?.Where(kvp => Utils.TypeUtils.IsNumericType(kvp.Value.Item1));

                profileset = true;
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            SetSettings();

            this.Loaded -= UserControl_Loaded;
        }

        private void ColorPicker_Burning_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
        {
            if (IsLoaded && settingsset && this.DataContext is CSGOBurningLayerHandler && sender is Xceed.Wpf.Toolkit.ColorPicker && (sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.HasValue)
                (this.DataContext as CSGOBurningLayerHandler).Properties._BurningColor = Utils.ColorUtils.MediaColorToDrawingColor((sender as Xceed.Wpf.Toolkit.ColorPicker).SelectedColor.Value);
        }

        private void checkBox_Animated_Checked(object sender, RoutedEventArgs e)
        {
            if (IsLoaded && settingsset && this.DataContext is CSGOBurningLayerHandler && sender is CheckBox && (sender as CheckBox).IsChecked.HasValue)
                (this.DataContext as CSGOBurningLayerHandler).Properties._Animated = (sender as CheckBox).IsChecked.Value;
        }
    }
}


text:
use iron;
use super::super::whisper::Cache;

// This is some weird voodoo so I can use persistent
// apparently I have to give a vtable which is used to resolve the
// type of the stored value so it can be recast "safely"
// but it adds one more level of indirection. Caveat emptor folks.
pub struct CacheHolder;
impl iron::typemap::Key for CacheHolder {
    // TODO: my brain hurts. what does this mean?
    type Value = Cache;
}


text:
using System.Linq;
using BuildingBlocks.Membership.Entities;

namespace BuildingBlocks.Membership.RavenDB.DomainModel
{
    public static class UserEntityMappingHelpers
    {
        public static User ToUser(this UserEntity entity)
        {
            var user = new User(entity.UserId, entity.Username, entity.Email, entity.ApplicationName)
                {
                    Password = entity.Password,
                    Roles    = entity.Roles.ToList(),
                    Comment = entity.Comment,
                    ConfirmationToken = entity.ConfirmationToken,
                    CreateDate = entity.CreateDate,
                    IsApproved = entity.IsApproved,
                    IsLockedOut = entity.IsLockedOut,
                    LastActivityDate = entity.LastActivityDate,
                    LastLockoutDate = entity.LastLockoutDate,
                    LastLoginDate = entity.LastLoginDate,
                    LastPasswordChangedDate = entity.LastPasswordChangedDate,
                    LastPasswordFailureDate = entity.LastPasswordFailureDate,
                    PasswordFailuresSinceLastSuccess = entity.PasswordFailuresSinceLastSuccess,
                    PasswordVerificationToken = entity.PasswordVerificationToken,
                    PasswordVerificationTokenExpirationDate = entity.PasswordVerificationTokenExpirationDate
                };
            return user;
        }

        public static UserEntity ToEntityWithoutRoles(this User user)
        {
            return new UserEntity
                {
                    UserId = user.UserId,
                    Username = user.Username,
                    ApplicationName = user.ApplicationName,
                    Email = user.Email,
                    Password = user.Password,
                    Comment = user.Comment,
                    ConfirmationToken = user.ConfirmationToken,
                    CreateDate = user.CreateDate,
                    IsApproved = user.IsApproved,
                    IsLockedOut = user.IsLockedOut,
                    LastActivityDate = user.LastActivityDate,
                    LastLockoutDate = user.LastLockoutDate,
                    LastLoginDate = user.LastLoginDate,
                    LastPasswordChangedDate = user.LastPasswordChangedDate,
                    LastPasswordFailureDate = user.LastPasswordFailureDate,
                    PasswordFailuresSinceLastSuccess = user.PasswordFailuresSinceLastSuccess,
                    PasswordVerificationToken = user.PasswordVerificationToken,
                    PasswordVerificationTokenExpirationDate = user.PasswordVerificationTokenExpirationDate
                };
        }
    }
}


text:
namespace _02.Advertisement_Message
{
    using System;

    public class ObjAndClassesExer
    {
        public static void Main()
        {
            var number = int.Parse(Console.ReadLine());
            var random = new Random();

            var phrases = GetPhrases();
            var events = GetEvent();
            var author = GetAuthor();
            var city = GetCity();

            for (int i = 0; i < number; i++)
            {
                var randomPhrase = phrases[random.Next(0, phrases.Length)];
                var randomEvent = events[random.Next(0, events.Length)];
                var randomAuthor = author[random.Next(0, author.Length)];
                var randomCity = city[random.Next(0, city.Length)];

                Console.Write($"{randomPhrase} {randomEvent} {randomAuthor} - {randomCity}");
                Console.WriteLine();
            }
        }

        private static string[] GetCity()
        {
            var city = new string[]
            {
                "Burgas",
                "Sofia",
                "Plovdiv",
                "Varna",
                "Ruse"
            };

            return city;
        }

        private static string[] GetAuthor()
        {
            var author = new string[]
           {
                "Diana",
                "Petya",
                "Stella",
                "Elena",
                "Katya",
                "Iva",
                "Annie",
                "Eva"
           };

            return author;
        }

        private static string[] GetEvent()
        {
            var events = new string[]
            {
                "Now I feel good.",
                "I have succeeded with this product.",
                "Makes miracles. I am happy of the results!",
                "I cannot believe but now I feel awesome.",
                "Try it yourself, I am very satisfied.",
                "I feel great!"
            };

            return events;
        }

        private static string[] GetPhrases()
        {
            var phrase = new string[]
            {
                "Excellent product.",
               "Such a great product.",
               "I always use that product.",
               "Best product of its category.",
               "Exceptional product.",
               "I can't live without this product."
            };

            return phrase;
        }
    }
}


text:
<?php

use yii\db\Migration;

class m161129_211624_site_options_types extends Migration
{
    /*public function up()
    {

    }

    public function down()
    {
        echo "m161129_211624_site_options_types cannot be reverted.\n";

        return false;
    }*/

    public function safeUp()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%site_options_types}}', [
            'id' => $this->primaryKey(),
            'type_name' => $this->string(255)->null(),
            'type_alias' => $this->string(255)->null(),
        ], $tableOptions);

    }

    public function safeDown()
    {
        $this->dropTable('{{%site_options_types}}');
    }
}


text:
"""
Created on 06 Nov 2020

@author: Jade Page (jade.page@southcoastscience.com)

"""

from collections import OrderedDict

from scs_core.data.json import PersistentJSONable

# --------------------------------------------------------------------------------------------------------------------

class UptimeList(PersistentJSONable):
    """
    classdocs
    """

    __FILENAME = "device_uptime_list"

    @classmethod
    def persistence_location(cls):
        return cls.aws_dir(), cls.__FILENAME

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct_from_jdict(cls, jdict, skeleton=False):
        if not jdict:
            return None

        uptime_list = jdict.get('uptime_list')

        return UptimeList(uptime_list)

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, uptime_list):
        """
        Constructor
        """
        super().__init__()

        self.__uptime_list = uptime_list

    # ----------------------------------------------------------------------------------------------------------------

    @property
    def uptime_list(self):
        return self.__uptime_list

    # ----------------------------------------------------------------------------------------------------------------

    def as_json(self):
        jdict = OrderedDict()

        jdict['uptime_list'] = self.__uptime_list

        return jdict

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "UptimeList:{uptime_list:%s}" %  \
               self.uptime_list


text:
/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_DSA)
   #include <botan/dsa.h>
   #include "test_pubkey.h"
#endif

namespace Botan_Tests {

namespace {

#if defined(BOTAN_HAS_DSA)

class DSA_KAT_Tests final : public PK_Signature_Generation_Test
   {
   public:
      DSA_KAT_Tests() : PK_Signature_Generation_Test(
            "DSA",
#if defined(BOTAN_HAS_RFC6979_GENERATOR)
            "pubkey/dsa_rfc6979.vec",
            "P,Q,G,X,Hash,Msg,Signature",
#else
            "pubkey/dsa_prob.vec",
            "P,Q,G,X,Hash,Msg,Nonce,Signature",
#endif
            "") {}

      bool clear_between_callbacks() const override
         {
         return false;
         }

      std::unique_ptr<Botan::Private_Key> load_private_key(const VarMap& vars) override
         {
         const Botan::BigInt p = get_req_bn(vars, "P");
         const Botan::BigInt q = get_req_bn(vars, "Q");
         const Botan::BigInt g = get_req_bn(vars, "G");
         const Botan::BigInt x = get_req_bn(vars, "X");

         const Botan::DL_Group grp(p, q, g);

         std::unique_ptr<Botan::Private_Key> key(new Botan::DSA_PrivateKey(Test::rng(), grp, x));
         return key;
         }

      std::string default_padding(const VarMap& vars) const override
         {
         return "EMSA1(" + get_req_str(vars, "Hash") + ")";
         }
   };

class DSA_Keygen_Tests final : public PK_Key_Generation_Test
   {
   public:
      std::vector<std::string> keygen_params() const override
         {
         return { "dsa/jce/1024" };
         }
      std::string algo_name() const override
         {
         return "DSA";
         }
   };

BOTAN_REGISTER_TEST("dsa_sign", DSA_KAT_Tests);
BOTAN_REGISTER_TEST("dsa_keygen", DSA_Keygen_Tests);

#endif

}

}


text:
#include "platform/CriticalSectionLock.h"
#include "hal/us_ticker_api.h"
#include "platform/mbed_assert.h"

#include "ble/BLE.h"
#include "ble/driver/CordioHCIDriver.h"

#include "source/pal/PalAttClient.h"
#include "source/pal/PalSecurityManager.h"
#include "source/pal/PalGap.h"
#if BLE_FEATURE_SIGNING
#include "source/pal/PalSigningMonitor.h"
#endif //BLE_FEATURE_SIGNING
#include "source/pal/PalAttClientToGattClient.h"

#include "source/BLEInstanceBaseImpl.h"
#include "source/GattServerImpl.h"
#include "source/PalSecurityManagerImpl.h"
#include "source/PalAttClientImpl.h"
#include "source/PalGenericAccessServiceImpl.h"
#include "source/PalGapImpl.h"

#include "wsf_types.h"
#include "wsf_msg.h"
#include "wsf_os.h"
#include "wsf_buf.h"
#include "wsf_timer.h"
#include "hci_handler.h"
#include "dm_handler.h"
#include "l2c_handler.h"
#include "att_handler.h"
#include "smp_handler.h"
#include "l2c_api.h"
#include "att_api.h"
#include "smp_api.h"
#include "hci_drv.h"
#include "bstream.h"

#include "stack_adaptation/mbed_wsf_trace.c"
#include "mbed-trace/mbed_trace.h"
#include "common/ble_trace_helpers.h"

#define TRACE_GROUP "BLE "

using namespace std::chrono;

/*! WSF handler ID */
wsfHandlerId_t stack_handler_id;

/* WSF heap allocation */
uint8_t *SystemHeapStart;
uint32_t SystemHeapSize;

/**
 * Weak definition of ble_cordio_get_hci_driver.
 * A runtime error is generated if the user does not define any
 * ble_cordio_get_hci_driver.
 */
MBED_WEAK ble::CordioHCIDriver &ble_cordio_get_hci_driver()
{
    MBED_ASSERT("No HCI driver");
    printf("Please provide an implementation for the HCI driver");
    ble::CordioHCIDriver *bad_instance = nullptr;
    return *bad_instance;
}

/**
 * Low level HCI interface between Cordio stack and the port.
 */
extern "C" uint16_t hci_mbed_os_drv_write(uint8_t type, uint16_t len, uint8_t *pData)
{
    return ble_cordio_get_hci_driver().write(type, len, pData);
}

extern "C" void hci_mbed_os_start_reset_sequence(void)
{
    tr_debug("Cordio HCI reset started");
    ble_cordio_get_hci_driver().start_reset_sequence();
}

extern "C" void hci_mbed_os_handle_reset_sequence(uint8_t *msg)
{
#if MBED_CONF_MBED_TRACE_ENABLE
    if (*msg == HCI_CMD_CMPL_EVT) {
        uint16_t opcode;
        uint8_t *peek_msg = msg + (HCI_EVT_HDR_LEN + 1 /* skip num packets */);
        BSTREAM_TO_UINT16(opcode, peek_msg);
        tr_debug("Reset sequence command complete: %s", ble::hci_opcode_to_string(opcode));
    }
#endif // MBED_CONF_MBED_TRACE_ENABLE

    ble_cordio_get_hci_driver().handle_reset_sequence(msg);
}

/*
 * This function will signal to the user code by calling signalEventsToProcess.
 * It is registered and called into the Wsf Stack.
 */
extern "C" MBED_WEAK void wsf_mbed_ble_signal_event(void)
{
    BLE::Instance().signalEventsToProcess();
}

/**
 * BLE-API requires an implementation of the following function in order to
 * obtain its transport handle.
 */
ble::BLEInstanceBase *ble::createBLEInstance()
{
    return (&(ble::impl::BLEInstanceBase::deviceInstance()));
}

namespace ble {
namespace impl {

BLEInstanceBase::BLEInstanceBase(CordioHCIDriver &hci_driver) :
    initialization_status(NOT_INITIALIZED),
    _event_queue(),
    _last_update_us(0)
{
    _hci_driver = &hci_driver;
    stack_setup();
}

BLEInstanceBase::~BLEInstanceBase() = default;

/**
 * The singleton which represents the BLE transport for the BLE.
 */
BLEInstanceBase &BLEInstanceBase::deviceInstance()
{
    static BLEInstanceBase instance(
        ble_cordio_get_hci_driver()
    );
    return instance;
}

ble_error_t BLEInstanceBase::init(
    FunctionPointerWithContext<::BLE::InitializationCompleteCallbackContext *> initCallback
)
{
    switch (initialization_status) {
        case NOT_INITIALIZED:
            tr_info("Initialising BLE instance");
            _timer.reset();
            _timer.start();
            _event_queue.initialize(this);
            _init_callback = initCallback;
            start_stack_reset();
            return BLE_ERROR_NONE;

        case INITIALIZING:
            tr_warning("Already initialising BLE instance");
            return BLE_ERROR_INITIALIZATION_INCOMPLETE;

        case INITIALIZED:
            return BLE_ERROR_NONE;

        default:
            return BLE_ERROR_UNSPECIFIED;
    }
}

bool BLEInstanceBase::hasInitialized() const
{
    return initialization_status == INITIALIZED;
}

ble_error_t BLEInstanceBase::shutdown()
{
    tr_info("shutting down BLE");
    if (initialization_status != INITIALIZED) {
        return BLE_ERROR_INITIALIZATION_INCOMPLETE;
    }

#if BLE_FEATURE_GATT_SERVER
    getGattServer().reset();
#endif

#if BLE_FEATURE_GATT_CLIENT
    getGattClient().reset();
#endif // BLE_FEATURE_GATT_CLIENT

    getGap().reset();
    _event_queue.clear();

    initialization_status = NOT_INITIALIZED;
    _hci_driver->terminate();

    return BLE_ERROR_NONE;
}

const char *BLEInstanceBase::getVersion()
{
    static const char version[] = "generic-cordio";
    return version;
}

ble::impl::Gap &BLEInstanceBase::getGapImpl()
{
    static ble::impl::PalGenericAccessService cordio_gap_service;
    static ble::impl::Gap gap(
        _event_queue,
        ble::impl::PalGap::get_gap(),
        cordio_gap_service
#if BLE_FEATURE_PRIVACY
        , getPrivateAddressRegistry()
#endif // BLE_FEATURE_PRIVACY
    );
    return gap;
}

ble::Gap &BLEInstanceBase::getGap()
{
    auto &impl = getGapImpl();
    static ble::Gap gap(&impl);
    return gap;
}

const ble::Gap &BLEInstanceBase::getGap() const
{
    auto &self = const_cast<BLEInstanceBase &>(*this);
    return const_cast<const ble::Gap &>(self.getGap());
};

#if BLE_FEATURE_GATT_SERVER
ble::impl::GattServer &BLEInstanceBase::getGattServerImpl()
{
    return ble::impl::GattServer::getInstance();
}

ble::GattServer &BLEInstanceBase::getGattServer()
{
    auto &impl = getGattServerImpl();
    static ble::GattServer server(&impl);
    return server;
}

const ble::GattServer &BLEInstanceBase::getGattServer() const
{
    auto &self = const_cast<BLEInstanceBase &>(*this);
    return const_cast<const ble::GattServer &>(self.getGattServer());
}
#endif // BLE_FEATURE_GATT_SERVER

#if BLE_FEATURE_GATT_CLIENT
ble::impl::GattClient &BLEInstanceBase::getGattClientImpl()
{
    static ble::impl::GattClient gatt_client(getPalGattClient());
    return gatt_client;
}

ble::GattClient &BLEInstanceBase::getGattClient()
{
    auto &impl = getGattClientImpl();
    static ble::GattClient gatt_client(&impl);
    return gatt_client;
}

PalGattClient &BLEInstanceBase::getPalGattClient()
{
    static PalAttClientToGattClient pal_gatt_client(impl::PalAttClient::get_client());
    return pal_gatt_client;
}
#endif // BLE_FEATURE_GATT_CLIENT

#if BLE_FEATURE_SECURITY
ble::impl::SecurityManager &BLEInstanceBase::getSecurityManagerImpl()
{
#if BLE_FEATURE_SIGNING
    // Creation of a proxy monitor to let the security manager register to
    // the gatt client and gatt server.
    static struct : ble::PalSigningMonitor {
        void set_signing_event_handler(PalSigningMonitorEventHandler *handler) final
        {
#if BLE_FEATURE_GATT_CLIENT
            BLEInstanceBase::deviceInstance().getGattClientImpl().set_signing_event_handler(handler);
#endif // BLE_FEATURE_GATT_CLIENT
#if BLE_FEATURE_GATT_SERVER
            BLEInstanceBase::deviceInstance().getGattServerImpl().set_signing_event_handler(handler);
#endif // BLE_FEATURE_GATT_SERVER
        }
    } signing_event_monitor;
#endif //BLE_FEATURE_SIGNING

    static ble::impl::SecurityManager m_instance(
        ble::impl::PalSecurityManager::get_security_manager(),
        getGapImpl()
#if BLE_FEATURE_SIGNING
        , signing_event_monitor
#endif //BLE_FEATURE_SIGNING
#if BLE_FEATURE_PRIVACY
        , getPrivateAddressRegistry()
#endif //BLE_FEATURE_PRIVACY
    );

    return m_instance;
}

#if BLE_FEATURE_SECURITY
ble::SecurityManager &BLEInstanceBase::getSecurityManager()
{
    static ble::SecurityManager m_instance(&getSecurityManagerImpl());
    return m_instance;
}

const ble::SecurityManager &BLEInstanceBase::getSecurityManager() const
{
    const BLEInstanceBase &self = const_cast<BLEInstanceBase &>(*this);
    return const_cast<const ble::SecurityManager &>(self.getSecurityManager());
}
#endif // BLE_FEATURE_SECURITY

#if BLE_FEATURE_PRIVACY
ble::PrivateAddressController &BLEInstanceBase::getPrivateAddressRegistry()
{
    static ble::PrivateAddressController registry(
        impl::PalPrivateAddressController::instance(),
        _event_queue,
        ble::resolvable_address_timeout_t{}
    );
    return registry;
}
#endif // BLE_FEATURE_PRIVACY
#endif // BLE_FEATURE_SECURITY

void BLEInstanceBase::waitForEvent()
{
    static mbed::Timeout nextTimeout;
    timestamp_t nextTimestamp;
    bool_t pTimerRunning;

    callDispatcher();

    if (wsfOsReadyToSleep()) {
        // setup an mbed timer for the next cordio timeout
        nextTimestamp = (timestamp_t) (WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK);
        if (pTimerRunning) {
            nextTimeout.attach(timeoutCallback, milliseconds(nextTimestamp));
        }
    }
}

void BLEInstanceBase::processEvents()
{
    callDispatcher();
}

void BLEInstanceBase::stack_handler(wsfEventMask_t event, wsfMsgHdr_t *msg)
{
    if (msg == nullptr) {
        tr_warning("stack_handler received NULL message");
        return;
    }

#if BLE_FEATURE_SECURITY
    if (ble::impl::PalSecurityManager::get_security_manager().sm_handler(msg)) {
        return;
    }

#if BLE_FEATURE_PRIVACY
    if (impl::PalPrivateAddressController::instance().cordio_handler(msg)) {
        return;
    }
#endif
#endif // BLE_FEATURE_SECURITY

    switch (msg->event) {
        case DM_RESET_CMPL_IND: {
            ::BLE::InitializationCompleteCallbackContext context = {
                ::BLE::Instance(),
                BLE_ERROR_NONE
            };
#if BLE_FEATURE_EXTENDED_ADVERTISING
            // initialize extended module if supported
            tr_info("Reset sequence complete. Controller supported features:");
#if MBED_CONF_MBED_TRACE_ENABLE
            trace_le_supported_features(HciGetLeSupFeat());
#endif // MBED_CONF_MBED_TRACE_ENABLE
            tr_info("Initialising extended features");
            if (HciGetLeSupFeat() & HCI_LE_SUP_FEAT_LE_EXT_ADV) {
#if BLE_ROLE_BROADCASTER
                tr_info("DmExtAdvInit");
                DmExtAdvInit();
#endif // BLE_ROLE_BROADCASTER
#if BLE_ROLE_OBSERVER
                tr_info("DmExtScanInit");
                DmExtScanInit();
#endif // BLE_ROLE_OBSERVER
#if BLE_ROLE_CENTRAL
                tr_info("DmExtConnMasterInit");
                DmExtConnMasterInit();
#endif // BLE_ROLE_CENTRAL
#if BLE_ROLE_PERIPHERAL
                tr_info("DmExtConnSlaveInit");
                DmExtConnSlaveInit();
#endif // BLE_ROLE_PERIPHERAL
            }
#endif // BLE_FEATURE_EXTENDED_ADVERTISING
#if BLE_FEATURE_GATT_SERVER
            deviceInstance().getGattServerImpl().initialize();
#endif

            deviceInstance().initialization_status = INITIALIZED;
            _init_callback.call(&context);
        }   break;

#if MBED_CONF_CORDIO_ROUTE_UNHANDLED_COMMAND_COMPLETE_EVENTS
        case DM_UNHANDLED_CMD_CMPL_EVT_IND: {
            // upcast to unhandled command complete event to access the payload
            hciUnhandledCmdCmplEvt_t *unhandled = (hciUnhandledCmdCmplEvt_t *) msg;
            if (unhandled->hdr.status == HCI_SUCCESS && unhandled->hdr.param == HCI_OPCODE_LE_TEST_END) {
                tr_info("Host received HCI_OPCODE_LE_TEST_END from controller - end test mode");
                // unhandled events are not parsed so we need to parse the payload ourselves
                uint8_t status;
                uint16_t packet_number;
                status = unhandled->param[0];
                BYTES_TO_UINT16(packet_number, unhandled->param + 1);

                _hci_driver->handle_test_end(status == 0, packet_number);
                return;
            }
        }   break;
#endif // MBED_CONF_CORDIO_ROUTE_UNHANDLED_COMMAND_COMPLETE_EVENTS

        default:
            ble::impl::PalGap::gap_handler(msg);
            break;
    }
}

void BLEInstanceBase::device_manager_cb(dmEvt_t *dm_event)
{
    tr_debug("stack_handler received %s", dm_callback_event_to_string(dm_event->hdr.event));

#if BLE_FEATURE_CONNECTABLE
    if (dm_event->hdr.status == HCI_SUCCESS && dm_event->hdr.event == DM_CONN_DATA_LEN_CHANGE_IND) {
        // this event can only happen after a connection has been established therefore gap is present
        ble::PalGapEventHandler *handler;
        handler = ble::impl::PalGap::get_gap().get_event_handler();
        if (handler) {
            handler->on_data_length_change(
                dm_event->hdr.param,
                dm_event->dataLenChange.maxTxOctets,
                dm_event->dataLenChange.maxRxOctets
            );
        }
        return;
    }
#endif

    BLEInstanceBase::deviceInstance().stack_handler(0, &dm_event->hdr);
}

/*
 * AttServerInitDeInitCback callback is used to Initialize/Deinitialize
 * the CCC Table of the ATT Server when a remote peer requests to Open
 * or Close the connection.
 */
void BLEInstanceBase::connection_handler(dmEvt_t *dm_event)
{
    dmConnId_t connId = (dmConnId_t) dm_event->hdr.param;

    switch (dm_event->hdr.event) {
        case DM_CONN_OPEN_IND:
            tr_debug("Connection %d - Initialise CCC table", connId);
            /* set up CCC table with uninitialized (all zero) values */
            AttsCccInitTable(connId, nullptr);
            break;
        case DM_CONN_CLOSE_IND:
            /* clear CCC table on connection close */
            tr_debug("Connection %d - Clear CCC table", connId);
            AttsCccClearTable(connId);
            break;
        default:
            break;
    }
}

void BLEInstanceBase::timeoutCallback()
{
    wsf_mbed_ble_signal_event();
}

void BLEInstanceBase::stack_setup()
{
    MBED_ASSERT(_hci_driver != nullptr);

#if MBED_CONF_MBED_TRACE_ENABLE
    wsf_mbed_trace_init();
#endif // MBED_CONF_MBED_TRACE_ENABLE

    wsfHandlerId_t handlerId;

    buf_pool_desc_t buf_pool_desc = _hci_driver->get_buffer_pool_description();

    tr_info("Allocated %d bytes for Cordio", buf_pool_desc.buffer_size);

    // use the buffer for the WSF heap
    SystemHeapStart = buf_pool_desc.buffer_memory;
    SystemHeapSize = buf_pool_desc.buffer_size;

    // Initialize buffers with the ones provided by the HCI driver
    uint16_t bytes_used = WsfBufInit(buf_pool_desc.pool_count, (wsfBufPoolDesc_t *) buf_pool_desc.pool_description);

    // Raise assert if not enough memory was allocated
    MBED_ASSERT(bytes_used != 0);

    SystemHeapStart += bytes_used;
    SystemHeapSize -= bytes_used;

    // This warning will be raised if we've allocated too much memory
    if (bytes_used < buf_pool_desc.buffer_size) {
        MBED_WARNING1(MBED_MAKE_ERROR(MBED_MODULE_BLE, MBED_ERROR_CODE_INVALID_SIZE),
            "Too much memory allocated for Cordio memory pool, reduce buf_pool_desc.buffer_size by value below.",
            buf_pool_desc.buffer_size - bytes_used);
    }

    tr_info("BLE features enabled:"
#if BLE_FEATURE_EXTENDED_ADVERTISING
            " EXTENDED_ADVERTISING"
#endif
#if BLE_FEATURE_GATT_CLIENT
            " GATT_CLIENT"
#endif
#if BLE_FEATURE_GATT_SERVER
            " GATT_SERVER"
#endif
#if BLE_FEATURE_PERIODIC_ADVERTISING
            " PERIODIC_ADVERTISING"
#endif
#if BLE_FEATURE_PHY_MANAGEMENT
            " PHY_MANAGEMENT"
#endif
#if BLE_FEATURE_PRIVACY
            " PRIVACY"
#endif
#if BLE_FEATURE_SECURE_CONNECTIONS
            " SECURE_CONNECTIONS"
#endif
#if BLE_FEATURE_SECURITY
            " SECURITY"
#endif
#if BLE_FEATURE_SIGNING
            " SIGNING"
#endif
#if BLE_FEATURE_WHITELIST
            " WHITELIST"
#endif
    );

    tr_info("BLE roles enabled:"
#if BLE_ROLE_PERIPHERAL
            " PERIPHERAL"
#elif BLE_ROLE_BROADCASTER
            " BROADCASTER"
#endif
#if BLE_ROLE_CENTRAL
            " CENTRAL"
#elif BLE_ROLE_OBSERVER
            " OBSERVER"
#endif
    );

    tr_info("Initialising Cordio host stack");

    WsfTimerInit();

    // Note: SecInit required for RandInit.
    SecInit();
    SecRandInit();

#if BLE_FEATURE_SECURITY
    SecAesInit();
    SecCmacInit();
    SecEccInit();
#endif

    handlerId = WsfOsSetNextHandler(HciHandler);
    tr_debug("HCI handler id: %x", handlerId);
    HciHandlerInit(handlerId);

    handlerId = WsfOsSetNextHandler(DmHandler);
    tr_debug("DM handler id: %x", handlerId);

#if BLE_ROLE_BROADCASTER
    DmAdvInit();
#endif

#if BLE_ROLE_OBSERVER
    DmScanInit();
#endif

#if BLE_FEATURE_CONNECTABLE
    DmConnInit();
#endif

#if BLE_ROLE_CENTRAL
    DmConnMasterInit();
#endif

#if BLE_ROLE_PERIPHERAL
    DmConnSlaveInit();
#endif

#if BLE_FEATURE_SECURITY
    DmSecInit();
#endif

#if BLE_FEATURE_PHY_MANAGEMENT
    DmPhyInit();
#endif

#if BLE_FEATURE_SECURE_CONNECTIONS
    DmSecLescInit();
#endif

#if BLE_FEATURE_PRIVACY
    DmPrivInit();
#endif

    DmHandlerInit(handlerId);

#if BLE_ROLE_PERIPHERAL
    handlerId = WsfOsSetNextHandler(L2cSlaveHandler);
    tr_debug("L2C slave handler id: %x", handlerId);
    L2cSlaveHandlerInit(handlerId);
#endif

#if BLE_FEATURE_CONNECTABLE
    L2cInit();
#endif

#if BLE_ROLE_PERIPHERAL
    L2cSlaveInit();
#endif

#if BLE_ROLE_CENTRAL
    L2cMasterInit();
#endif

#if BLE_FEATURE_ATT
    handlerId = WsfOsSetNextHandler(AttHandler);
    tr_debug("ATT handler id: %x", handlerId);
    AttHandlerInit(handlerId);

#if BLE_FEATURE_GATT_SERVER
    AttsInit();
    AttsIndInit();
#if BLE_FEATURE_SECURITY
    AttsAuthorRegister(impl::GattServer::atts_auth_cb);
#endif
#if BLE_FEATURE_SIGNING
    AttsSignInit();
#endif
#endif // BLE_FEATURE_GATT_SERVER

#if BLE_FEATURE_GATT_CLIENT
    AttcInit();
#if BLE_FEATURE_SIGNING
    AttcSignInit();
#endif
#endif // BLE_FEATURE_GATT_CLIENT

#endif // BLE_FEATURE_ATT

#if BLE_FEATURE_SECURITY
    handlerId = WsfOsSetNextHandler(SmpHandler);
    tr_debug("SMP handler id: %x", handlerId);
    SmpHandlerInit(handlerId);

#if BLE_ROLE_PERIPHERAL
    SmprInit();
#if BLE_FEATURE_SECURE_CONNECTIONS
    SmprScInit();
#endif
#endif

#if BLE_ROLE_CENTRAL
    SmpiInit();
#if BLE_FEATURE_SECURE_CONNECTIONS
    SmpiScInit();
#endif
#endif // BLE_ROLE_CENTRAL

#endif // BLE_FEATURE_SECURITY

    stack_handler_id = WsfOsSetNextHandler(&BLEInstanceBase::stack_handler);
    tr_debug("stack handler id: %x", stack_handler_id);

    HciSetMaxRxAclLen(MBED_CONF_CORDIO_RX_ACL_BUFFER_SIZE);

    DmRegister(BLEInstanceBase::device_manager_cb);
#if BLE_FEATURE_CONNECTABLE
    DmConnRegister(DM_CLIENT_ID_APP, BLEInstanceBase::device_manager_cb);
#endif

#if BLE_FEATURE_GATT_SERVER
    AttConnRegister(BLEInstanceBase::connection_handler);
#endif

#if BLE_FEATURE_ATT
#if BLE_FEATURE_GATT_CLIENT
    AttRegister((attCback_t) impl::PalAttClient::att_client_handler);
#else
    AttRegister((attCback_t) impl::GattServer::att_cb);
#endif // BLE_FEATURE_GATT_CLIENT
#endif
}

void BLEInstanceBase::start_stack_reset()
{
    _hci_driver->initialize();
    DmDevReset();
}

void BLEInstanceBase::callDispatcher()
{
    // process the external event queue
    _event_queue.process();

    _last_update_us += (uint64_t) _timer.elapsed_time().count();
    _timer.reset();

    uint64_t last_update_ms = (_last_update_us / 1000);
    wsfTimerTicks_t wsf_ticks = (last_update_ms / WSF_MS_PER_TICK);

    if (wsf_ticks > 0) {
        WsfTimerUpdate(wsf_ticks);

        _last_update_us -= (last_update_ms * 1000);
    }

    wsfOsDispatcher();

    static Timeout nextTimeout;
    mbed::CriticalSectionLock critical_section;

    if (wsfOsReadyToSleep()) {
        // setup an mbed timer for the next Cordio timeout
        bool_t pTimerRunning;
        timestamp_t nextTimestamp = (timestamp_t) (WsfTimerNextExpiration(&pTimerRunning) * WSF_MS_PER_TICK);
        if (pTimerRunning) {
            nextTimeout.attach(timeoutCallback, milliseconds(nextTimestamp));
        } else {
            critical_section.disable();
            _hci_driver->on_host_stack_inactivity();
        }
    }
}

CordioHCIDriver *BLEInstanceBase::_hci_driver = nullptr;

FunctionPointerWithContext<::BLE::InitializationCompleteCallbackContext *> BLEInstanceBase::_init_callback;

} // namespace impl
} // namespace ble


text:
/* Generic Style definitions */
.ExpansionPlus
{
	background-image: url("../images/icons/navigate_plus.png");
	background-repeat: no-repeat;
	background-position: left center;
	padding-left: 20px;
}

.ExpansionMinus
{
	background-image: url("../images/icons/navigate_minus.png");
	background-repeat: no-repeat;
	background-position: left center;
	padding-left: 20px;
}

.HiddenContent
{
	visibility: hidden;
/*		position: relative; */
	display: none;
}

.ShownContent
{
	visibility: visible;
	display: inline;
}

.borderless
{
	border:0px solid;
	background-color: transparent;
}

.borderlessbuttons
{
	border:0px solid;
	background-color: transparent;
	width:20px;
	padding: 0px;
}

.inlinebutton
{
	float:left;
	position: relative;

	border:0px solid;
	background-color: transparent;
	padding: 0px;
	margin: 0px;
}

.SelectSavedFilter
{
	margin-top: 2px;
	border: 1px solid;
	border-color: #233B51 #124A7C #124A7C #233B51;
}

.syslogdetails, a.syslogdetails, a.syslogdetails:link, a.syslogdetails:active, a.syslogdetails:visited
{
	font-weight:normal;
    text-decoration:none;
    position:relative;
	overflow:visible;
}
.syslogdetails
{
    position:relative;
	overflow:visible;
	z-index:4;
}

.syslogdetails:hover
{
    position:relative; /*this is the key*/
	font-weight:normal;
	z-index:5;
}
.syslogdetails span
{
    position:relative;
	overflow:visible;
	display: none;
	z-index:-1;

}
/*the span will display just on :hover state*/
.syslogdetails_popup span
{
    display:block;
    position:absolute;
	overflow:auto;
	z-index:5;

/*    top:15px; */
/*    left:15px; */
}

.gridline
{
	vertical-align: top;
	height: 16px;
}

/*
* POPUP Helper Styles
*/
.popupdetails
{
	position: absolute;
	visibility: hidden;
	z-index:1
}
.popupdetails:hover
{
	position: absolute;
	visibility: hidden;
	z-index: 2;
}

.popupdetails_popup
{
	position: absolute;
	visibility: visible;
	z-index: 2;
}


text:
#ifndef ELFWRITE_H_
#define ELFWRITE_H_

#include <stdio.h>
#include <stdint.h>

/**
 *  @brief Writes an ELF executable with the given parameters to the given file.
 *  @param file File to write to
 *  @param entry_point Virtual address of entry point
 *  @param text_vaddr Address to load .text segment to
 *  @param text Code to write
 *  @param text_size Size of the given code
 *  @param rodata_vaddr Address to load .rodata segment to
 *  @param rodata Read only data to write
 *  @param rodata_size Size of the given read only data
 *  @param data_vaddr Address to load .data segment to
 *  @param data Writable data to write (== initialized variables)
 *  @param data_size Size of the given writable data
 *  @param bss_vaddr Address to put the zero initialized writable segment at (== 0 initialized variables)
 *  @param bss_size Size to reserve for the zero initialized data
 */
void elf_write(FILE *file,
        uint32_t entry_point,
        uint32_t text_vaddr,
        const unsigned char *text, size_t text_size,
        uint32_t rodata_vaddr,
        const unsigned char *rodata, size_t rodata_size,
        uint32_t data_vaddr,
        const unsigned char *data, size_t data_size,
        uint32_t bss_vaddr,
        size_t bss_size);

/**
 *  @brief Return a set of addresses for the required sizes that prevent
 *         padding from being required in files written with elf_write.
 *
 *  @param base_vaddr Lowest vaddr to consider.
 *  @param text_size Size of text segment
 *  @param rodata_size Size of rodata segment
 *  @param data_size Size of data segment
 *  @param text_vaddr Target variable for optimal text vaddr.
 *  @param rodata_vaddr Target variable for optimal rodata vaddr.
 *  @param data_vaddr Target variable for optimal data vaddr.
 *  @param bss_vaddr Target variable for optimal bss vaddr.
 */
void elf_optimize_alignment(
        uint32_t base_vaddr,
        uint32_t text_size,
        uint32_t rodata_size,
        uint32_t data_size,
        uint32_t *text_vaddr,
        uint32_t *rodata_vaddr,
        uint32_t *data_vaddr,
        uint32_t *bss_vaddr);

#endif /* ELFWRITE_H_ */


text:
import _ from 'highland'
import logger from '../stream-utils/logger'

let constructor = (net, guid, boilerBayPath, serverPort) => {
  let boilerBayHost = boilerBayPath.split(':')[0]
  let boilerBayPort = parseInt(boilerBayPath.split(':')[1], 10)

  let server = net.createServer((cannonvilleConnection) => {

    let boilerBayConnection = net.connect(boilerBayPort, boilerBayHost)

    let commandsForBoilerBay = _(cannonvilleConnection)
      .split()
      .compact()
      .map((x) => JSON.parse(x))
      .map((command) => {
        if (command.event) {
          return 'send ' +
            command.event.book + ' ' +
            (guid().replace(/-/g,'')) + ' ' +
            JSON.stringify(command.event.body) +
            '\n'
        } else if(command.consume) {
          return 'consume ' +
            command.consume.book + ' ' +
            (command.consume.group || guid()) + ' ' +
            command.consume.offsetReset +
            '\n'
        } else if (command.next) {
          return 'next\n'
        } else if (command.commit) {
          return 'commit\n'
        }
      })

    boilerBayConnection.on('connect', () =>
      commandsForBoilerBay.pipe(boilerBayConnection))

    _(boilerBayConnection)
      .fork()
      .map((buffer) => {
        let body = buffer.toString()
        if (body.match(/msg/)) {
          return {
            event: JSON.parse(body.match(/msg\s(.+)/)[1])
          }
        } else if (body.match(/consume\-started/)) {
          return {
            consumeStarted: true
          }
        } else if (body.match(/commit\-ok/)) {
          return {
            commitOK: true
          }
        } else if (body.match(/^error/)){
          var parts = body.match(/error\s(\S+)\s(.+)/)
          return {
            error: {
              code: parts[1],
              message: parts[2]
            }
          }
        }
      })
      .compact()
      .errors(({code, message}, push) =>
        push(null, { error: {
          code,
          message: 'Boiler Bay emitted an error with message: ' + message
        }}))
      .map((x) => JSON.stringify(x) + '\n')
      .pipe(cannonvilleConnection)
  })
  server.listen(serverPort)
}

export default constructor


text:
class RoundCategoryController extends Controller<RoundCategory> {
	public classname = "round_category";

	public constructor(server:string){
		super(server);
	}

	public factory(obj:IRoundCategory):RoundCategory{
		return new RoundCategory(obj);
	}

}


text:
// Copyright 2012 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {
  ASSERT_NAME,
  CREATE_NAME,
  RUNTIME,
  TRACEUR
} from '../syntax/PredefinedName.js';
import {TempVarTransformer} from './TempVarTransformer.js';
import {CONST} from '../syntax/TokenType.js';
import {
  VariableDeclarationList,
  VariableStatement
} from '../syntax/trees/ParseTrees.js';
import {
  createArgumentList,
  createCallExpression,
  createEmptyArgumentList,
  createIdentifierExpression,
  createMemberExpression,
  createVariableDeclaration
} from './ParseTreeFactory.js';

/**
 * Desugars the private name syntax, @name.
 *
 * @see http://wiki.ecmascript.org/doku.php?id=strawman:syntactic_support_for_private_names
 */
export class PrivateNameSyntaxTransformer extends TempVarTransformer {

  getTransformedName_(token) {
    return this.identifierGenerator.getUniqueIdentifier(token.value);
  }

  transformAtNameExpression(tree) {
    var transformedName = this.getTransformedName_(tree.atNameToken);
    return createIdentifierExpression(transformedName);
  }

  transformNameStatement(tree) {
    // private @a, @b = expr;
    //  =>
    // const __a = traceur.runtime.createName(),
    //       __b = traceur.runtime.assertName(expr)
    var declarations = this.transformList(tree.declarations);
    return new VariableStatement(tree.location,
        new VariableDeclarationList(tree.location, CONST, declarations));
  }

  transformAtNameDeclaration(tree) {
    var transformedName = this.getTransformedName_(tree.atNameToken);

    var args, name;
    if (tree.initializer) {
      args = createArgumentList(this.transformAny(tree.initializer));
      name = ASSERT_NAME;
    } else {
      args = createEmptyArgumentList();
      name = CREATE_NAME;
    }

    return createVariableDeclaration(transformedName,
      createCallExpression(
        createMemberExpression(TRACEUR, RUNTIME, name),
        args));
  }

  /**
   * @param {UniqueIdentifierGenerator} identifierGenerator
   * @param {ParseTree} tree
   */
  static transformTree(identifierGenerator, tree) {
    return new PrivateNameSyntaxTransformer(identifierGenerator).
        transformAny(tree);
  }
}


text:
const notify = require('node-notify');
const {NOTIFICATION_TITLE} = require('../constants');

const send = ({cfg, version, secrets, changelog}, message) => {
  return new Promise((resolve, reject) => {
    notify({
      title: NOTIFICATION_TITLE,
      message
    });
    resolve();
  });
};

const fail = ({cfg, version, secrets, changelog}, failMessage) => {
  if (cfg.has('notify')) {
    const message = `Release Failed: ${failMessage}`;
    return send({cfg, version, secrets, changelog}, message);
  } else {
    return Promise.resolve();
  }
};

const success = ({cfg, version, secrets, changelog}) => {
  if (cfg.has('notify')) {
    const message = `Just released ${cfg.releaseUrl()} - Version ${version}`;
    return send({cfg, version, secrets, changelog}, message);
  } else {
    return Promise.resolve();
  }
};

module.exports = {
  success,
  fail
};


text:
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Rasmus Mikkelsen
// Copyright (c) 2015-2018 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using EventFlow.TestHelpers;
using EventFlow.TestHelpers.Aggregates;
using FluentAssertions;
using NUnit.Framework;

namespace EventFlow.Tests.UnitTests.Aggregates
{
    [Category(Categories.Unit)]
    public class AggregateIdTests
    {
        [Test]
        public void ManuallyCreatedIsOk()
        {
            // Arrange
            const string value = "thingy-d15b1562-11f2-4645-8b1a-f8b946b566d3";

            // Act
            var testId = ThingyId.With(value);

            // Test
            testId.Value.Should().Be(value);
        }

        [Test]
        public void CreatedIsDifferent()
        {
            // Act
            var id1 = ThingyId.New;
            var id2 = ThingyId.New;

            // Assert
            id1.Value.Should().NotBe(id2.Value);
        }

        [Test]
        public void SameIdsAreEqual()
        {
            // Arrange
            const string value = "thingy-d15b1562-11f2-4645-8b1a-f8b946b566d3";
            var id1 = ThingyId.With(value);
            var id2 = ThingyId.With(value);

            // Assert
            id1.Equals(id2).Should().BeTrue();
            (id1 == id2).Should().BeTrue();
        }

        [Test]
        public void DifferentAreNotEqual()
        {
            // Arrange
            var id1 = ThingyId.With("thingy-7ddc487f-02ad-4be3-a6ef-71203d333c61");
            var id2 = ThingyId.With("thingy-d15b1562-11f2-4645-8b1a-f8b946b566d3");

            // Assert
            id1.Equals(id2).Should().BeFalse();
            (id1 == id2).Should().BeFalse();
        }
    }
}


text:
description(

"This test checks that activation objects (the local scope for a function) don't have the special __proto__ property that lets you get and set a normal object's prototype. This is important because the impossibility of swizzling activation object prototype chains allows various optimizations."

);

shouldBe("(function() { __proto__.testVariable = 'found'; return window.testVariable; })()", "'found'");


text:
<?php

namespace Organizations\Factory\Controller;

use Interop\Container\ContainerInterface;
use Organizations\Controller\ProfileController;
use Zend\ServiceManager\Factory\FactoryInterface;

/**
 * Create new ProfileController object
 *
 * @author Anthonius Munthi <me@itstoni.com>
 * @package Organizations\Factory\Controller
 * @since 0.30
 */
class ProfileControllerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $repo = $container->get('repositories')
            ->get('Organizations/Organization')
        ;
        $jobRepository = $container->get('repositories')
            ->get('Jobs/Job')
        ;
        $translator = $container->get('translator');
        $imageFileCacheManager = $container->get('Organizations\ImageFileCache\Manager');
        $options = $container->get('Jobs/JobboardSearchOptions');
        return new ProfileController($repo, $jobRepository, $translator, $imageFileCacheManager, ['count' => $options->getPerPage()]);
    }
}


text:
import { META, Navigation } from '../../../src/tags/navigation/gb-navigation';
import { displayRefinement } from '../../../src/utils/common';
import * as common from '../../../src/utils/common';
import { refinement } from '../../utils/fixtures';
import suite from './_suite';
import { expect } from 'chai';
import { Events } from 'groupby-api';

suite('gb-navigation', Navigation, ({
  flux, tag, spy, stub,
  expectSubscriptions,
  itShouldHaveMeta,
  itShouldAlias
}) => {
  itShouldHaveMeta(Navigation, META);

  describe('init()', () => {
    itShouldAlias('navigable');

    it('should mixin toView()', () => {
      const mixin = tag().mixin = spy();

      tag().init();

      expect(mixin).to.be.calledWith({ toView: displayRefinement });
    });

    it('should listen for flux events', () => {
      expectSubscriptions(() => tag().init(), {
        [Events.RESULTS]: tag().updateNavigations,
        [Events.REFINEMENT_RESULTS]: tag().updateRefinements
      });
    });
  });

  describe('updateRefinements()', () => {
    it('should call update() with processed', () => {
      const results: any = { a: 'b' };
      const processed = [{ c: 'd' }];
      const update = tag().update = spy();
      const replaceRefinements = stub(tag(), 'replaceRefinements').returns(processed);

      tag().updateRefinements(results);

      expect(replaceRefinements).to.be.calledWith(results);
      expect(update).to.be.calledWith({ processed });
    });
  });

  describe('replaceRefinements()', () => {
    it('should replace refinements', () => {
      const mergeRefinements = stub(tag(), 'mergeRefinements');
      tag().flux.results = <any>{ selectedNavigation: [] };
      tag().processed = <any>[
        {
          name: 'a',
          refinements: [{ type: 'Value', value: 'b' }]
        }, {
          name: 'c',
          refinements: [{ type: 'Value', value: 'b' }],
          selected: [{ type: 'Value', value: 'd' }]
        }, {
          name: 'e',
          refinements: [{ type: 'Value', value: 'f' }]
        }
      ];

      const processed = tag().replaceRefinements(<any>{
        navigation: {
          name: 'e',
          refinements: [
            { type: 'Value', value: 'm' },
            { type: 'Value', value: 'n' }
          ]
        }
      });

      expect(processed).to.have.length(3);
      expect(processed[2].refinements).to.have.length(2);
      expect((<any>processed[2].refinements[0]).value).to.eq('m');
      expect((<any>processed[2].refinements[1]).value).to.eq('n');
      expect(mergeRefinements).to.not.be.called;
    });

    it('should not replace refinements', () => {
      tag().processed = [];

      const processed = tag().replaceRefinements(<any>{
        navigation: {
          name: 'e',
          refinements: [{ type: 'Value', value: 'n' }]
        }
      });

      expect(processed).to.have.length(0);
    });

    it('should call mergeRefinements', () => {
      const mergeRefinements = stub(tag(), 'mergeRefinements');
      const availableNavigation: any = { name: 'a', refinements: [] };
      const selectedNavigation: any = { name: 'a' };
      tag().flux.results = <any>{ selectedNavigation: [selectedNavigation] };
      tag().processed = [availableNavigation];

      tag().replaceRefinements(<any>{ navigation: { name: 'a' } });

      expect(mergeRefinements).to.be.calledWith(availableNavigation, selectedNavigation);
    });
  });

  describe('processNavigations()', () => {
    it('should clone availableNavigation', () => {
      const availableNavigation = [{ a: 'b' }];
      const processed = [];
      const clone = stub(common, 'clone').returns(processed);

      const actualProcessed = tag().processNavigations(<any>{ availableNavigation, selectedNavigation: [] });

      expect(actualProcessed).to.eq(processed);
      expect(clone).to.be.calledWith(availableNavigation);
    });

    it('should pass matching navigation to mergeRefinements()', () => {
      const available1 = { name: 'a' };
      const available2 = { name: 'b' };
      const selected1 = { name: 'b' };
      const selected2 = { name: 'a' };
      const mergeRefinements = stub(tag(), 'mergeRefinements');

      tag().processNavigations(<any>{
        availableNavigation: [available1, available2],
        selectedNavigation: [selected1, selected2]
      });

      expect(mergeRefinements).to.be.calledTwice;
      expect(mergeRefinements).to.be.calledWith(available1, selected2);
      expect(mergeRefinements).to.be.calledWith(available2, selected1);
    });

    it('orphaned selected navigations should be pushed to the top', () => {
      const selected = { name: 'a', refinements: <any[]>[{}, {}] };

      const processed = tag().processNavigations(<any>{ availableNavigation: [], selectedNavigation: [selected] });

      expect(processed[0]).to.eq(selected);
      selected.refinements.forEach((refinement) => expect(refinement.selected).to.be.true);
    });
  });

  describe('mergeRefinements()', () => {
    it('should check for refinement matches', () => {
      const available1 = {};
      const available2 = {};
      const selected1 = {};
      const selected2 = {};
      const refinementMatches = stub(common, 'refinementMatches');

      tag().mergeRefinements(
        {
          refinements: [available1, available2]
        },
        {
          refinements: [selected1, selected2]
        });

      expect(refinementMatches).to.be.calledWith(available1, selected1);
      expect(refinementMatches).to.be.calledWith(available2, selected1);
      expect(refinementMatches).to.be.calledWith(available1, selected2);
      expect(refinementMatches).to.be.calledWith(available2, selected2);
    });

    it('should select matching refinements', () => {
      const available: any = {};
      const selected = {};
      stub(common, 'refinementMatches').returns(true);

      tag().mergeRefinements({ refinements: [available] }, { refinements: [selected] });

      expect(available.selected).to.be.true;
    });

    it('should add orphan selected refinements', () => {
      const availableNavigation = { refinements: [{}] };
      const selected = {};
      stub(common, 'refinementMatches');

      tag().mergeRefinements(availableNavigation, { refinements: [selected] });

      expect(availableNavigation.refinements).to.have.length(2);
      expect(availableNavigation.refinements[0]).to.eq(selected);
    });

    it('should call sortRefinements()', () => {
      const ref1 = {};
      const ref2 = {};
      const availableNavigation = { refinements: [ref1, ref2] };
      const sortRefinements = stub(tag(), 'sortRefinements');
      tag().hoistSelected = true;
      stub(common, 'refinementMatches');

      tag().mergeRefinements(availableNavigation, { refinements: [] });

      expect(sortRefinements).to.be.calledOnce;
      expect(sortRefinements).to.be.calledWith(ref1, ref2);
    });

    it('should not sort when hoistSelected is false', () => {
      const availableNavigation = { refinements: [{}, {}] };
      const sortRefinements = stub(tag(), 'sortRefinements');
      tag().hoistSelected = false;
      stub(common, 'refinementMatches');

      tag().mergeRefinements(availableNavigation, { refinements: [] });

      expect(sortRefinements).to.not.be.called;
    });
  });

  describe('sortRefinements()', () => {
    it('should return 1 if neither is selected', () => {
      expect(tag().sortRefinements({}, {})).to.eq(1);
    });

    it('should sort selected to the top', () => {
      expect(tag().sortRefinements({ selected: true }, {})).to.eq(-1);
      expect(tag().sortRefinements({}, { selected: true })).to.eq(1);
    });

    it('should sort within selected by value', () => {
      const ref1 = { selected: true, value: 'b' };
      const ref2 = { selected: true, value: 'a' };

      expect(tag().sortRefinements(ref2, ref1)).to.eq(-1);
      expect(tag().sortRefinements(ref1, ref2)).to.eq(1);
    });
  });

  describe('send()', () => {
    it('should refine on send()', () => {
      const refine = stub(flux(), 'refine');

      tag().send({ type: 'Range', low: 4, high: 6 }, { name: 'price' });

      expect(refine).to.be.calledWith(refinement('price', 4, 6));
    });
  });

  describe('remove()', () => {
    it('should unrefine on remove()', () => {
      const unrefine = stub(flux(), 'unrefine');

      tag().remove({ type: 'Range', low: 4, high: 6 }, { name: 'price' });

      expect(unrefine).to.be.calledWith(refinement('price', 4, 6));
    });
  });
});


text:
LYMenuDrawer
============

Left menu drawer for iOS.

# Feature

1. Full screen pan gesture for swipe menu.
2. Two speed for menu animation.

# Setup
## Step 1. setup delegate property

in your mainController interface, set property 'delegate' for menuDelegation.
```
#import <UIKit/UIKit.h>

#import "LYMenuDrawerDelegation.h"

@interface LYViewController : UIViewController

// delegate for menu
@property (weak, nonatomic) id<LYMenuDrawerDelegation> delegate;

@end
```

## Step 2. setup delegate method

in your mainController implementation, enable/disable menuDelegate panGesture when view controller appear/dissappear.

Binding toggle event with left bar buttion item.

```
#import "LYViewController.h"

@interface LYViewController ()

@end

@implementation LYViewController

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [_delegate enablePanGesture];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [_delegate disablePanGesture];
}

- (IBAction)toggleMenu:(id)sender
{
    [_delegate toggleMenuDidClicked];
}

@end
```


text:
package org.apache.sysml.test.integration.functions.ternary;

import java.util.HashMap;

import org.junit.Test;

import org.apache.sysml.api.DMLScript;
import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;
import org.apache.sysml.hops.TernaryOp;
import org.apache.sysml.lops.LopProperties.ExecType;
import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;
import org.apache.sysml.test.utils.TestUtils;

/**
 * This test investigates the specific Hop-Lop rewrite ctable(seq(1,nrow(X)),X).
 *
 * NOTES:
 * * table in R treats every distinct value of X as a specific value, while
 *   we cast those double values to long. Hence, we need to round the generated
 *   dataset.
 * * May, 16 2014: extended tests to include aggregate because some specific issues
 *   only show up on subsequent GMR operations after ctable produced the output in
 *   matrix cell.
 *
 */
public class CTableSequenceTest extends AutomatedTestBase
{

	private final static String TEST_NAME1 = "CTableSequenceLeft";
	private final static String TEST_NAME2 = "CTableSequenceRight";

	private final static String TEST_DIR = "functions/ternary/";
	private final static String TEST_CLASS_DIR = TEST_DIR + CTableSequenceTest.class.getSimpleName() + "/";
	private final static double eps = 1e-10;

	private final static int rows = 2407;
	private final static int maxVal = 7;

	@Override
	public void setUp()
	{
		TestUtils.clearAssertionInformation();
		addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { "B" }) );
		addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] { "B" }) );
	}

	@Test
	public void testCTableSequenceLeftNoRewriteSP()
	{
		runCTableSequenceTest(false, true, false, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceLeftRewriteSP()
	{
		runCTableSequenceTest(true, true, false, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceRightNoRewriteSP()
	{
		runCTableSequenceTest(false, false, false, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceRightRewriteSP()
	{
		runCTableSequenceTest(true, false, false, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceLeftNoRewriteAggSP()
	{
		runCTableSequenceTest(false, true, true, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceLeftRewriteAggSP()
	{
		runCTableSequenceTest(true, true, true, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceRightNoRewriteAggSP()
	{
		runCTableSequenceTest(false, false, true, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceRightRewriteAggSP()
	{
		runCTableSequenceTest(true, false, true, ExecType.SPARK);
	}

	@Test
	public void testCTableSequenceLeftNoRewriteCP()
	{
		runCTableSequenceTest(false, true, false, ExecType.CP);
	}

	@Test
	public void testCTableSequenceLeftRewriteCP()
	{
		runCTableSequenceTest(true, true, false, ExecType.CP);
	}

	@Test
	public void testCTableSequenceLeftNoRewriteMR()
	{
		runCTableSequenceTest(false, true, false, ExecType.MR);
	}

	@Test
	public void testCTableSequenceLeftRewriteMR()
	{
		runCTableSequenceTest(true, true, false, ExecType.MR);
	}

	@Test
	public void testCTableSequenceRightNoRewriteCP()
	{
		runCTableSequenceTest(false, false, false, ExecType.CP);
	}

	@Test
	public void testCTableSequenceRightRewriteCP()
	{
		runCTableSequenceTest(true, false, false, ExecType.CP);
	}

	@Test
	public void testCTableSequenceRightNoRewriteMR()
	{
		runCTableSequenceTest(false, false, false, ExecType.MR);
	}

	@Test
	public void testCTableSequenceRightRewriteMR()
	{
		runCTableSequenceTest(true, false, false, ExecType.MR);
	}

	@Test
	public void testCTableSequenceLeftNoRewriteAggCP()
	{
		runCTableSequenceTest(false, true, true, ExecType.CP);
	}

	@Test
	public void testCTableSequenceLeftRewriteAggCP()
	{
		runCTableSequenceTest(true, true, true, ExecType.CP);
	}

	@Test
	public void testCTableSequenceLeftNoRewriteAggMR()
	{
		runCTableSequenceTest(false, true, true, ExecType.MR);
	}

	@Test
	public void testCTableSequenceLeftRewriteAggMR()
	{
		runCTableSequenceTest(true, true, true, ExecType.MR);
	}

	@Test
	public void testCTableSequenceRightNoRewriteAggCP()
	{
		runCTableSequenceTest(false, false, true, ExecType.CP);
	}

	@Test
	public void testCTableSequenceRightRewriteAggCP()
	{
		runCTableSequenceTest(true, false, true, ExecType.CP);
	}

	@Test
	public void testCTableSequenceRightNoRewriteAggMR()
	{
		runCTableSequenceTest(false, false, true, ExecType.MR);
	}

	@Test
	public void testCTableSequenceRightRewriteAggMR()
	{
		runCTableSequenceTest(true, false, true, ExecType.MR);
	}

	/**
	 *
	 * @param sparseM1
	 * @param sparseM2
	 * @param instType
	 */
	private void runCTableSequenceTest( boolean rewrite, boolean left, boolean withAgg, ExecType et)
	{
		String TEST_NAME = left ? TEST_NAME1 : TEST_NAME2;

		//rtplatform for MR
		RUNTIME_PLATFORM platformOld = rtplatform;
		boolean rewriteOld = TernaryOp.ALLOW_CTABLE_SEQUENCE_REWRITES;

		switch( et ){
			case MR: rtplatform = RUNTIME_PLATFORM.HADOOP; break;
			case SPARK: rtplatform = RUNTIME_PLATFORM.SPARK; break;
			default: rtplatform = RUNTIME_PLATFORM.HYBRID; break;
		}

		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
		if( rtplatform == RUNTIME_PLATFORM.SPARK )
			DMLScript.USE_LOCAL_SPARK_CONFIG = true;

		TernaryOp.ALLOW_CTABLE_SEQUENCE_REWRITES = rewrite;

		try
		{
			TestConfiguration config = getTestConfiguration(TEST_NAME);
			loadTestConfiguration(config);

			/* This is for running the junit test the new way, i.e., construct the arguments directly */
			String HOME = SCRIPT_DIR + TEST_DIR;
			fullDMLScriptName = HOME + TEST_NAME + ".dml";
			programArgs = new String[]{"-explain","-args", input("A"),
				Integer.toString(rows),
				Integer.toString(1),
				Integer.toString(withAgg?1:0),
				output("B")};

			fullRScriptName = HOME + TEST_NAME + ".R";
			rCmd = "Rscript" + " " + fullRScriptName + " " + inputDir() + " " + expectedDir();

			//generate actual dataset (always dense because values <=0 invalid)
			double[][] A = floor(getRandomMatrix(rows, 1, 1, maxVal, 1.0, 7), rows, 1);
			writeInputMatrix("A", A, true);

			runTest(true, false, null, -1);
			runRScript(true);

			//compare matrices
			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("B");
			HashMap<CellIndex, Double> rfile  = readRMatrixFromFS("B");
			TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R");

			//w/ rewrite: 4 instead of 6 because seq and aggregation are not required for ctable_expand
			//2 for CP due to reblock jobs for input and table
			if(et != ExecType.SPARK) {
				int expectedNumCompiled = ((et==ExecType.CP) ? 2 :(rewrite ? 4 : 6))+(withAgg ? 1 : 0);
				checkNumCompiledMRJobs(expectedNumCompiled);
			}

		}
		finally
		{
			rtplatform = platformOld;
			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
			TernaryOp.ALLOW_CTABLE_SEQUENCE_REWRITES = rewriteOld;
		}
	}

	/**
	 *
	 * @param X
	 * @param rows
	 * @param cols
	 * @return
	 */
	private double[][] floor( double[][] X, int rows, int cols )
	{
		for( int i=0; i<rows; i++ )
			for( int j=0; j<cols; j++ )
				X[i][j] = Math.floor(X[i][j]);
		return X;
	}
}


text:
@interface UserInfoView : UIView

@property (nonatomic, retain) UserModel            *user;
@property (nonatomic, retain) IBOutlet UIImageView *userImage;       //头像
@property (nonatomic, retain) IBOutlet UILabel     *nickLabel;       //昵称
@property (nonatomic, retain) IBOutlet UILabel     *addressLabel;    //地址
@property (nonatomic, retain) IBOutlet UILabel     *infoLabel;       //简介
@property (nonatomic, retain) IBOutlet RectButton  *attButton;       //关注按钮
@property (nonatomic, retain) IBOutlet RectButton  *fansButton;      //粉丝按钮
@property (nonatomic, retain) IBOutlet RectButton  *profileButton;   //资料按钮
@property (nonatomic, retain) IBOutlet RectButton  *moreButton;      //更多按钮
@property (nonatomic, retain) IBOutlet UILabel     *contentLabel;    //微博总数量

- (IBAction)attAction:(id)sender;
- (IBAction)fansAction:(id)sender;

@end


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

<title>com.cybozu.labs.langdetect.util Class Hierarchy</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.cybozu.labs.langdetect.util

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.cybozu.labs.langdetect.util.LangProfile

com.cybozu.labs.langdetect.util.LangProfileTest

com.cybozu.labs.langdetect.util.Messages

com.cybozu.labs.langdetect.util.NGram

com.cybozu.labs.langdetect.util.NGramTest

com.cybozu.labs.langdetect.util.TagExtractor

com.cybozu.labs.langdetect.util.TagExtractorTest

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
using GTuner.Audio.Interfaces;
using System;
using System.Resources;

namespace GTuner.Audio
{
    public class WavResourceHandler : IResourceHandler
    {
        public object GetResource(string resourceName)
        {
            if(string.IsNullOrEmpty(resourceName))
                throw new ArgumentException("null or empty forbidden", "resourceName");

            ResourceManager resourceManager = Properties.Resources.ResourceManager;

            object wavResource = resourceManager.GetObject(resourceName);

            return wavResource;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:lang="http://www.springframework.org/schema/lang"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
>

<lang:groovy id="moduleInject" script-source="classpath:com/gxb/groovy/util/ModuleInject.groovy">
	<lang:property  name="title" value="Hello World, it'me" />
</lang:groovy>

</beans>


text:
// TYPE_CHECKING,CODE_GENERATION
/**
 * Typecheck:
 * - Type A[] is not assignable to type A.
 */
public class J1_6_Assignable_Object_ObjectArray {

    public J1_6_Assignable_Object_ObjectArray () {}

    public static int test() {
	Object j = new Object[123];
	return ((Object[])j).length;
    }

}


text:
![npm](https://img.shields.io/npm/v/react-asyncbutton.svg) ![license](https://img.shields.io/npm/l/react-asyncbutton.svg) ![github-issues](https://img.shields.io/github/issues/revolunet/react-asyncbutton.svg)

async button to call urls with visual feedback

![demo](./examples/asyncbutton.gif)

## Install

`npm install --save-dev react-asyncbutton`

## Usage

```html
<AsyncButton url={ url } onSuccess={ this.onSuccess }/>
```

See [examples](./examples)

## Scripts

 - **npm run test** : `rackt test`
 - **npm run test-chrome** : `./node_modules/.bin/testem -l Chrome`
 - **npm run start** : `rackt server`

## Dependencies

Package | Version | Dev
--- |:---:|:---:
[babel-runtime](https://www.npmjs.com/package/babel-runtime) | 6.1.4 | ✖
[browser-request](https://www.npmjs.com/package/browser-request) | ^0.3.3 | ✖
[babel-runtime](https://www.npmjs.com/package/babel-runtime) | ^6.1.4 | ✔
[node-readme](https://www.npmjs.com/package/node-readme) | 0.1.9 | ✔
[rackt-cli-revolunet](https://www.npmjs.com/package/rackt-cli-revolunet) | ^0.5.10 | ✔
[react](https://www.npmjs.com/package/react) | ^0.14 | ✔

## Contributing

Contributions welcome; Please submit all pull requests the against master branch. If your pull request contains JavaScript patches or features, you should include relevant unit tests. Please check the [Contributing Guidelines](contributng.md) for more details. Thanks!

## Author

Julien Bouquillon <julien@revolunet.com>> undefined

## License

 - **MIT** : http://opensource.org/licenses/MIT


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>win.hgfdodo.zookeeper</groupId>
    <artifactId>autoswitch</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!--curator 2.X.X 兼容zookeeper3.4.X,3.5.X-->
        <!--curator 3.X.X 兼容zookeeper3.5.X-->
        <curator.version>2.12.0</curator.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>${curator.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-client</artifactId>
            <version>${curator.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>${curator.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.zookeeper</groupId>
                    <artifactId>zookeeper</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--zk 测试-->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-test</artifactId>
            <version>${curator.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>

</project>


text:
//
//  ARPopScrollView.h
//  ARPopScrollController
//
//  Created by Puru Shukla on 11/18/14.
//  Copyright (c) 2014 arrps. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "ARPopScrollViewDataSource.h"
#import "ARPopScrollViewDelegate.h"

@interface ARPopScrollView : UIView

/**
 * Private property: the scroll view
 */
@property (nonatomic, readonly)UIView* contentView;

/**
 * @property Datasource of the ARPopScrollView
 */
@property (nonatomic, weak)id<ARPopScrollViewDataSource> datasource;

/**
 * @property Delegate of the ARPopScrollView
 */
@property (nonatomic, weak)id<ARPopScrollViewDelegate> delegate;

@end


text:
/**
 * @brief  Hardware initialization for the iMote2
 * @author Andrew Barton-Sweeney (abs@cs.yale.edu)
 */

#include "hardware.h"
#include <kertable.h>
#include <kertable_proc.h>
#include <kertable_plat.h>
//#include "pxa27xhardware_once.h"

#include "pxa27x_init.h"
#include "dvfs.h"
#include "pmic.h"

#define LED_DEBUG
#include <led_dbg.h>

// Move the conditional includes into the sub-routines
#ifndef NO_SOS_UART
#include <uart_system.h>
#include <sos_uart.h>
#endif

#ifndef NO_SOS_I2C
#include <sos_i2c.h>
#include <sos_i2c_mgr.h>
#endif

//----------------------------------------------------------------------------
//  Typedefs
//----------------------------------------------------------------------------

//----------------------------------------------------------------------------
//  GLOBAL DATA
//----------------------------------------------------------------------------
//static uint8_t reset_flag NOINIT_VAR;

/**
 * @brief Kernel jump table
 * The table entries are defined in kertable.h
 */

/** Append any processor or platform specific kernel tables */
#if defined(PROC_KER_TABLE) && defined(PLAT_KER_TABLE)

PGM_VOID_P ker_jumptable[128] PROGMEM = SOS_KER_TABLE( CONCAT_TABLES(PROC_KER_TABLE , PLAT_KER_TABLE) );

#elif defined(PROC_KER_TABLE)

PGM_VOID_P ker_jumptable[128] PROGMEM = SOS_KER_TABLE(PROC_KER_TABLE);

#elif defined(PLAT_KER_TABLE)

PGM_VOID_P ker_jumptable[128] PROGMEM = SOS_KER_TABLE(PLAT_KER_TABLE);

#else

PGM_VOID_P ker_jumptable[128] PROGMEM = SOS_KER_TABLE(NULL);

#endif

//-------------------------------------------------------------------------
// FUNCTION DECLARATION
//-------------------------------------------------------------------------
// Move the conditional code to inside the init sub-routines
void hardware_init(void)
{
	uart_system_init();						// UART
#ifndef NO_SOS_UART
	//! Initalize uart comm channel
	sos_uart_init();
#endif
	//i2c_system_init();					// I2C
#ifndef NO_SOS_I2C
	//! Initalize i2c comm channel
	sos_i2c_init();
	sos_i2c_mgr_init();
#endif
	//adc_proc_init();						// ADC
#ifndef SOS_EMU
	mac_init();								// init the vmac and start the radio
#endif
}

/**
 * @brief functions for handling reset
 */
//void sos_watchdog_processing() __attribute__ ((naked)) __attribute__ ((section (".init3")));
void sos_watchdog_processing()
{
	return;
}

//-------------------------------------------------------------------------
// MAIN
//-------------------------------------------------------------------------
int main(void)
{
	oscc_init();							// Oscillator
	PSSR = (PSSR_RDH | PSSR_PH);   			// Reenable the GPIO buffers (needed out of reset)
	//SOS_SET_PIN_DIRECTIONS();				// GPIO
	DVFS_SwitchCoreFreq(104, 104);			// Switch to 104MHz mode
	//DVFS_SwitchCoreFreq(13, 13);			// Switch to 13MHz mode
	memory_init();							// SDRAM
	mmu_init();								// MMU
	//gpio_init();							// GPIO Interrupts
	//wdt_init();							// WATCHDOG
	PXA27XGPIOInt_init();
	pmic_init();
	led_init();								// LEDS
	//systime_init();						// LOCAL TIME
	timer_hardware_init(
		DEFAULT_INTERVAL, DEFAULT_SCALE);	// SYSTEM TIMER
	sos_main(SOS_BOOT_NORMAL);
	return 0;
}


text:
using namespace System;

namespace zuki::tools::llvm::clang {

//---------------------------------------------------------------------------
// Enum Linkage
//
// Describes the linkage of the entity referred to by a cursor
//---------------------------------------------------------------------------

public enum class Linkage
{
	Invalid			= CXLinkageKind::CXLinkage_Invalid,
	NoLinkage		= CXLinkageKind::CXLinkage_NoLinkage,
	Internal		= CXLinkageKind::CXLinkage_Internal,
	UniqueExternal	= CXLinkageKind::CXLinkage_UniqueExternal,
	External		= CXLinkageKind::CXLinkage_External,
};

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

} // zuki::tools::llvm::clang

#pragma warning(pop)

#endif	// __LINKAGE_H_


text:
package scouter.javassist.compiler.ast;

import java.io.Serializable;

import scouter.javassist.compiler.CompileError;
import scouter.javassist.compiler.ast.Visitor;

/**
 * Abstract Syntax Tree.  An ASTree object represents a node of
 * a binary tree.  If the node is a leaf node, both getLeft()
 * and getRight() returns null.
 */
public abstract class ASTree implements Serializable {
    public ASTree getLeft() { return null; }

    public ASTree getRight() { return null; }

    public void setLeft(ASTree _left) {}

    public void setRight(ASTree _right) {}

    /**
     * Is a method for the visitor pattern.  It calls
     * atXXX() on the given visitor, where
     * XXX is the class name of the node object.
     */
    public abstract void accept(Visitor v) throws CompileError;

    public String toString() {
        StringBuffer sbuf = new StringBuffer();
        sbuf.append('<');
        sbuf.append(getTag());
        sbuf.append('>');
        return sbuf.toString();
    }

    /**
     * Returns the type of this node.  This method is used by
     * toString().
     */
    protected String getTag() {
        String name = getClass().getName();
        return name.substring(name.lastIndexOf('.') + 1);
    }
}


text:
package de.iritgo.aktario.core.iobject;

import de.iritgo.aktario.core.event.EventListener;

/**
 */
public interface IObjectListListener extends EventListener
{
	public void iObjectListEvent(IObjectListEvent event);
}


text:
namespace fs = boost::filesystem;

// A path represents the location of a file in the
// file system.
using Path = fs::path;

// A sequence of paths.
using Path_seq = std::vector<Path>;

// An input file.
class File
{
public:
  File(char const*);

  Path const&   path() const     { return path_; }
  String const& pathname() const { return path_.string(); }

private:
  Path path_;
};

// -------------------------------------------------------------------------- //
// Kinds of files

// The different kinds of files that can be operated
// on by tools in the toolchain.
enum File_kind
{
  unspecified_file, // Not one of the files below.

  // Input languages
  beaker_file,     // Beaker source text

  // Intermediate languages
  ir_file,         // LLVM source text
  bitcode_file,    // LLVM bitcode
  asm_file,        // Native assembly source text

  // Binary representations
  object_file,     // Native objectd file
  library_file,    // Dynamic libraries (.so/.dylib/.dll)
  archive_file,    // Static libraries (.a/.lib)
  program_file     // Executable programs (<noext>/.exe)
};

File_kind get_file_kind(Path const&);

// Returns true if the file kind is the product
// of linking.
inline bool
is_linked_file(File_kind k)
{
  switch (k) {
    case library_file:
    case archive_file:
    case program_file:
      return true;
    default:
      return false;
  }
}

// Return a new path by replacing a .bkr extension
// with a .ll extension.
inline Path
to_ir_file(Path p)
{
  return p.replace_extension(".ll");
}

// Return a new path by replacing a .ll extension
// with a .s extension.
inline Path
to_asm_file(Path p)
{
  return p.replace_extension(".s");
}

// Return a new path by replacing a .s extension
// with a .o extension.
inline Path
to_object_file(Path p)
{
  return p.replace_extension(object_extension());
}

#endif


text:
package de.k4lly.enchant.listener;

import de.k4lly.enchant.controller.PluginController;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class Join implements Listener {

    private PluginController controller;

    public Join(PluginController controller) {
        this.controller=controller;
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent playerJoinEvent) {
        //System.out.print("[k4llyEnchant] Update checker will bei implemented soon.");
    }
}


text:
'use strict';

var config = require('../config/environment');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compose = require('composable-middleware');
var User = require('../api/user/user.model');
var validateJwt = expressJwt({secret: config.secrets.session});
var UnauthorizedError = require('../components/errors/unauthorized.error');
var common = require('../api/common');

/**
 * Attaches the user object to the request if authenticated
 * Otherwise returns 403
 */
exports.isAuthenticated = function () {
  return compose()
    // Validate jwt
    .use(function (req, res, next) {
      // allow access_token to be passed through query parameter as well
      /* jshint camelcase:false */
      if (req.query && req.query.hasOwnProperty('access_token')) {
        req.headers.authorization = 'Bearer ' + req.query.access_token;
      }
      validateJwt(req, res, next);
    })
    // Attach user to request
    .use(function (req, res, next) {
      User.findById(req.user._id, common.nextIfErr(next, function (user) {
        if (user) {
          req.user = user;
          next();
        } else {
          next(new UnauthorizedError('user_not_found', 'User not found'));
        }
      }));
    });
};

/**
 * Returns a jwt token signed by the app secret
 */
var signToken = exports.signToken = function (id, role, expiresInMinutes) {
  return jwt.sign({_id: id, role: role}, config.secrets.session, {expiresInMinutes: expiresInMinutes});
};

/**
 * Set token cookie directly for oAuth strategies
 */
exports.setToken = function (req, res) {
  if (req.user) {
    var token = signToken(req.user._id, req.user.role, config.tokenDuration.session);
    res.redirect('/login/' + token);
  } else {
    res.status(404).json({message: 'Something went wrong, please try again.'});
  }
};