text:
package oap.http.server.nio;

import com.google.common.base.Preconditions;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;
import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.conduits.GzipStreamSourceConduit;
import io.undertow.conduits.InflatingStreamSourceConduit;
import io.undertow.server.ConnectorStatistics;
import io.undertow.server.handlers.BlockingHandler;
import io.undertow.server.handlers.BlockingReadTimeoutHandler;
import io.undertow.server.handlers.GracefulShutdownHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.encoding.ContentEncodingRepository;
import io.undertow.server.handlers.encoding.DeflateEncodingProvider;
import io.undertow.server.handlers.encoding.EncodingHandler;
import io.undertow.server.handlers.encoding.GzipEncodingProvider;
import io.undertow.server.handlers.encoding.RequestEncodingHandler;
import lombok.extern.slf4j.Slf4j;
import oap.util.Dates;
import org.xnio.Options;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class NioHttpServer implements Closeable, AutoCloseable {
    public final int defaultPort;

    private final HashMap<Integer, PathHandler> pathHandler = new HashMap<>();
    private final ContentEncodingRepository contentEncodingRepository;
    private final AtomicLong requestId = new AtomicLong();
    public int backlog = -1;
    public long idleTimeout = -1;
    public boolean tcpNodelay = true;
    public int ioThreads = -1; // default = max(2, Runtime.getRuntime().availableProcessors())
    public int workerThreads = -1; // default = Runtime.getRuntime().availableProcessors() * 8
    public long maxEntitySize = -1; // default = unlimited
    public int maxParameters = -1; // default = 1000
    public int maxHeaders = -1; // default = 200
    public int maxHeaderSize = -1; // default = 1024 * 1024
    public boolean statistics = false;
    public volatile HashMap<Integer, Undertow> servers;
    public boolean forceCompressionSupport = false;
    public boolean alwaysSetDate = true;
    public boolean alwaysSetKeepAlive = true;
    public long readTimeout = Dates.s( 60 );

    public NioHttpServer( int port ) {
        this.defaultPort = port;

        pathHandler.put( defaultPort, new PathHandler() );

        contentEncodingRepository = new ContentEncodingRepository();
        contentEncodingRepository.addEncodingHandler( "gzip", new GzipEncodingProvider(), 100 );
        contentEncodingRepository.addEncodingHandler( "deflate", new DeflateEncodingProvider(), 100 );
    }

    public synchronized void start() {
        servers = new HashMap<>();
        for( var port : pathHandler.keySet() ) {
            startNewPort( port );
        }
    }

    private void startNewPort( int port ) {
        var portPathHandler = pathHandler.get( port );

        Preconditions.checkNotNull( portPathHandler );

        log.info( "bind {}", portPathHandler );

        Undertow.Builder builder = Undertow.builder()
            .setSocketOption( Options.REUSE_ADDRESSES, true )
            .setSocketOption( Options.TCP_NODELAY, tcpNodelay )
            .setServerOption( UndertowOptions.RECORD_REQUEST_START_TIME, true );

        if( backlog > 0 ) builder.setSocketOption( Options.BACKLOG, backlog );
        if( ioThreads > 0 ) builder.setIoThreads( ioThreads );
        if( workerThreads > 0 ) builder.setWorkerThreads( workerThreads );
        if( idleTimeout > 0 ) builder.setServerOption( UndertowOptions.IDLE_TIMEOUT, ( int ) idleTimeout );
        if( maxEntitySize > 0 ) builder.setServerOption( UndertowOptions.MAX_ENTITY_SIZE, maxEntitySize );
        if( maxParameters > 0 ) builder.setServerOption( UndertowOptions.MAX_PARAMETERS, maxParameters );
        if( maxHeaders > 0 ) builder.setServerOption( UndertowOptions.MAX_HEADERS, maxHeaders );
        if( maxHeaderSize > 0 ) builder.setServerOption( UndertowOptions.MAX_HEADER_SIZE, maxHeaderSize );
        if( statistics ) builder.setServerOption( UndertowOptions.ENABLE_STATISTICS, true );

        builder.setServerOption( UndertowOptions.ALWAYS_SET_DATE, alwaysSetDate );
        builder.setServerOption( UndertowOptions.ALWAYS_SET_KEEP_ALIVE, alwaysSetKeepAlive );

        io.undertow.server.HttpHandler handler = portPathHandler;
        if( forceCompressionSupport ) {
            handler = new EncodingHandler( handler, contentEncodingRepository );
            handler = new RequestEncodingHandler( handler )
                .addEncoding( "gzip", GzipStreamSourceConduit.WRAPPER )
                .addEncoding( "deflate", InflatingStreamSourceConduit.WRAPPER );
        }

        if( readTimeout > 0 )
            handler = BlockingReadTimeoutHandler.builder().readTimeout( Duration.ofMillis( readTimeout ) ).nextHandler( handler ).build();
        handler = new BlockingHandler( handler );
        handler = new GracefulShutdownHandler( handler );

        builder.addHttpListener( port, "0.0.0.0", handler );

        var server = builder.build();

        servers.put( port, server );

        server.start();

        log.info( "port {} statistics {} ioThreads {} workerThreads {}",
            port, statistics,
            server.getWorker().getMXBean().getIoThreadCount(),
            server.getWorker().getMXBean().getMaxWorkerPoolSize()
        );

        if( statistics ) {
            for( var listenerInfo : server.getListenerInfo() ) {
                var sa = ( InetSocketAddress ) listenerInfo.getAddress();
                var sPort = String.valueOf( sa.getPort() );

                ConnectorStatistics connectorStatistics = listenerInfo.getConnectorStatistics();

                Metrics.gauge( "nio_requests", Tags.of( "port", sPort, "type", "total" ), connectorStatistics, ConnectorStatistics::getRequestCount );
                Metrics.gauge( "nio_requests", Tags.of( "port", sPort, "type", "active" ), connectorStatistics, ConnectorStatistics::getActiveRequests );
                Metrics.gauge( "nio_requests", Tags.of( "port", sPort, "type", "errors" ), connectorStatistics, ConnectorStatistics::getErrorCount );

                Metrics.gauge( "nio_connections", Tags.of( "port", sPort, "type", "active" ), connectorStatistics, ConnectorStatistics::getActiveConnections );

                Metrics.gauge( "nio_pool_size", Tags.of( "port", sPort, "name", "worker", "type", "active" ), server, s -> s.getWorker().getMXBean().getWorkerPoolSize() );
                Metrics.gauge( "nio_pool_size", Tags.of( "port", sPort, "name", "worker", "type", "core" ), server, s -> s.getWorker().getMXBean().getCoreWorkerPoolSize() );
                Metrics.gauge( "nio_pool_size", Tags.of( "port", sPort, "name", "worker", "type", "max" ), server, s -> s.getWorker().getMXBean().getMaxWorkerPoolSize() );
                Metrics.gauge( "nio_pool_size", Tags.of( "port", sPort, "name", "worker", "type", "busy" ), server, s -> s.getWorker().getMXBean().getBusyWorkerThreadCount() );
                Metrics.gauge( "nio_pool_size", Tags.of( "port", sPort, "name", "worker", "type", "queue" ), server, s -> s.getWorker().getMXBean().getWorkerQueueSize() );

            }
        }
    }

    public void bind( String prefix, HttpHandler handler, boolean compressionSupport ) {
        bind( prefix, handler, compressionSupport, this.defaultPort );
    }

    public synchronized void bind( String prefix, HttpHandler handler, boolean compressionSupport, int port ) {
        log.debug( "bind {}", prefix );

        Preconditions.checkNotNull( prefix );
        Preconditions.checkArgument( !prefix.isEmpty() );

        io.undertow.server.HttpHandler httpHandler = exchange -> handler.handleRequest( new HttpServerExchange( exchange, requestId.incrementAndGet() ) );

        if( !forceCompressionSupport && compressionSupport ) {
            httpHandler = new EncodingHandler( httpHandler, contentEncodingRepository );
            httpHandler = new RequestEncodingHandler( httpHandler )
                .addEncoding( "gzip", GzipStreamSourceConduit.WRAPPER )
                .addEncoding( "deflate", InflatingStreamSourceConduit.WRAPPER );
        }

        pathHandler.computeIfAbsent( port, p -> new PathHandler() ).addPrefixPath( prefix, httpHandler );

        if( servers != null && !servers.containsKey( port ) ) {
            startNewPort( port );
        }
    }

    public void bind( String prefix, HttpHandler handler ) {
        bind( prefix, handler, this.defaultPort );
    }

    public void bind( String prefix, HttpHandler handler, int port ) {
        bind( prefix, handler, true, port );
    }

    public synchronized void preStop() {
        if( servers != null ) {
            for( var server : servers.values() ) {
                try {
                    server.stop();
                } catch( Exception ex ) {
                   log.error( "Cannot stop server", ex );
                }
            }
            pathHandler.clear();
            servers = null;
        }
    }

    @Override
    public void close() throws IOException {
        preStop();
    }
}


text:
package fi.lahtevanoja.hallofboids.card;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Lists;
import java.util.List;

public class CardsResponse {

  @JsonProperty("_data")
  private List<Card> data;

  public CardsResponse(Card card) {
    this.data = Lists.newArrayList(card);
  }

  public CardsResponse(List<Card> cards) {
    this.data = Lists.newArrayList(cards);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    Copyright (c) 2016 The Dirty Unicorns Project

    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.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="64dp"
    android:height="64dp"
    android:viewportWidth="24"
    android:viewportHeight="24">

    <path
        android:fillColor="#FFFFFFFF"
        android:pathData="M6,16H18V18H6V16M6,13V15H2V13H6M7,15V13H10V15H7M11,15V13H13V15H11M14,15V13H17V15H14M18,15V13H22V15H18M2,10H5V12H2V10M19,12V10H22V12H19M18,12H16V10H18V12M8,12H6V10H8V12M12,12H9V10H12V12M15,12H13V10H15V12M2,9V7H4V9H2M5,9V7H7V9H5M8,9V7H10V9H8M11,9V7H13V9H11M14,9V7H16V9H14M17,9V7H22V9H17Z" />
</vector>


text:
import React from 'react'
import { storiesOf } from '@storybook/react-native'
import { action } from '@storybook/addon-actions'
import { linkTo } from '@storybook/addon-links'

import Artboard from 'storybook/stories/Artboard/index.js'
import UserConnect from 'storybook/stories/UserConnect/index.js'


text:
using System;
using ECS;

namespace Test
{
    public static class RealWorldExample
    {
        // components

        public class Position : Component
        {
            public float x, y, z;
        }

        public class AI : Component
        {
        }

        public class Health : Component
        {
            public float HP { get; set; } = 100;
        }

        // systems

        public class PositionSystem : System<Position>
        {
        }

        public class AISystem : System<AI>
        {
            protected override void Update(AI component, object updateData)
            {
                base.Update(component, updateData);

                Console.WriteLine("Enemy with ID " + component.EntityID + " looks for someone to attack.");

                // get my position (methods like this only iterate over the elements of a cached list of components of this entity)
                var myPosition = Context.GetFirstComponentOfTypeOfEntity<Position>(component.EntityID);

                // find the first entity nearby
                foreach( Position enemyPosition in Context.GetComponentsOfType<Position>() )
                {
                    if( enemyPosition == myPosition )
                        continue; // it's me (note that we're comparing component references, not values)

                    if( Math.Abs(myPosition.x - enemyPosition.x) <= 10f
                        && Math.Abs(myPosition.y - enemyPosition.y) <= 10f
                        && Math.Abs(myPosition.z - enemyPosition.z) <= 10f )
                    {
                        // attack
                        var args = new AttackEventArgs { TargetEntityID = enemyPosition.EntityID, AttackStrength = 25 };
                        SendEvent(component.EntityID, args);
                        break;
                    }
                }
            }
        }

        public class HealthSystem : System<Health>
        {
            public override void ReceiveEvent(Event ev)
            {
                base.ReceiveEvent(ev);

                if( ev.Data is AttackEventArgs attack )
                {
                    var victimHealth = GetComponentOfEntity(attack.TargetEntityID);
                    victimHealth.HP -= attack.AttackStrength;

                    Console.WriteLine("Player with ID " + attack.TargetEntityID + " attacked by enemy with ID " + ev.EntityID + "! HP left: " + victimHealth.HP);
                }
            }
        }

        // events

        public class AttackEventArgs
        {
            public int TargetEntityID { get; set; }
            public float AttackStrength { get; set; }
        }

        public static void Run()
        {
            // create context
            var context = new Context();

            // add all systems
            context.AddSystem<PositionSystem>();
            context.AddSystem<HealthSystem>();
            context.AddSystem<AISystem>();

            // add player with Position and Health
            int player = context.AddEntity();
            var playerPosition = context.AddComponent<Position>(player);
            var playerHealth = context.AddComponent<Health>(player);
            playerPosition.x = 5;

            // add enemy with Position, Health, and AI
            int enemy = context.AddEntity();
            var enemyPosition = context.AddComponent<Position>(enemy);
            enemyPosition.x = 10;
            context.AddComponent<Health>(enemy);
            context.AddComponent<AI>(enemy);

            // do the simulation if the player is still alive
            while( playerHealth.HP > 0 )
            {
                context.Update();
            }

            Console.WriteLine("Player died.");
            Console.ReadLine();
        }
    }
}


text:
import React, {PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

import ReduxMUIForm from '../components/ReduxMUIForm';

import {
  setCount
} from '../actions/demoActions';

function mapStateToProps(state) {
  return {
    count: state.demoAppState.count
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({
      setCount
    }, dispatch)
  };
}

export class ReduxMUIPage extends React.Component {

  constructor() {
    super();

    this.handleDecrementClicked = this.handleDecrementClicked.bind(this);
    this.handleIncrementClicked = this.handleIncrementClicked.bind(this);
    this.handleResetClicked = this.handleResetClicked.bind(this);
  }

  handleDecrementClicked() {
    this.props.actions.setCount(this.props.count - 1);
  }

  handleIncrementClicked() {
    this.props.actions.setCount(this.props.count + 1);
  }

  handleResetClicked() {
    this.props.actions.setCount(0);
  }

  render() {
    return (
      <ReduxMUIForm
        onDecrementClicked={this.handleDecrementClicked}
        onIncrementClicked={this.handleIncrementClicked}
        onResetClicked={this.handleResetClicked}
        count={this.props.count}
      />
    );
  }
}

ReduxMUIPage.propTypes = {
  actions: PropTypes.shape({
    setCount: PropTypes.func
  }),
  count: PropTypes.number
};

export default connect(mapStateToProps, mapDispatchToProps)(ReduxMUIPage);


text:
"""Test to ensure correct midi input and output."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import os.path
import tempfile

from magenta.music import constants
from magenta.music import midi_io
from magenta.protobuf import music_pb2
import mido
import pretty_midi
import tensorflow as tf

# self.midi_simple_filename contains a c-major scale of 8 quarter notes each
# with a sustain of .95 of the entire note. Here are the first two notes dumped
# using mididump.py:
#   midi.NoteOnEvent(tick=0, channel=0, data=[60, 100]),
#   midi.NoteOnEvent(tick=209, channel=0, data=[60, 0]),
#   midi.NoteOnEvent(tick=11, channel=0, data=[62, 100]),
#   midi.NoteOnEvent(tick=209, channel=0, data=[62, 0]),
_SIMPLE_MIDI_FILE_VELO = 100
_SIMPLE_MIDI_FILE_NUM_NOTES = 8
_SIMPLE_MIDI_FILE_SUSTAIN = .95

# self.midi_complex_filename contains many instruments including percussion as
# well as control change and pitch bend events.

# self.midi_is_drum_filename contains 41 tracks, two of which are on channel 9.

# self.midi_event_order_filename contains notes ordered
# non-monotonically by pitch.  Here are relevent events as printed by
# mididump.py:
#   midi.NoteOnEvent(tick=0, channel=0, data=[1, 100]),
#   midi.NoteOnEvent(tick=0, channel=0, data=[3, 100]),
#   midi.NoteOnEvent(tick=0, channel=0, data=[2, 100]),
#   midi.NoteOnEvent(tick=4400, channel=0, data=[3, 0]),
#   midi.NoteOnEvent(tick=0, channel=0, data=[1, 0]),
#   midi.NoteOnEvent(tick=0, channel=0, data=[2, 0]),

class MidiIoTest(tf.test.TestCase):

  def setUp(self):
    self.midi_simple_filename = os.path.join(
        tf.resource_loader.get_data_files_path(), '../testdata/example.mid')
    self.midi_complex_filename = os.path.join(
        tf.resource_loader.get_data_files_path(),
        '../testdata/example_complex.mid')
    self.midi_is_drum_filename = os.path.join(
        tf.resource_loader.get_data_files_path(),
        '../testdata/example_is_drum.mid')
    self.midi_event_order_filename = os.path.join(
        tf.resource_loader.get_data_files_path(),
        '../testdata/example_event_order.mid')

  def CheckPrettyMidiAndSequence(self, midi, sequence_proto):
    """Compares PrettyMIDI object against a sequence proto.

    Args:
      midi: A pretty_midi.PrettyMIDI object.
      sequence_proto: A tensorflow.magenta.Sequence proto.
    """
    # Test time signature changes.
    self.assertEqual(len(midi.time_signature_changes),
                     len(sequence_proto.time_signatures))
    for midi_time, sequence_time in zip(midi.time_signature_changes,
                                        sequence_proto.time_signatures):
      self.assertEqual(midi_time.numerator, sequence_time.numerator)
      self.assertEqual(midi_time.denominator, sequence_time.denominator)
      self.assertAlmostEqual(midi_time.time, sequence_time.time)

    # Test key signature changes.
    self.assertEqual(len(midi.key_signature_changes),
                     len(sequence_proto.key_signatures))
    for midi_key, sequence_key in zip(midi.key_signature_changes,
                                      sequence_proto.key_signatures):
      self.assertEqual(midi_key.key_number % 12, sequence_key.key)
      self.assertEqual(midi_key.key_number // 12, sequence_key.mode)
      self.assertAlmostEqual(midi_key.time, sequence_key.time)

    # Test tempos.
    midi_times, midi_qpms = midi.get_tempo_changes()
    self.assertEqual(len(midi_times),
                     len(sequence_proto.tempos))
    self.assertEqual(len(midi_qpms),
                     len(sequence_proto.tempos))
    for midi_time, midi_qpm, sequence_tempo in zip(
        midi_times, midi_qpms, sequence_proto.tempos):
      self.assertAlmostEqual(midi_qpm, sequence_tempo.qpm)
      self.assertAlmostEqual(midi_time, sequence_tempo.time)

    # Test instruments.
    seq_instruments = collections.defaultdict(
        lambda: collections.defaultdict(list))
    for seq_note in sequence_proto.notes:
      seq_instruments[
          (seq_note.instrument, seq_note.program, seq_note.is_drum)][
              'notes'].append(seq_note)
    for seq_bend in sequence_proto.pitch_bends:
      seq_instruments[
          (seq_bend.instrument, seq_bend.program, seq_bend.is_drum)][
              'bends'].append(seq_bend)
    for seq_control in sequence_proto.control_changes:
      seq_instruments[
          (seq_control.instrument, seq_control.program, seq_control.is_drum)][
              'controls'].append(seq_control)

    sorted_seq_instrument_keys = sorted(seq_instruments.keys())

    if seq_instruments:
      self.assertEqual(len(midi.instruments), len(seq_instruments))
    else:
      self.assertEqual(1, len(midi.instruments))
      self.assertEqual(0, len(midi.instruments[0].notes))
      self.assertEqual(0, len(midi.instruments[0].pitch_bends))

    for midi_instrument, seq_instrument_key in zip(
        midi.instruments, sorted_seq_instrument_keys):

      seq_instrument_notes = seq_instruments[seq_instrument_key]['notes']

      self.assertEqual(len(midi_instrument.notes), len(seq_instrument_notes))
      for midi_note, sequence_note in zip(midi_instrument.notes,
                                          seq_instrument_notes):
        self.assertEqual(midi_note.pitch, sequence_note.pitch)
        self.assertEqual(midi_note.velocity, sequence_note.velocity)
        self.assertAlmostEqual(midi_note.start, sequence_note.start_time)
        self.assertAlmostEqual(midi_note.end, sequence_note.end_time)

      seq_instrument_pitch_bends = seq_instruments[seq_instrument_key]['bends']
      self.assertEqual(len(midi_instrument.pitch_bends),
                       len(seq_instrument_pitch_bends))
      for midi_pitch_bend, sequence_pitch_bend in zip(
          midi_instrument.pitch_bends,
          seq_instrument_pitch_bends):
        self.assertEqual(midi_pitch_bend.pitch, sequence_pitch_bend.bend)
        self.assertAlmostEqual(midi_pitch_bend.time, sequence_pitch_bend.time)

  def CheckMidiToSequence(self, filename):
    """Test the translation from PrettyMIDI to Sequence proto."""
    source_midi = pretty_midi.PrettyMIDI(filename)
    sequence_proto = midi_io.midi_to_sequence_proto(source_midi)
    self.CheckPrettyMidiAndSequence(source_midi, sequence_proto)

  def CheckSequenceToPrettyMidi(self, filename):
    """Test the translation from Sequence proto to PrettyMIDI."""
    source_midi = pretty_midi.PrettyMIDI(filename)
    sequence_proto = midi_io.midi_to_sequence_proto(source_midi)
    translated_midi = midi_io.sequence_proto_to_pretty_midi(sequence_proto)
    self.CheckPrettyMidiAndSequence(translated_midi, sequence_proto)

  def CheckReadWriteMidi(self, filename):
    """Test writing to a MIDI file and comparing it to the original Sequence."""

    # TODO(deck): The input MIDI file is opened in pretty-midi and
    # re-written to a temp file, sanitizing the MIDI data (reordering
    # note ons, etc). Issue 85 in the pretty-midi GitHub
    # (http://github.com/craffel/pretty-midi/issues/85) requests that
    # this sanitization be available outside of the context of a file
    # write. If that is implemented, this rewrite code should be
    # modified or deleted.

    # When writing to the temp file, use the file object itself instead of
    # file.name to avoid the permission error on Windows.
    with tempfile.NamedTemporaryFile(prefix='MidiIoTest') as rewrite_file:
      original_midi = pretty_midi.PrettyMIDI(filename)
      original_midi.write(rewrite_file)  # Use file object
      # Back the file position to top to reload the rewrite_file
      rewrite_file.seek(0)
      source_midi = pretty_midi.PrettyMIDI(rewrite_file)  # Use file object
      sequence_proto = midi_io.midi_to_sequence_proto(source_midi)

    # Translate the NoteSequence to MIDI and write to a file.
    with tempfile.NamedTemporaryFile(prefix='MidiIoTest') as temp_file:
      midi_io.sequence_proto_to_midi_file(sequence_proto, temp_file.name)
      # Read it back in and compare to source.
      created_midi = pretty_midi.PrettyMIDI(temp_file)  # Use file object

    self.CheckPrettyMidiAndSequence(created_midi, sequence_proto)

  def testSimplePrettyMidiToSequence(self):
    self.CheckMidiToSequence(self.midi_simple_filename)

  def testSimpleSequenceToPrettyMidi(self):
    self.CheckSequenceToPrettyMidi(self.midi_simple_filename)

  def testSimpleSequenceToPrettyMidi_DefaultTicksAndTempo(self):
    source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename)
    stripped_sequence_proto = midi_io.midi_to_sequence_proto(source_midi)
    del stripped_sequence_proto.tempos[:]
    stripped_sequence_proto.ClearField('ticks_per_quarter')

    expected_sequence_proto = music_pb2.NoteSequence()
    expected_sequence_proto.CopyFrom(stripped_sequence_proto)
    expected_sequence_proto.tempos.add(
        qpm=constants.DEFAULT_QUARTERS_PER_MINUTE)
    expected_sequence_proto.ticks_per_quarter = constants.STANDARD_PPQ

    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        stripped_sequence_proto)

    self.CheckPrettyMidiAndSequence(translated_midi, expected_sequence_proto)

  def testSimpleSequenceToPrettyMidi_MultipleTempos(self):
    source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename)
    multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi)
    multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60)
    multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120)

    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        multi_tempo_sequence_proto)

    self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)

  def testSimpleSequenceToPrettyMidi_FirstTempoNotAtZero(self):
    source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename)
    multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi)
    del multi_tempo_sequence_proto.tempos[:]
    multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60)
    multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120)

    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        multi_tempo_sequence_proto)

    # Translating to MIDI adds an implicit DEFAULT_QUARTERS_PER_MINUTE tempo
    # at time 0, so recreate the list with that in place.
    del multi_tempo_sequence_proto.tempos[:]
    multi_tempo_sequence_proto.tempos.add(
        time=0.0, qpm=constants.DEFAULT_QUARTERS_PER_MINUTE)
    multi_tempo_sequence_proto.tempos.add(time=1.0, qpm=60)
    multi_tempo_sequence_proto.tempos.add(time=2.0, qpm=120)

    self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)

  def testSimpleSequenceToPrettyMidi_DropEventsAfterLastNote(self):
    source_midi = pretty_midi.PrettyMIDI(self.midi_simple_filename)
    multi_tempo_sequence_proto = midi_io.midi_to_sequence_proto(source_midi)
    # Add a final tempo long after the last note.
    multi_tempo_sequence_proto.tempos.add(time=600.0, qpm=120)

    # Translate without dropping.
    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        multi_tempo_sequence_proto)
    self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)

    # Translate dropping anything after the last note.
    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        multi_tempo_sequence_proto, drop_events_n_seconds_after_last_note=0)
    # The added tempo should have been dropped.
    del multi_tempo_sequence_proto.tempos[-1]
    self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)

    # Add a final tempo 15 seconds after the last note.
    last_note_time = max([n.end_time for n in multi_tempo_sequence_proto.notes])
    multi_tempo_sequence_proto.tempos.add(time=last_note_time + 15, qpm=120)
    # Translate dropping anything 30 seconds after the last note, which should
    # preserve the added tempo.
    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        multi_tempo_sequence_proto, drop_events_n_seconds_after_last_note=30)
    self.CheckPrettyMidiAndSequence(translated_midi, multi_tempo_sequence_proto)

  def testEmptySequenceToPrettyMidi_DropEventsAfterLastNote(self):
    source_sequence = music_pb2.NoteSequence()

    # Translate without dropping.
    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        source_sequence)
    self.assertEqual(1, len(translated_midi.instruments))
    self.assertEqual(0, len(translated_midi.instruments[0].notes))

    # Translate dropping anything after 30 seconds.
    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        source_sequence, drop_events_n_seconds_after_last_note=30)
    self.assertEqual(1, len(translated_midi.instruments))
    self.assertEqual(0, len(translated_midi.instruments[0].notes))

  def testNonEmptySequenceWithNoNotesToPrettyMidi_DropEventsAfterLastNote(self):
    source_sequence = music_pb2.NoteSequence()
    source_sequence.tempos.add(time=0, qpm=120)
    source_sequence.tempos.add(time=10, qpm=160)
    source_sequence.tempos.add(time=40, qpm=240)

    # Translate without dropping.
    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        source_sequence)
    self.CheckPrettyMidiAndSequence(translated_midi, source_sequence)

    # Translate dropping anything after 30 seconds.
    translated_midi = midi_io.sequence_proto_to_pretty_midi(
        source_sequence, drop_events_n_seconds_after_last_note=30)
    del source_sequence.tempos[-1]
    self.CheckPrettyMidiAndSequence(translated_midi, source_sequence)

  def testSimpleReadWriteMidi(self):
    self.CheckReadWriteMidi(self.midi_simple_filename)

  def testComplexPrettyMidiToSequence(self):
    self.CheckMidiToSequence(self.midi_complex_filename)

  def testComplexSequenceToPrettyMidi(self):
    self.CheckSequenceToPrettyMidi(self.midi_complex_filename)

  def testIsDrumDetection(self):
    """Verify that is_drum instruments are properly tracked.

    self.midi_is_drum_filename is a MIDI file containing two tracks
    set to channel 9 (is_drum == True). Each contains one NoteOn. This
    test is designed to catch a bug where the second track would lose
    is_drum, remapping the drum track to an instrument track.
    """
    sequence_proto = midi_io.midi_file_to_sequence_proto(
        self.midi_is_drum_filename)
    with tempfile.NamedTemporaryFile(prefix='MidiDrumTest') as temp_file:
      midi_io.sequence_proto_to_midi_file(sequence_proto, temp_file.name)
      midi_data1 = mido.MidiFile(filename=self.midi_is_drum_filename)
      # Use the file object when writing to the tempfile
      # to avoid permission error.
      midi_data2 = mido.MidiFile(file=temp_file)

    # Count number of channel 9 Note Ons.
    channel_counts = [0, 0]
    for index, midi_data in enumerate([midi_data1, midi_data2]):
      for event in midi_data:
        if (event.type == 'note_on' and
            event.velocity > 0 and event.channel == 9):
          channel_counts[index] += 1
    self.assertEqual(channel_counts, [2, 2])

  def testComplexReadWriteMidi(self):
    self.CheckReadWriteMidi(self.midi_complex_filename)

  def testEventOrdering(self):
    self.CheckReadWriteMidi(self.midi_event_order_filename)

if __name__ == '__main__':
  tf.test.main()


text:
<!DOCTYPE html>

		<meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
         <title>Parallax Content Slider with CSS3 and jQuery</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Parallax Content Slider with CSS3 and jQuery" />
        <meta name="keywords" content="slider, animations, parallax, delayed, easing, jquery, css3, kendo UI" />
        <meta name="author" content="Codrops" />
        <link rel="shortcut icon" href="../favicon.ico">
        <link rel="stylesheet" type="text/css" href="css/demo.css" />
        <link rel="stylesheet" type="text/css" href="css/style2.css" />

		<link href='http://fonts.googleapis.com/css?family=Economica:700,400italic' rel='stylesheet' type='text/css'>

			<link rel="stylesheet" type="text/css" href="css/nojs.css" />

                    « Previous Demo: Accordion with CSS3

					Pattern from Dinpattern
					Icons by: LazyCrazy via MediaLoot

                        Back to the Codrops Article

Parallax Content Slider with CSS3 and jQuery

A content slider with delayed animations and background parallax effect

					Default
					Autoplay
					Parallax off

Easy management

Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.

					Read more

Revolution

A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth.

					Read more

Warm welcome

When she reached the first hills of the Italic Mountains, she had a last view back on the skyline of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, the Line Lane.

					Read more

Quality Control

Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar.

					Read more


text:
import * as _ from "lodash";
import * as assert from "assert";
import * as fs from "fs";

import { SubtitlePiece } from "../data/SubtitlePiece";
import { convertFormatToSeconds } from "../utils";

const subtitlesParser = require('subtitles-parser');

const getJaccardIndexInternal = (a, b) => {
        assert(typeof a.start === 'number');
        assert(typeof a.end === 'number');
        assert(a.start < a.end);
        assert(typeof b.start === 'number');
        assert(typeof b.end === 'number');
        assert(b.start < b.end);

        const intersection = _.max([0, _.min([a.end, b.end]) - _.max([a.start, b.start])]);
        const union = (a.end - a.start) + (b.end - b.start) - intersection;

        return intersection / union;
};

const mean = array => _.round(_.mean(array), 2);
const zeros = n => _.fill(_.range(n), 0);

export const getJaccardIndex = (a: SubtitlePiece, b: SubtitlePiece) => {
        const aSeconds = {
                start: convertFormatToSeconds(a.startTime),
                end: convertFormatToSeconds(a.endTime),
        };
        const bSeconds = {
                start: convertFormatToSeconds(b.startTime),
                end: convertFormatToSeconds(b.endTime),
        }
        return getJaccardIndexInternal(aSeconds, bSeconds);
};


text:
<?php

if (!defined('SMF'))
	die('No direct access...');

/**
 * Check if the user is who he/she says he is
 * Makes sure the user is who they claim to be by requiring a password to be typed in every hour.
 * Is turned on and off by the securityDisable setting.
 * Uses the adminLogin() function of Subs-Auth.php if they need to login, which saves all request (post and get) data.
 *
 * @param string $type What type of session this is
 * @param string $force When true, require a password even if we normally wouldn't
 * @return void|string Returns 'session_verify_fail' if verification failed
 */
function validateSession($type = 'admin', $force = false)
{
	global $modSettings, $sourcedir, $user_info;

	// We don't care if the option is off, because Guests should NEVER get past here.
	is_not_guest();

	// Validate what type of session check this is.
	$types = array();
	call_integration_hook('integrate_validateSession', array(&$types));
	$type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';

	// If we're using XML give an additional ten minutes grace as an admin can't log on in XML mode.
	$refreshTime = isset($_GET['xml']) ? 4200 : 3600;

	if (empty($force))
	{
		// Is the security option off?
		if (!empty($modSettings['securityDisable' . ($type != 'admin' ? '_' . $type : '')]))
			return;

		// Or are they already logged in?, Moderator or admin session is need for this area
		if ((!empty($_SESSION[$type . '_time']) && $_SESSION[$type . '_time'] + $refreshTime >= time()) || (!empty($_SESSION['admin_time']) && $_SESSION['admin_time'] + $refreshTime >= time()))
			return;
	}

	require_once($sourcedir . '/Subs-Auth.php');

	// Posting the password... check it.
	if (isset($_POST[$type . '_pass']))
	{
		// Check to ensure we're forcing SSL for authentication
		if (!empty($modSettings['force_ssl']) && empty($maintenance) && !httpsOn())
			fatal_lang_error('login_ssl_required');

		checkSession();

		$good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST[$type . '_pass'], false)), true);

		// Password correct?
		if ($good_password || hash_verify_password($user_info['username'], $_POST[$type . '_pass'], $user_info['passwd']))
		{
			$_SESSION[$type . '_time'] = time();
			unset($_SESSION['request_referer']);
			return;
		}
	}

	// Better be sure to remember the real referer
	if (empty($_SESSION['request_referer']))
		$_SESSION['request_referer'] = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
	elseif (empty($_POST))
		unset($_SESSION['request_referer']);

	// Need to type in a password for that, man.
	if (!isset($_GET['xml']))
		adminLogin($type);
	else
		return 'session_verify_fail';
}

/**
 * Require a user who is logged in. (not a guest.)
 * Checks if the user is currently a guest, and if so asks them to login with a message telling them why.
 * Message is what to tell them when asking them to login.
 *
 * @param string $message The message to display to the guest
 */
function is_not_guest($message = '')
{
	global $user_info, $txt, $context, $scripturl, $modSettings;

	// Luckily, this person isn't a guest.
	if (!$user_info['is_guest'])
		return;

	// Log what they were trying to do didn't work)
	if (!empty($modSettings['who_enabled']))
		$_GET['error'] = 'guest_login';
	writeLog(true);

	// Just die.
	if (isset($_REQUEST['xml']))
		obExit(false);

	// Attempt to detect if they came from dlattach.
	if (SMF != 'SSI' && empty($context['theme_loaded']))
		loadTheme();

	// Never redirect to an attachment
	if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
		$_SESSION['login_url'] = $_SERVER['REQUEST_URL'];

	// Load the Login template and language file.
	loadLanguage('Login');

	// Apparently we're not in a position to handle this now. Let's go to a safer location for now.
	if (empty($context['template_layers']))
	{
		$_SESSION['login_url'] = $scripturl . '?' . $_SERVER['QUERY_STRING'];
		redirectexit('action=login');
	}
	else
	{
		loadTemplate('Login');
		$context['sub_template'] = 'kick_guest';
		$context['robot_no_index'] = true;
	}

	// Use the kick_guest sub template...
	$context['kick_message'] = $message;
	$context['page_title'] = $txt['login'];

	obExit();

	// We should never get to this point, but if we did we wouldn't know the user isn't a guest.
	trigger_error('Hacking attempt...', E_USER_ERROR);
}

/**
 * Do banning related stuff.  (ie. disallow access....)
 * Checks if the user is banned, and if so dies with an error.
 * Caches this information for optimization purposes.
 *
 * @param bool $forceCheck Whether to force a recheck
 */
function is_not_banned($forceCheck = false)
{
	global $txt, $modSettings, $context, $user_info;
	global $sourcedir, $cookiename, $user_settings, $smcFunc;

	// You cannot be banned if you are an admin - doesn't help if you log out.
	if ($user_info['is_admin'])
		return;

	// Only check the ban every so often. (to reduce load.)
	if ($forceCheck || !isset($_SESSION['ban']) || empty($modSettings['banLastUpdated']) || ($_SESSION['ban']['last_checked'] < $modSettings['banLastUpdated']) || $_SESSION['ban']['id_member'] != $user_info['id'] || $_SESSION['ban']['ip'] != $user_info['ip'] || $_SESSION['ban']['ip2'] != $user_info['ip2'] || (isset($user_info['email'], $_SESSION['ban']['email']) && $_SESSION['ban']['email'] != $user_info['email']))
	{
		// Innocent until proven guilty.  (but we know you are! :P)
		$_SESSION['ban'] = array(
			'last_checked' => time(),
			'id_member' => $user_info['id'],
			'ip' => $user_info['ip'],
			'ip2' => $user_info['ip2'],
			'email' => $user_info['email'],
		);

		$ban_query = array();
		$ban_query_vars = array('current_time' => time());
		$flag_is_activated = false;

		// Check both IP addresses.
		foreach (array('ip', 'ip2') as $ip_number)
		{
			if ($ip_number == 'ip2' && $user_info['ip2'] == $user_info['ip'])
				continue;
			$ban_query[] = ' {inet:' . $ip_number . '} BETWEEN bi.ip_low and bi.ip_high';
			$ban_query_vars[$ip_number] = $user_info[$ip_number];
			// IP was valid, maybe there's also a hostname...
			if (empty($modSettings['disableHostnameLookup']) && $user_info[$ip_number] != 'unknown')
			{
				$hostname = host_from_ip($user_info[$ip_number]);
				if (strlen($hostname) > 0)
				{
					$ban_query[] = '({string:hostname' . $ip_number . '} LIKE bi.hostname)';
					$ban_query_vars['hostname' . $ip_number] = $hostname;
				}
			}
		}

		// Is their email address banned?
		if (strlen($user_info['email']) != 0)
		{
			$ban_query[] = '({string:email} LIKE bi.email_address)';
			$ban_query_vars['email'] = $user_info['email'];
		}

		// How about this user?
		if (!$user_info['is_guest'] && !empty($user_info['id']))
		{
			$ban_query[] = 'bi.id_member = {int:id_member}';
			$ban_query_vars['id_member'] = $user_info['id'];
		}

		// Check the ban, if there's information.
		if (!empty($ban_query))
		{
			$restrictions = array(
				'cannot_access',
				'cannot_login',
				'cannot_post',
				'cannot_register',
			);
			$request = $smcFunc['db_query']('', '
				SELECT bi.id_ban, bi.email_address, bi.id_member, bg.cannot_access, bg.cannot_register,
					bg.cannot_post, bg.cannot_login, bg.reason, COALESCE(bg.expire_time, 0) AS expire_time
				FROM {db_prefix}ban_items AS bi
					INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time}))
				WHERE
					(' . implode(' OR ', $ban_query) . ')',
				$ban_query_vars
			);
			// Store every type of ban that applies to you in your session.
			while ($row = $smcFunc['db_fetch_assoc']($request))
			{
				foreach ($restrictions as $restriction)
					if (!empty($row[$restriction]))
					{
						$_SESSION['ban'][$restriction]['reason'] = $row['reason'];
						$_SESSION['ban'][$restriction]['ids'][] = $row['id_ban'];
						if (!isset($_SESSION['ban']['expire_time']) || ($_SESSION['ban']['expire_time'] != 0 && ($row['expire_time'] == 0 || $row['expire_time'] > $_SESSION['ban']['expire_time'])))
							$_SESSION['ban']['expire_time'] = $row['expire_time'];

						if (!$user_info['is_guest'] && $restriction == 'cannot_access' && ($row['id_member'] == $user_info['id'] || $row['email_address'] == $user_info['email']))
							$flag_is_activated = true;
					}
			}
			$smcFunc['db_free_result']($request);
		}

		// Mark the cannot_access and cannot_post bans as being 'hit'.
		if (isset($_SESSION['ban']['cannot_access']) || isset($_SESSION['ban']['cannot_post']) || isset($_SESSION['ban']['cannot_login']))
			log_ban(array_merge(isset($_SESSION['ban']['cannot_access']) ? $_SESSION['ban']['cannot_access']['ids'] : array(), isset($_SESSION['ban']['cannot_post']) ? $_SESSION['ban']['cannot_post']['ids'] : array(), isset($_SESSION['ban']['cannot_login']) ? $_SESSION['ban']['cannot_login']['ids'] : array()));

		// If for whatever reason the is_activated flag seems wrong, do a little work to clear it up.
		if ($user_info['id'] && (($user_settings['is_activated'] >= 10 && !$flag_is_activated)
			|| ($user_settings['is_activated'] < 10 && $flag_is_activated)))
		{
			require_once($sourcedir . '/ManageBans.php');
			updateBanMembers();
		}
	}

	// Hey, I know you! You're ehm...
	if (!isset($_SESSION['ban']['cannot_access']) && !empty($_COOKIE[$cookiename . '_']))
	{
		$bans = explode(',', $_COOKIE[$cookiename . '_']);
		foreach ($bans as $key => $value)
			$bans[$key] = (int) $value;
		$request = $smcFunc['db_query']('', '
			SELECT bi.id_ban, bg.reason, COALESCE(bg.expire_time, 0) AS expire_time
			FROM {db_prefix}ban_items AS bi
				INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
			WHERE bi.id_ban IN ({array_int:ban_list})
				AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})
				AND bg.cannot_access = {int:cannot_access}
			LIMIT {int:limit}',
			array(
				'cannot_access' => 1,
				'ban_list' => $bans,
				'current_time' => time(),
				'limit' => count($bans),
			)
		);
		while ($row = $smcFunc['db_fetch_assoc']($request))
		{
			$_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
			$_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
			$_SESSION['ban']['expire_time'] = $row['expire_time'];
		}
		$smcFunc['db_free_result']($request);

		// My mistake. Next time better.
		if (!isset($_SESSION['ban']['cannot_access']))
		{
			require_once($sourcedir . '/Subs-Auth.php');
			$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
			smf_setcookie($cookiename . '_', '', time() - 3600, $cookie_url[1], $cookie_url[0], false, false);
		}
	}

	// If you're fully banned, it's end of the story for you.
	if (isset($_SESSION['ban']['cannot_access']))
	{
		// We don't wanna see you!
		if (!$user_info['is_guest'])
			$smcFunc['db_query']('', '
				DELETE FROM {db_prefix}log_online
				WHERE id_member = {int:current_member}',
				array(
					'current_member' => $user_info['id'],
				)
			);

		// 'Log' the user out.  Can't have any funny business... (save the name!)
		$old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
		$user_info['name'] = '';
		$user_info['username'] = '';
		$user_info['is_guest'] = true;
		$user_info['is_admin'] = false;
		$user_info['permissions'] = array();
		$user_info['id'] = 0;
		$context['user'] = array(
			'id' => 0,
			'username' => '',
			'name' => $txt['guest_title'],
			'is_guest' => true,
			'is_logged' => false,
			'is_admin' => false,
			'is_mod' => false,
			'can_mod' => false,
			'language' => $user_info['language'],
		);

		// A goodbye present.
		require_once($sourcedir . '/Subs-Auth.php');
		require_once($sourcedir . '/LogInOut.php');
		$cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
		smf_setcookie($cookiename . '_', implode(',', $_SESSION['ban']['cannot_access']['ids']), time() + 3153600, $cookie_url[1], $cookie_url[0], false, false);

		// Don't scare anyone, now.
		$_GET['action'] = '';
		$_GET['board'] = '';
		$_GET['topic'] = '';
		writeLog(true);
		Logout(true, false);

		// You banned, sucka!
		fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_access']['reason']) ? '' : '
' . $_SESSION['ban']['cannot_access']['reason']) . '
' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']), false, 403);

		// If we get here, something's gone wrong.... but let's try anyway.
		trigger_error('Hacking attempt...', E_USER_ERROR);
	}
	// You're not allowed to log in but yet you are. Let's fix that.
	elseif (isset($_SESSION['ban']['cannot_login']) && !$user_info['is_guest'])
	{
		// We don't wanna see you!
		$smcFunc['db_query']('', '
			DELETE FROM {db_prefix}log_online
			WHERE id_member = {int:current_member}',
			array(
				'current_member' => $user_info['id'],
			)
		);

		// 'Log' the user out.  Can't have any funny business... (save the name!)
		$old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
		$user_info['name'] = '';
		$user_info['username'] = '';
		$user_info['is_guest'] = true;
		$user_info['is_admin'] = false;
		$user_info['permissions'] = array();
		$user_info['id'] = 0;
		$context['user'] = array(
			'id' => 0,
			'username' => '',
			'name' => $txt['guest_title'],
			'is_guest' => true,
			'is_logged' => false,
			'is_admin' => false,
			'is_mod' => false,
			'can_mod' => false,
			'language' => $user_info['language'],
		);

		// SMF's Wipe 'n Clean(r) erases all traces.
		$_GET['action'] = '';
		$_GET['board'] = '';
		$_GET['topic'] = '';
		writeLog(true);

		require_once($sourcedir . '/LogInOut.php');
		Logout(true, false);

		fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_login']['reason']) ? '' : '
' . $_SESSION['ban']['cannot_login']['reason']) . '
' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']) . '
' . $txt['ban_continue_browse'], false, 403);
	}

	// Fix up the banning permissions.
	if (isset($user_info['permissions']))
		banPermissions();
}

/**
 * Fix permissions according to ban status.
 * Applies any states of banning by removing permissions the user cannot have.
 */
function banPermissions()
{
	global $user_info, $sourcedir, $modSettings, $context;

	// Somehow they got here, at least take away all permissions...
	if (isset($_SESSION['ban']['cannot_access']))
		$user_info['permissions'] = array();
	// Okay, well, you can watch, but don't touch a thing.
	elseif (isset($_SESSION['ban']['cannot_post']) || (!empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $user_info['warning']))
	{
		$denied_permissions = array(
			'pm_send',
			'calendar_post', 'calendar_edit_own', 'calendar_edit_any',
			'poll_post',
			'poll_add_own', 'poll_add_any',
			'poll_edit_own', 'poll_edit_any',
			'poll_lock_own', 'poll_lock_any',
			'poll_remove_own', 'poll_remove_any',
			'manage_attachments', 'manage_smileys', 'manage_boards', 'admin_forum', 'manage_permissions',
			'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news',
			'profile_identity_any', 'profile_extra_any', 'profile_title_any',
			'profile_forum_any', 'profile_other_any', 'profile_signature_any',
			'post_new', 'post_reply_own', 'post_reply_any',
			'delete_own', 'delete_any', 'delete_replies',
			'make_sticky',
			'merge_any', 'split_any',
			'modify_own', 'modify_any', 'modify_replies',
			'move_any',
			'lock_own', 'lock_any',
			'remove_own', 'remove_any',
			'post_unapproved_topics', 'post_unapproved_replies_own', 'post_unapproved_replies_any',
		);
		call_integration_hook('integrate_post_ban_permissions', array(&$denied_permissions));
		$user_info['permissions'] = array_diff($user_info['permissions'], $denied_permissions);
	}
	// Are they absolutely under moderation?
	elseif (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $user_info['warning'])
	{
		// Work out what permissions should change...
		$permission_change = array(
			'post_new' => 'post_unapproved_topics',
			'post_reply_own' => 'post_unapproved_replies_own',
			'post_reply_any' => 'post_unapproved_replies_any',
			'post_attachment' => 'post_unapproved_attachments',
		);
		call_integration_hook('integrate_warn_permissions', array(&$permission_change));
		foreach ($permission_change as $old => $new)
		{
			if (!in_array($old, $user_info['permissions']))
				unset($permission_change[$old]);
			else
				$user_info['permissions'][] = $new;
		}
		$user_info['permissions'] = array_diff($user_info['permissions'], array_keys($permission_change));
	}

	// @todo Find a better place to call this? Needs to be after permissions loaded!
	// Finally, some bits we cache in the session because it saves queries.
	if (isset($_SESSION['mc']) && $_SESSION['mc']['time'] > $modSettings['settings_updated'] && $_SESSION['mc']['id'] == $user_info['id'])
		$user_info['mod_cache'] = $_SESSION['mc'];
	else
	{
		require_once($sourcedir . '/Subs-Auth.php');
		rebuildModCache();
	}

	// Now that we have the mod cache taken care of lets setup a cache for the number of mod reports still open
	if (isset($_SESSION['rc']['reports']) && isset($_SESSION['rc']['member_reports']) && $_SESSION['rc']['time'] > $modSettings['last_mod_report_action'] && $_SESSION['rc']['id'] == $user_info['id'])
	{
		$context['open_mod_reports'] = $_SESSION['rc']['reports'];
		$context['open_member_reports'] = $_SESSION['rc']['member_reports'];
	}
	elseif ($_SESSION['mc']['bq'] != '0=1')
	{
		require_once($sourcedir . '/Subs-ReportedContent.php');
		$context['open_mod_reports'] = recountOpenReports('posts');
		$context['open_member_reports'] = recountOpenReports('members');
	}
	else
	{
		$context['open_mod_reports'] = 0;
		$context['open_member_reports'] = 0;
	}
}

/**
 * Log a ban in the database.
 * Log the current user in the ban logs.
 * Increment the hit counters for the specified ban ID's (if any.)
 *
 * @param array $ban_ids The IDs of the bans
 * @param string $email The email address associated with the user that triggered this hit
 */
function log_ban($ban_ids = array(), $email = null)
{
	global $user_info, $smcFunc;

	// Don't log web accelerators, it's very confusing...
	if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
		return;

	$smcFunc['db_insert']('',
		'{db_prefix}log_banned',
		array('id_member' => 'int', 'ip' => 'inet', 'email' => 'string', 'log_time' => 'int'),
		array($user_info['id'], $user_info['ip'], ($email === null ? ($user_info['is_guest'] ? '' : $user_info['email']) : $email), time()),
		array('id_ban_log')
	);

	// One extra point for these bans.
	if (!empty($ban_ids))
		$smcFunc['db_query']('', '
			UPDATE {db_prefix}ban_items
			SET hits = hits + 1
			WHERE id_ban IN ({array_int:ban_ids})',
			array(
				'ban_ids' => $ban_ids,
			)
		);
}

/**
 * Checks if a given email address might be banned.
 * Check if a given email is banned.
 * Performs an immediate ban if the turns turns out positive.
 *
 * @param string $email The email to check
 * @param string $restriction What type of restriction (cannot_post, cannot_register, etc.)
 * @param string $error The error message to display if they are indeed banned
 */
function isBannedEmail($email, $restriction, $error)
{
	global $txt, $smcFunc;

	// Can't ban an empty email
	if (empty($email) || trim($email) == '')
		return;

	// Let's start with the bans based on your IP/hostname/memberID...
	$ban_ids = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['ids'] : array();
	$ban_reason = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['reason'] : '';

	// ...and add to that the email address you're trying to register.
	$request = $smcFunc['db_query']('', '
		SELECT bi.id_ban, bg.' . $restriction . ', bg.cannot_access, bg.reason
		FROM {db_prefix}ban_items AS bi
			INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
		WHERE {string:email} LIKE bi.email_address
			AND (bg.' . $restriction . ' = {int:cannot_access} OR bg.cannot_access = {int:cannot_access})
			AND (bg.expire_time IS NULL OR bg.expire_time >= {int:now})',
		array(
			'email' => $email,
			'cannot_access' => 1,
			'now' => time(),
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		if (!empty($row['cannot_access']))
		{
			$_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
			$_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
		}
		if (!empty($row[$restriction]))
		{
			$ban_ids[] = $row['id_ban'];
			$ban_reason = $row['reason'];
		}
	}
	$smcFunc['db_free_result']($request);

	// You're in biiig trouble.  Banned for the rest of this session!
	if (isset($_SESSION['ban']['cannot_access']))
	{
		log_ban($_SESSION['ban']['cannot_access']['ids']);
		$_SESSION['ban']['last_checked'] = time();

		fatal_error(sprintf($txt['your_ban'], $txt['guest_title']) . $_SESSION['ban']['cannot_access']['reason'], false);
	}

	if (!empty($ban_ids))
	{
		// Log this ban for future reference.
		log_ban($ban_ids, $email);
		fatal_error($error . $ban_reason, false);
	}
}

/**
 * Make sure the user's correct session was passed, and they came from here.
 * Checks the current session, verifying that the person is who he or she should be.
 * Also checks the referrer to make sure they didn't get sent here.
 * Depends on the disableCheckUA setting, which is usually missing.
 * Will check GET, POST, or REQUEST depending on the passed type.
 * Also optionally checks the referring action if passed. (note that the referring action must be by GET.)
 *
 * @param string $type The type of check (post, get, request)
 * @param string $from_action The action this is coming from
 * @param bool $is_fatal Whether to die with a fatal error if the check fails
 * @return string The error message if is_fatal is false.
 */
function checkSession($type = 'post', $from_action = '', $is_fatal = true)
{
	global $context, $sc, $modSettings, $boardurl;

	// Is it in as $_POST['sc']?
	if ($type == 'post')
	{
		$check = isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null);
		if ($check !== $sc)
			$error = 'session_timeout';
	}

	// How about $_GET['sesc']?
	elseif ($type == 'get')
	{
		$check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : null);
		if ($check !== $sc)
			$error = 'session_verify_fail';
	}

	// Or can it be in either?
	elseif ($type == 'request')
	{
		$check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : (isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null)));

		if ($check !== $sc)
			$error = 'session_verify_fail';
	}

	// Verify that they aren't changing user agents on us - that could be bad.
	if ((!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] != $_SERVER['HTTP_USER_AGENT']) && empty($modSettings['disableCheckUA']))
		$error = 'session_verify_fail';

	// Make sure a page with session check requirement is not being prefetched.
	if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
	{
		ob_end_clean();
		send_http_status(403);
		die;
	}

	// Check the referring site - it should be the same server at least!
	if (isset($_SESSION['request_referer']))
		$referrer = $_SESSION['request_referer'];
	else
		$referrer = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();

	// Check the refer but if we have CORS enabled and it came from a trusted source, we can skip this check.
	if (!empty($referrer['host']) && (empty($modSettings['allow_cors']) || empty($context['valid_cors_found']) || !in_array($context['valid_cors_found'], array('same', 'subdomain'))))
	{
		if (strpos($_SERVER['HTTP_HOST'], ':') !== false)
			$real_host = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
		else
			$real_host = $_SERVER['HTTP_HOST'];

		$parsed_url = parse_url($boardurl);

		// Are global cookies on?  If so, let's check them ;).
		if (!empty($modSettings['globalCookies']))
		{
			if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
				$parsed_url['host'] = $parts[1];

			if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $referrer['host'], $parts) == 1)
				$referrer['host'] = $parts[1];

			if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $real_host, $parts) == 1)
				$real_host = $parts[1];
		}

		// Okay: referrer must either match parsed_url or real_host.
		if (isset($parsed_url['host']) && strtolower($referrer['host']) != strtolower($parsed_url['host']) && strtolower($referrer['host']) != strtolower($real_host))
		{
			$error = 'verify_url_fail';
			$log_error = true;
		}
	}

	// Well, first of all, if a from_action is specified you'd better have an old_url.
	if (!empty($from_action) && (!isset($_SESSION['old_url']) || preg_match('~[?;&]action=' . $from_action . '([;&]|$)~', $_SESSION['old_url']) == 0))
	{
		$error = 'verify_url_fail';
		$log_error = true;
	}

	if (strtolower($_SERVER['HTTP_USER_AGENT']) == 'hacker')
		fatal_error('Sound the alarm!  It\'s a hacker!  Close the castle gates!!', false);

	// Everything is ok, return an empty string.
	if (!isset($error))
		return '';
	// A session error occurred, show the error.
	elseif ($is_fatal)
	{
		if (isset($_GET['xml']))
		{
			ob_end_clean();
			send_http_status(403, 'Forbidden - Session timeout');
			die;
		}
		else
			fatal_lang_error($error, isset($log_error) ? 'user' : false);
	}
	// A session error occurred, return the error to the calling function.
	else
		return $error;

	// We really should never fall through here, for very important reasons.  Let's make sure.
	trigger_error('Hacking attempt...', E_USER_ERROR);
}

/**
 * Check if a specific confirm parameter was given.
 *
 * @param string $action The action we want to check against
 * @return bool|string True if the check passed or a token
 */
function checkConfirm($action)
{
	global $modSettings, $smcFunc;

	if (isset($_GET['confirm']) && isset($_SESSION['confirm_' . $action]) && md5($_GET['confirm'] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['confirm_' . $action])
		return true;

	else
	{
		$token = md5($smcFunc['random_int']() . session_id() . (string) microtime() . $modSettings['rand_seed']);
		$_SESSION['confirm_' . $action] = md5($token . $_SERVER['HTTP_USER_AGENT']);

		return $token;
	}
}

/**
 * Lets give you a token of our appreciation.
 *
 * @param string $action The action to create the token for
 * @param string $type The type of token ('post', 'get' or 'request')
 * @return array An array containing the name of the token var and the actual token
 */
function createToken($action, $type = 'post')
{
	global $modSettings, $context, $smcFunc;

	$token = md5($smcFunc['random_int']() . session_id() . (string) microtime() . $modSettings['rand_seed'] . $type);
	$token_var = substr(preg_replace('~^\d+~', '', md5($smcFunc['random_int']() . (string) microtime() . $smcFunc['random_int']())), 0, $smcFunc['random_int'](7, 12));

	$_SESSION['token'][$type . '-' . $action] = array($token_var, md5($token . $_SERVER['HTTP_USER_AGENT']), time(), $token);

	$context[$action . '_token'] = $token;
	$context[$action . '_token_var'] = $token_var;

	return array($action . '_token_var' => $token_var, $action . '_token' => $token);
}

/**
 * Only patrons with valid tokens can ride this ride.
 *
 * @param string $action The action to validate the token for
 * @param string $type The type of request (get, request, or post)
 * @param bool $reset Whether to reset the token and display an error if validation fails
 * @return bool returns whether the validation was successful
 */
function validateToken($action, $type = 'post', $reset = true)
{
	$type = $type == 'get' || $type == 'request' ? $type : 'post';

	// This nasty piece of code validates a token.
	/*
		1. The token exists in session.
		2. The {$type} variable should exist.
		3. We concat the variable we received with the user agent
		4. Match that result against what is in the session.
		5. If it matches, success, otherwise we fallout.
	*/
	if (isset($_SESSION['token'][$type . '-' . $action], $GLOBALS['_' . strtoupper($type)][$_SESSION['token'][$type . '-' . $action][0]]) && md5($GLOBALS['_' . strtoupper($type)][$_SESSION['token'][$type . '-' . $action][0]] . $_SERVER['HTTP_USER_AGENT']) === $_SESSION['token'][$type . '-' . $action][1])
	{
		// Invalidate this token now.
		unset($_SESSION['token'][$type . '-' . $action]);

		return true;
	}

	// Patrons with invalid tokens get the boot.
	if ($reset)
	{
		// Might as well do some cleanup on this.
		cleanTokens();

		// I'm back baby.
		createToken($action, $type);

		fatal_lang_error('token_verify_fail', false);
	}
	// Remove this token as its useless
	else
		unset($_SESSION['token'][$type . '-' . $action]);

	// Randomly check if we should remove some older tokens.
	if (mt_rand(0, 138) == 23)
		cleanTokens();

	return false;
}

/**
 * Removes old unused tokens from session
 * defaults to 3 hours before a token is considered expired
 * if $complete = true will remove all tokens
 *
 * @param bool $complete Whether to remove all tokens or only expired ones
 */
function cleanTokens($complete = false)
{
	// We appreciate cleaning up after yourselves.
	if (!isset($_SESSION['token']))
		return;

	// Clean up tokens, trying to give enough time still.
	foreach ($_SESSION['token'] as $key => $data)
		if ($data[2] + 10800 < time() || $complete)
			unset($_SESSION['token'][$key]);
}

/**
 * Check whether a form has been submitted twice.
 * Registers a sequence number for a form.
 * Checks whether a submitted sequence number is registered in the current session.
 * Depending on the value of is_fatal shows an error or returns true or false.
 * Frees a sequence number from the stack after it's been checked.
 * Frees a sequence number without checking if action == 'free'.
 *
 * @param string $action The action - can be 'register', 'check' or 'free'
 * @param bool $is_fatal Whether to die with a fatal error
 * @return void|bool If the action isn't check, returns nothing, otherwise returns whether the check was successful
 */
function checkSubmitOnce($action, $is_fatal = true)
{
	global $context, $txt;

	if (!isset($_SESSION['forms']))
		$_SESSION['forms'] = array();

	// Register a form number and store it in the session stack. (use this on the page that has the form.)
	if ($action == 'register')
	{
		$context['form_sequence_number'] = 0;
		while (empty($context['form_sequence_number']) || in_array($context['form_sequence_number'], $_SESSION['forms']))
			$context['form_sequence_number'] = mt_rand(1, 16000000);
	}
	// Check whether the submitted number can be found in the session.
	elseif ($action == 'check')
	{
		if (!isset($_REQUEST['seqnum']))
			return true;
		elseif (!in_array($_REQUEST['seqnum'], $_SESSION['forms']))
		{
			$_SESSION['forms'][] = (int) $_REQUEST['seqnum'];
			return true;
		}
		elseif ($is_fatal)
			fatal_lang_error('error_form_already_submitted', false);
		else
			return false;
	}
	// Don't check, just free the stack number.
	elseif ($action == 'free' && isset($_REQUEST['seqnum']) && in_array($_REQUEST['seqnum'], $_SESSION['forms']))
		$_SESSION['forms'] = array_diff($_SESSION['forms'], array($_REQUEST['seqnum']));
	elseif ($action != 'free')
	{
		loadLanguage('Errors');
		trigger_error(sprintf($txt['check_submit_once_invalid_action'], $action), E_USER_WARNING);
	}
}

/**
 * Check the user's permissions.
 * checks whether the user is allowed to do permission. (ie. post_new.)
 * If boards is specified, checks those boards instead of the current one.
 * If any is true, will return true if the user has the permission on any of the specified boards
 * Always returns true if the user is an administrator.
 *
 * @param string|array $permission A single permission to check or an array of permissions to check
 * @param int|array $boards The ID of a board or an array of board IDs if we want to check board-level permissions
 * @param bool $any Whether to check for permission on at least one board instead of all boards
 * @return bool Whether the user has the specified permission
 */
function allowedTo($permission, $boards = null, $any = false)
{
	global $user_info, $smcFunc;
	static $perm_cache = array();

	// You're always allowed to do nothing. (unless you're a working man, MR. LAZY :P!)
	if (empty($permission))
		return true;

	// You're never allowed to do something if your data hasn't been loaded yet!
	if (empty($user_info) || !isset($user_info['permissions']))
		return false;

	// Administrators are supermen :P.
	if ($user_info['is_admin'])
		return true;

	// Let's ensure this is an array.
	$permission = (array) $permission;

	// Are we checking the _current_ board, or some other boards?
	if ($boards === null)
	{
		if (count(array_intersect($permission, $user_info['permissions'])) != 0)
			return true;
		// You aren't allowed, by default.
		else
			return false;
	}
	elseif (!is_array($boards))
		$boards = array($boards);

	$cache_key = hash('md5', $user_info['id'] . '-' . implode(',', $permission) . '-' . implode(',', $boards) . '-' . $any);

	if (isset($perm_cache[$cache_key]))
		return $perm_cache[$cache_key];

	$request = $smcFunc['db_query']('', '
		SELECT MIN(bp.add_deny) AS add_deny
		FROM {db_prefix}boards AS b
			INNER JOIN {db_prefix}board_permissions AS bp ON (bp.id_profile = b.id_profile)
			LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
			LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND modgs.id_group IN ({array_int:group_list}))
		WHERE b.id_board IN ({array_int:board_list})
			AND bp.id_group IN ({array_int:group_list}, {int:moderator_group})
			AND bp.permission IN ({array_string:permission_list})
			AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})
		GROUP BY b.id_board',
		array(
			'current_member' => $user_info['id'],
			'board_list' => $boards,
			'group_list' => $user_info['groups'],
			'moderator_group' => 3,
			'permission_list' => $permission,
		)
	);

	if ($any)
	{
		$result = false;
		while ($row = $smcFunc['db_fetch_assoc']($request))
		{
			$result = !empty($row['add_deny']);
			if ($result == true)
				break;
		}
		$smcFunc['db_free_result']($request);
		$return = $result;
	}

	// Make sure they can do it on all of the boards.
	elseif ($smcFunc['db_num_rows']($request) != count($boards))
		$return = false;

	else
	{
		$result = true;
		while ($row = $smcFunc['db_fetch_assoc']($request))
			$result &= !empty($row['add_deny']);
		$smcFunc['db_free_result']($request);
		$return = $result;
	}

	$perm_cache[$cache_key] = $return;

	// If the query returned 1, they can do it... otherwise, they can't.
	return $return;
}

/**
 * Fatal error if they cannot.
 * Uses allowedTo() to check if the user is allowed to do permission.
 * Checks the passed boards or current board for the permission.
 * If $any is true, the user only needs permission on at least one of the boards to pass
 * If they are not, it loads the Errors language file and shows an error using $txt['cannot_' . $permission].
 * If they are a guest and cannot do it, this calls is_not_guest().
 *
 * @param string|array $permission A single permission to check or an array of permissions to check
 * @param int|array $boards The ID of a single board or an array of board IDs if we're checking board-level permissions (null otherwise)
 * @param bool $any Whether to check for permission on at least one board instead of all boards
 */
function isAllowedTo($permission, $boards = null, $any = false)
{
	global $user_info, $txt;

	$heavy_permissions = array(
		'admin_forum',
		'manage_attachments',
		'manage_smileys',
		'manage_boards',
		'edit_news',
		'moderate_forum',
		'manage_bans',
		'manage_membergroups',
		'manage_permissions',
	);

	// Make it an array, even if a string was passed.
	$permission = (array) $permission;

	call_integration_hook('integrate_heavy_permissions_session', array(&$heavy_permissions));

	// Check the permission and return an error...
	if (!allowedTo($permission, $boards, $any))
	{
		// Pick the last array entry as the permission shown as the error.
		$error_permission = array_shift($permission);

		// If they are a guest, show a login. (because the error might be gone if they do!)
		if ($user_info['is_guest'])
		{
			loadLanguage('Errors');
			is_not_guest($txt['cannot_' . $error_permission]);
		}

		// Clear the action because they aren't really doing that!
		$_GET['action'] = '';
		$_GET['board'] = '';
		$_GET['topic'] = '';
		writeLog(true);

		fatal_lang_error('cannot_' . $error_permission, false);

		// Getting this far is a really big problem, but let's try our best to prevent any cases...
		trigger_error('Hacking attempt...', E_USER_ERROR);
	}

	// If you're doing something on behalf of some "heavy" permissions, validate your session.
	// (take out the heavy permissions, and if you can't do anything but those, you need a validated session.)
	if (!allowedTo(array_diff($permission, $heavy_permissions), $boards))
		validateSession();
}

/**
 * Return the boards a user has a certain (board) permission on. (array(0) if all.)
 *  - returns a list of boards on which the user is allowed to do the specified permission.
 *  - returns an array with only a 0 in it if the user has permission to do this on every board.
 *  - returns an empty array if he or she cannot do this on any board.
 * If check_access is true will also make sure the group has proper access to that board.
 *
 * @param string|array $permissions A single permission to check or an array of permissions to check
 * @param bool $check_access Whether to check only the boards the user has access to
 * @param bool $simple Whether to return a simple array of board IDs or one with permissions as the keys
 * @return array An array of board IDs or an array containing 'permission' => 'board,board2,...' pairs
 */
function boardsAllowedTo($permissions, $check_access = true, $simple = true)
{
	global $user_info, $smcFunc;

	// Arrays are nice, most of the time.
	$permissions = (array) $permissions;

	/*
	 * Set $simple to true to use this function as it were in SMF 2.0.x.
	 * Otherwise, the resultant array becomes split into the multiple
	 * permissions that were passed. Other than that, it's just the normal
	 * state of play that you're used to.
	 */

	// Administrators are all powerful, sorry.
	if ($user_info['is_admin'])
	{
		if ($simple)
			return array(0);
		else
		{
			$boards = array();
			foreach ($permissions as $permission)
				$boards[$permission] = array(0);

			return $boards;
		}
	}

	// All groups the user is in except 'moderator'.
	$groups = array_diff($user_info['groups'], array(3));

	$request = $smcFunc['db_query']('', '
		SELECT b.id_board, bp.add_deny' . ($simple ? '' : ', bp.permission') . '
		FROM {db_prefix}board_permissions AS bp
			INNER JOIN {db_prefix}boards AS b ON (b.id_profile = bp.id_profile)
			LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
			LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND modgs.id_group IN ({array_int:group_list}))
		WHERE bp.id_group IN ({array_int:group_list}, {int:moderator_group})
			AND bp.permission IN ({array_string:permissions})
			AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})' .
			($check_access ? ' AND {query_see_board}' : ''),
		array(
			'current_member' => $user_info['id'],
			'group_list' => $groups,
			'moderator_group' => 3,
			'permissions' => $permissions,
		)
	);
	$boards = array();
	$deny_boards = array();
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		if ($simple)
		{
			if (empty($row['add_deny']))
				$deny_boards[] = $row['id_board'];
			else
				$boards[] = $row['id_board'];
		}
		else
		{
			if (empty($row['add_deny']))
				$deny_boards[$row['permission']][] = $row['id_board'];
			else
				$boards[$row['permission']][] = $row['id_board'];
		}
	}
	$smcFunc['db_free_result']($request);

	if ($simple)
		$boards = array_unique(array_values(array_diff($boards, $deny_boards)));
	else
	{
		foreach ($permissions as $permission)
		{
			// never had it to start with
			if (empty($boards[$permission]))
				$boards[$permission] = array();
			else
			{
				// Or it may have been removed
				$deny_boards[$permission] = isset($deny_boards[$permission]) ? $deny_boards[$permission] : array();
				$boards[$permission] = array_unique(array_values(array_diff($boards[$permission], $deny_boards[$permission])));
			}
		}
	}

	return $boards;
}

/**
 * This function attempts to protect from spammed messages and the like.
 * The time taken depends on error_type - generally uses the modSetting.
 *
 * @param string $error_type The error type. Also used as a $txt index (not an actual string).
 * @param boolean $only_return_result Whether you want the function to die with a fatal_lang_error.
 * @return bool Whether they've posted within the limit
 */
function spamProtection($error_type, $only_return_result = false)
{
	global $modSettings, $user_info, $smcFunc;

	// Certain types take less/more time.
	$timeOverrides = array(
		'login' => 2,
		'register' => 2,
		'remind' => 30,
		'sendmail' => $modSettings['spamWaitTime'] * 5,
		'reporttm' => $modSettings['spamWaitTime'] * 4,
		'search' => !empty($modSettings['search_floodcontrol_time']) ? $modSettings['search_floodcontrol_time'] : 1,
	);

	call_integration_hook('integrate_spam_protection', array(&$timeOverrides));

	// Moderators are free...
	if (!allowedTo('moderate_board'))
		$timeLimit = isset($timeOverrides[$error_type]) ? $timeOverrides[$error_type] : $modSettings['spamWaitTime'];
	else
		$timeLimit = 2;

	// Delete old entries...
	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}log_floodcontrol
		WHERE log_time < {int:log_time}
			AND log_type = {string:log_type}',
		array(
			'log_time' => time() - $timeLimit,
			'log_type' => $error_type,
		)
	);

	// Add a new entry, deleting the old if necessary.
	$smcFunc['db_insert']('replace',
		'{db_prefix}log_floodcontrol',
		array('ip' => 'inet', 'log_time' => 'int', 'log_type' => 'string'),
		array($user_info['ip'], time(), $error_type),
		array('ip', 'log_type')
	);

	// If affected is 0 or 2, it was there already.
	if ($smcFunc['db_affected_rows']() != 1)
	{
		// Spammer!  You only have to wait a *few* seconds!
		if (!$only_return_result)
			fatal_lang_error($error_type . '_WaitTime_broken', false, array($timeLimit));

		return true;
	}

	// They haven't posted within the limit.
	return false;
}

/**
 * A generic function to create a pair of index.php and .htaccess files in a directory
 *
 * @param string|array $paths The (absolute) directory path
 * @param boolean $attachments Whether this is an attachment directory
 * @return bool|array True on success an array of errors if anything fails
 */
function secureDirectory($paths, $attachments = false)
{
	$errors = array();

	// Work with arrays
	$paths = (array) $paths;

	if (empty($paths))
		$errors[] = 'empty_path';

	if (!empty($errors))
		return $errors;

	foreach ($paths as $path)
	{
		if (!is_writable($path))
		{
			$errors[] = 'path_not_writable';

			continue;
		}

		$directory_name = basename($path);

		$close = empty($attachments) ? '
</Files>' : '
	Allow from localhost
</Files>

RemoveHandler .php .php3 .phtml .cgi .fcgi .pl .fpl .shtml';

		if (file_exists($path . '/.htaccess'))
		{
			$errors[] = 'htaccess_exists';

			continue;
		}

		else
		{
			$fh = @fopen($path . '/.htaccess', 'w');

			if ($fh)
			{
				fwrite($fh, '<Files *>
	Order Deny,Allow
	Deny from all' . $close);
				fclose($fh);
			}

			else
				$errors[] = 'htaccess_cannot_create_file';
		}

		if (file_exists($path . '/index.php'))
		{
			$errors[] = 'index-php_exists';

			continue;
		}

		else
		{
			$fh = @fopen($path . '/index.php', 'w');

			if ($fh)
			{
				fwrite($fh, '<' . '?php

/**
 * This file is here solely to protect your ' . $directory_name . ' directory.
 */

// Look for Settings.php....
if (file_exists(dirname(dirname(__FILE__)) . \'/Settings.php\'))
{
	// Found it!
	require(dirname(dirname(__FILE__)) . \'/Settings.php\');
	header(\'location: \' . $boardurl);
}
// Can\'t find it... just forget it.
else
	exit;

?' . '>');
				fclose($fh);
			}

			else
				$errors[] = 'index-php_cannot_create_file';
		}
	}

	if (!empty($errors))
		return $errors;

	else
		return true;
}

/**
 * This sets the X-Frame-Options header.
 *
 * @param string $override An option to override (either 'SAMEORIGIN' or 'DENY')
 * @since 2.1
 */
function frameOptionsHeader($override = null)
{
	global $modSettings;

	$option = 'SAMEORIGIN';
	if (is_null($override) && !empty($modSettings['frame_security']))
		$option = $modSettings['frame_security'];
	elseif (in_array($override, array('SAMEORIGIN', 'DENY')))
		$option = $override;

	// Don't bother setting the header if we have disabled it.
	if ($option == 'DISABLE')
		return;

	// Finally set it.
	header('x-frame-options: ' . $option);

	// And some other useful ones.
	header('x-xss-protection: 1');
	header('x-content-type-options: nosniff');
}

/**
 * This sets the Access-Control-Allow-Origin header.
 * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
 *
 * @param bool $set_header (Default: true): When false, we will do the logic, but not send the headers.  The relevant logic is still saved in the $context and can be sent manually.
 *
 * @since 2.1
 */
function corsPolicyHeader($set_header = true)
{
	global $boardurl, $modSettings, $context;

	if (empty($modSettings['allow_cors']))
		return;

	// We want weak security.
	if (!empty($modSettings['cors_domains']) && $modSettings['cors_domains'] === '*')
		$context['cors_domain'] = '*';

	// If subdomain-independent cookies are on, allow sub domains. This will have issues if the forum is at forum.domain.tld and the origin we are at is another.sub.domain.tld.
	if (empty($context['cors_domain']) && !empty($modSettings['globalCookies']) && !empty($_SERVER['HTTP_ORIGIN']) && filter_var($_SERVER['HTTP_ORIGIN'], FILTER_VALIDATE_URL) !== false && FindCorsBaseUrl($boardurl, true) === FindCorsBaseUrl($_SERVER['HTTP_ORIGIN'], true))
	{
		$context['cors_domain'] = $_SERVER['HTTP_ORIGIN'];
		$context['valid_cors_found'] = 'subdomain';
	}

	// Support forum_alias_urls as well, which is supported by our login cookie, so we implant it similar here.
	if (empty($context['cors_domain']) && !empty($modSettings['forum_alias_urls']) && !empty($_SERVER['HTTP_ORIGIN']) && filter_var($_SERVER['HTTP_ORIGIN'], FILTER_VALIDATE_URL) !== false)
	{
		$aliases = explode(',', $modSettings['forum_alias_urls']);

		foreach ($aliases as $alias)
		{
			if ($alias === $_SERVER['HTTP_ORIGIN'])
			{
				$context['cors_domain'] = $_SERVER['HTTP_ORIGIN'];
				$context['valid_cors_found'] = 'alias';
				break;
			}
		}
	}

	// Additional CORS domains but its just a wildcard for everything.
	if (empty($context['cors_domain']) && !empty($modSettings['cors_domains']) && !empty($_SERVER['HTTP_ORIGIN']) && filter_var($_SERVER['HTTP_ORIGIN'], FILTER_VALIDATE_URL) !== false)
	{
		$cors_domains = explode(',', $modSettings['cors_domains']);
		$origin_base = FindCorsBaseUrl($_SERVER['HTTP_ORIGIN']);

		foreach ($cors_domains as $domain)
		{
			if ($domain === $_SERVER['HTTP_ORIGIN'])
			{
				$context['cors_domain'] = $_SERVER['HTTP_ORIGIN'];
				$context['valid_cors_found'] = 'additional';
				break;
			}

			// If we find a * in the host, then its a wildcard and lets allow it.  This will have issues if the forum is at forum.domain.tld and the origin we are at is more.sub.domain.tld.
			if ('*' === implode('.', array_slice(explode('.', parse_url($domain, PHP_URL_HOST)), 0, 1)) && FindCorsBaseUrl($domain, true) === $origin_base)
			{
				$context['cors_domain'] = $_SERVER['HTTP_ORIGIN'];
				$context['valid_cors_found'] = 'additional_wildcard';
				break;
			}
		}
	}

	// The default is just to place the domain of the boardurl into the policy.
	if (empty($context['cors_domain']) || empty($context['valid_cors_found']))
	{
		$boardurl_parts = parse_url($boardurl);

		// Default the CORS to the current domain
		$context['cors_domain'] = $boardurl_parts['scheme'] . '://' . $boardurl_parts['host'];

		// Attach the port if needed.
		if (!empty($boardurl_parts['port']))
			$context['cors_domain'] .= ':' . $boardurl_parts['port'];

		$context['valid_cors_found'] = 'same';
	}

	$context['cors_headers'] = 'X-SMF-AJAX';

	// Any additional headers?
	if (!empty($modSettings['cors_headers']))
	{
		// Cleanup any typos.
		$cors_headers = explode(',', $modSettings['cors_headers']);
		foreach ($cors_headers as &$ch)
			$ch = trim(str_replace(' ', '-', $ch));

		$context['cors_headers'] += implode(',', $cors_headers);
	}

	// Allowing Cross-Origin Resource Sharing (CORS).
	if ($set_header && !empty($modSettings['allow_cors']) && !empty($context['valid_cors_found']) && !empty($context['cors_domain']))
	{
		header('Access-Control-Allow-Origin: ' . $context['cors_domain']);
		header('Access-Control-Allow-Headers: ' . $context['cors_headers']);

		// Be careful with this, you're allowing an external site to allow the browser to send cookies with this.
		if (!empty($modSettings['allow_cors_credentials']))
			header('Access-Control-Allow-Credentials: true');
	}
}

/**
 * Helper function to figure out a urls base domain.
 *
 * @param string $url The url/domain/host we are attempting to vaalidate for the base domain.
 * @param bool $sub_domain (Default: false): When true it will lowest level of a domain off before performing any other logic.

 * @since 2.1
 */
function FindCorsBaseUrl($url, $sub_domain = false)
{
	global $modSettings;

	$base_domain = parse_url($url, PHP_URL_HOST);

	// Are we saying this is a sub domain and to remove another domain level?
	if ($sub_domain)
		$base_domain = implode('.', array_slice(explode('.', parse_url($base_domain, PHP_URL_HOST)), 1));

	// If we find www, pop it out.
	else if ('www' === array_slice(explode('.', $base_domain), 0, 1))
		$base_domain = implode('.', array_slice(explode('.', $base_domain, 1)), 1);

	/*	Note, we do have a TLD regex for the autolinker, however it can not reliably be used here due to
		Country Code Second Level Domains (example: co.uk) as they are not TLDs.  As these are also
		controlled by their respective countries, there is no uniformity or standards on these domains.
		If this wasn't true, we could use this tld regex to just find the next domain level
		after the TLD and that would be our "truest" base.
	*/

	return $base_domain;
}

?>


text:
package com.jetbrains.jsonSchema;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.ZipperUpdater;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileContentsChangedAdapter;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.impl.BulkVirtualFileListenerAdapter;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiTreeAnyChangeAbstractAdapter;
import com.intellij.util.Alarm;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.Topic;
import com.jetbrains.jsonSchema.ide.JsonSchemaService;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * @author Irina.Chernushina on 3/30/2016.
 */
public class JsonSchemaVfsListener extends BulkVirtualFileListenerAdapter {
  public static final Topic<Runnable> JSON_SCHEMA_CHANGED = Topic.create("JsonSchemaVfsListener.Json.Schema.Changed", Runnable.class);

  public static void startListening(@NotNull Project project, @NotNull final JsonSchemaService service) {
    final MyUpdater updater = new MyUpdater(project, service);
    ApplicationManager.getApplication().getMessageBus().connect(project)
      .subscribe(VirtualFileManager.VFS_CHANGES, new JsonSchemaVfsListener(updater));
    PsiManager.getInstance(project).addPsiTreeChangeListener(new PsiTreeAnyChangeAbstractAdapter() {
      @Override
      protected void onChange(@Nullable PsiFile file) {
        if (file != null) updater.onFileChange(file.getViewProvider().getVirtualFile());
      }
    });
  }

  private JsonSchemaVfsListener(@NotNull MyUpdater updater) {
    super(new VirtualFileContentsChangedAdapter() {
      private final MyUpdater myUpdater = updater;

      protected void onFileChange(@NotNull final VirtualFile schemaFile) {
        myUpdater.onFileChange(schemaFile);
      }

      @Override
      protected void onBeforeFileChange(@NotNull VirtualFile schemaFile) {
        myUpdater.onFileChange(schemaFile);
      }
    });
  }

  private static class MyUpdater {
    @NotNull private final Project myProject;
    private final ZipperUpdater myUpdater;
    @NotNull private final JsonSchemaService myService;
    private final Set<VirtualFile> myDirtySchemas = ContainerUtil.newConcurrentSet();
    private final Runnable myRunnable;

    protected MyUpdater(@NotNull Project project, @NotNull JsonSchemaService service) {
      myProject = project;
      myUpdater = new ZipperUpdater(200, Alarm.ThreadToUse.POOLED_THREAD, project);
      myService = service;
      myRunnable = () -> {
        final Set<VirtualFile> scope = new HashSet<>(myDirtySchemas);
        myDirtySchemas.removeAll(scope);
        if (scope.isEmpty()) return;

        final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(project);
        final PsiManager psiManager = PsiManager.getInstance(project);
        final Editor[] editors = EditorFactory.getInstance().getAllEditors();
        Arrays.stream(editors).filter(editor -> editor instanceof EditorEx)
          .map(editor -> ((EditorEx)editor).getVirtualFile())
          .filter(file -> file != null && file.isValid())
          .forEach(file -> {
            final Collection<VirtualFile> schemaFiles = myService.getSchemaFilesForFile(file);
            if (schemaFiles.stream().anyMatch(scope::contains)) {
              ReadAction.run(() -> Optional.ofNullable(psiManager.findFile(file)).ifPresent(analyzer::restart));
            }
          });
      };
    }

    protected void onFileChange(@NotNull final VirtualFile schemaFile) {
      if (myService.isSchemaFile(schemaFile)) {
        myProject.getMessageBus().syncPublisher(JSON_SCHEMA_CHANGED).run();
        myDirtySchemas.add(schemaFile);
        myUpdater.queue(myRunnable);
      }
    }
  }
}


text:
using System;
using System.Collections.Generic;
using CrossStitch.Core.Models;

namespace CrossStitch.Core.Utility
{
    public interface IDataRepository
    {
        bool Delete<TEntity>(string id) where TEntity : class, IDataEntity;
        TEntity Get<TEntity>(string id) where TEntity : class, IDataEntity;
        IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class, IDataEntity;
        TEntity Insert<TEntity>(TEntity entity) where TEntity : class, IDataEntity;
        bool Save<TEntity>(TEntity entity, bool force = false) where TEntity : class, IDataEntity;
        TEntity Update<TEntity>(string id, Action<TEntity> update) where TEntity : class, IDataEntity;
    }
}


text:
const BigNumber = web3.BigNumber

require('chai')
  .use(require('chai-as-promised'))
  .use(require('chai-bignumber')(BigNumber))
  .should();

import EVMThrow from './helpers/EVMThrow'
import latestTime from './helpers/latestTime';
import {increaseTimeTo, duration} from './helpers/increaseTime';

const MintableToken = artifacts.require('MintableToken');
const TokenVesting = artifacts.require('TokenVesting');

contract('TokenVesting', function ([_, owner, beneficiary]) {

  const amount = new BigNumber(1000);

  beforeEach(async function () {
    this.token = await MintableToken.new({ from: owner });

    this.start = latestTime() + duration.minutes(1); // +1 minute so it starts after contract instantiation
    this.cliff = duration.years(1);
    this.duration = duration.years(2);

    this.vesting = await TokenVesting.new(beneficiary, this.start, this.cliff, this.duration, true, { from: owner });

    await this.token.mint(this.vesting.address, amount, { from: owner });
  });

  it('cannot be released before cliff', async function () {
    await this.vesting.release(this.token.address).should.be.rejectedWith(EVMThrow);
  });

  it('can be released after cliff', async function () {
    await increaseTimeTo(this.start + this.cliff + duration.weeks(1));
    await this.vesting.release(this.token.address).should.be.fulfilled;
  });

  it('should release proper amount after cliff', async function () {
    await increaseTimeTo(this.start + this.cliff);

    const { receipt } = await this.vesting.release(this.token.address);
    const releaseTime = web3.eth.getBlock(receipt.blockNumber).timestamp;

    const balance = await this.token.balanceOf(beneficiary);
    balance.should.bignumber.equal(amount.mul(releaseTime - this.start).div(this.duration).floor());
  });

  it('should linearly release tokens during vesting period', async function () {
    const vestingPeriod = this.duration - this.cliff;
    const checkpoints = 4;

    for (let i = 1; i <= checkpoints; i++) {
      const now = this.start + this.cliff + i * (vestingPeriod / checkpoints);
      await increaseTimeTo(now);

      await this.vesting.release(this.token.address);
      const balance = await this.token.balanceOf(beneficiary);
      const expectedVesting = amount.mul(now - this.start).div(this.duration).floor();

      balance.should.bignumber.equal(expectedVesting);
    }
  });

  it('should have released all after end', async function () {
    await increaseTimeTo(this.start + this.duration);
    await this.vesting.release(this.token.address);
    const balance = await this.token.balanceOf(beneficiary);
    balance.should.bignumber.equal(amount);
  });

  it('should be revoked by owner if revocable is set', async function () {
    await this.vesting.revoke(this.token.address, { from: owner }).should.be.fulfilled;
  });

  it('should fail to be revoked by owner if revocable not set', async function () {
    const vesting = await TokenVesting.new(beneficiary, this.start, this.cliff, this.duration, false, { from: owner } );
    await vesting.revoke(this.token.address, { from: owner }).should.be.rejectedWith(EVMThrow);
  });

  it('should return the non-vested tokens when revoked by owner', async function () {
    await increaseTimeTo(this.start + this.cliff + duration.weeks(12));

    const vested = await this.vesting.vestedAmount(this.token.address);
    const balance = await this.token.balanceOf(this.vesting.address);

    await this.vesting.revoke(this.token.address, { from: owner });

    const ownerBalance = await this.token.balanceOf(owner);
    ownerBalance.should.bignumber.equal(balance.sub(vested));
  });

  it('should keep the vested tokens when revoked by owner', async function () {
    await increaseTimeTo(this.start + this.cliff + duration.weeks(12));

    const vestedPre = await this.vesting.vestedAmount(this.token.address);

    await this.vesting.revoke(this.token.address, { from: owner });

    const vestedPost = await this.vesting.vestedAmount(this.token.address);

    vestedPre.should.bignumber.equal(vestedPost);
  });

  it('should fail to be revoked a second time', async function () {
    await increaseTimeTo(this.start + this.cliff + duration.weeks(12));

    const vested = await this.vesting.vestedAmount(this.token.address);

    await this.vesting.revoke(this.token.address, { from: owner });

    await this.vesting.revoke(this.token.address, { from: owner }).should.be.rejectedWith(EVMThrow);
  });

});


text:
:man_page: mongoc_client_set_read_concern

mongoc_client_set_read_concern()
================================

Synopsis
--------

.. code-block:: c

  void
  mongoc_client_set_read_concern (mongoc_client_t *client,
                                  const mongoc_read_concern_t *read_concern);

Sets the read concern for the client. This only affects future operations, collections, and databases inheriting from ``client``.

The default read concern is MONGOC_READ_CONCERN_LEVEL_LOCAL. This is the correct read concern for the great majority of applications.

It is a programming error to call this function on a client from a :symbol:`mongoc_client_pool_t`. For pooled clients, set the read concern with the :ref:`MongoDB URI <mongoc_uri_t_read_concern_options>` instead.

Parameters
----------

* ``client``: A :symbol:`mongoc_client_t`.
* ``read_concern``: A :symbol:`mongoc_read_concern_t`.