text:
class Profile;

// Clears cookies and local storage for origins that are defined as session-only
// through settings, extensions or enterprise policy and clears session cookies
// (cookies without expiration date) unless the startup preference is set to
// continue the previous session or |skip_session_cookies| is true.
// |callback| is called when session-only origin cookies and storage deletions
// are finished. It does not wait for deletion of regular session cookies since
// these cookies are cleaned up on startup as well.
class SessionDataDeleter {
 public:
  explicit SessionDataDeleter(Profile* profile);
  SessionDataDeleter(const SessionDataDeleter&) = delete;
  SessionDataDeleter& operator=(const SessionDataDeleter&) = delete;
  virtual ~SessionDataDeleter();

  // Starts deletion of session data. Keeps the Profile and browser process
  // alive until deletion is finished. Must not be called when the browser is
  // already shutting down (browser_shutdown::IsTryingToQuit()).
  virtual void DeleteSessionOnlyData(bool skip_session_cookies,
                                     base::OnceClosure callback);

 private:
  raw_ptr<Profile> profile_;
};

#endif  // CHROME_BROWSER_SESSIONS_SESSION_DATA_DELETER_H_


text:
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>or-tools/src/base/: operations_research::MutableIter< Container > Class Template Reference - Doxy</title>
    <link rel="shortcut icon" href="../../../favicon.ico">

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

          Generated on: Thu Mar 29 07:46:58 PDT 2012
            for custom file set

        <tt>//
            doxy/
            or-tools/
            src/
            base/
            </tt>

Main Page

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

operations_research::MutableIter

operations_research::MutableIter< Container > Class Template Reference
Note: this class is not compatible with sets (operator* returns a non-const reference).
More...

#include <concise_iterator.h>

List of all members.

Public Types

typedef Container 	container_type

typedef Container::value_type 	value_type

typedef Container::iterator 	iterator_type

typedef Container::const_iterator 	const_iterator_type

Public Member Functions

 	MutableIter (container_type &container)

 	NOLINT.

 	MutableIter (const MutableIter &source)

MutableIter & 	operator= (const MutableIter &source)

bool 	operator== (const MutableIter &iter) const

value_type * 	operator-> () const

value_type & 	operator* () const

const container_type * 	const_container () const

const_iterator_type 	const_iterator () const

container_type * 	container () const

iterator_type 	iterator () const

MutableIter & 	operator++ ()

MutableIter 	operator++ (int unused)

bool 	at_end () const

MutableIter & 	erase ()

Detailed Description

template<class Container>

 class operations_research::MutableIter< Container >

Note: this class is not compatible with sets (operator* returns a non-const reference).

Definition at line 111 of file concise_iterator.h.

Member Typedef Documentation

template<class Container>

          typedef Container operations_research::MutableIter< Container >::container_type

Definition at line 113 of file concise_iterator.h.

template<class Container>

          typedef Container::value_type operations_research::MutableIter< Container >::value_type

Definition at line 114 of file concise_iterator.h.

template<class Container>

          typedef Container::iterator operations_research::MutableIter< Container >::iterator_type

Definition at line 115 of file concise_iterator.h.

template<class Container>

          typedef Container::const_iterator operations_research::MutableIter< Container >::const_iterator_type

Definition at line 116 of file concise_iterator.h.

Constructor & Destructor Documentation

template<class Container>

          operations_research::MutableIter< Container >::MutableIter
          (
          container_type &
           container
           )
           [inline, explicit]

NOLINT.

Definition at line 118 of file concise_iterator.h.

template<class Container>

          operations_research::MutableIter< Container >::MutableIter
          (
          const MutableIter< Container > &
           source
           )
           [inline]

Definition at line 120 of file concise_iterator.h.

Member Function Documentation

template<class Container>

          MutableIter& operations_research::MutableIter< Container >::operator=
          (
          const MutableIter< Container > &
           source
           )
           [inline]

Definition at line 124 of file concise_iterator.h.

template<class Container>

          bool operations_research::MutableIter< Container >::operator==
          (
          const MutableIter< Container > &
           iter
           )
           const [inline]

Definition at line 129 of file concise_iterator.h.

template<class Container>

          value_type* operations_research::MutableIter< Container >::operator->
          (

           )
           const [inline]

Definition at line 132 of file concise_iterator.h.

template<class Container>

          value_type& operations_research::MutableIter< Container >::operator*
          (

           )
           const [inline]

Definition at line 133 of file concise_iterator.h.

template<class Container>

          const container_type* operations_research::MutableIter< Container >::const_container
          (

           )
           const [inline]

Definition at line 134 of file concise_iterator.h.

template<class Container>

          const_iterator_type operations_research::MutableIter< Container >::const_iterator
          (

           )
           const [inline]

Definition at line 135 of file concise_iterator.h.

template<class Container>

          container_type* operations_research::MutableIter< Container >::container
          (

           )
           const [inline]

Definition at line 136 of file concise_iterator.h.

template<class Container>

          iterator_type operations_research::MutableIter< Container >::iterator
          (

           )
           const [inline]

Definition at line 137 of file concise_iterator.h.

template<class Container>

          MutableIter& operations_research::MutableIter< Container >::operator++
          (

           )
           [inline]

Definition at line 138 of file concise_iterator.h.

template<class Container>

          MutableIter operations_research::MutableIter< Container >::operator++
          (
          int
           unused
           )
           [inline]

Definition at line 142 of file concise_iterator.h.

template<class Container>

          bool operations_research::MutableIter< Container >::at_end
          (

           )
           const [inline]

Definition at line 147 of file concise_iterator.h.

template<class Container>

          MutableIter& operations_research::MutableIter< Container >::erase
          (

           )
           [inline]

Definition at line 148 of file concise_iterator.h.

The documentation for this class was generated from the following file:

or-tools/src/base/concise_iterator.h

redpajama_set_name: RedPajamaGithub


text:
/* @flow */
/* eslint max-len: 0 */

import {Reporter} from '../../src/reporters/index.js';
import Config from '../../src/config.js';
import * as fs from '../../src/util/fs.js';

jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;

const https = require('https');
const path = require('path');

test('RequestManager.request with cafile', async () => {
  let body;
  const options = {
    key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
    cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
  };
  const server = https.createServer(options, (req, res) => { res.end('ok'); });
  try {
    server.listen(0);
    const config = await Config.create({'cafile': path.join(__dirname, '..', 'fixtures', 'certificates', 'cacerts.pem')});
    const port = server.address().port;
    body = await config.requestManager.request({url: `https://localhost:${port}/?nocache`, headers: {Connection: 'close'}});
  } finally {
    server.close();
  }
  expect(body).toBe('ok');
});

test('RequestManager.request with ca (string)', async () => {
  let body;
  const options = {
    key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
    cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
  };
  const server = https.createServer(options, (req, res) => { res.end('ok'); });
  try {
    server.listen(0);
    const bundle = await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'cacerts.pem'));
    const hasPemPrefix = (block) => block.startsWith('-----BEGIN ');
    const caCerts = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix);
    // the 2nd cert is valid one
    const config = await Config.create({'ca': caCerts[1]});
    const port = server.address().port;
    body = await config.requestManager.request({url: `https://localhost:${port}/?nocache`, headers: {Connection: 'close'}});
  } finally {
    server.close();
  }
  expect(body).toBe('ok');
});

test('RequestManager.request with ca (array)', async () => {
  let body;
  const options = {
    key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
    cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
  };
  const server = https.createServer(options, (req, res) => { res.end('ok'); });
  try {
    server.listen(0);
    const bundle = await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'cacerts.pem'));
    const hasPemPrefix = (block) => block.startsWith('-----BEGIN ');
    const caCerts = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix);
    const config = await Config.create({'ca': caCerts});
    const port = server.address().port;
    body = await config.requestManager.request({url: `https://localhost:${port}/?nocache`, headers: {Connection: 'close'}});
  } finally {
    server.close();
  }
  expect(body).toBe('ok');
});

test('RequestManager.request with mutual TLS', async () => {
  let body;
  const options = {
    key: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-key.pem')),
    cert: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-cert.pem')),
    ca: await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'server-ca-cert.pem')),
    requestCert: true,
    rejectUnauthorized: true,
  };
  const server = https.createServer(options, (req, res) => { res.end('ok'); });
  try {
    server.listen(0);
    const config = await Config.create({
      'cafile': path.join(__dirname, '..', 'fixtures', 'certificates', 'server-ca-cert.pem'),
      'key': await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'client-key.pem')),
      'cert': await fs.readFile(path.join(__dirname, '..', 'fixtures', 'certificates', 'client-cert.pem')),
    });
    const port = server.address().port;
    body = await config.requestManager.request({url: `https://localhost:${port}/?nocache`, headers: {Connection: 'close'}});
  } finally {
    server.close();
  }
  expect(body).toBe('ok');
});

test('RequestManager.execute Request 403 error', async () => {
  const config = await Config.create({}, new Reporter());
  jest.mock('request', (factory) => (options) => {
    options.callback('', {statusCode: 403}, '');
    return {
      on: () => {},
    };
  });
  await config.requestManager.execute({
    params: {url: `https://localhost:port/?nocache`, headers: {Connection: 'close'}},
    resolve: (body) => {},
    reject: (err) => {
      expect(err.message).toBe('https://localhost:port/?nocache: Request "https://localhost:port/?nocache" returned a 403');
    },
  });
});

test('RequestManager.request with offlineNoRequests', async () => {
  const config = await Config.create({offline: true}, new Reporter());
  try {
    await config.requestManager.request({url: `https://localhost:port/?nocache`, headers: {Connection: 'close'}});
  } catch (err) {
    expect(err.message).toBe('Can\'t make a request in offline mode');
  }
});

test('RequestManager.saveHar no captureHar error message', async () => {
  const config = await Config.create({captureHar: false}, new Reporter());
  try {
    config.requestManager.saveHar('testFile');
  } catch (err) {
    expect(err.message).toBe('RequestManager was not setup to capture HAR files');
  }
});


text:
<?php

namespace Drush\Queue;

class QueueException extends \Exception {}


text:
import { Component } from '@angular/core';

@Component({
  selector: 'step-6',
  templateUrl: './step-6.component.html'
})
export class Step6Component {

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#pragma once
#include <utility>
#include <vector>
#include <string>
#include <mutex>
#include <condition_variable>
#include "core/common/common.h"
#include "core/common/path_string.h"
#include "core/framework/framework_common.h"
#include "core/framework/ort_value.h"
#include "core/platform/path_lib.h"
#include "core/platform/threadpool.h"
#include "orttraining/models/runner/training_util.h"

namespace onnxruntime {
namespace training {

/*
This buffer is thread safe, to make sure data set
could be loaded asynchronously.
*/
class DataSetBuffer {
 public:
  DataSetBuffer() {
  }

  // For our data prefetch scenario, when we are getting one data set
  // which's not ready, we should wait until it's ready.
  std::shared_ptr<DataSet> Get(size_t index) {
    std::unique_lock<std::mutex> lk(mutex_);
    cv_.wait(lk, [&] { return data_sets_.count(index) != 0; });
    return data_sets_[index];
  }

  void Set(size_t index, std::shared_ptr<DataSet> data_set) {
    std::unique_lock<std::mutex> lk(mutex_);
    data_sets_[index] = data_set;
    lk.unlock();
    cv_.notify_all();
  }

  bool Remove(size_t index) {
    std::lock_guard<std::mutex> lk(mutex_);
    if (data_sets_.count(index) == 0) {
      return false;
    }

    data_sets_[index].reset();
    data_sets_.erase(index);
    return true;
  }

 private:
  std::unordered_map<size_t, std::shared_ptr<DataSet>> data_sets_;
  std::mutex mutex_;
  std::condition_variable cv_;
};

class IDataLoader {
 public:
  virtual ~IDataLoader() = default;

  // Sets the initial data set index. It should be set at most once prior to calling other functions.
  virtual Status InitializeDataSetIndex(size_t initial_data_set_index) = 0;

  virtual std::shared_ptr<DataSet> CurrentDataSet() = 0;

  virtual size_t CurrentDataSetIndex() const = 0;

  virtual size_t NumShards() const = 0;

  virtual std::shared_ptr<DataSet> MoveToNextDataSet() = 0;

  // Input Name for Graph
  virtual const VectorString& DataSetTensorNames() const = 0;
};

/*
Training file is organized in the following format:

  [Sample ByteSize] [Feature0 ByteSize] [Feature0 TensorProto] ... [FeatureN ByteSize] [FeatureN TensorProto]
  next sample ...

All the bytesize fields are stored as 4 bytes uint32_t
*/
class DataLoader : public IDataLoader {
 public:
  DataLoader(const MapStringToString& input_name_map,
             const PathString& dir_path,
             size_t max_num_files_preload = 2,
             size_t world_rank = 0,
             size_t world_size = 1);

  Status InitializeDataSetIndex(size_t initial_data_set_index) override;

  std::shared_ptr<DataSet> CurrentDataSet() override {
    EnsurePreloadedOrThrow();
    return buffer_.Get(active_file_index_);
  }

  size_t CurrentDataSetIndex() const override { return active_file_index_; }

  size_t NumShards() const override { return data_files_.size(); }

  std::shared_ptr<DataSet> MoveToNextDataSet() override;

  const VectorString& DataSetTensorNames() const override {
    return input_tensor_names_;
  }

 private:
  common::Status InitialPreLoadAsync();

  void EnsurePreloadedOrThrow();

  size_t NumInputs() const { return input_tensor_names_.size(); }

  common::Status LoadFile(const PathString& file_path, std::shared_ptr<DataSet>& data_set);

  common::Status LoadOneSample(google::protobuf::io::CodedInputStream& coded_in,
                               uint32_t sample_size,
                               std::shared_ptr<DataSet>& data_set);

  void LoadAndRemoveInternalAsync(size_t index_to_load, bool need_remove, size_t index_to_remove);

  // TensorName in File -> Input Name for Graph
  MapStringToString input_name_map_;

  // Input Name for Graph
  VectorString input_tensor_names_;

  // TensorName in File -> Index in input_tensor_names_
  std::map<std::string, size_t> input_to_feature_index_map_;

  const size_t max_num_files_preload_;

  std::vector<PathString> data_files_;

  size_t active_file_index_ = 0;

  DataSetBuffer buffer_;

  std::unique_ptr<onnxruntime::concurrency::ThreadPool> data_loader_thread_pool_;

  // number of thread pool threads
  // NOTE: Currently, thread pool requests should be serialized for correctness
  //     (i.e., this should be 1). Otherwise, race conditions can occur - e.g.,
  //     a data set gets removed and then waited for indefinitely.
  const int32_t thread_pool_size_ = 1;

  // indicates whether initial preloading has occurred
  bool is_preloaded_ = false;
};

// Loader that only load one single DataSet.
class SingleDataLoader : public IDataLoader {
 public:
  SingleDataLoader(std::shared_ptr<DataSet> single_data_set, VectorString input_tensor_names)
      : data_set_(single_data_set), input_tensor_names_(input_tensor_names) {}

  Status InitializeDataSetIndex(size_t initial_data_set_index) override {
    ORT_RETURN_IF_NOT(initial_data_set_index == 0, "initial_data_set_index != 0");
    return Status::OK();
  }

  std::shared_ptr<DataSet> CurrentDataSet() override {
    return data_set_;
  }

  size_t CurrentDataSetIndex() const override { return 0; }

  size_t NumShards() const override { return 1; }

  std::shared_ptr<DataSet> MoveToNextDataSet() override {
    return data_set_;
  }

  const VectorString& DataSetTensorNames() const override {
    return input_tensor_names_;
  }

 private:
  const std::shared_ptr<DataSet> data_set_;
  const VectorString input_tensor_names_;
};

}  // namespace training
}  // namespace onnxruntime


text:
using System;
using System.Collections.Generic;
using Wave.Configuration;

namespace Wave
{
    /// <summary>
    /// Represents a serialized message - Used as a convienance object since C# doesn't allow for multiple return types
    /// </summary>
    [Serializable]
    public class RawMessage
    {
        private Dictionary<string, string> headers;

        public string Data { get; set; }

        public DateTime? DelayUntil
        {
            get
            {
                if (this.Headers.ContainsKey("DelayUntil") && !string.IsNullOrEmpty(this.Headers["DelayUntil"]))
                {
                    return new DateTime(DateTime.Parse(this.Headers["DelayUntil"]).Ticks, DateTimeKind.Utc);
                }

                return null;
            }

            set
            {
                this.Headers["DelayUntil"] = value.ToString();
            }
        }

        public Dictionary<string, string> Headers
        {
            get { return this.headers ?? (this.headers = new Dictionary<string, string>()); }
            set { this.headers = value; }
        }

        public Guid Id { get; set; }

        public string ReplyTopic
        {
            get
            {
                if (this.Headers.ContainsKey("ReplyTopic"))
                {
                    return this.Headers["ReplyTopic"];
                }

                return string.Empty;
            }

            set
            {
                this.Headers["ReplyTopic"] = value;
            }
        }

        public int RetryCount
        {
            get
            {
                if (this.Headers.ContainsKey("RetryCount") && !string.IsNullOrEmpty(this.headers["RetryCount"]))
                {
                    return int.Parse(this.Headers["RetryCount"]);
                }

                return 0;
            }

            set
            {
                this.Headers["RetryCount"] = value.ToString();
            }
        }
        public string Type
        {
            get
            {
                if (this.Headers.ContainsKey("Type"))
                {
                    return this.Headers["Type"];
                }

                return string.Empty;
            }

            set
            {
                this.Headers["Type"] = value;
            }
        }

        public static RawMessage Create(object message)
        {
            return new RawMessage
            {
                Data = ConfigurationContext.Current.Serializer.Serialize(message),
                Id = Guid.NewGuid(),
                Type = ConfigurationContext.Current.SubscriptionKeyResolver.GetKey(message.GetType()),
                ReplyTopic = ConfigurationContext.Current.QueueNameResolver.GetPrimaryQueueName()
            };
        }

        public override string ToString()
        {
            return this.Id.ToString();
        }
    }
}


text:
package com.opentok.accelerator.core.listeners;

import android.view.View;
import com.opentok.android.OpentokError;

public interface RetriableBasicListener<Wrapper>
  extends BasicListener<Wrapper>, RetriableOTListener {

  @Override
  void onConnected(Wrapper wrapper, int participantsNumber, String connId, String data);

  @Override
  void onDisconnected(Wrapper wrapper, int participantsNumber, String connId, String data);

  @Override
  void onPreviewViewReady(Wrapper wrapper, View localView);

  @Override
  void onPreviewViewDestroyed(Wrapper wrapper);

  @Override
  void onStartedPublishingMedia(Wrapper wrapper, boolean screenSharing);

  @Override
  void onStoppedPublishingMedia(Wrapper wrapper, boolean screenSharing);

  @Override
  void onRemoteViewReady(Wrapper wrapper, View remoteView, String remoteId, String data);

  @Override
  void onRemoteViewDestroyed(Wrapper wrapper, String remoteId);

  @Override
  void onRemoteJoined(Wrapper wrapper, String remoteId);

  @Override
  void onRemoteLeft(Wrapper wrapper, String remoteId);

  @Override
  void onRemoteVideoChanged(Wrapper wrapper, String remoteId, String reason, boolean videoActive,
                            boolean subscribed);

  @Override
  void onError(Wrapper wrapper, OpentokError error);
}


text:
<?php

use BoomCMS\Database\Models\Role;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class PopulateRolesTable extends Migration
{
    protected $roles = [
        ['name' => 'managePeople', 'tree' => false],
        ['name' => 'manageAssets', 'tree' => false],
        ['name' => 'toolbar', 'tree' => true],
        ['name' => 'delete', 'tree' => true],
        ['name' => 'add', 'tree' => true],
        ['name' => 'editFeature', 'tree' => true],
        ['name' => 'editTemplate', 'tree' => true],
        ['name' => 'publish', 'tree' => true],
        ['name' => 'editNavBasic', 'tree' => true],
        ['name' => 'editNavAdvanced', 'tree' => true],
        ['name' => 'editSearchBasic', 'tree' => true],
        ['name' => 'editSearchAdvanced', 'tree' => true],
        ['name' => 'editChildrenBasic', 'tree' => true],
        ['name' => 'editChildrenAdvanced', 'tree' => true],
        ['name' => 'editAdmin', 'tree' => true],
        ['name' => 'edit', 'tree' => true],
        ['name' => 'editUrls', 'tree' => true],
        ['name' => 'editAcl', 'tree' => true],
        ['name' => 'uploadAssets', 'tree' => false],
        ['name' => 'manageSites', 'tree' => false],
    ];

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Role::insert($this->roles);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('truncate roles');
    }
}


text:
#ifndef HELPERS_H
#define HELPERS_H

#ifdef WIN32
#include "win32_helpers.h"
#endif

#include "eiface.h"
#include "game/server/iplayerinfo.h"

extern IVEngineServer *engine;
extern IPlayerInfoManager *playerInfoManager;
extern CGlobalVars *gpGlobals;

enum TFTeam {
	TFTeam_Unassigned = 0,
	TFTeam_Spectator = 1,
	TFTeam_Red = 2,
	TFTeam_Blue = 3
};

// Ordered by TF2's internal indexes,
// not class selection screen ingame
enum TFClass {
	TFClass_Unknown = 0,
	TFClass_Scout,
	TFClass_Sniper,
	TFClass_Soldier,
	TFClass_DemoMan,
	TFClass_Medic,
	TFClass_Heavy,
	TFClass_Pyro,
	TFClass_Spy,
	TFClass_Engineer
};

#define Round(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))

extern int GetClientIndexForUserID(int userid);

#endif


text:
/*
    !!!!!!!!!!!!!!!!!

    THIS FILE SHOULD ACTUALLY BE SPLIT INTO TWO PIECES
    - ONE WITH THE COMMON PARTS BETWEEN OPIUM AND OPIUM LIGHT
    - ONE WITH THE PARTICULARITIES OF EACH
*/

/*
 *   everything which has to be defined in Opium but which is
 *   not part of an Opium scenario
 */

%:- import opium_level/1  from sepia_kernel.
:- import fd_open/3 	 from sepia_kernel.

/* set print_depth */
:- set_flag(print_depth, 1000).  % for writing lists and terms

/*  -----------------------
 *   init system variables
 *  -----------------------
 */

:- make_local_array(opium_loop_running).
% :- setval(opium_loop_running, 0).

:- make_local_array(tracing).
% :- setval(tracing, 0).

%% when opium_light is called there is necessarily an opium_loop_running !
:- setval(opium_loop_running, 1), setval(tracing, 1).

/*  ----------------------------------
 *   initialize toplevel module opium
 *  ----------------------------------
 */
% :- get_opium_file("opium_module", File),
%    compile(File, opium).

/*  ---------------------------------------------------------
 *   definition of MU-Prolog builtins not available in Sepia
 *  ---------------------------------------------------------
 */

:- global sprintf/3.
:- global namevar/2.

% :- skipped sprintf/3.
% :- skipped namevar/2.

/*
 *  sprintf/3
 *  the formatted string is converted to an atom an
 *  instantiated to the first parameter
 */
sprintf(Atom, Format, List) :-
	open(_, string, Stream),
	printf(Stream, Format, List),
	current_stream(String, _, Stream),
	atom_string(Atom, String),
	close(Stream).

/*
 *  namevar/2
 *  returns the name of a sepia variable as atom
 */
namevar(V, VN) :-
	var(V),
	open(_, string, Stream),
	printf(Stream, "%QDw", [V]),
	current_stream(S, _, Stream),
	atom_string(VN, S),
	close(Stream).

/*  -----------------------------------------------------
 *   opium_error_handler/3
 *   common declaration for all the error handlers which
 *   are modified in Opium
 *  -----------------------------------------------------
 */

opium_error_handler(68, Goal, Module) :-	% undefined procedure called
	to_be_autoloaded(Goal, Module, NewGoal),
	!,
	call(NewGoal, Module).
opium_error_handler(68, Goal, Module) :-
	error(default(68), Goal, Module).
opium_error_handler(134, Goal, Module) :-	% not consecutive clauses
	is_opium_obj(Goal),
	!,
	fail.
opium_error_handler(134, Goal, Module) :-
	error(default(134), Goal, Module).

is_opium_obj(opium_scenario/4).
is_opium_obj(opium_command/9).
is_opium_obj(opium_parameter/7).
is_opium_obj(opium_primitive/6).
is_opium_obj(opium_procedure/5).
is_opium_obj(opium_type/3).
is_opium_obj(opium_demo/4).

:- set_error_handler(134, opium_error_handler/3).
%:- set_error_handler(68,  opium_error_handler/3).  	% Opium's autoload

/*  -------------------------------
 *   re-definition of Sepia events
 *  -------------------------------
 */

/*
 *  banner printed in Opium session
 */
% :- dynamic boot_date/1.
% :- date(D), assert(boot_date(D)).
%
% opium_banner(_, Sepiabanner) :-
% 	write(toplevel_output, "SEPIA + Opium 3.1  "),
% 	boot_date(D),
% 	substring(D, 1, 10, D1),
% 	substring(D, 20, 5, D2),
% 	concat_strings(D1, D2, DD),
% 	write(toplevel_output, DD),
 *
% 	flush(toplevel_output).
%
% :- set_error_handler(164, opium_banner/2).

/*
 *  re-definition of opium_answer/2
 *  defined in ~/sepia/workdir/sepia/pl/boot_bips.pl
 */
opium_answer(_, yes).
opium_answer(_, no) :-
	write(toplevel_output, 'no.\n').
opium_answer(_, no_answer) :-
	write(toplevel_output, 'no (more) solution.\n').
opium_answer(_, last_yes).
opium_answer(_, last_answer) :-
	write(toplevel_output, '\n').
opium_answer(_, more_answers) :-
	write(toplevel_output, '     More? (;) '),
	flush(toplevel_output),
	tyi(toplevel_input, C),
	(C == 0'; ->
		write(toplevel_output, '\n'),
		fail
	;
		write(toplevel_output, '\n')
	).

:- set_error_handler(156, opium_answer/2).

/*
 *  to get number of break level in toplevel prompt
 */
% opium_toplevel_prompt(_, Module) :-
% 	get_prompt(toplevel_input, _, Out),
% 	write(Out, "["),
% 	write(Out, Module),
% 	get_flag(break_level, L),
% 	(L > 0 ->
% 		write(Out, " "),
% 		write(Out, L)
% 	;
% 		true
% 	),
% 	write(Out, "]: "),
% 	flush(Out).
%
% :- set_error_handler(153, opium_toplevel_prompt/2).

/*  --------------------------------------
 *   init_opium
 *   to be executed when Opium is started
 *  --------------------------------------
 */

%%% REPLACEMENT FOR OPIUM_LIGHT

:- setval(opium_level, 1).

% init_opium(X1, X2) :-
% 	set_interrupt_handler(18, true/0),	% disable ^Z in Opium
% 	set_interrupt_handler(2,  true/0),	% disable ^C
% 	argc(NArgs),
% 	NInitGoal is NArgs - 6,
% 	argv(NInitGoal, SInitGoal),
% 	term_string(InitGoal, SInitGoal),
% 	NP is NArgs - 5,
% 	argv(NP, PIDS),
% 	term_string(PID, PIDS),
% 	NL is NArgs - 4,
% 	argv(NL, LevS),
% 	term_string(Lev, LevS),
% 	set_opium_level(Lev),		% set level of current session
% 	NI is NArgs - 3,
% 	argv(NI, FD_Input),
% 	term_string(I, FD_Input),
% 	fd_open(I, read, from_prolog),	% open pipe to read from Prolog
% 	NO is NArgs - 2,
% 	argv(NO, FD_Output),
% 	term_string(O, FD_Output),
% 	fd_open(O, write, to_prolog),	% open pipe to write to Prolog
% 	NIAsy is NArgs - 1,
% 	argv(NIAsy, FD_InputAsy),
% 	term_string(IAsy, FD_InputAsy),
% 	fd_open(IAsy, read, from_prolog_asynch),
% 	setval(prolog_pid, PID),
% 	set_opium_pid_in_prolog,
% 	initialize_c_parameters,	% system parameters
% 	set_opium(X1, X2),		% opium is toplevel module
% 	call(InitGoal, X2),		% call the init goal
% 	opium_init_file,		% compile ".opiumrc"
% 	set_error_handler(150, true/0),	% no opium_init on re-start
% 	reset_interrupt_handler(2).	% enable ^C
%
% set_opium_pid_in_prolog :-
% 	get_flag(pid, OpiumPid),
% 	remote_once(setval(opium_pid, OpiumPid), sepia_kernel).

/*
 *  initialize parameters of type 'c'  (cannot be done without traced session)
 */
% initialize_c_parameters :-
% 	set_default_in_module(limit_depth,  opium_kernel),
% 	set_default_in_module(limit_call,   opium_kernel),
% 	set_default_in_module(record_trace, opium_kernel).

/*
 *  get opium as toplevel module
 */
% set_opium(_, opium).

/*
 *  load ./.opiumrc or ~/.opiumrc if you are an Opium session
 */
opium_init_file :-
	opium_level(0),
	!.
opium_init_file :-
	exists('.opiumrc'),
	!,
	compile('.opiumrc', opium).
opium_init_file :-
	getenv('HOME', X),
	append_strings(X, "/.opiumrc", M),
	atom_string(F, M),
	exists(F),
	!,
	compile(F, opium).
opium_init_file.

% :- set_error_handler(150, init_opium/2).

/*
 * Put the demo directory inside the library path.
 * This is duplicated in the opium_slave.pl as for the development
 *   version of sepium opium_slave.p is not loaded in opium-1 unless a
 *   second opium is explicitely called.
 */
:-	get_opiumdir(OD),
  	concat_strings(OD, "demo", OpiumDemo),
	get_flag(library_path, PathList),
	( member(OpiumDemo, PathList)
	-> true
	; append(PathList,[OpiumDemo], NewPathList),
	  set_flag(library_path, NewPathList)
	).


text:
require "spec_helper"

describe MpWeixin::Interface::Base do
  let(:access_token) { 'ACCESS_TOKEN' }
  let(:token_hash) { {"expires_in" => "7200", "access_token" => access_token} }
  let (:client) { MpWeixin::Client.from_hash(token_hash) }

  context "#initialize interface" do
    subject { MpWeixin::Interface::Base.new(client) }

    it "should have default_request_params" do
      expect(subject.default_request_params).to eq({"access_token" => access_token})
    end

  end
end


text:
<?php

namespace Frontend\FrontendBundle\Controller;

use MES\UserBundle\Entity\MesCompany;
use MES\UserBundle\Entity\MesProfile;
use MES\UserBundle\Form\MesCompanyType;
use MES\UserBundle\Form\MesProfileType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;

/**
 * @Route("/uzytkownik")
 */
class UserController extends Controller
{

    /**
     * @Route("/", name="frontend.user.index")
     * @Template()
     */
    public function indexAction()
    {
        return [];
    }

    /**
     * @Route("/moje-dane", name="frontend.user.details")
     * @Template()
     */
    public function detailsAction(Request $request)
    {
        $profileForm = $this->getProfileForm();
        $companyForm = $this->getCompanyForm();
        if ($request->isMethod('POST')) {
            $request->request->set('mesUser', $this->getUser()->getId());
            $companyForm->handleRequest($request);
            $profileForm->handleRequest($request);
            $em = $this->getDoctrine()->getManager();
            if ($profileForm->getClickedButton() && $profileForm->isValid()) {
                $data = $profileForm->getData();
                $data->setMesUser($this->getUser());
                $em->persist($data);
            }
            if ($companyForm->getClickedButton() && $companyForm->isValid()) {
                $data = $companyForm->getData();
                $data->setMesUser($this->getUser());
                $em->persist($data);
                $em->flush();
            }
        }
        return [
            'formDetails' => $profileForm->createView(),
            'formCompany' => $companyForm->createView()
        ];
    }

    /**
     *
     * @return Form
     */
    protected function getProfileForm()
    {
        $form = $this->createForm(new MesProfileType(), $this->getUserProfile());
        $form->add('submit', 'submit',
            [
            'label' => "Zapisz",
            'attr' => [
                'class' => 'btn-default'
            ],
        ]);
        return $form;
    }

    /**
     *
     * @return Form
     */
    protected function getCompanyForm()
    {
        $form = $this->createForm(new MesCompanyType(), $this->getUserCompany());
        $form->add('submit', 'submit',
            [
            'label' => "Zapisz",
            'attr' => [
                'class' => 'btn-default'
            ],
        ]);
        return $form;
    }

    /**
     *
     * @return MesProfile
     */
    protected function getUserProfile()
    {
        $em = $this->getDoctrine()->getManager();
        return $em->getRepository('MESUserBundle:MesProfile')->findOneBy(['mesUser' => $this->getUser()->getId()]);
    }

    /**
     *
     * @return MesCompany
     */
    protected function getUserCompany()
    {
        $em = $this->getDoctrine()->getManager();
        return $em->getRepository('MESUserBundle:MesCompany')->findOneBy(['mesUser' => $this->getUser()->getId()]);
    }

    /**
     * @Route("/moje-zamowienia/{orderId}", name="frontend.user.orders")
     * @Template()
     */
    public function ordersAction($orderId = null)
    {
        $products = [];
        if (is_numeric($orderId)) {
            /* @var $order \Frontend\OrderBundle\Entity\MesOrder */
            $order = $this->getDoctrine()->getManager()->getRepository('Frontend\OrderBundle\Entity\MesOrder')->findOneBy(['id' => $orderId]);
            if ($order->getMesUser()->contains($this->getUser())) {
                $products = ['order' => $order];
            }
        }
        return $products;
    }
}


text:
Rails.application.routes.draw do

  get 'boot/index'
  get 'boot/form'

  get 'welcome/index'

  get '/login' => 'session#new'
  get '/auth/github/callback' => 'session#create'
  get '/logout' => 'session#destroy'

  get 'appointments/results', to: 'appointment#result', as: :appointment_results
  get '/appointments/:id/cancel', to: 'appointment#cancel'
  get '/appointments/:id/edit', to: 'appointment#edit'
  get '/appointments/:id/confirm', to: 'appointment#confirm'
  get '/appointments/:id/decline', to: 'appointment#decline'

  post 'appointments/search', to: 'appointment#search', as: :appointment_search
  post 'appointments/book', to: 'appointment#book', as: :appointment_book
  post '/appointments/:id/edit', to: 'appointment#edit'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'welcome#index'

  resources :student, :tutor, :appointment

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end


text:
require "rom/associations/many_to_one"
require "rom/sql/associations/core"
require "rom/sql/associations/self_ref"

module ROM
  module SQL
    module Associations
      class ManyToOne < ROM::Associations::ManyToOne
        include Associations::Core
        include Associations::SelfRef

        # @api public
        def call(target: self.target, preload: false)
          if preload
            schema = target.schema.qualified
            relation = target
          else
            right = source

            target_pk = target.schema.primary_key_name
            right_fk = target.foreign_key(source.name)

            target_schema = target.schema
            right_schema = right.schema.project_pk

            schema =
              if target.schema.key?(right_fk)
                target_schema
              else
                target_schema.merge(right_schema.project_fk(target_pk => right_fk))
              end.qualified

            relation = target.join(source_table, join_keys)
          end

          if view
            apply_view(schema, relation)
          else
            schema.(relation)
          end
        end

        # @api public
        def join(type, source = self.source, target = self.target)
          source.__send__(type, target.name.dataset, join_keys).qualified
        end

        # @api private
        def prepare(target)
          call(target: target, preload: true)
        end
      end
    end
  end
end


text:
package zipkin2.server.internal.elasticsearch;

import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import zipkin2.elasticsearch.ElasticsearchStorage;
import zipkin2.server.internal.brave.ZipkinSelfTracingConfiguration;

import static org.assertj.core.api.Assertions.assertThat;
import static zipkin2.server.internal.elasticsearch.TestResponses.VERSION_RESPONSE;
import static zipkin2.server.internal.elasticsearch.TestResponses.YELLOW_RESPONSE;

class ITElasticsearchSelfTracing {

  @RegisterExtension static MockWebServerExtension server = new MockWebServerExtension();

  AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
  ElasticsearchStorage storage;

  @BeforeEach void init() {
    TestPropertyValues.of(
      "spring.config.name=zipkin-server",
      "zipkin.self-tracing.enabled=true",
      "zipkin.self-tracing.message-timeout=1ms",
      "zipkin.self-tracing.traces-per-second=10",
      "zipkin.storage.type=elasticsearch",
      "zipkin.storage.elasticsearch.ensure-templates=false",
      "zipkin.storage.elasticsearch.hosts=" + server.httpUri()).applyTo(context);
    Access.registerElasticsearch(context);
    context.register(ZipkinSelfTracingConfiguration.class);
    context.refresh();
    storage = context.getBean(ElasticsearchStorage.class);
  }

  @AfterEach void close() {
    storage.close();
  }

  /**
   * We currently don't have a nice way to mute outbound propagation in Brave. This just makes sure
   * we are nicer.
   */
  @Test void healthcheck_usesB3Single() {
    server.enqueue(VERSION_RESPONSE.toHttpResponse());
    server.enqueue(YELLOW_RESPONSE.toHttpResponse());

    assertThat(storage.check().ok()).isTrue();

    assertThat(server.takeRequest().request().headers())
      .extracting(e -> e.getKey().toString())
      .contains("b3")
      .doesNotContain("x-b3-traceid");
  }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>basic_static_string::erase (2 of 3 overloads)</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../index.html" title="Boost.StaticString">
<link rel="up" href="../erase.html" title="basic_static_string::erase">
<link rel="prev" href="overload1.html" title="basic_static_string::erase (1 of 3 overloads)">
<link rel="next" href="overload3.html" title="basic_static_string::erase (3 of 3 overloads)">

Home
Libraries
People
FAQ
More

basic_static_string::erase
          (2 of 3 overloads)

            Erase from the string.

            Synopsis

constexpr iterator
erase(
    const_iterator pos);

            Description

            Erases the character at pos.

            Preconditions

            posshall be valid within
            {data(),
            data()
            + size()}

            Exception
            Safety

            Strong guarantee.

            Remarks

            All references, pointers, or iterators referring to contained elements
            are invalidated. Any past-the-end iterators are also invalidated.

            Return
            Value

            An iterator referring to character immediately following the erased character,
            or end()
            if one does not exist.

            Parameters

<colgroup>
<col>
<col>
</colgroup>

                      Name

                      Description

                      pos

                      An iterator referring to the character to erase.

Copyright © 2019, 2020 Krystian Stasiowski
Copyright © 2016-2019 Vinnie
      Falco

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
fn main() {
    ● //~ ERROR: unknown start of token
}


text:
Since the introduction of WebView as an updatable APK in Android L, WebView has
had some conception of pre-release channels. The details of the implementation
of these channels has differed between different generations of WebView, and
this document explains those details.

[TOC]

## Standalone WebView (Android L - M)

The pre-release channels strategy of Chrome for Android has been to build
separate APKs, each with a unique package name, so that they can be installed
side-by-side. In contrast, Standalone WebView has only a single package name
(com.google.android.webview) that is recognized by Android as a valid WebView
provider, and instead utilizes [the "tracks"
API](https://developers.google.com/android-publisher/tracks) provided by Google
Play. This allows users to opt-in to beta updates, but users cannot have
simultaneous installations of both stable and beta Standalone WebView on a
single device.

All users that have Android System WebView installed and enabled are eligible to
receive updates published to the production track. In addition, users can opt-in
to the beta track by [joining the beta tester
program](/android_webview/docs/prerelease.md#android-l-or-m-plus-all-versions-of-android-without-chrome).
Once a user's account is in the beta program, it is eligible to receive updates
that have been published to the beta track. The Play Store updates users to the
APK with the highest `versionCode` among eligible tracks.

Google publishes an APK of Android System WebView to the beta track based on the
[same release cycle](https://chromiumdash.appspot.com/schedule) as Chrome Beta.

Similarly, builds of Chrome for "Dev" channel releases include a build of
WebView which gets published to an alpha track. Only users belonging to specific
internal Google groups are eligible for Play Store updates from Android System
WebView alpha track, including members of Google's internal Chrome for Android
and Android WebView teams.

### Changes in version 75.0.3770.40

Prior to version 75, WebView's internal logic had no way of knowing whether it
had been built for a dev, beta, or stable release. Beginning with version
75.0.3770.40, Google builds separate APKs for each of stable, beta, and dev
channels, with the internal logic differing only in that it is aware of which
channel it was built for.

This change allows for different logic flow depending on the channel, such as
sampling crash reports differently, targeting beta users for experiments, etc.

With this change, the WebView APKs belonging to the three different channels
were given [unique `versionCode` values](/build/util/android_chrome_version.py),
with stable having a final digit of 0, beta a final digit of 1, and dev 2.
Having identical package names required unique versionCodes for the different
channel builds to exist simultaneously on platforms like Google Play and
Google's internal crash and performance analytics infrastructure. These specific
values were chosen so that a user who has opted into the beta program will still
receive the beta APK (Play Store delivers the APK with the higher `versionCode`
value) even if a stable APK from the same build is available (such as when we
promote a beta build to stable), so that the user can receive beta-targeted
experiments.

To avoid conflicting with [Trichrome WebView's pre-release channel
strategy](#trichrome-android-q), Standalone WebView APKs are given a
`maxSdkVersion` value of 28, so that users who have opted into the beta program
described above do not experience the Play Store updating their Trichrome
WebView stable APK to Standalone WebView beta (since they share the same package
name).

## Monochrome (Android N - P)

For Android versions N - P, WebView is built as a part of the Chrome APK. Since
Chrome already supported side-by-side installs of different Chrome channels on
Android, a menu was added to Android's Developer Options Settings that [allows a
user to choose](/android_webview/docs/prerelease.md#android-n_o_or-p) which of
the installed versions of Chrome to use as the WebView.

## Trichrome (Android Q+)

For Android Q+, WebView and Chrome are again separately installed APKs. However,
Google began building a separate package of WebView for each of the four Chrome
channels: Stable, Beta, Dev, and Canary. Like with Monochrome, users can find
each of these four channels of WebView on the Play Store and install them
simultaneously on a single device. Also like Monochrome, users can use the
"WebView implementation" menu to choose which installed WebView the system should
use.

Trichrome WebView APKs (of all channels) have a `versionCode` value with a final
digit of 3 ([to match Trichrome Chrome's
`versionCode`](https://cs.chromium.org/chromium/src/build/util/android_chrome_version.py)).

Users may choose to opt into the beta program for Android System WebView
(com.google.android.webview), but it will have no effect on Android Q, as the
only APK of this package that gets published to the beta track is Standalone
WebView, which has a `maxSdkVersion` value of 28. While confusing, this helps
avoid the user's stable WebView installation being updated to beta, since the
preferred method for using WebView beta on Android Q is installing the separate
package from the Play Store. Without this, the same package would receive
updates from the builds of both Trichrome WebView stable (at the time of a
stable release) and Standalone WebView beta (at the time of a beta promotion).
Switching back and forth between these generations would involve very large
update deltas.

## See Also

- [Try out WebView beta](/android_webview/docs/prerelease.md)
- [Chrome Release
  Channels](https://www.chromium.org/getting-involved/dev-channel)


text:
package com.dianping.cat.alarm.spi.decorator;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;

import com.dianping.cat.Cat;

public class RuleFTLDecorator implements Initializable {

	public Configuration m_configuration;

	public String generateConfigsHtml(String templateValue) {
		Map<Object, Object> dataMap = new HashMap<Object, Object>();
		StringWriter sw = new StringWriter(5000);

		dataMap.put("configs", templateValue);
		try {
			Template configsTemplate = m_configuration.getTemplate("rule_configs.ftl");
			configsTemplate.process(dataMap, sw);
		} catch (Exception e) {
			Cat.logError(e);
		}
		return sw.toString();
	}

	@Override
	public void initialize() throws InitializationException {
		m_configuration = new Configuration();
		m_configuration.setDefaultEncoding("UTF-8");
		try {
			m_configuration.setClassForTemplateLoading(this.getClass(), "/freemaker");
		} catch (Exception e) {
			Cat.logError(e);
		}
	}
}


text:
<?php
declare(strict_types = 1);

namespace Tinker1987\BeanstalkBundle\Tests\Lib;

use Tinker1987\BeanstalkBundle\Exceptions\InvalidArgumentException;
use Tinker1987\BeanstalkBundle\Interfaces\JobInterface;
use Tinker1987\BeanstalkBundle\Lib\{
    HandledJob, Job, JobAdapter
};
use Pheanstalk\Job as PJob;

/**
 * Class JobAdapterTest
 * @package BeanstalkBundle\Tests
 * @author Dmytro Paiareli <dmitriy.payareli@gmail.com>
 */
class JobAdapterTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();
    }

    public function toPheanstalkJobDataProvider()
    {
        return [
            [new Job(1, 'payload'), new PJob(1, 'payload')],
            [new HandledJob(1, 'payload'), new PJob(1, 'payload')],
            [new PJob(1, 'payload'), new PJob(1, 'payload'), true]
        ];
    }

    /**
     * @dataProvider toPheanstalkJobDataProvider
     * @param JobInterface $inputJob
     * @param \Pheanstalk\Job $outputJob
     * @param $expectsError
     */
    public function testToPheanstalkJob($inputJob, $outputJob, $expectsError = false)
    {
        if ($expectsError) {
            $this->expectException(\TypeError::class);
        }

        self::assertEquals(
            get_class($outputJob),
            get_class(JobAdapter::toPheanstalkJob($inputJob)),
            'Wrong output class!'
        );
        self::assertEquals($outputJob->getId(), $inputJob->getId(), 'Jobs ID doesn\'t match!');
        self::assertEquals($outputJob->getData(), $inputJob->getData(), 'Jobs payload doesn\'t match!');
    }

    public function fromPheanstalkJobDataProvider()
    {
        return [
            [new PJob(1, 'payload'), new Job(1, 'payload'), Job::class],
            [new PJob(1, 'payload'), new HandledJob(1, 'payload'), HandledJob::class],
            [new PJob(1, 'payload'), new PJob(1, 'payload'), 'WrongJobClass', true]
        ];
    }

    /**
     * @dataProvider fromPheanstalkJobDataProvider
     * @param \Pheanstalk\Job $inputJob
     * @param JobInterface $outputJob
     * @param $outputClass
     * @param $expectsException
     */
    public function testFromPheanstalkJob($inputJob, $outputJob, $outputClass, $expectsException = false)
    {
        if ($expectsException) {
            $this->expectException(InvalidArgumentException::class);
        }

        self::assertEquals(
            get_class($outputJob),
            get_class(JobAdapter::fromPheanstalkJob($inputJob, $outputClass)),
            'Wrong output class!'
        );
        self::assertEquals($outputJob->getId(), $inputJob->getId(), 'Jobs ID doesn\'t match!');
        self::assertEquals($outputJob->getData(), $inputJob->getData(), 'Jobs payload doesn\'t match!');
    }
}


text:
/**
 * @author Alexander V. Astapchuk
 * @version $Revision$
 */
package org.apache.harmony.auth.module;

import java.util.Map;

import org.apache.harmony.auth.NTSidGroupPrincipal;
import org.apache.harmony.auth.NTSidPrimaryGroupPrincipal;
import org.apache.harmony.auth.NTSidUserPrincipal;

/**
 * A helper class which queries information about the current NT user.
 */
public final class NTSystem {

    // Shows whether the hyauth library was loaded or not
    private static boolean loadLibDone;

    // User's sid, domain and name
    private NTSidUserPrincipal user;

    // User's domain sid
    private String domainSid;

    // User's primary group
    /**/NTSidPrimaryGroupPrincipal mainGroup;

    // A list of groups the user belongs to
    /**/NTSidGroupPrincipal[] groups;

    // Impersonation token
    private long token;

    // May be used to trace the native library execution
    @SuppressWarnings("unused")
    private boolean debugNative;

    /**
     * The default constructor. Loads hyauth library if necessary.
     * @throws UnsatisfiedLinkError if library hyauth not found
     */
    public NTSystem() {
        super();
        synchronized (NTSystem.class) {
            if (!loadLibDone) {
                System.loadLibrary("hyauth"); //$NON-NLS-1$
                initNatives();
                loadLibDone = true;
            }
        }
    }

    /**
     * Constructs an instance with options.
     * @param options
     */
    public NTSystem(Map<String, ?> options) {
        this();
        debugNative = "true".equalsIgnoreCase((String) options //$NON-NLS-1$
                .get("debugNative")); //$NON-NLS-1$
    }

    /**
     * Initializes internal data.
     */
    private static native void initNatives();

    /**
     * Load the security information about user.
     */
    public native void load();

    /**
     * Frees internal data stored during login().
     */
    public native void free();

    /**
     * Returns name of user's domain
     */
    public String getDomain() {
        return user.getObjectDomain();
    }

    /**
     * Returns String representation of SID of user's domain
     */
    public String getDomainSID() {
        return domainSid;
    }

    /**
     * Returns array of SIDs of groups the user belongs to
     */
    public String[] getGroupIDs() {
        if (groups == null || groups.length == 0) {
            return null;
        }
        String[] gids = new String[groups.length];
        for (int i = 0; i < groups.length; i++) {
            gids[i] = groups[i].getName();
        }
        return gids;
    }

    /**
     * Returns implementation token
     */
    public long getImpersonationToken() {
        return token;
    }

    /**
     * Returns user name
     */
    public String getName() {
        return user.getObjectName();
    }

    /**
     * Returns a SID of user's main group
     */
    public String getPrimaryGroupID() {
        return mainGroup.getSid();
    }

    /**
     * Returns user's SID
     */
    public String getUserSID() {
        return user.getSid();
    }

    /**
     * Returns a String representation of this object.
     */
    @Override
    public String toString() {
        String s = "NTSystem:\n"; //$NON-NLS-1$
        s += "   user         : " + user + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
        s += "   domainSid    : " + domainSid + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
        s += "   mainGroup    : " + mainGroup + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
        s += "   token        : " + token + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
        s += "   groups count : " + (groups == null ? 0 : groups.length); //$NON-NLS-1$
        if (groups != null) {
            s += "\n"; //$NON-NLS-1$
            for (int i = 0; i < groups.length; i++) {
                s += "      " + i + "] " + groups[i] + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            }
        }
        return s;
    }

    /**
     * Returns an array of groups the user belongs to
     */
    public NTSidGroupPrincipal[] getGroups() {
        if (groups == null) {
            return null;
        }
        NTSidGroupPrincipal[] tmp = new NTSidGroupPrincipal[groups.length];
        System.arraycopy(groups, 0, tmp, 0, groups.length);
        return tmp;
    }
}


text:
#include "boot.h"

/*
  This code loads the OS Startup code from the disk to proper location in memory.
*/

void loadStartupCode()
{
  mode = KERNEL_MODE;
  emptyPage(OS_STARTUP_CODE_PAGENO);
  readFromDisk(OS_STARTUP_CODE_PAGENO, BOOT_BLOCK);
  storeInteger(reg[IP_REG], OS_STARTUP_CODE_PAGENO * PAGE_SIZE);
}

/*
  This function initialises all the registers to zero
*/
void initializeRegs() {
	int i;
	for(i=0; i<NUM_REGS; i++)
		storeInteger(reg[i],0);
}


text:
if ! docker ps -a | grep tt_instance >/dev/null; then
    docker run -d --dns 8.8.8.8 --dns 8.8.4.4 -it -v `pwd`:/app --name tt_instance tt /bin/bash;
    echo "tt_instance created" ;
else
    docker start tt_instance ;
    echo "Started existing tt instance" ;
fi
docker attach tt_instance


text:
Puppet module to manage pacemaker via pcs.

The puppet-pacemaker project has moved to: https://github.com/openstack/puppet-pacemaker


text:
<?php

namespace Flarum\Flags\Listeners;

use Flarum\Events\RegisterLocales;
use Flarum\Events\BuildClientView;
use Illuminate\Contracts\Events\Dispatcher;

class AddClientAssets
{
    public function subscribe(Dispatcher $events)
    {
        $events->listen(RegisterLocales::class, [$this, 'addLocale']);
        $events->listen(BuildClientView::class, [$this, 'addAssets']);
    }

    public function addLocale(RegisterLocales $event)
    {
        $event->addTranslations('en', __DIR__.'/../../locale/en.yml');
    }

    public function addAssets(BuildClientView $event)
    {
        $event->forumAssets([
            __DIR__.'/../../js/forum/dist/extension.js',
            __DIR__.'/../../less/forum/extension.less'
        ]);

        $event->forumBootstrapper('flags/main');

        $event->forumTranslations([
            'flags.reason_off_topic',
            'flags.reason_spam',
            'flags.reason_inappropriate',
            'flags.reason_other',
            'flags.flagged_by',
            'flags.flagged_by_with_reason',
            'flags.no_flags'
        ]);

        $event->adminAssets([
            __DIR__.'/../../js/admin/dist/extension.js',
            __DIR__.'/../../less/admin/extension.less'
        ]);

        $event->adminBootstrapper('flags/main');

        $event->adminTranslations([
            // 'flag.hello_world'
        ]);
    }
}


text:
package org.traccar.protocol;

import org.junit.Test;
import org.traccar.ProtocolTest;

public class ObdDongleProtocolDecoderTest extends ProtocolTest {

    @Test
    public void testDecode() throws Exception {

        ObdDongleProtocolDecoder decoder = new ObdDongleProtocolDecoder(new ObdDongleProtocol());

        verifyNull(decoder, binary(
                "55550003383634383637303232353131303135010009010011023402010201ABAAAA"));

        verifyPosition(decoder, binary(
                "5555000338363438363730323235313130313503000100010355AABBCC184F1ABC614E21C1FA08712A84ABAAAA"),
                position("2015-07-18 20:49:16.000", true, 22.12346, -123.45678));

    }

}


text:
package com.fruit.sales.common;

import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 * SpringMVC通用工具
 *
 *
 */
public final class WebContextHolder {

    private static final Logger logger = LoggerFactory.getLogger(WebContextHolder.class);

    public static String getSessionUsername(){
    	String username = (String) getSession().getAttribute(LoginUtil.USER_SESSION);
    	if(StringUtils.isEmpty(username)){
    		return LoginUtil.UNKONWN_USER;
    	}else{
    		return username;
    	}
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attributes.getRequest();
    }

    public static HttpSession getSession() {
        return getSession(true);
    }

    public static HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    public String getSessionId() {
        return getSession().getId();
    }

    public ServletContext getServletContext() {
        return getSession().getServletContext();    // servlet2.3
    }

    public Locale getLocale() {
        return RequestContextUtils.getLocale(getRequest());
    }

    public Theme getTheme() {
        return RequestContextUtils.getTheme(getRequest());
    }

    public ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }

    public ApplicationEventPublisher getApplicationEventPublisher() {
        return (ApplicationEventPublisher) getApplicationContext();
    }

    public LocaleResolver getLocaleResolver() {
        return RequestContextUtils.getLocaleResolver(getRequest());
    }

    public ThemeResolver getThemeResolver() {
        return RequestContextUtils.getThemeResolver(getRequest());
    }

    public ResourceLoader getResourceLoader() {
        return (ResourceLoader) getApplicationContext();
    }

    public ResourcePatternResolver getResourcePatternResolver() {
        return (ResourcePatternResolver) getApplicationContext();
    }

    public MessageSource getMessageSource() {
        return (MessageSource) getApplicationContext();
    }

    public ConversionService getConversionService() {
        return getBeanFromApplicationContext(ConversionService.class);
    }

    public Collection<String> getActiveProfiles() {
        return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
    }

    public ClassLoader getBeanClassLoader() {
        return ClassUtils.getDefaultClassLoader();
    }

    private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
        try {
            return getApplicationContext().getBean(requiredType);
        } catch (NoUniqueBeanDefinitionException e) {
        	logger.error(e.getMessage(), e);
            throw e;
        } catch (NoSuchBeanDefinitionException e) {
        	logger.warn(e.getMessage());
            return null;
        }
    }

}


text:
.class public interface abstract Lcom/sonyericsson/fmradio/service/SystemStateHandler$SystemStateListener;
.super Ljava/lang/Object;
.source "SystemStateHandler.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/sonyericsson/fmradio/service/SystemStateHandler;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "SystemStateListener"
.end annotation

# virtual methods
.method public abstract onAudioBecomingNoisy()V
.end method

.method public abstract onSleep()V
.end method

.method public abstract onWake()V
.end method


text:
<?php

declare(strict_types=1);

namespace Sphp\Html\Exceptions;

use Sphp\Exceptions\SphpException;

/**
 * Exception thrown if an HTML error occurs
 *
 * @author  Sami Holck <sami.holck@gmail.com>
 * @license https://opensource.org/licenses/MIT MIT License
 * @link    https://github.com/samhol/SPHP-framework Github repository
 * @filesource
 */
class HtmlException extends SphpException {

}


text:
package org.broadleafcommerce.core.search.domain;

import org.broadleafcommerce.core.search.redirect.domain.SearchRedirect;

/**
 * @deprecated Replaced in functionality by {@link SearchRedirect}
 */
@Deprecated
public interface SearchIntercept {

    public abstract String getTerm();

    public abstract void setTerm(String term);

    public abstract String getRedirect();

    public abstract void setRedirect(String redirect);

}


text:
@import '../common/styles/variables.css';

body {
  color: $domo-blue;
}


text:
<TITLE>Review for Three Kings (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Three Kings (1999)

reviewed by
Stephen Graham Jones

Three Kings opens just as Desert Storm is winding down, but still, manages
to emblemize the whole war in that one opening scene, where the conflict is
pared down to its most ridiculous: the American soldier fighting the Iraqi
soldier for possession of one small little hill (mound) in the middle of the
desert. With an opening like that the movie can only get more ridiculous. It
does. It even gets side-splitting ridiculous at times, via a steady run of
one-liners, but none of it is without purpose. Journalist Adrianna Cruz
(Nora Dunn) sums it all up nicely: "The war is over and I don't know what
the hell it was about." No one seems to, especially the soldiers, our three
(four) 'kings,' whom we meet mid-celebration via the freeze-frame/subtitle
trick (Pulp Fiction, Trainspotting, Lock, Stock & 2 Smoking Barrels, etc)
that's still cool, but just barely. First there's the American soldier from
the opening scene, Troy (Mark Wahlberg), vying for main-characterhood with
Archie (George Clooney), the disillusioned special forces guy. Next there's
Chief (Ice Cube), something of a holy roller qua LL Cool J in Deep Blue Sea,
but a bit more effective. Last there's the wholly uneducated Vig (Spike
Jonze), acolyte of Troy, token Texan.
As the trailer spells out, too, soon enough the four of them get a lead on
Saddam Hussein's stolen gold, and--making the cinematic leap that stealing
from a thief isn't wrong--they set out one hot, final morning to quietly
'recover' it. But of course everything goes wrong, not the least of which is
that their consciences kick in, and they begin to figure out 'why' they're
there after all: to save refugees (i.e., be the Schindlers of the Persian
Gulf). It's no big leap from there to the convention that when the thief in
the movie is both sympathetic and gets the 'loot' early on, then that loot
will have to be traded in for something more lasting. It even happens like
that in Trapped in Paradise, a movie without all the moral clutter of a
morally-dubious war, the kind of war which, in Lethal Weapon, produced
Shadow Company, the bad guys who did essentially the same thing our three
(four) kings are doing in Three Kings.
Nevertheless, though, we know who the good guys are, who the bad guys are.
War movies tend to work like this whether they want to or not. It takes an
especially cool hand like Kubrick's to rise above it (Full Metal Jacket).
Three Kings isn't Kubrick, not quite, although it does have its own brand of
camera/editing work, which, when combined with the sepiatone cinematography
qua the Courage Under Fire flashbacks, manages both to rush everything past
and wash it out in a way we suspect accurately captures the American
soldier's experience. Or, rather, it seems to capture what we imagine the
memory of that experience must be like, which is quite a feat in itself for
director David O. Russell.
But of course this 'thirsty' cinematography could be called Peckinpah, too,
and, with Three Kings, convincingly so, as the story of these four soldiers
is almost uncomfortably similar to The Wild Bunch (Clooney as Holden, etc),
even going so far as to leave the simpleton/hick back to the guard the
prisoners, or, on a larger scale, having the good bad guys get righteous
when it really counts. And then of course too one of their own gets taken
hostage, tortured, all that. At least it strays from the path a little when
Troy--the hostage--has a few bonding-type scenes with his captor, which
writer John Ridley and Russell wisely back out of just as it was starting to
feel Crying Game-ish.
In the end, though--and beneath all the fancy camerawork perhaps meant to
appeal to an audience usually not tuned into social issues--Three Kings is
more or less a social statement: that America was motivated into the Gulf by
greed. In case we miss this, the three (four) kings become aware for us,
when they have to see firsthand the results of that war ('their
actions')--or, when Troy is forced to drink oil, which is a touch
heavy-handed, but so be it. The point gets made, at least. And it's not the
only one: after Wag the Dog, of course the media has to play a role here, in
a war fought on CNN. In this case, however--as with Electric Horsemen--that
role is a redemptive one, which dovetails nicely with the Biblical allegory
operating behind the scenes, ever so quietly. At one point a tanker of milk
even spills out into this Euphrates valley, tempting us to make all kinds of
allegorical connections. Before we can, though, Russell's rushed on to the
next scene, opted to let it all accrete when he could have dwelt on it,
which, like nearly everything else in Three Kings, was the correct decision,
the proper amount of restraint, not the easy way out. It shows. The only
thing missing is the Buffalo Springfield the trailer promised, but it's more
than made up for, simply by the pleasant surprise that the trailer only
covered the first third of the movie. Which is to say there's a lot more to
Three Kings than you go in expecting, but, too, just enough conventional
stuff that you never get lost.
(c) 1999 Stephen Graham Jones

for more like this, check out http://www.cinemuck.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
/*
 * SGI image decoder
 * Todd Kirby <doubleshot@pacbell.net>
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "avcodec.h"
#include "bytestream.h"
#include "sgi.h"

typedef struct SgiState {
    AVFrame picture;
    unsigned int width;
    unsigned int height;
    unsigned int depth;
    unsigned int bytes_per_channel;
    int linesize;
} SgiState;

/**
 * Expand an RLE row into a channel.
 * @param in_buf input buffer
 * @param in_end end of input buffer
 * @param out_buf Points to one line after the output buffer.
 * @param out_end end of line in output buffer
 * @param pixelstride pixel stride of input buffer
 * @return size of output in bytes, -1 if buffer overflows
 */
static int expand_rle_row(const uint8_t *in_buf, const uint8_t* in_end,
            unsigned char *out_buf, uint8_t* out_end, int pixelstride)
{
    unsigned char pixel, count;
    unsigned char *orig = out_buf;

    while (1) {
        if(in_buf + 1 > in_end) return -1;
        pixel = bytestream_get_byte(&in_buf);
        if (!(count = (pixel & 0x7f))) {
            return (out_buf - orig) / pixelstride;
        }

        /* Check for buffer overflow. */
        if(out_buf + pixelstride * count >= out_end) return -1;

        if (pixel & 0x80) {
            while (count--) {
                *out_buf = bytestream_get_byte(&in_buf);
                out_buf += pixelstride;
            }
        } else {
            pixel = bytestream_get_byte(&in_buf);

            while (count--) {
                *out_buf = pixel;
                out_buf += pixelstride;
            }
        }
    }
}

/**
 * Read a run length encoded SGI image.
 * @param out_buf output buffer
 * @param in_buf input buffer
 * @param in_end end of input buffer
 * @param s the current image state
 * @return 0 if no error, else return error number.
 */
static int read_rle_sgi(unsigned char* out_buf, const uint8_t *in_buf,
                        const uint8_t *in_end, SgiState* s)
{
    uint8_t *dest_row;
    unsigned int len = s->height * s->depth * 4;
    const uint8_t *start_table = in_buf;
    unsigned int y, z;
    unsigned int start_offset;

    /* size of  RLE offset and length tables */
    if(len * 2  > in_end - in_buf) {
        return AVERROR_INVALIDDATA;
    }

    in_buf -= SGI_HEADER_SIZE;
    for (z = 0; z < s->depth; z++) {
        dest_row = out_buf;
        for (y = 0; y < s->height; y++) {
            dest_row -= s->linesize;
            start_offset = bytestream_get_be32(&start_table);
            if(start_offset > in_end - in_buf) {
                return AVERROR_INVALIDDATA;
            }
            if (expand_rle_row(in_buf + start_offset, in_end, dest_row + z,
                dest_row + FFABS(s->linesize), s->depth) != s->width)
                return AVERROR_INVALIDDATA;
        }
    }
    return 0;
}

/**
 * Read an uncompressed SGI image.
 * @param out_buf output buffer
 * @param out_end end ofoutput buffer
 * @param in_buf input buffer
 * @param in_end end of input buffer
 * @param s the current image state
 * @return 0 if read success, otherwise return -1.
 */
static int read_uncompressed_sgi(unsigned char* out_buf, uint8_t* out_end,
                const uint8_t *in_buf, const uint8_t *in_end, SgiState* s)
{
    int x, y, z;
    const uint8_t *ptr;
    unsigned int offset = s->height * s->width * s->bytes_per_channel;

    /* Test buffer size. */
    if (offset * s->depth > in_end - in_buf) {
       return -1;
    }

    for (y = s->height - 1; y >= 0; y--) {
        out_end = out_buf + (y * s->linesize);
        for (x = s->width; x > 0; x--) {
            ptr = in_buf += s->bytes_per_channel;
            for(z = 0; z < s->depth; z ++) {
                memcpy(out_end, ptr, s->bytes_per_channel);
                out_end += s->bytes_per_channel;
                ptr += offset;
            }
        }
    }
    return 0;
}

static int decode_frame(AVCodecContext *avctx,
                        void *data, int *data_size,
                        AVPacket *avpkt)
{
    const uint8_t *in_buf = avpkt->data;
    int buf_size = avpkt->size;
    SgiState *s = avctx->priv_data;
    AVFrame *picture = data;
    AVFrame *p = &s->picture;
    const uint8_t *in_end = in_buf + buf_size;
    unsigned int dimension, rle;
    int ret = 0;
    uint8_t *out_buf, *out_end;

    if (buf_size < SGI_HEADER_SIZE){
        av_log(avctx, AV_LOG_ERROR, "buf_size too small (%d)\n", buf_size);
        return -1;
    }

    /* Test for SGI magic. */
    if (bytestream_get_be16(&in_buf) != SGI_MAGIC) {
        av_log(avctx, AV_LOG_ERROR, "bad magic number\n");
        return -1;
    }

    rle = bytestream_get_byte(&in_buf);
    s->bytes_per_channel = bytestream_get_byte(&in_buf);
    dimension = bytestream_get_be16(&in_buf);
    s->width  = bytestream_get_be16(&in_buf);
    s->height = bytestream_get_be16(&in_buf);
    s->depth  = bytestream_get_be16(&in_buf);

    if (s->bytes_per_channel != 1 && (s->bytes_per_channel != 2 || rle)) {
        av_log(avctx, AV_LOG_ERROR, "wrong channel number\n");
        return -1;
    }

    /* Check for supported image dimensions. */
    if (dimension != 2 && dimension != 3) {
        av_log(avctx, AV_LOG_ERROR, "wrong dimension number\n");
        return -1;
    }

    if (s->depth == SGI_GRAYSCALE) {
        avctx->pix_fmt = s->bytes_per_channel == 2 ? PIX_FMT_GRAY16BE : PIX_FMT_GRAY8;
    } else if (s->depth == SGI_RGB) {
        avctx->pix_fmt = s->bytes_per_channel == 2 ? PIX_FMT_RGB48BE : PIX_FMT_RGB24;
    } else if (s->depth == SGI_RGBA && s->bytes_per_channel == 1) {
        avctx->pix_fmt = PIX_FMT_RGBA;
    } else {
        av_log(avctx, AV_LOG_ERROR, "wrong picture format\n");
        return -1;
    }

    if (avcodec_check_dimensions(avctx, s->width, s->height))
        return -1;
    avcodec_set_dimensions(avctx, s->width, s->height);

    if (p->data[0])
        avctx->release_buffer(avctx, p);

    p->reference = 0;
    if (avctx->get_buffer(avctx, p) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed.\n");
        return -1;
    }

    p->pict_type = FF_I_TYPE;
    p->key_frame = 1;
    out_buf = p->data[0];

    out_end = out_buf + p->linesize[0] * s->height;

    s->linesize = p->linesize[0];

    /* Skip header. */
    in_buf += SGI_HEADER_SIZE - 12;
    if (rle) {
        ret = read_rle_sgi(out_end, in_buf, in_end, s);
    } else {
        ret = read_uncompressed_sgi(out_buf, out_end, in_buf, in_end, s);
    }

    if (ret == 0) {
        *picture   = s->picture;
        *data_size = sizeof(AVPicture);
        return buf_size;
    } else {
        return -1;
    }
}

static av_cold int sgi_init(AVCodecContext *avctx){
    SgiState *s = avctx->priv_data;

    avcodec_get_frame_defaults(&s->picture);
    avctx->coded_frame = &s->picture;

    return 0;
}

static av_cold int sgi_end(AVCodecContext *avctx)
{
    SgiState * const s = avctx->priv_data;

    if (s->picture.data[0])
        avctx->release_buffer(avctx, &s->picture);

    return 0;
}

AVCodec sgi_decoder = {
    "sgi",
    AVMEDIA_TYPE_VIDEO,
    CODEC_ID_SGI,
    sizeof(SgiState),
    sgi_init,
    NULL,
    sgi_end,
    decode_frame,
    .long_name = NULL_IF_CONFIG_SMALL("SGI image"),
};


text:
var utils = {
  isMsie: function() {
    var match = /(msie) ([\w.]+)/i.exec(navigator.userAgent);

    return match ? parseInt(match[2], 10) : false;
  },

  isBlankString: function(str) { return !str || /^\s*$/.test(str); },

  // http://stackoverflow.com/a/6969486
  escapeRegExChars: function(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
  },

  isString: function(obj) { return typeof obj === 'string'; },

  isNumber: function(obj) { return typeof obj === 'number'; },

  isArray: $.isArray,

  isFunction: $.isFunction,

  isObject: $.isPlainObject,

  isUndefined: function(obj) { return typeof obj === 'undefined'; },

  bind: $.proxy,

  bindAll: function(obj) {
    var val;
    for (var key in obj) {
      $.isFunction(val = obj[key]) && (obj[key] = $.proxy(val, obj));
    }
  },

  indexOf: function(haystack, needle) {
    for (var i = 0; i < haystack.length; i++) {
      if (haystack[i] === needle) { return i; }
    }

    return -1;
  },

  each: $.each,

  map: $.map,

  filter: $.grep,

  disableRequests: false,

  every: function(obj, test) {
    var result = true;

    if (!obj) { return result; }

    $.each(obj, function(key, val) {
      if (!(result = test.call(null, val, key, obj))) {
        return false;
      }
    });

    return !!result;
  },

  some: function(obj, test) {
    var result = false;

    if (!obj) { return result; }

    $.each(obj, function(key, val) {
      if (result = test.call(null, val, key, obj)) {
        return false;
      }
    });

    return !!result;
  },

  mixin: $.extend,

  getUniqueId: (function() {
    var counter = 0;
    return function() { return counter++; };
  })(),

  defer: function(fn) { setTimeout(fn, 0); },

  debounce: function(func, wait, immediate) {
    var timeout, result;

    return function() {
      var context = this, args = arguments, later, callNow;

      later = function() {
        timeout = null;
        if(utils.disableRequests) {
          utils.disableRequests = false;
          result = null;
        }
        else {
          if (!immediate) { result = func.apply(context, args); }
        }
      };

      callNow = immediate && !timeout;

      clearTimeout(timeout);
      timeout = setTimeout(later, wait);

      if (callNow) { result = func.apply(context, args); }

      return result;
    };
  },

  throttle: function(func, wait) {
    var context, args, timeout, result, previous, later;

    previous = 0;
    later = function() {
      previous = new Date();
      timeout = null;
      result = func.apply(context, args);
    };

    return function() {
      var now = new Date(),
          remaining = wait - (now - previous);

      context = this;
      args = arguments;

      if (remaining <= 0) {
        clearTimeout(timeout);
        timeout = null;
        previous = now;
        result = func.apply(context, args);
      }

      else if (!timeout) {
        timeout = setTimeout(later, remaining);
      }

      return result;
    };
  },

  tokenizeQuery: function(str) {
    return $.trim(str).toLowerCase().split(/[\s]+/);
  },

  tokenizeText: function(str) {
    return $.trim(str).toLowerCase().split(/[\s\-_]+/);
  },

  getProtocol: function() {
    return location.protocol;
  },

  noop: function() {}
};


text:
bool doResourceAllocation(stack<Variable*>* simplificationStack, InterferenceGraph* ig){

	list<Regs> regs;
	list<Variable*> colored;

	for(int i = 0; i < __REG_NUMBER__; i++) regs.push_back((Regs)i);

	while(!simplificationStack->empty()){

		Variable* temp = simplificationStack->top();

		bool interference = false;

		for(auto it = colored.begin(); it != colored.end(); it++)
			if((*ig).values[temp->pos][(*it)->pos] == __INTERFERENCE__) interference = true;

		if(!interference) temp->assigment = regs.front();
		else {
			if(!regs.empty()){
				regs.pop_front();
				temp->assigment = regs.front();
			}
			else return false;
		}

		colored.push_back(temp);
		simplificationStack->pop();
	}

	return true;
}

Instructions* removeMove(Instructions* instrs){

	for (auto it = instrs->begin(); it != instrs->end(); it++) {
		if ( (*it)->type == T_MOVE ) {
			if ( (*it)->src1->assigment == (*it)->dst->assigment && (*it)->src2 == NULL) {
				instrs->remove(*it);
				break;
			}
		}
	}

	return instrs;
}


text:
package org.apache.maven;

import org.apache.maven.execution.MavenSession;

/**
 * Allows core extensions to participate in Maven build session lifecycle.
 *
 * All callback methods (will) follow beforeXXX/afterXXX naming pattern to
 * indicate at what lifecycle point it is being called.
 *
 * @see example
 * @see MNG-4224
 * @since 3.0-alpha-3
 */
public abstract class AbstractMavenLifecycleParticipant
{

    /**
     * Invoked after all MavenProject instances have been created.
     *
     * This callback is intended to allow extensions to manipulate MavenProjects
     * before they are sorted and actual build execution starts.
     */
    public void afterProjectsRead( MavenSession session )
        throws MavenExecutionException
    {
        // do nothing
    }

    /**
     * Invoked after MavenSession instance has been created.
     *
     * This callback is intended to allow extensions to inject execution properties,
     * activate profiles and perform similar tasks that affect MavenProject
     * instance construction.
     */
    // TODO: This is too early for build extensions, so maybe just remove it?
    public void afterSessionStart( MavenSession session )
        throws MavenExecutionException
    {
        // do nothing
    }

    /**
     * Invoked after all projects were built.
     *
     * This callback is intended to allow extensions to perform cleanup of any
     * allocated external resources after the build. It is invoked on best-effort
     * basis and may be missed due to an Error or RuntimeException in Maven core
     * code.
     * @since 3.2.1, MNG-5389
     */
    public void afterSessionEnd( MavenSession session )
        throws MavenExecutionException
    {
        // do nothing
    }
}


text:
/**
 * imguri
 */

var fs = require('fs');
var util = require('util');
var mime = require('mime');
var async = require('async');
var request = require('request');
var urljoin = require('url-join');

var validate = require('./validate');

var EACH_LIMIT = 10;

var imguri = {
    encode: function (paths, options, callback) {
    	var url = options.url,
    		bases = {};
        if (typeof options === 'function') {
            callback = options;
            options = {};
        }else if (url !== undefined) {
        	paths = paths.map(function (path) {
				var fullpath = urljoin(url, path);
				bases[fullpath] = path;
				return fullpath;
        	});
        }

        if (!util.isArray(paths)) paths = [paths];

        var results = {};

        var encodeSingle = function (item, cb) {
            if (results[item]) {
                // duplicate entry?
                return cb();
            }

            var type = validate.mimetype(item);
            imguri[type](item, options, function (err, data) {
                // silent error
                results[item] = {
                    err: err,
                    data: data,
                };

                if(url !== undefined) {
                	results[item].base = bases[item];
                }

                cb();
            });
        };

        async.eachLimit(paths, EACH_LIMIT, encodeSingle, function (err) {
            callback(err, results);
        });
    },

    local: function (item, options, callback) {
        validate.local(item, options, itemValidated);

        function itemValidated(err) {
            if (err) {
                return callback(err);
            }

            fs.readFile(item, processFile);
        }

        function processFile(err, data) {
            if (!err && data) {
                callback(null, imguri.base64(data, mime.lookup(item)));
            } else {
                callback(err || new Error('unable to stat: ' + item));
            }
        }
    },

    network: function (item, options, callback) {
        validate.network(item, options, itemValidated);

        var reqOptions = {
            encoding: 'binary',
            timeout: 20 * 1000
        };

        function itemValidated(err) {
            if (!err) {
                request(item, reqOptions, fetchedImage);
            } else {
                callback(err);
            }
        }

        function fetchedImage(err, res) {
            if (!err && res && res.body) {
                callback(null, imguri.base64(res.body, reqOptions.encoding));
            } else {
                callback(err || new Error('unable to fetch: ' + item));
            }
        }
    },

    base64: function (content, type) {
        var buffer = (/binary/i).test(type) ? new Buffer(content, "binary") :
            new Buffer(content);
        return "data:" + type + ";base64," + buffer.toString('base64');
    }
};

module.exports = imguri;

/** Test Code --------------------------------------------------------------- */
if (require.main === module) {
    (function () {
        var options = {
            force: false
        };
        var paths = ['test/test.png', 'test/nofile',
            'http://www.vnykmshr.com/images/favicon.ico',
            'http://www.vnykmshrx.com/',
            'http://www.vnykmshr.com/images/whois.png'];
        imguri.encode(paths, options, console.log);
    })();
}


text:
import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Form, Button, Input, Row, Col, message, Modal, Radio } from 'antd'
import Spin from 'COMPONENT/effects/Spin'
import { closeAddEditBox, addPostList, modifyPost } from 'REDUCER/pages/postManage'

const FormItem = Form.Item
const RadioGroup = Radio.Group

@connect(
  state => {
    const {
      pages: {
        postManage: {
          addEditBoxVisible,
          addEditBoxType,
          addEditBoxInitVals
        }
      }
    } = state
    return {
      visible: addEditBoxVisible,
      formType: addEditBoxType,
      initVals: addEditBoxInitVals
    }
  },
  dispatch => bindActionCreators({ closeAddEditBox, addPostList, modifyPost }, dispatch)
)

@Form.create()

export default class AddEditPostBoxView extends React.Component {

  constructor (props) {
    super(props)
    this.state = {
      loading: false
    }
  }

  componentWillMount () {
    this.props.form.resetFields()
  }

  onClose () {
    this.props.closeAddEditBox()
    this.onClear()
  }

  onClear () {
    this.props.form.resetFields()
  }

  onSubmit () {
    const { form, formType, addPostList, modifyPost, initVals } = this.props
    const { getFieldsValue, validateFields } = form
    validateFields((errors, values) => {
      if (errors) {
        message.error('请正确填写内容!')
      } else {
        let formData = getFieldsValue()
        let handle = addPostList

        if (formType === 'edit') {
          formData.postId = initVals.postId
          handle = modifyPost
        }

        const showSpin = () => {
          this.setState({
            loading: true
          })
        }

        const hideSpin = () => {
          this.setState({
            loading: false
          })
        }

        showSpin()
        handle(formData, () => {
          this.onClear()
          this.onClose()
          hideSpin()
        }, hideSpin)
      }
    })
  }

  render () {
    const { visible, formType, initVals, form } = this.props
    const { getFieldDecorator } = form

    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 }
    }

    let addType = formType === 'add'

    return (
      <div className='AddRoleBox'>
        <Modal
          title={addType ? '新增岗位' : '修改岗位'}
          width={600}
          visible={visible}
          onOk={this.onSubmit}
          onCancel={e => this.onClose()}
          footer={[
            <Button
              key='back'
              type='ghost'
              size='large'
              onClick={e => this.onClose()}
            >
              返 回
            </Button>,

            addType
              ? <Button
                key='clean'
                type='ghost'
                size='large'
                onClick={e => this.onClear()}
              >
                清除
              </Button>
              : '',

            <Button
              key='submit'
              type='primary'
              size='large'
              onClick={e => this.onSubmit()}
            >
              提 交
            </Button>
          ]}
        >
          <Form layout='horizontal'>
            <Row>
              <Col span={11}>
                <FormItem
                  label='岗位名称:'
                  {...formItemLayout}
                  required
                >
                  {
                    getFieldDecorator('postName', {
                      initialValue: addType ? '' : initVals.postName,
                      rules: [
                        {
                          required: true,
                          message: '请输入岗位名称'
                        }
                      ]
                    })(
                      <Input
                        placeholder='请输入岗位名称'
                        size='large'
                      />
                    )
                  }
                </FormItem>
                <FormItem
                  label='状态:'
                  {...formItemLayout}
                  required
                >
                  {
                    getFieldDecorator('state', {
                      initialValue: addType ? '0' : initVals.state,
                      rules: [{
                        message: ' '
                      }]
                    })(
                      <RadioGroup>
                        <Radio key='a' value='1'>可用</Radio>
                        <Radio key='b' value='0'>禁用</Radio>
                      </RadioGroup>
                    )
                  }
                </FormItem>
              </Col>

              <Col span={13}>
                <FormItem
                  label='备注:'
                  {...formItemLayout}
                >
                  {
                    getFieldDecorator('remark', {
                      initialValue: addType ? '' : initVals.remark
                    })(
                      <Input
                        placeholder='请输入备注'
                        size='large'
                      />
                    )
                  }
                </FormItem>
              </Col>
            </Row>
          </Form>
          <Spin loading={this.state.loading} />
        </Modal>
      </div>
    )
  }
}