text:
using System;
using System.Collections.Concurrent;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Threading.Tasks;
using Kerberos.NET.Entities;
using Kerberos.NET.Transport;
using Microsoft.Extensions.Logging;
using MessageHandlerConstructor = System.Func<System.ReadOnlyMemory<byte>, Kerberos.NET.Server.KdcServerOptions, Kerberos.NET.Server.KdcMessageHandlerBase>;
using PreAuthHandlerConstructor = System.Func<Kerberos.NET.Server.IRealmService, Kerberos.NET.Server.KdcPreAuthenticationHandlerBase>;

namespace Kerberos.NET.Server
{
    public class KdcServer
    {
        private readonly KdcServerOptions options;

        private readonly ILogger<KdcServer> logger;

        public KdcServer(KdcServerOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            this.options = options;
            this.logger = options.Log.CreateLoggerSafe<KdcServer>();

            if (options.Configuration.KdcDefaults.RegisterDefaultAsReqHandler)
            {
                this.RegisterMessageHandler(MessageType.KRB_AS_REQ, (message, op) => new KdcAsReqMessageHandler(message, op));
                this.RegisterPreAuthHandler(PaDataType.PA_ENC_TIMESTAMP, (service) => new PaDataTimestampHandler(service));

                if (options.Configuration.KdcDefaults.RegisterDefaultPkInitPreAuthHandler)
                {
                    this.RegisterPreAuthHandler(PaDataType.PA_PK_AS_REQ, (service) => new PaDataPkAsReqHandler(service));
                }
            }

            if (options.Configuration.KdcDefaults.RegisterDefaultTgsReqHandler)
            {
                this.RegisterMessageHandler(MessageType.KRB_TGS_REQ, (message, op) => new KdcTgsReqMessageHandler(message, op));
            }
        }

        private readonly ConcurrentDictionary<MessageType, MessageHandlerConstructor> messageHandlers =
            new ConcurrentDictionary<MessageType, MessageHandlerConstructor>();

        private readonly ConcurrentDictionary<PaDataType, PreAuthHandlerConstructor> preAuthHandlers =
            new ConcurrentDictionary<PaDataType, PreAuthHandlerConstructor>();

        public void RegisterMessageHandler(MessageType type, MessageHandlerConstructor builder)
        {
            ValidateSupportedMessageType(type);

            this.messageHandlers[type] = builder;
        }

        private static void ValidateSupportedMessageType(MessageType type)
        {
            if (!type.IsValidMessageType())
            {
                throw new InvalidOperationException(
                    $"Cannot register {type}. Can only register application messages >= 10 and <= 30"
                );
            }
        }

        public void RegisterPreAuthHandler(PaDataType type, PreAuthHandlerConstructor builder)
        {
            this.preAuthHandlers[type] = builder;
        }

        public async Task<ReadOnlyMemory<byte>> ProcessMessage(ReadOnlyMemory<byte> request)
        {
            // This should probably only process AS-REQs and TGS-REQs
            // Everything else should fail miserably with an error
            // But we'll leave it to the registered handlers to decide
            // what they are willing to process

            // but we also need to process Kdc Proxy messages

            var tag = KrbMessage.PeekTag(request);

            if (tag == Asn1Tag.Sequence && this.options.Configuration.KdcDefaults.ProxyEnabled)
            {
                try
                {
                    return await this.ProcessProxyMessageAsync(request).ConfigureAwait(false);
                }
                catch (Exception ex) when (IsProtocolException(ex))
                {
                    this.logger.LogWarning(ex, "Proxy message could not be parsed correctly");

                    return KdcMessageHandlerBase.GenerateGenericError(ex, this.options);
                }
            }

            return await this.ProcessMessageCoreAsync(request, tag).ConfigureAwait(false);
        }

        private static bool IsProtocolException(Exception ex)
        {
            // These checks should only apply when you're trying to return a graceful
            // failure to the client with a krb-error and a generic error message

            // All other failures should be handled by the caller

            if (ex is KerberosProtocolException || ex is KerberosValidationException || ex is KerberosTransportException)
            {
                return true;
            }

            if (ex is CryptographicException || ex is SecurityException)
            {
                return true;
            }

            if (ex is ArgumentException || ex is ArgumentNullException || ex is InvalidOperationException)
            {
                return true;
            }

            return false;
        }

        internal virtual async Task<ReadOnlyMemory<byte>> ProcessMessageCoreAsync(ReadOnlyMemory<byte> request, Asn1Tag tag)
        {
            KdcMessageHandlerBase messageHandler;

            try
            {
                messageHandler = this.LocateMessageHandler(request, tag);
            }
            catch (Exception ex) when (IsProtocolException(ex))
            {
                this.logger.LogWarning(ex, "Message handler could not be located for message");

                return KdcMessageHandlerBase.GenerateGenericError(ex, this.options);
            }

            try
            {
                return await messageHandler.ExecuteAsync().ConfigureAwait(false);
            }
            catch (Exception ex) when (IsProtocolException(ex))
            {
                this.logger.LogWarning(ex, "Message handler {MessageHandler} could not process message", messageHandler.GetType());

                return KdcMessageHandlerBase.GenerateGenericError(ex, this.options);
            }
        }

        private KdcMessageHandlerBase LocateMessageHandler(ReadOnlyMemory<byte> request, Asn1Tag tag)
        {
            MessageType messageType = KrbMessage.DetectMessageType(tag);

            ValidateSupportedMessageType(messageType);

            if (!this.messageHandlers.TryGetValue(messageType, out MessageHandlerConstructor builder))
            {
                throw new KerberosProtocolException(
                    KerberosErrorCode.KRB_ERR_GENERIC,
                    $"Application tag {messageType} doesn't have a message handler registered"
                );
            }

            var handler = builder(request, this.options);

            if (handler == null)
            {
                throw new InvalidOperationException($"Message handler builder {messageType} must not return null");
            }

            handler.RegisterPreAuthHandlers(this.preAuthHandlers);

            return handler;
        }

        private async Task<ReadOnlyMemory<byte>> ProcessProxyMessageAsync(ReadOnlyMemory<byte> request)
        {
            var proxyMessage = KdcProxyMessage.Decode(request);

            var unwrapped = proxyMessage.UnwrapMessage(out KdcProxyMessageMode mode);

            var tag = KrbMessage.PeekTag(unwrapped);

            var response = await this.ProcessMessageCoreAsync(unwrapped, tag).ConfigureAwait(false);

            return EncodeProxyResponse(response, mode);
        }

        private static ReadOnlyMemory<byte> EncodeProxyResponse(ReadOnlyMemory<byte> response, KdcProxyMessageMode mode)
        {
            return KdcProxyMessage.WrapMessage(response, mode: mode).Encode();
        }
    }
}


text:
/**
* @jsx React.DOM
*/

var _ = require('lodash');
var moment = require('moment');
var React = require('react/addons');
var AbsolutePicker = require('./absolute_picker.js');
var RelativePicker = require('./relative_picker.js');
var Select = require('./select.js');
var FieldsToggle = require('./fields_toggle.js');
var ReactSelect = require('./react_select.js');
var Timezone = require('./timezone.js');

var ExplorerActions = require('../../actions/ExplorerActions');
var ExplorerUtils = require('../../utils/ExplorerUtils');
var ProjectUtils = require('../../utils/ProjectUtils');

function relativeDefaults() {
  return {
    relativity: 'this',
    amount: '14',
    sub_timeframe: 'days'
  };
}

function absoluteDefaults() {
  return {
    start: new Date(moment().subtract(1, 'days').startOf('day').format()),
    end: new Date(moment().startOf('day').format())
  };
}

var Timeframe = React.createClass({

  toggleTimeframeType: function(event) {
    event.preventDefault();
    var type = event.currentTarget.dataset.type;
    var updates = _.cloneDeep(this.props.model);
    updates.timeframe_type = type;
    updates.query.time = (type === 'absolute') ? absoluteDefaults() : relativeDefaults();
    ExplorerActions.update(this.props.model.id, updates);
  },

  timeframeFieldsToggled: function(toggleState) {
    if (toggleState && !ExplorerUtils.getTimeframe(this.props.model)) {
      var updates = _.cloneDeep(this.props.model);
      if (this.isRelative()) {
        updates.query.time = relativeDefaults();
      } else {
        updates.query.time = absoluteDefaults();
      }
      ExplorerActions.update(this.props.model.id, updates);
    }
  },

  setInterval: function(event) {
    var updates = _.cloneDeep(this.props.model.query);
    updates.interval = event.target.value;
    ExplorerActions.update(this.props.model.id, { query: updates });
  },

  isAbsolute: function() {
    return this.props.model.timeframe_type === 'absolute';
  },

  isRelative: function() {
    return this.props.model.timeframe_type === 'relative';
  },

  intervalFieldsToggled: function(toggleState){
    if (toggleState && !this.props.model.query.interval) {
      var updates = _.cloneDeep(this.props.model.query);
      updates.interval = 'daily';
      ExplorerActions.update(this.props.model.id, { query: updates });
    }
  },

  buildIntervalInput: function(){
    if (this.props.model.query.analysis_type !== 'extraction') {
      var hasTimeframe = ExplorerUtils.getTimeframe(this.props.model) ? true : false;
      var warningMessage =
Intervals require a timeframe property.
;

      return (

          <FieldsToggle ref="interval-toggle"
                        name="Interval"
                        initialOpenState={this.props.model.query.interval}
                        attrsToStore={'interval'}
                        getFn={this.timeframeGetFn}
                        updateFn={this.timeframeUpdateFn}
                        toggleCallback={this.intervalFieldsToggled}>
            {hasTimeframe ? null : warningMessage}
            <Select label={false}
                    name="interval"
                    classes="interval-type"
                    options={ProjectUtils.getConstant('ABSOLUTE_INTERVAL_TYPES')}
                    emptyOption={false}
                    handleSelection={this.setInterval}
                    selectedOption={this.props.model.query.interval}
                    sort={false} />
          </FieldsToggle>

      );
    }
  },

  timeframeUpdateFn: function(updates) {
    ExplorerActions.update(this.props.model.id, {
      query: _.assign({}, this.props.model.query, updates)
    });
  },

  timeframeGetFn: function(attr) {
    return this.props.model.query[attr];
  },

  // React Methods

  render: function() {
    var timezone = this.props.model.query.timezone || ProjectUtils.getConstant('DEFAULT_TIMEZONE');
    var intervalToggle = this.buildIntervalInput();

    if (this.isAbsolute()) {
      var timeframePicker = <AbsolutePicker model={this.props.model}/>;
    } else {
      var timeframePicker = <RelativePicker relativeIntervalTypes={ProjectUtils.getConstant('RELATIVE_INTERVAL_TYPES')}
                                            model={this.props.model}/>;
    }

    return (

          <FieldsToggle name="Timeframe"
                        ref="toggle"
                        updateFn={this.timeframeUpdateFn}
                        getFn={this.timeframeGetFn}
                        initialOpenState={ExplorerUtils.getTimeframe(this.props.model)}
                        attrsToStore={['time', 'timezone']}
                        resetValues={
                          {
                            time: {},
                            timezone: ProjectUtils.getConstant('DEFAULT_TIMEZONE')
                          }
                        }
                        toggleCallback={this.timeframeFieldsToggled}>

                Relative

                Absolute

            {timeframePicker}
            <Timezone model={this.props.model} />
          </FieldsToggle>

        {intervalToggle}

    );
  }
});

module.exports = Timeframe;

redpajama_set_name: RedPajamaGithub


text:
/*
 * Authors:
 *   Keith Whitwell <keith@tungstengraphics.com>
 */

#include <sched.h>
#include <errno.h>

#include "main/glheader.h"
#include "main/imports.h"
#include "main/macros.h"
#include "main/context.h"
#include "swrast/swrast.h"

#include "radeon_common.h"
#include "r200_context.h"
#include "r200_ioctl.h"
#include "radeon_reg.h"

#define R200_TIMEOUT             512
#define R200_IDLE_RETRY           16

/* ================================================================
 * Buffer clear
 */
static void r200Clear( struct gl_context *ctx, GLbitfield mask )
{
   r200ContextPtr rmesa = R200_CONTEXT(ctx);
   GLuint flags = 0;
   GLuint orig_mask = mask;

   if ( R200_DEBUG & RADEON_IOCTL ) {
	   if (rmesa->radeon.sarea)
	       fprintf( stderr, "r200Clear %x %d\n", mask, rmesa->radeon.sarea->pfCurrentPage);
	   else
	       fprintf( stderr, "r200Clear %x radeon->sarea is NULL\n", mask);
   }

   radeonFlush( ctx );

   if ( mask & BUFFER_BIT_FRONT_LEFT ) {
      flags |= RADEON_FRONT;
      mask &= ~BUFFER_BIT_FRONT_LEFT;
   }

   if ( mask & BUFFER_BIT_BACK_LEFT ) {
      flags |= RADEON_BACK;
      mask &= ~BUFFER_BIT_BACK_LEFT;
   }

   if ( mask & BUFFER_BIT_DEPTH ) {
      flags |= RADEON_DEPTH;
      mask &= ~BUFFER_BIT_DEPTH;
   }

   if ( (mask & BUFFER_BIT_STENCIL) ) {
      flags |= RADEON_STENCIL;
      mask &= ~BUFFER_BIT_STENCIL;
   }

   if ( mask ) {
      if (R200_DEBUG & RADEON_FALLBACKS)
	 fprintf(stderr, "%s: swrast clear, mask: %x\n", __FUNCTION__, mask);
      _swrast_Clear( ctx, mask );
   }

   if ( !flags )
      return;

   if (rmesa->using_hyperz) {
      flags |= RADEON_USE_COMP_ZBUF;
/*      if (rmesa->radeon.radeonScreen->chip_family == CHIP_FAMILY_R200)
	 flags |= RADEON_USE_HIERZ; */
      if (!((flags & RADEON_DEPTH) && (flags & RADEON_STENCIL) &&
	    ((rmesa->radeon.state.stencil.clear & R200_STENCIL_WRITE_MASK) == R200_STENCIL_WRITE_MASK))) {
	  flags |= RADEON_CLEAR_FASTZ;
      }
   }

   radeonUserClear(ctx, orig_mask);
}

GLboolean r200IsGartMemory( r200ContextPtr rmesa, const GLvoid *pointer,
			   GLint size )
{
   ptrdiff_t offset = (char *)pointer - (char *)rmesa->radeon.radeonScreen->gartTextures.map;
   int valid = (size >= 0 &&
		offset >= 0 &&
		offset + size < rmesa->radeon.radeonScreen->gartTextures.size);

   if (R200_DEBUG & RADEON_IOCTL)
      fprintf(stderr, "r200IsGartMemory( %p ) : %d\n", pointer, valid );

   return valid;
}

GLuint r200GartOffsetFromVirtual( r200ContextPtr rmesa, const GLvoid *pointer )
{
   ptrdiff_t offset = (char *)pointer - (char *)rmesa->radeon.radeonScreen->gartTextures.map;

   if (offset < 0 || offset > rmesa->radeon.radeonScreen->gartTextures.size)
      return ~0;
   else
      return rmesa->radeon.radeonScreen->gart_texture_offset + offset;
}

void r200InitIoctlFuncs( struct dd_function_table *functions )
{
    functions->Clear = r200Clear;
    functions->Finish = radeonFinish;
    functions->Flush = radeonFlush;
}


text:
package cn.netkiller.component;

import org.springframework.stereotype.Component;

@Component
@Aspect
public class NeoLoggerAspect {
	@Pointcut("@annotation(cn.netkiller.annotation.NeoLogger)")
    private void cut() { }

    @Around("cut()")
    public void advice(ProceedingJoinPoint joinPoint){
        System.out.println("@Around Begin");
        try {
            joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("@Around End");
    }

    @Before("cut()")
    public void before() {
        this.printLog("@Before");
    }

    @After("recordLog()")
    public void after() {
        this.printLog("@After");
    }
}


text:
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const baseConfig = require('./webpack.config.js');

// tell webpack to leave node_modules alone
// http://jlongster.com/Backend-Apps-with-Webpack--Part-I
const nodeModules = {};
fs.readdirSync('node_modules')
    .filter(x => ['.bin'].indexOf(x) === -1)
    .forEach(mod => (nodeModules[mod] = `commonjs ${mod}`));

// add any that don't fit the above pattern
nodeModules['react-dom/server'] = 'commonjs react-dom/server';
nodeModules['react-router'] = 'commonjs react-router';

module.exports = Object.assign(baseConfig, {
  target: 'node',
  entry: [
    'src/web/server/serverSideRender.tsx',
  ],
  output: {
    path: path.join(__dirname, 'dist/ssr'),
    filename: 'serverSideRender.js',
    libraryTarget: 'commonjs2',
  },
  externals: nodeModules,
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        include: __dirname,
        use: ExtractTextPlugin.extract({
          use: [
            {
              loader: 'css-loader',
              options: {
                localIdentName: '[hash:base64]-[name]-[local]',
                modules: true,
              },
            },
            {
              loader: 'sass-loader',
            },
          ],
        }),
      },
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      __CLIENT__: false,
    }),
    new ExtractTextPlugin('styles.css'),
  ],
});


text:
NATabBarController
=========================

NATabBarController is a fully customizable subclass of UITabBarController with additional features.

Features
--------

- Full customizable look
- A popup menu replacement for the 'More Navigation Controller'
- Different tab bar height for portrait and landscape
- Uses the default UITabBarControllerDelegate
- Supported on iPhone and iPad with iOS 5 onwards
- Requires ARC

Installation
------------

1. Add the `NATabBarController` folder to your Xcode project

2. Import the `NATabBarController.h` file

Usage
-----

Usage is similar to that of a typical UITabBarController. NATabBarController will use the titles and images specified in the `tabBarItem` property of each view controller.

You can also specify a different height for the tab bar when in landscape mode.

    self.tabBarController = [[NATabBarController alloc] initWithViewControllers:viewControllers tabBarHeight:44];
    [self.tabBarController setTabBarLandscapeHeight:32];

Customization
-------------

To customize the look of the tab bar, access the `tabBarView` property of NATabBarController and use the following methods:

    - (void)setBackgroundImage:(UIImage *)image
    - (void)setSelectedTabBackgroundImage:(UIImage *)image
    - (void)setMoreTabImage:(UIImage *)image selectedImage:(UIImage *)selectedImage


text:
CFLAGS=-Wall -g

all: smaris_dungeon

smaris_dungeon: object.o

clean:
	rm -f smaris_dungeon
	rm -f object.o


text:
import { Model } from '../index';

export interface IProfile {
  profile: Model.Profile;
  loading: boolean;
}


text:
#ifndef BOUNDS_H_HEADER_GUARD
#define BOUNDS_H_HEADER_GUARD

struct Aabb
{
	float m_min[3];
	float m_max[3];
};

struct Cylinder
{
	float m_pos[3];
	float m_end[3];
	float m_radius;
};

struct Disk
{
	float m_center[3];
	float m_normal[3];
	float m_radius;
};

struct Obb
{
	float m_mtx[16];
};

struct Plane
{
	float m_normal[3];
	float m_dist;
};

struct Ray
{
	float m_pos[3];
	float m_dir[3];
};

struct Sphere
{
	float m_center[3];
	float m_radius;
};

struct Tris
{
	float m_v0[3];
	float m_v1[3];
	float m_v2[3];
};

struct Intersection
{
	float m_pos[3];
	float m_normal[3];
	float m_dist;
};

/// Convert axis aligned bounding box to oriented bounding box.
void aabbToObb(Obb& _obb, const Aabb& _aabb);

/// Convert sphere to axis aligned bounding box.
void sphereToAabb(Aabb& _aabb, const Sphere& _sphere);

/// Calculate surface area of axis aligned bounding box.
float calcAabbArea(Aabb& _aabb);

/// Calculate axis aligned bounding box.
void calcAabb(Aabb& _aabb, const void* _vertices, uint32_t _numVertices, uint32_t _stride);

/// Transform vertices and calculate axis aligned bounding box.
void calcAabb(Aabb& _aabb, const float* _mtx, const void* _vertices, uint32_t _numVertices, uint32_t _stride);

/// Expand AABB.
void aabbExpand(Aabb& _aabb, float _factor);

/// Returns 0 is two AABB don't overlap, otherwise returns flags of overlap
/// test.
uint32_t aabbOverlapTest(const Aabb& _aabb0, const Aabb& _aabb1);

/// Calculate oriented bounding box.
void calcObb(Obb& _obb, const void* _vertices, uint32_t _numVertices, uint32_t _stride, uint32_t _steps = 17);

/// Calculate maximum bounding sphere.
void calcMaxBoundingSphere(Sphere& _sphere, const void* _vertices, uint32_t _numVertices, uint32_t _stride);

/// Calculate minimum bounding sphere.
void calcMinBoundingSphere(Sphere& _sphere, const void* _vertices, uint32_t _numVertices, uint32_t _stride, float _step = 0.01f);

/// Returns 6 (near, far, left, right, top, bottom) planes representing frustum planes.
void buildFrustumPlanes(Plane* _planes, const float* _viewProj);

/// Returns point from 3 intersecting planes.
void intersectPlanes(float _result[3], const Plane& _pa, const Plane& _pb, const Plane& _pc);

/// Make screen space ray from x, y coordinate and inverse view-projection matrix.
Ray makeRay(float _x, float _y, const float* _invVp);

/// Intersect ray / aabb.
bool intersect(const Ray& _ray, const Aabb& _aabb, Intersection* _intersection = NULL);

/// Intersect ray / cylinder.
bool intersect(const Ray& _ray, const Cylinder& _cylinder, bool _capsule, Intersection* _intersection = NULL);

/// Intersect ray / disk.
bool intersect(const Ray& _ray, const Disk& _disk, Intersection* _intersection = NULL);

/// Intersect ray / plane.
bool intersect(const Ray& _ray, const Plane& _plane, Intersection* _intersection = NULL);

/// Intersect ray / sphere.
bool intersect(const Ray& _ray, const Sphere& _sphere, Intersection* _intersection = NULL);

/// Intersect ray / triangle.
bool intersect(const Ray& _ray, const Tris& _triangle, Intersection* _intersection = NULL);

#endif // BOUNDS_H_HEADER_GUARD


text:
@implementation SeriesObject

-(id)init {

    self = [super init];

    if (self) {

        _seasonID = @"";
        _topTeam = @"";
        _bottomTeam = @"";
        _conference = @"";
    }

    return self;
}

-(NSString *)getSeriesID {
    return [NSString stringWithFormat:@"%@0%d%d%%", _seasonID, _round, [self normalizedSeed]];
}

-(NSString *)getRelativeSeriesID {
    return [NSString stringWithFormat:@"%d%d", _round, [self normalizedSeed]];
}

-(int)normalizedSeed {

    int westOffset = 0;

    if ([_conference isEqualToString:@"w"]) {

        switch (_round) {
            case 1:
                westOffset = 4;
                break;
            case 2:
                westOffset = 2;
                break;
            case 3:
                westOffset = 1;
                break;
            default:
                westOffset = 0;
                break;
        }
    }

    return _seed + westOffset;
}

-(NSString *)description {
    return [self pm_description];
}

@end


text:
actions   :create, :destroy

# House keeping
attribute :name,  :kind_of => String, :name_attribute => true
attribute :user,  :kind_of => String, :default => "redis"
attribute :group, :kind_of => String, :default => "redis"
attribute :init_style,      :kind_of => String, :default => "init"
attribute :pidfile,         :kind_of => String
attribute :log_file,        :kind_of => String
attribute :conf_dir,        :kind_of => String, :default => "/etc/redis"
attribute :daemonize,       :kind_of => [TrueClass, FalseClass], :default => true

# Interesting part
attribute :master_name,             :kind_of => String, :required => true
attribute :monitor_address,         :kind_of => String, :default => "127.0.0.1"
attribute :monitor_port,            :kind_of => Fixnum, :default => 6379
attribute :monitor,                 :kind_of => String
attribute :down_after_milliseconds, :kind_of => Fixnum, :default => 60000
attribute :failover_timeout,        :kind_of => Fixnum, :default => 900000
attribute :can_failover,            :kind_of => [TrueClass, FalseClass], :default => true
attribute :parallel_syncs,          :kind_of => Fixnum, :default => 1
attribute :quorum,                  :kind_of => Fixnum, :default => 2
attribute :port,                    :kind_of => Fixnum, :default => 26379

# Example generated config
#sentinel monitor mymaster 127.0.0.1 6379 2
#sentinel down-after-milliseconds mymaster 60000
#sentinel failover-timeout mymaster 900000
#sentinel can-failover mymaster yes
#sentinel parallel-syncs mymaster 1

def initialize(*args)
  super
  @action = :create
end

state_attrs(
  :monitor,
  :down_after_milliseconds,
  :failover_timeout,
  :can_failover,
  :parallel_syncs
)


text:
var React = require('react');

var RadioItem = React.createClass({
  render: function() {
    return (

          <input type="radio" {...this.props}/>

    );
  }
});

module.exports = RadioItem;


text:
These files make it easy to launch command-line apps from spotlight. To use them:

- Run `chmod +x` on each command to make it executable.
- Update `pugdebug.command` to point to your copy of pugdebug.
- Configure terminal to [close if the shell exited cleanly](http://superuser.com/a/158376/284351) so you don't have an extra terminal window hanging around after the command runs.
- Type `pugdebug.command` or even just `pugdebug.com` into spotlight to launch the app!


text:
package org.ovirt.engine.extensions.aaa.builtin.kerberosldap.utils.kerberos;

public enum AuthenticationResult {
    OK("", 0),

    INVALID_CREDENTIALS(
            "Authentication Failed. Please verify the username and password.",
            11),

    CLOCK_SKEW_TOO_GREAT(
            "Authentication Failed. The Engine clock is not synchronized with directory services (must be within 5"
                    + " minutes difference). Please verify the clocks are synchronized",
            12),

    NO_KDCS_FOUND(
            "Authentication Failed. Please verify the fully qualified domain name that is used for authentication is"
                    + " correct.",
            13),

    DNS_ERROR(
            "Authentication Failed. Error in DNS configuration. Please verify the Engine host has a valid reverse"
                    + " DNS (PTR) record.",
            14),

    OTHER(
            "Kerberos error. Please check log for further details.",
            15),

    USER_ACCOUNT_DISABLED_OR_LOCKED(
            "Authentication failed. The user is either locked or disabled",
            16),

    DNS_COMMUNICATION_ERROR(
            "Authentication Failed. Cannot lookup DNS for SRV records. Please check your DNS configuration",
            17),

    CONNECTION_TIMED_OUT(
            "Authentication Failed. Connection to LDAP server has timed out. Please contact your system"
                    + " administrator",
            18),

    WRONG_REALM(
            "Authentication Failed. Wrong domain name was provided for authentication.",
            19),

    CONNECTION_ERROR(
            "Connection refused or some configuration problems exist. Possible DNS error." +
                    " Check your Kerberos and LDAP records",
            20),

    CANNOT_FIND_LDAP_SERVER_FOR_DOMAIN(
            "Cannot find valid LDAP server for domain",
            21),

    NO_USER_INFORMATION_WAS_FOUND_FOR_USER(
            "No user information was found for user",
            22),

    PASSWORD_EXPIRED(
            "Authentication Failed. The password has expired. Please change your password and login again.",
            23),

    CLIENT_NOT_FOUND_IN_KERBEROS_DATABASE(
            "Authentication Failed. Client not found in kerberos database.",
            24),

    INTERNAL_KERBEROS_ERROR(
            "An internal error has ocurred in the Kerberos implementation of the Java virtual machine. This usually"
                    + " means that the LDAP server is configured with a minimum security strength factor (minssf)"
                    + " of 0. Change it to 1 and try again.",
            25);

    private String detailedMessage;
    private final int exitCode;

    private AuthenticationResult(String detailedMsg, int exitCode) {
        this.detailedMessage = detailedMsg;
        this.exitCode = exitCode;
    }

    public String getDetailedMessage() {
        return detailedMessage;
    }

    public int getExitCode() {
        return exitCode;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<folder exportedWithPermissions="false">
    <parent>/public/SESamples/ExtraSamples/Resources/OLAP</parent>
    <name>Schemas</name>
    <label>Schemas</label>
    <description></description>
    <creationDate>2014-06-19T19:06:37.110+02:00</creationDate>
    <updateDate>2013-04-04T10:27:26.000+02:00</updateDate>
</folder>


text:
function [ alpha ] = backtracking_line_search(problem, p, x, rho, c)
% Backtracking line search
%
% Inputs:
%       problem     function (cost/grad/hess)
%       p           search direction
%       x           current iterate
%       rho         backtrack step between (0,1), e.g., 1/2
%       c           parameter between 0 and 1, e.g., 1e^-4
% Output:
%       alpha       step size calculated by this algorithm
%
% Reference:
%       Jorge Nocedal and Stephen Wright,
%       "Numerical optimization,"
%       Springer Science & Business Media, 2006.
%
%       Algorithm 3.1 in Section 3.1.
%
%
% This file is part of GDLibrary.
%
% Created by H.Kasai on Feb. 29, 2016

    alpha = 1;
    f0 = problem.cost(x);
    g0 = problem.full_grad(x);
    x0 = x;
    x = x + alpha * p;
    fk = problem.cost(x);

    % repeat until the Armijo condition meets
    while fk > f0 + c * alpha * (g0'*p)
      alpha = rho * alpha;
      x = x0 + alpha * p;
      fk = problem.cost(x);
    end

end


text:
package armrecoveryservicessiterecovery

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// ReplicationVaultSettingClient contains the methods for the ReplicationVaultSetting group.
// Don't use this type directly, use NewReplicationVaultSettingClient() instead.
type ReplicationVaultSettingClient struct {
	host              string
	resourceName      string
	resourceGroupName string
	subscriptionID    string
	pl                runtime.Pipeline
}

// NewReplicationVaultSettingClient creates a new instance of ReplicationVaultSettingClient with the specified values.
// resourceName - The name of the recovery services vault.
// resourceGroupName - The name of the resource group where the recovery services vault is present.
// subscriptionID - The subscription Id.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewReplicationVaultSettingClient(resourceName string, resourceGroupName string, subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ReplicationVaultSettingClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &ReplicationVaultSettingClient{
		resourceName:      resourceName,
		resourceGroupName: resourceGroupName,
		subscriptionID:    subscriptionID,
		host:              ep,
		pl:                pl,
	}
	return client, nil
}

// BeginCreate - The operation to configure vault setting.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-01
// vaultSettingName - Vault setting name.
// input - Vault setting creation input.
// options - ReplicationVaultSettingClientBeginCreateOptions contains the optional parameters for the ReplicationVaultSettingClient.BeginCreate
// method.
func (client *ReplicationVaultSettingClient) BeginCreate(ctx context.Context, vaultSettingName string, input VaultSettingCreationInput, options *ReplicationVaultSettingClientBeginCreateOptions) (*runtime.Poller[ReplicationVaultSettingClientCreateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.create(ctx, vaultSettingName, input, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[ReplicationVaultSettingClientCreateResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[ReplicationVaultSettingClientCreateResponse](options.ResumeToken, client.pl, nil)
	}
}

// Create - The operation to configure vault setting.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-01
func (client *ReplicationVaultSettingClient) create(ctx context.Context, vaultSettingName string, input VaultSettingCreationInput, options *ReplicationVaultSettingClientBeginCreateOptions) (*http.Response, error) {
	req, err := client.createCreateRequest(ctx, vaultSettingName, input, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// createCreateRequest creates the Create request.
func (client *ReplicationVaultSettingClient) createCreateRequest(ctx context.Context, vaultSettingName string, input VaultSettingCreationInput, options *ReplicationVaultSettingClientBeginCreateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultSettings/{vaultSettingName}"
	if client.resourceName == "" {
		return nil, errors.New("parameter client.resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(client.resourceName))
	if client.resourceGroupName == "" {
		return nil, errors.New("parameter client.resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(client.resourceGroupName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if vaultSettingName == "" {
		return nil, errors.New("parameter vaultSettingName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{vaultSettingName}", url.PathEscape(vaultSettingName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-02-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, input)
}

// Get - Gets the vault setting. This includes the Migration Hub connection settings.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-01
// vaultSettingName - Vault setting name.
// options - ReplicationVaultSettingClientGetOptions contains the optional parameters for the ReplicationVaultSettingClient.Get
// method.
func (client *ReplicationVaultSettingClient) Get(ctx context.Context, vaultSettingName string, options *ReplicationVaultSettingClientGetOptions) (ReplicationVaultSettingClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, vaultSettingName, options)
	if err != nil {
		return ReplicationVaultSettingClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return ReplicationVaultSettingClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return ReplicationVaultSettingClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *ReplicationVaultSettingClient) getCreateRequest(ctx context.Context, vaultSettingName string, options *ReplicationVaultSettingClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultSettings/{vaultSettingName}"
	if client.resourceName == "" {
		return nil, errors.New("parameter client.resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(client.resourceName))
	if client.resourceGroupName == "" {
		return nil, errors.New("parameter client.resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(client.resourceGroupName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if vaultSettingName == "" {
		return nil, errors.New("parameter vaultSettingName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{vaultSettingName}", url.PathEscape(vaultSettingName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-02-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *ReplicationVaultSettingClient) getHandleResponse(resp *http.Response) (ReplicationVaultSettingClientGetResponse, error) {
	result := ReplicationVaultSettingClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.VaultSetting); err != nil {
		return ReplicationVaultSettingClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - Gets the list of vault setting. This includes the Migration Hub connection settings.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-01
// options - ReplicationVaultSettingClientListOptions contains the optional parameters for the ReplicationVaultSettingClient.List
// method.
func (client *ReplicationVaultSettingClient) NewListPager(options *ReplicationVaultSettingClientListOptions) *runtime.Pager[ReplicationVaultSettingClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[ReplicationVaultSettingClientListResponse]{
		More: func(page ReplicationVaultSettingClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *ReplicationVaultSettingClientListResponse) (ReplicationVaultSettingClientListResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listCreateRequest(ctx, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return ReplicationVaultSettingClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return ReplicationVaultSettingClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return ReplicationVaultSettingClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

// listCreateRequest creates the List request.
func (client *ReplicationVaultSettingClient) listCreateRequest(ctx context.Context, options *ReplicationVaultSettingClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationVaultSettings"
	if client.resourceName == "" {
		return nil, errors.New("parameter client.resourceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(client.resourceName))
	if client.resourceGroupName == "" {
		return nil, errors.New("parameter client.resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(client.resourceGroupName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-02-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *ReplicationVaultSettingClient) listHandleResponse(resp *http.Response) (ReplicationVaultSettingClientListResponse, error) {
	result := ReplicationVaultSettingClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.VaultSettingCollection); err != nil {
		return ReplicationVaultSettingClientListResponse{}, err
	}
	return result, nil
}


text:
<!--

-->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.libraries.mobiledatadownload.internal.util">
  <uses-sdk
      android:minSdkVersion="16"
      android:targetSdkVersion="27"/>
  <application>
    <uses-library android:name="android.test.runner" />
  </application>
  <instrumentation
      android:name="com.google.android.apps.common.testing.testrunner.Google3InstrumentationTestRunner"
      android:targetPackage="com.google.android.libraries.mobiledatadownload.internal.util" />
</manifest>


text:
"""
Problem Testing Module
"""

import pytest
import re

import api

from api.common import APIException
from common import clear_collections, ensure_empty_collections, clear_cache
from common import new_team_user
from conftest import setup_db, teardown_db

class TestProblems(object):
    """
    API Tests for problem.py
    """

    # test keys
    correct = "test"
    wrong = "wrong"
    fake_sid = "acdb6a09cd2bae5f1bf53ed186a17248"

    def generate_base_problems(correct):
        """A workaround for python3's list comprehension scoping"""
        # create 5 base problems
        base_problems = [
            {
                "name": "base-" + str(i),
                "sanitized_name": "base-" + str(i),
                "score": 10,
                "author": "haxxor",
                "category": "Binary Exploitation",
                "description": "Base problem " + str(i),
                "hints": ["test", "test2"],
                "instances": [
                    {
                        "description": "Base problem " + str(i),
                        "flag": correct,
                        "iid": 0,
                        "server": "hack.com",
                        "instance_number": 0
                    }
                ]
            }
            for i in range(5)
        ]

        return base_problems

    base_problems = generate_base_problems(correct)

    def generate_disabled_problems(correct):
        """A workaround for python3's list comprehension scoping"""
        # create 5 disabled problems
        disabled_problems = [
            {
                "name" : "locked-" + str(i),
                "sanitized_name": "locked-" + str(i),
                "author": "haxxor",
                "score" : 10,
                "category": "Reverse Engineering",
                "description" : "Test",
                "hints": ["test", "test2"],
                "instances": [
                    {
                        "description": "disabled problem " + str(i),
                        "flag": correct,
                        "iid": 0,
                        "server": "hack.com",
                        "instance_number": 0
                    }
                ]
            }
            for i in range(5)
        ]
        return disabled_problems

    disabled_problems = generate_disabled_problems(correct)

    def generate_problems(correct, base_problems):
        """A workaround for python3's list comprehension scoping"""

        # create 5 level1 problems
        level1_problems = [
            {
                "name" : "level1-" + str(i),
                "sanitized_name": "level1-" + str(i),
                "score" : 60,
                "author": "haxxor",
                "category": "Forensics",
                "hints": ["test", "test"],
                "description" : "Level1 problem " + str(i),
                "instances": [
                    {
                        "description": "Level1 problem " + str(i),
                        "flag": correct,
                        "iid": 0,
                        "server": "hack.com",
                        "instance_number": 0
                    }
                ]
            }
            for i in range(5)
        ]

        return level1_problems

    level1_problems = generate_problems(correct, base_problems)

    def generate_bundle(base_problems, level1_problems):
        bundle = {
            "name": "test bundle",
            "author": "hacker joe",
            "categories": ["Test Problems"],
            "problems": [p["sanitized_name"] for p in base_problems+level1_problems],
            "description": "this is a test bundle",
        }

        dependencies = {}
        for p in level1_problems:
            dependency = {}
            dependency["weightmap"] = {dst["sanitized_name"]:1 for dst in base_problems}
            dependency["threshold"] = len(base_problems)
            dependencies[p["sanitized_name"]] = dependency

        bundle["dependencies"] = dependencies
        return bundle

    bundle = generate_bundle(base_problems, level1_problems)

    enabled_problems = base_problems + level1_problems
    all_problems = enabled_problems + disabled_problems

    def setup_class(self):
        """
        Class setup code
        """

        setup_db()

        # initialization code
        self.uid = api.user.create_simple_user_request(new_team_user)
        self.tid = api.user.get_team(uid=self.uid)['tid']

        # insert all problems
        self.base_pids = []
        for problem in self.base_problems:
            pid = api.problem.insert_problem(problem,self.fake_sid)
            api.problem.update_problem(pid, {"disabled": False})
            self.base_pids.append(pid)

        self.enabled_pids = self.base_pids[:]
        for problem in self.level1_problems:
            pid = api.problem.insert_problem(problem,self.fake_sid)
            api.problem.update_problem(pid, {"disabled": False})
            self.enabled_pids.append(pid)

        self.disabled_pids = []
        for problem in self.disabled_problems:
            pid = api.problem.insert_problem(problem,self.fake_sid)
            self.disabled_pids.append(pid)

        self.all_pids = self.enabled_pids + self.disabled_pids

        # set the key as though they were generated properly
        # TODO: actually run generation
        for problem in api.problem.get_all_problems():
            api.problem.update_problem(problem["pid"], {"key":self.correct})

        # insert bundle and enable dependencies
        api.problem.insert_bundle(self.bundle)
        api.problem.set_bundle_dependencies_enabled(self.bundle["bid"], True)

    def teardown_class(self):
        teardown_db()

    def test_insert_problems(self):
        """
        Tests problem insertion.

        Covers:
            problem.insert_problem
            problem.get_problem
            problem.get_all_problems
        """

        # problems were inserted in initialization - try to insert the problems again
        for problem in self.all_problems:
            with pytest.raises(APIException):
                api.problem.insert_problem(problem,self.fake_sid)
                api.problem.update_problem(problem["pid"], {"disabled": False})
                assert False, "Was able to insert a problem twice."

        # verify that the enabled problems match
        db_problems = api.problem.get_all_problems()
        for problem in db_problems:
            assert problem['pid'] in self.enabled_pids, "Problems do not match"
            assert problem['pid'] not in self.disabled_pids, "Problem should not be enabled"

        # verify that the disabled problems match
        db_all_problems = api.problem.get_all_problems(show_disabled=True)
        for problem in db_problems:
            assert problem['pid'] in self.all_pids

    @ensure_empty_collections("submissions")
    @clear_collections("submissions")
    @clear_cache()
    def test_submissions(self):
        """
        Tests key submissions.

        Covers:
            problem.submit_key
            problem.get_submissions
            problem.get_team_submissions
        """

        # test correct submissions
        for problem in self.base_problems[:2]:
            result = api.problem.submit_key(self.tid, problem['pid'], self.correct, uid=self.uid)
            assert result['correct'], "Correct key was not accepted"
            assert result['points'] == problem['score'], "Did not return correct score"

            solved = api.problem.get_solved_pids(self.tid)
            assert problem['pid'] in solved

        # test incorrect submissions
        for problem in self.base_problems[2:]:
            result = api.problem.submit_key(self.tid, problem['pid'], self.wrong+"asd", uid=self.uid)
            assert not result['correct'], "Incorrect key was accepted"
            assert result['points'] == problem['score'], "Did not return correct score"

            solved = api.problem.get_solved_problems(self.tid)
            assert api.problem.get_problem(pid=problem['pid']) not in solved

        # test submitting correct twice
        with pytest.raises(APIException):
            api.problem.submit_key(self.tid, self.base_problems[0]['pid'], self.correct, uid=self.uid)
            assert False, "Submitted key to problem that was already solved"

        # test submitting to disabled problem
        with pytest.raises(APIException):
            api.problem.submit_key(self.tid, self.disabled_problems[0]['pid'], self.correct, uid=self.uid)
            assert False, "Submitted key to disabled problem"

        # test getting submissions two ways
        assert len(api.problem.get_submissions(uid=self.uid)) == len(self.base_problems)
        assert len(api.problem.get_submissions(tid=self.tid)) == len(self.base_problems)

    @ensure_empty_collections("submissions")
    @clear_collections("submissions")
    @clear_cache()
    def test_get_unlocked_problems(self):
        """
        Tests getting the unlocked problems

        Covers:
            problem.get_unlocked_problems
            problem.submit_key
        """

        # check that base problems are unlocked
        unlocked = api.problem.get_unlocked_problems(self.tid)
        unlocked_pids = [p['pid'] for p in unlocked]
        for pid in self.base_pids:
            assert pid in unlocked_pids, "Base problem didn't unlock"

        # unlock more problems
        for problem in self.base_problems:
            api.problem.submit_key(self.tid, problem['pid'], self.correct, uid=self.uid)

        unlocked_pids = api.problem.get_unlocked_pids(self.tid)

        for pid in unlocked_pids:
            assert pid not in self.disabled_pids, "Disabled problem is unlocked"

        for pid in self.enabled_pids:
            assert pid in unlocked_pids, "Level1 problem didn't unlock"

    @ensure_empty_collections("submissions")
    @clear_collections("submissions", "problems")
    @clear_cache()
    def test_scoring(self):
        correct_total = 0
        for i, pid in enumerate(self.enabled_pids):
            problem = api.problem.get_problem(pid=pid)
            score = api.problem.submit_key(self.tid, problem['pid'], self.correct, uid=self.uid)['points']
            correct_total += problem['score']
            assert score == problem['score'], "submit_key return wrong score"
            team_total = api.stats.get_score(tid=self.tid)
            user_total = api.stats.get_score(uid=self.uid)
            solved_problems = api.problem.get_solved_pids(tid=self.tid)

            assert len(solved_problems) == i+1, "The team has solved too many problems."
            assert api.stats.get_score(tid=self.tid) == correct_total, "Team score is calculating incorrectly!"
            assert api.stats.get_score(uid=self.uid) == correct_total, "User score is calculating incorrectly!"


text:
package no.nrk.ietf.rfc7519.jwt;

import java.util.Date;

import no.nrk.common.util.ToString;

/**
 * From https://tools.ietf.org/html/rfc7519: <tt>
 * A JSON numeric value representing the number of seconds from
 * 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap
 * seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1]
 * definition "Seconds Since the Epoch", in which each day is accounted for by
 * exactly 86400 seconds, other than that non-integer values can be represented.
 * See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in
 * particular.
 * </tt>
 */
public abstract class NumericDate {

	/**
	 * Ignores leap seconds.
	 */
	public abstract long secondsSinceEpoch();

	/**
	 * Implementors should do a best-effort in handling leap-seconds as well and
	 * not only base it on {@link #secondsSinceEpoch()}.
	 */
	public abstract Date asDate();

	@Override
	public int hashCode() {
		return 37 * Long.valueOf(secondsSinceEpoch()).hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof NumericDate) {
			NumericDate rhs = (NumericDate) obj;
			return secondsSinceEpoch() == rhs.secondsSinceEpoch();
		}
		return false;
	}

	@Override
	public String toString() {
		return ToString.of(this)
				.with("secondsSinceEpoch", secondsSinceEpoch())
				.toString();
	}
}