text:
require 'pp'
require 'net/http'

module Lightspeed
  class Request
    attr_accessor :raw_request, :bucket_max, :bucket_level

    SECONDS_TO_WAIT_WHEN_THROTTLED = 60 # API requirements.

    class << self
      attr_writer :verbose
    end

    def self.verbose?
      !! @verbose
    end

    def self.base_host
      "api.merchantos.com"
    end

    def self.base_path
      "/API"
    end

    def initialize(client, method:, path:, params: nil, body: nil)
      @method = method
      @params = params
      @path = path
      @bucket_max = Float::INFINITY
      @bucket_level = 0
      @http = Net::HTTP.new(self.class.base_host, 443)
      @http.use_ssl = true
      @raw_request = request_class.new(uri)
      @raw_request.body = body if body
      @raw_request.set_form_data(@params) if @params && @method != :get
      @client = client
      set_authorization_header
    end

    def set_authorization_header
      @raw_request["Authorization"] = "Bearer #{@client.oauth_token}" if @client.oauth_token
    end

    def perform_raw
      response = @http.request(raw_request)
      extract_rate_limits(response)
      if response.code == "200"
        handle_success(response)
      else
        handle_error(response)
      end
    end

    def perform
      perform_raw
    rescue Lightspeed::Error::Throttled
      retry_throttled_request
    rescue Lightspeed::Error::Unauthorized => e
      raise e if @attempted_oauth_token_refresh
      @client.refresh_oauth_token
      set_authorization_header
      @attempted_oauth_token_refresh = true
      perform
    end

    private

    def handle_success(response)
      json = Yajl::Parser.parse(response.body)
      pp json if self.class.verbose?
      json
    end

    def retry_throttled_request
      puts 'retrying throttled request after 60s.' if self.class.verbose?
      sleep SECONDS_TO_WAIT_WHEN_THROTTLED
      perform
    end

    def handle_error(response)
      error = case response.code.to_s
      when '400' then Lightspeed::Error::BadRequest
      when '401' then Lightspeed::Error::Unauthorized
      when '403' then Lightspeed::Error::NotAuthorized
      when '404' then Lightspeed::Error::NotFound
      when '429' then Lightspeed::Error::Throttled
      when /5../ then Lightspeed::Error::InternalServerError
      else Lightspeed::Error
      end

      # We may not get back valid JSON for a failed request
      begin
        data = Yajl::Parser.parse(response.body)
        raise error, data["message"]
      rescue Yajl::ParseError
        raise error, response.code
      end
    end

    def extract_rate_limits(response)
      if bucket_headers = response["X-LS-API-Bucket-Level"]
        @bucket_level, @bucket_max = bucket_headers.split("/").map(&:to_f)
      end
    end

    def uri
      uri = self.class.base_path + @path
      uri += "?#{URI.encode_www_form(@params)}" if @params && @method == :get
      uri
    end

    def request_class
      case @method
      when :get then Net::HTTP::Get
      when :put then Net::HTTP::Put
      when :post then Net::HTTP::Post
      when :delete then Net::HTTP::Delete
      end
    end
  end
end


text:
from openstack.network.v2 import router
from openstack.tests.functional import base

class TestRouter(base.BaseFunctionalTest):

    ID = None

    def setUp(self):
        super(TestRouter, self).setUp()
        self.NAME = self.getUniqueString()
        self.UPDATE_NAME = self.getUniqueString()
        sot = self.conn.network.create_router(name=self.NAME)
        assert isinstance(sot, router.Router)
        self.assertEqual(self.NAME, sot.name)
        self.ID = sot.id

    def tearDown(self):
        sot = self.conn.network.delete_router(self.ID, ignore_missing=False)
        self.assertIsNone(sot)
        super(TestRouter, self).tearDown()

    def test_find(self):
        sot = self.conn.network.find_router(self.NAME)
        self.assertEqual(self.ID, sot.id)

    def test_get(self):
        sot = self.conn.network.get_router(self.ID)
        self.assertEqual(self.NAME, sot.name)
        self.assertEqual(self.ID, sot.id)
        self.assertFalse(sot.is_ha)

    def test_list(self):
        names = [o.name for o in self.conn.network.routers()]
        self.assertIn(self.NAME, names)
        ha = [o.is_ha for o in self.conn.network.routers()]
        self.assertIn(False, ha)

    def test_update(self):
        sot = self.conn.network.update_router(self.ID, name=self.UPDATE_NAME)
        self.assertEqual(self.UPDATE_NAME, sot.name)

    def test_set_tags(self):
        sot = self.conn.network.get_router(self.ID)
        self.assertEqual([], sot.tags)

        self.conn.network.set_tags(sot, ['blue'])
        sot = self.conn.network.get_router(self.ID)
        self.assertEqual(['blue'], sot.tags)

        self.conn.network.set_tags(sot, [])
        sot = self.conn.network.get_router(self.ID)
        self.assertEqual([], sot.tags)

redpajama_set_name: RedPajamaGithub


text:
hqi
==========================
hexa query interface

Introduction
---------------------------------
Work In Progress,
hqi is meant to interface a flat table query into a common solution and also to easly mock the interface for testing units

Usage
---------------------------

to create query interface we use `q := hqi.NewQuery( driver )`
Using slicedrv
Lets define a struct:

```go
type Model struct {
	Field1 string,
	Field2 int
}
```

Next we instantiate our slice:
```go
collection := []Model{}
```

Now we get a query interface using slice driver passing our collection to driver:
```go
q := hqi.NewQuery(&slicedrv.Driver{&collection})
```

And we can start:
```go
q.Insert(Model{"f1","f2"},Model{"f1_1","f2_2"})   // Inserts the two elements into slice

var result []Model{}
q.Find(Model{"f1","f2"}).List(&result)
q.Find(`{"Field1":"f1"}`,Model{"f1_1","f2_2"}).List(&result)   // Find where Field1 is f1 OR field1 "f1_1" AND field2 "f2_2"
```

[slice example](/examples/slice/main.go)

#### TODO

* Create driver capabilitie struct so if we are registering a subDocument driver will identify if it can process
* Finder features with operators >= <= < > !=
* Update operation
* Matcher with Greater,Smaller checks, Zero fields
* Create a cursor to fetch parcels of data

#### DONE

* Schemer (information to pass to driver when user wants a scheme) (staging)
* Insert operation (staging)
* Delete (staging)

#### Operations (planning)

oper   | function               | equivalence
-------|------------------------|------------
NOT    | Inverse match          | !
GT     | Greater Than           |  >
GTE    | Greater equal or equal | >=
LT     | Less than              | <
LTE    | Less than or equal     | <

Matcher executor
--------------------------
* Match
* Sort
* Range
* Retrieve, Count,Delete,Update (CRUD here)

Stage based query
-------------------------

On stage based means, that if we perform a
query. means we should have only Find option/Match
After find we can have SORT, LIMIT,RESULT
after SORT: LIMIT,RESULT
after RANGE: RESULT

* Stage1 return Find/Schema/Insert (Match)
* Stage2 sort, range, results
* Stage3 All/Delete/Count executors

#### QuerySampler

rules for Find, if we have a model:

```go
type Person struct {
	Name string
	Age int
}
```

we could create a "cloned" Sampler as:

```go
type PersonSampler struct {
	Name interface{}
	Age interface{}
}

q.FindS(PersonSampler{Age:0}).  // Usually 0 is nothing and won't match
  List(&res)
// Or also:
q.FindS(PersonSampler{Age:hqi.Greater(10)}).
  List(&res)

```

-----

- [DRIVER](/drv/README.md)

#### Changes:

* 19-04-2017: Update implemented in mgo and slice


text:
@interface LocationViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSDictionary *params;
@property (strong, nonatomic) NSArray *dataList;
@property (strong, nonatomic) NSNumber *originalSelectedID;
@property (strong, nonatomic) NSDictionary *selectedPlace;
@property (assign, nonatomic) NSUInteger curLevel;
@end

@implementation LocationViewController

- (void)viewDidLoad{
    [super viewDidLoad];

    _tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        tableView.backgroundColor = kColorTableSectionBg;
        tableView.delegate = self;
        tableView.dataSource = self;
        [tableView registerClass:[LocationCell class] forCellReuseIdentifier:kCellIdentifier_LocationCell];
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        tableView.separatorColor = kColorDDD;
        tableView.separatorInset = UIEdgeInsetsMake(0, 12, 0, 12);
        [self.view addSubview:tableView];
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView;
    });

    if (_selectedList.count <= 0) {
        _selectedList = [NSMutableArray new];
        _curLevel = 1;
        _params = @{@"parent": @(0),
                    @"level": @(_curLevel)};
        self.title = @"选择地区";
    }else{
        NSDictionary *place = [_selectedList lastObject];
        _curLevel = _selectedList.count +1;
        _params = @{@"parent": place[@"id"],
                    @"level": @(_curLevel)};
        self.title = place[@"name"];
    }
    if (_originalSelectedList.count >= _curLevel) {
        _originalSelectedID = _originalSelectedList[_curLevel - 1];
    }
    if (_selectedList.count >= _curLevel) {
        _selectedPlace = _selectedList[_curLevel - 1];
    }
    if (_dataList.count <= 0) {
        [self refresh];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)refresh{
    [self.view beginLoading];
    [[Coding_NetAPIManager sharedManager] request_LocationListWithParams:_params block:^(id data, NSError *error) {
        [self.view endLoading];
        if (data) {
            self.dataList = data;
            [self.tableView reloadData];
        }
    }];
}

- (BOOL)navigationShouldPopOnBackButton{
    [_selectedList removeObject:_selectedList.lastObject];
    return YES;
}
#pragma mark Table M
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"全部";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataList? 1: 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LocationCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_LocationCell forIndexPath:indexPath];
    NSDictionary *place = _dataList[indexPath.row];
    cell.leftL.text = place[@"name"];
    cell.accessoryType = _curLevel < 3? UITableViewCellAccessoryDisclosureIndicator: UITableViewCellAccessoryNone;
    if (_selectedPlace) {
        cell.rightL.text = [_selectedPlace[@"id"] isEqualToNumber:place[@"id"]]? @"已选地区": @"";
    }else{
        cell.rightL.text = [_originalSelectedID isEqualToNumber:place[@"id"]]? @"已选地区": @"";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    _selectedPlace = _dataList[indexPath.row];
    _selectedList[_curLevel - 1] = _selectedPlace;

    if (_curLevel == 3) {
        [self complate];
    }else{
//        NSDictionary *params = @{@"parent": _selectedPlace[@"id"],
//                    @"level": @(_curLevel +1)};
        NSDictionary *params = @{@"parent_id": _selectedPlace[@"id"]};
        [NSObject showHUDQueryStr:nil];
        [[Coding_NetAPIManager sharedManager] request_LocationListWithParams:params block:^(id data, NSError *error) {
            [NSObject hideHUDQuery];
            if (data) {
                [self goToNextWithData:data];
            }
        }];
    }
}

- (void)goToNextWithData:(NSArray *)data{
    if (data.count > 0) {
        LocationViewController *vc = [LocationViewController new];
        vc.dataList = data;
        vc.originalSelectedList = _originalSelectedList;
        vc.selectedList = _selectedList;
        vc.complateBlock = _complateBlock;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self complate];
    }
}

- (void)complate{
    if (self.complateBlock) {
        self.complateBlock(self.selectedList);
    }
    NSUInteger count = self.navigationController.viewControllers.count;
    UIViewController *vc = self.navigationController.viewControllers[(count - 1) - _curLevel];
    [self.navigationController popToViewController:vc animated:YES];
}
@end


text:
@implementation JKLOrder

- (instancetype)initWithOrderId:(NSString *)orderId timeStamp:(NSDate *)timeStamp
{
    self = [super init];
    if(self)
    {
        _orderId = orderId;
        _timeStamp = timeStamp;
    }
    return self;
}

- (id)copy
{
    return self;
}

- (id)mutableCopy
{
    JKLMutableOrder * mutableCopy = [[JKLMutableOrder alloc] init];
    mutableCopy.orderId = self.orderId;
    mutableCopy.timeStamp = self.timeStamp;

    return mutableCopy;
}

@end


text:
<?php

namespace Platformsh\Cli\Tests\Local\BuildFlavor;

use Platformsh\Cli\Service\Shell;

/**
 * @group slow
 */
class DependenciesTest extends BaseBuildFlavorTest
{
    protected $sourceDir = 'tests/data/apps/build-deps';

    public function testBuildSucceedsIfDepsNotRequired()
    {
        $this->assertBuildSucceeds($this->sourceDir, ['no-deps' => true, 'no-build-hooks' => true]);
    }

    public function testBuildFailsIfDepsNotInstalled()
    {
        $this->assertBuildSucceeds($this->sourceDir, ['no-deps' => true], false);
    }

    public function testBuildSucceedsIfNodejsDepsInstalled()
    {
        $shell = new Shell();
        if ($shell->commandExists('npm')) {
            $this->assertBuildSucceeds($this->sourceDir . '/nodejs');
        } else {
            $this->markTestSkipped();
        }
    }

    public function testBuildSucceedsIfPhpDepsInstalled()
    {
        $shell = new Shell();
        if ($shell->commandExists('composer')) {
            $this->assertBuildSucceeds($this->sourceDir . '/php');
        } else {
            $this->markTestSkipped();
        }
    }

    public function testBuildSucceedsIfPythonDepsInstalled()
    {
        $shell = new Shell();
        if ($shell->commandExists('pip') || $shell->commandExists('pip3')) {
            // Python dependencies are known to fail on the Travis PHP environment:
            // python and pip are available but too old or mis-configured.
            // @todo review this
            try {
                $this->assertBuildSucceeds($this->sourceDir . '/python');
            } catch (\RuntimeException $e) {
                if (\getenv('TRAVIS') && strpos($e->getMessage(), 'The command failed') !== false && strpos($e->getMessage(), 'pip install') !== false) {
                    $this->markTestSkipped('Installing python dependencies is known to fail on Travis');
                    return;
                }
                throw $e;
            }
        } else {
            $this->markTestSkipped();
        }
    }

    public function testBuildSucceedsIfRubyDepsInstalled()
    {
        $shell = new Shell();
        if ($shell->commandExists('bundle')) {
            $this->assertBuildSucceeds($this->sourceDir . '/ruby');
        } else {
            $this->markTestSkipped();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace EasyDb
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            System.Threading.Thread.Sleep(1000);
            Current.DispatcherUnhandledException +=
                new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException);
            base.OnStartup(e);
        }

        void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
            e.Handled = true;
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IntegrationTests.cs" company="CatenaLogic">
//   Copyright (c) 2014 - 2015 CatenaLogic. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace JiraCli.Tests.IntegrationTests
{
    using System;
    using System.Threading.Tasks;
    using Catel;
    using Catel.IoC;
    using Catel.Logging;
    using NUnit.Framework;

    [TestFixture, Explicit]
    public partial class IntegrationTests
    {
        public IntegrationTests()
        {
            LogManager.AddDebugListener(true);
        }

        private T ResolveService<T>()
        {
            return ServiceLocator.Default.ResolveType<T>();
        }

        private Context CreateContext(string version, string[] issues = null)
        {
            var context = new Context
            {
                JiraUrl = JiraUrl,
                Project = JiraProject,
                UserName = JiraUser,
                Password = JiraPassword,
                Version = version,
                Issues = issues ?? new string[] { }
            };

            return context;
        }

        [TestCase]
        public async Task ReleaseVersions()
        {
            var actionManager = ResolveService<IActionManager>();

            var action = actionManager.GetAction("CreateAndReleaseVersion");

            var createV100Context = CreateContext("1.0.0");
            Assert.IsTrue(await action.ExecuteAsync(createV100Context));

            var createV110Context = CreateContext("1.1.0");
            Assert.IsTrue(await action.ExecuteAsync(createV110Context));

            var createV111Context = CreateContext("1.1.1");
            Assert.IsTrue(await action.ExecuteAsync(createV111Context));
            Assert.IsFalse(await action.ExecuteAsync(createV111Context));
        }

        [TestCase]
        public async Task ReleaseVersionsThatShouldBeMerged()
        {
            var actionManager = ResolveService<IActionManager>();

            var action = actionManager.GetAction("CreateAndReleaseVersion");

            var createV1Context = CreateContext("2.0.0-unstable42");
            Assert.IsTrue(await action.ExecuteAsync(createV1Context));

            var createV2Context = CreateContext("2.0.0-unstable48");
            Assert.IsTrue(await action.ExecuteAsync(createV2Context));

            var createV3Context = CreateContext("2.0.0-unstable56");
            Assert.IsTrue(await action.ExecuteAsync(createV3Context));

            var createStableVersionContext = CreateContext("2.0.0");
            Assert.IsTrue(await action.ExecuteAsync(createStableVersionContext));
        }

        [TestCase("TS-1,TS-2,TS-3")]
        public async Task AssignVersion(string issueNumbers)
        {

            var actionManager = ResolveService<IActionManager>();

            var action = actionManager.GetAction("AssignVersion");
            var issues = issueNumbers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            var createV100Context = CreateContext("1.0.0", issues);
            Assert.IsTrue(await action.ExecuteAsync(createV100Context));

        }
    }
}


text:
if [ -d deploy ]
then
  echo "Removing old deploy directory"
  rm -rf deploy
fi
if [ -f policeboard.zip ]
then
  rm policeboard.zip
fi
mkdir deploy
zip deploy/policeboard.zip -r * .ebextensions/* .elasticbeanstalk/*  -x 'tmp/*' -x 'log/*' -x 'node_modules/*'
cd deploy
unzip policeboard.zip
mv policeboard.zip ../


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('posts', function (Blueprint $table) {
          $table->unique('_id');
          $table->string('title');
          $table->text('text');
          $table->boolean('draft');
          $table->string('user_id')->index();
          $table->timestamps();
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }
}


text:
<?php
/**
 * 类目API.
 */

namespace hVenus\JingdongAPI\API;

trait CATEGORY
{

    /**
     * 普通 基础	jingdong.category.read.findAttrById	2.    获取类目属性
     * @param $params
     * @return mixed
     */
    public function CategoryFindAttributeByID($params) {
        return $this->call_jd_function('jingdong.category.read.findAttrById', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findValuesByAttrId	3.    通过类目属性ID获取属性值列表
     * @param $params
     * @return mixed
     */
    public function CategoryFindValuesByAttributeID($params) {
        return $this->call_jd_function('jingdong.category.read.findValuesByAttrId', $params);
    }

    /**
     * 普通 基础	360buy.warecats.get	4.    获取商家类目信息
     * @param $params
     * @return mixed
     */
    public function CategoryGetWareCats($params) {
        return $this->call_jd_function('360buy.warecats.get', $params);
    }

    /**
     * 普通 基础	360buy.wares.vendersellsku.add	5.    添加商家商品销售属性
     * @param $params
     * @return mixed
     */
    public function CategoryAddVendorSellSKU($params) {
        return $this->call_jd_function('360buy.wares.vendersellsku.add', $params);
    }

    /**
     * 普通 基础	360buy.wares.vendersellsku.update	6.    更新商家商品销售属性
     * @param $params
     * @return mixed
     */
    public function CategoryUpdateVendorSellSKU($params) {
        return $this->call_jd_function('360buy.wares.vendersellsku.update', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findAttrsByCategoryId	7.    获取类目属性列表
     * @param $params
     * @return mixed
     */
    public function CategoryFindAttributesByCategoryID($params) {
        return $this->call_jd_function('jingdong.category.read.findAttrsByCategoryId', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findValuesById	8.    获取类目属性值
     * @param $params
     * @return mixed
     */
    public function CategoryFindValuesByID($params) {
        return $this->call_jd_function('jingdong.category.read.findValuesById', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findById	9.    获取单个类目信息
     * @param $params
     * @return mixed
     */
    public function CategoryFindByID($params) {
        return $this->call_jd_function('jingdong.category.read.findById', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findByPId	10.    查找子类目列表
     * @param $params
     * @return mixed
     */
    public function CategoryFindByPID($params) {
        return $this->call_jd_function('jingdong.category.read.findByPId', $params);
    }

    /**
     * 普通 基础	jingdong.pop.vender.cener.venderBrand.query	11.    查询商家已授权的品牌
     * @param $params
     * @return mixed
     */
    public function CategoryQueryVendorBrand($params) {
        return $this->call_jd_function('jingdong.pop.vender.cener.venderBrand.query', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findValuesByIdJos	13.    获取类目属性值
     * @param $params
     * @return mixed
     */
    public function CategoryFindValuesByIDJos($params) {
        return $this->call_jd_function('jingdong.category.read.findValuesByIdJos', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findAttrsByCategoryIdJos	14.    获取类目属性列表
     * @param $params
     * @return mixed
     */
    public function CategoryFindAttributesByCategoryIDJos($params) {
        return $this->call_jd_function('jingdong.category.read.findAttrsByCategoryIdJos', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findAttrByIdJos	14.    获取属性的可选值列表(过滤重复字段名)
     * @param $params
     * @return mixed
     */
    public function CategoryFindAttributeByIDJos($params) {
        return $this->call_jd_function('jingdong.category.read.findAttrByIdJos', $params);
    }

    /**
     * 普通 基础	jingdong.category.read.findValuesByAttrIdJos	15.    通过类目属性ID获取属性值列表
     * @param $params
     * @return mixed
     */
    public function CategoryFindValuesByAttributeIDJos($params) {
        return $this->call_jd_function('jingdong.category.read.findValuesByAttrIdJos', $params);
    }

}


text:
module FeatureSystem
  class ApplicationController < ActionController::Base
  end
end


text:
<title>Cyclometric Complexity</title>

Class : Report

Total Complexity: 10

Total Lines: 46

Method	Complexity	# Lines

Class : OrderReport

Total Complexity: 4

Total Lines: 28

Method	Complexity	# Lines

Class : RevenueReport

Total Complexity: 13

Total Lines: 60

Method	Complexity	# Lines


text:
describe('authHttpInterceptorService', function() {

  beforeEach(module('authentication'));

  it('should ...', inject(function(authHttpInterceptorService) {

	//expect(authHttpInterceptorService.doSomething()).toEqual('something');

  }));

});


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context=".DieActivity">

    <item
        android:id="@+id/menu_die_roll"
        android:title="@string/roll"
        app:showAsAction="never"/>

</menu>


text:
from __future__ import division
import argparse
import sys
import pysam
from pycluster import cluster as cl, parse_clusters
# import pdb

def rpc_classify(cfile, prefix, insert_handles, gcov_dict,
                 cluster_bedpe, event_bedpe):
    """
    Classify a set of rpcluster output.

    Args:
        cfile (file)          : rpcluster ouput file
        prefix (str)          : Prefix to include in all breakpoint IDs,
                                generally cohort name
        insert_handles (dict) : Insert coverage files
                                {sampleID (str) : icov_f (pysam.Tabixfile)}
        gcov_dict (dict)      : Global coverage
                                {sampleID (str) : gcov (int)}
        cluster_bedpe (file)  : Output file for raw breakpoint clusters
        event_bedpe (file)    : Output file for merged breakpoints (events)
    """

    # contigs = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8',
               # 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15',
               # 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22',
               # 'chrX', 'chrY']
    # contigs = contigs + [contig[3:] for contig in contigs]

    # pdb.set_trace()
    for cluster_list in parse_clusters(cfile, prefix):
        # We currently do not have insert coverage over unplaced/random
        # contigs. Skip any clusters that map to one.
        # cltest = cluster_list[0]
        # if cltest.chrA not in contigs or cltest.chrB not in contigs:
            # continue

        # mapq and uniq are calculated in cluster instantiation
        # Calculate local/global coverage, then write out
        max_gcov = 0
        max_localA = 0
        max_localB = 0

        for cluster in cluster_list:
            gcov = cluster.global_cov(gcov_dict)
            localA, localB = cluster.local_cov(insert_handles)
            cluster_bedpe.write("%s\t%.3f\t%.3f\t%.3f\t%d\t[%s]\n" %
                                (str(cluster), gcov, localA, localB,
                                 len(cluster.samples.keys()),
                                 ",".join(cluster.samples.keys())))

            if gcov > max_gcov:
                max_gcov = gcov
            if localA > max_localA:
                max_localA = localA
            if localB > max_localB:
                max_localB = localB

        event = cl.merge(cluster_list)
        call, branch = event.classify(max_gcov, max_localA, max_localB)
        event_bedpe.write("%s\t%.3f\t%.3f\t%.3f\t%d\t[%s]\t%s\t%d\n" %
                          (str(event), max_gcov, max_localA, max_localB,
                           len(event.samples.keys()),
                           ",".join(event.samples.keys()),
                           call, branch))

def main():
    parser = argparse.ArgumentParser(
        description="SV classifier. Computes mapq, uniqueness, global cov, "
        "and local cov for every cluster output by rpcluster. Decision tree "
        "then classifies based on these metrics. Outputs to bedpe format.")
    parser.add_argument('rpcluster', nargs='?',
                        type=argparse.FileType('r'), default=sys.stdin,
                        help="rpCluster output file [stdin]")

    parser.add_argument('event_bedpe', nargs='?',
                        type=argparse.FileType('w'), default=sys.stdout,
                        help="Event output file [stdout]")

    parser.add_argument('sample_list', type=argparse.FileType('r'),
                        help="List of sample IDs. Column format: "
                        "sample_ID bstat_dir cl_dist cutoff "
                        "global_cov insert_cov_file")

    parser.add_argument('--cluster-bedpe', type=argparse.FileType('w'),
                        help="Cluster output file")

    parser.add_argument('cluster_name',
                        help="Prefix for cluster IDs")

    args = parser.parse_args()

    # Skip header
    # TODO: add --no-header flag
    # args.sample_list.next()

    cluster_header = ("chrA\tstartA\tendA\tchrB\tstartB\tendB\t"
                      "name\tscore\tstrandA\tstrandB\t"
                      "size\tmapqA\tmapqB\tuniqA\tuniqB\t"
                      "global\tlocalA\tlocalB\tpoly_count\tsamples\n")

    event_header = ("%s\tcall\tbranch\n" % cluster_header.rstrip())

    args.cluster_bedpe.write(cluster_header)
    args.event_bedpe.write(event_header)

    # Create coverage dictionaries
    # gcov_dict = {sample_ID: int(sample_haploid_coverage)}
    # insert_handles = {sample_ID: pysam.Tabixfile(sample_insert_coverage)}
    gcov_dict = {}
    insert_handles = {}
    for line in args.sample_list:
        if line.startswith("#"):
            continue

        sample = line.split()[0]
        gcov, icov_f = line.split()[4:6]

        gcov_dict[sample] = int(gcov)
        insert_handles[sample] = pysam.Tabixfile(icov_f)

    rpc_classify(args.rpcluster, args.cluster_name, insert_handles,
                 gcov_dict, args.cluster_bedpe, args.event_bedpe)

if __name__ == '__main__':
    main()


text:
var tape = require("tape"),
    jsdom = require("./jsdom"),
    d3 = require("d3-selection"),
    d3_graphviz = require("../");

tape("graphviz().width() sets svg width.", function(test) {
    var window = global.window = jsdom('

');
    var document = global.document = window.document;
    var graphviz = d3_graphviz.graphviz("#graph")
        .on('initEnd', startTest)
        .tweenShapes(false)
        .zoom(false);

    function startTest() {
        var originalWidthPt = 62;
        var originalHeightPt = 116;

        var originalViewBox = '0.00 0.00 62.00 116.00'

        // Original settings

        graphviz
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), originalViewBox, "SVG viewBox is the original viewBox");

        // Set width/height with fit, without scale

        var width = originalWidthPt * 2;
        var height = originalHeightPt * 2;

        graphviz
            .width(width)
            .height(null)
            .fit(true)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), originalViewBox, "SVG viewBox is the original viewBox when fit is true and scale is not specified");

        graphviz
            .width(null)
            .height(height)
            .fit(true)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), originalViewBox, "SVG viewBox is the original viewBox when fit is true and scale is not specified");

        graphviz
            .width(width)
            .height(height)
            .fit(true)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), originalViewBox, "SVG viewBox is the original viewBox when fit is true and scale is not specified");

        // Set width/height without fit and scale

        let viewBox = `0 0 ${width * 3 / 4} ${height * 3 / 4}`;
        const originalWidthViewBox = `0 0 ${originalWidthPt} ${height * 3 / 4}`;
        const originalHeightViewBox = `0 0 ${width * 3 / 4} ${originalHeightPt}`;

        graphviz
            .width(width)
            .height(null)
            .fit(false)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), originalHeightViewBox, "SVG viewBox is set to svg width and original height when width is set and height is not set and fit is false and scale is not specified");

        graphviz
            .width(null)
            .height(height)
            .fit(false)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), originalWidthViewBox, "SVG viewBox is set to svg width and original height when width is not set and height is set and fit is false and scale is not specified");

        graphviz
            .width(width)
            .height(height)
            .fit(false)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), viewBox, "SVG viewBox is set to svg size when both width and height is set and fit is false and scale is not specified");

        // Set width/height, with fit and scale

        var width = originalWidthPt * 2;
        var height = originalHeightPt * 2;
        var scale = 0.5;

        viewBox = `0 0 ${originalWidthPt / scale} ${originalHeightPt / scale}`;

        graphviz
            .width(width)
            .height(null)
            .fit(true)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), viewBox, "SVG viewBox is set to svg size when fit is true and scale <> 1");

        graphviz
            .width(null)
            .height(height)
            .fit(true)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), viewBox, "SVG viewBox is the original viewBox when fit is true and scale <> 1");

        graphviz
            .width(width)
            .height(height)
            .fit(true)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), viewBox, "SVG viewBox is the original viewBox when fit is true and scale <> 1");

        // Set width/height, without fit, with scale

        const scaledViewBox = `0 0 ${width * 3 / 4 / scale} ${height * 3 / 4 / scale}`;
        const scaledOriginalWidthViewBox = `0 0 ${originalWidthPt / scale} ${height * 3 / 4 / scale}`;
        const scaledOriginalHeightViewBox = `0 0 ${width * 3 / 4 / scale} ${originalHeightPt / scale}`;
        const scaledOriginalViewBox = `0 0 ${originalWidthPt / scale} ${originalHeightPt / scale}`;

        graphviz
            .width(width)
            .height(null)
            .fit(false)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), scaledOriginalHeightViewBox, "SVG viewBox has scaled svg width and scaled original height when width is set and height is not set and fit is false and scale <> 1");

        graphviz
            .width(null)
            .height(height)
            .fit(false)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), scaledOriginalWidthViewBox, "SVG viewBox has scaled original width and scaled svg height when width is not set and height is set and fit is false and scale <> 1");

        graphviz
            .width(width)
            .height(height)
            .fit(false)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width"), width, "SVG width is set with .width()");
        test.equal(+d3.select('svg').attr("height"), height, "SVG height is set with .height()");
        test.equal(d3.select('svg').attr("viewBox"), scaledViewBox, "SVG viewBox is the scaled svg size when both width and height is set and fit is false and scale <> 1");

        // Don't set width/height, but with fit (nop), without scale
        graphviz
            .width(null)
            .height(null)
            .fit(true)
            .scale(1)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), originalViewBox, "SVG viewBox is the scaled original viewBox when svg size is unchanged, fit is true and scale is 1");

        // Don't set width/height, but with fit (nop) and scale

        viewBox = `0 0 ${originalWidthPt / scale} ${originalHeightPt / scale}`;

        graphviz
            .width(null)
            .height(null)
            .fit(true)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), viewBox, "SVG viewBox is scaled when svg size is unchanged and fit is true and scale is not 1");

        // Don't set width/height or fit, but with and scale

        viewBox = `0 0 ${originalWidthPt / scale} ${originalHeightPt / scale}`;

        graphviz
            .width(null)
            .height(null)
            .fit(null)
            .scale(scale)
            .renderDot('digraph {a -> b;}');

        test.equal(+d3.select('svg').attr("width").replace('pt', ''), originalWidthPt, "SVG width is the original width");
        test.equal(+d3.select('svg').attr("height").replace('pt', ''), originalHeightPt, "SVG height is the original height");
        test.equal(d3.select('svg').attr("viewBox"), viewBox, "SVG viewBox is scaled when svg size is unchanged and fit is false and scale is not 1");

        test.end();
    }
});


text: My name is Parham Doustdar. I am a completely blind manager and back-end programmer working at Booking.com. I enjoy improving myself 1% every day, and helping other people in person and through products I help build.


text:
@interface IDEMappingModelSourceChooserAssistant : IDEMappingModelChooserAssistant
{
}

- (id)nextAssistantIdentifier;
- (id)labelText;
- (id)filePathStorageKey;
- (id)fileURLStorageKey;

@end


text:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require_once '../../bootstrap.php';

use NFePHP\NFe\ToolsNFe;

$nfe = new ToolsNFe('../../config/config.json');
$nfe->setModelo('55');

//210200 – Confirmação da Operação
//210210 – Ciência da Operação
//210220 – Desconhecimento da Operação
//210240 – Operação não Realizada ===> é obritatoria uma justificativa para esse caso
$chave = '35150158716523000119550010000000071000000076';
$tpAmb = '2';
$xJust = '';
$tpEvento = '210210'; //ciencia da operação
$aResposta = array();
$xml = $nfe->sefazManifesta($chave, $tpAmb, $xJust = '', $tpEvento = '', $aResposta);
echo '

';
echo htmlspecialchars($nfe->soapDebug);
echo '

';
print_r($aResposta);
echo "
";


text:
class AddSupercategoryToClue < ActiveRecord::Migration
  def change
    add_column :clues, :supercategory, :string
  end
end


text:
using System;
using System.Windows;
using MS.Internal.Documents;
using MS.Internal.PtsHost.UnsafeNativeMethods;

namespace MS.Internal.PtsHost
{
    /// <summary>
    /// EmbeddedObject class stores information about object embedded within
    /// a text paragraph.
    /// </summary>
    internal abstract class EmbeddedObject
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="dcp">
        /// Embedded object's character position.
        /// </param>
        protected EmbeddedObject(int dcp)
        {
            Dcp = dcp;
        }

        /// <summary>
        /// Dispose object.
        /// </summary>
        internal virtual void Dispose()
        {
        }

        /// <summary>
        /// Update object using date from another embedded object of the same
        /// type.
        /// </summary>
        /// <param name="newObject">
        /// Source of updated data.
        /// </param>
        internal abstract void Update(EmbeddedObject newObject);

        /// <summary>
        /// Embedded object's owner.
        /// </summary>
        internal abstract DependencyObject Element
        {
            get;
        }

        /// <summary>
        /// Position within a text paragraph (number of characters from the
        /// beginning of text paragraph).
        /// </summary>
        internal int Dcp;
    }

    /// <summary>
    /// Stores information about attached object embedded within a text paragraph.
    /// </summary>
    internal class AttachedObject : EmbeddedObject
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="dcp">
        /// Attached object's character position.
        /// </param>
        /// <param name="para">
        /// Paragraph associated with attached object.
        /// </param>
        internal AttachedObject(int dcp, BaseParagraph para)
            : base(dcp)
        {
            Para = para;
        }

        /// <summary>
        /// Dispose object.
        /// </summary>
        internal override void Dispose()
        {
            Para.Dispose();
            Para = null;
            base.Dispose();
        }

        /// <summary>
        /// Update object using date from another attached object of the same
        /// type.
        /// </summary>
        /// <param name="newObject">
        /// Source of updated data.
        /// </param>
        internal override void Update(EmbeddedObject newObject)
        {
            AttachedObject newAttachedObject = newObject as AttachedObject;
            ErrorHandler.Assert(newAttachedObject != null, ErrorHandler.EmbeddedObjectTypeMismatch);
            ErrorHandler.Assert(newAttachedObject.Element.Equals(Element), ErrorHandler.EmbeddedObjectOwnerMismatch);
            Dcp = newAttachedObject.Dcp;
            Para.SetUpdateInfo(PTS.FSKCHANGE.fskchInside, false);
        }

        /// <summary>
        /// Attached object's owner.
        /// </summary>
        internal override DependencyObject Element
        {
            get
            {
                return Para.Element;
            }
        }

        /// <summary>
        /// Paragraph associated with attached object.
        /// </summary>
        internal BaseParagraph Para;
    }

    /// <summary>
    /// Stores information about inline object embedded within a text line.
    /// </summary>
    internal sealed class InlineObject : EmbeddedObject
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="dcp">
        /// Embedded object's character position.
        /// </param>
        /// <param name="uiElementIsland">
        /// UIElementIsland associated with embedded object.
        /// </param>
        /// <param name="para">
        /// TextParagraph associated with embedded object.
        /// </param>
        internal InlineObject(int dcp, UIElementIsland uiElementIsland, TextParagraph para)
            : base(dcp)
        {
            _para = para;
            _uiElementIsland = uiElementIsland;
            _uiElementIsland.DesiredSizeChanged += new DesiredSizeChangedEventHandler(_para.OnUIElementDesiredSizeChanged);
        }

        /// <summary>
        /// Dispose object.
        /// </summary>
        internal override void Dispose()
        {
            if (_uiElementIsland != null)
            {
                _uiElementIsland.DesiredSizeChanged -= new DesiredSizeChangedEventHandler(_para.OnUIElementDesiredSizeChanged);
            }
            base.Dispose();
        }

        /// <summary>
        /// Update object using date from another embedded object of the same
        /// type.
        /// </summary>
        /// <param name="newObject">
        /// Source of updated data.
        /// </param>
        internal override void Update(EmbeddedObject newObject)
        {
            // These should definitely be the same
            InlineObject newInline = newObject as InlineObject;

            ErrorHandler.Assert(newInline != null, ErrorHandler.EmbeddedObjectTypeMismatch);
            ErrorHandler.Assert(newInline._uiElementIsland == _uiElementIsland, ErrorHandler.EmbeddedObjectOwnerMismatch);

            // We've ensured ownership is still with the old InlineObject, so we now null this out to prevent dispose from disconnecting.
            newInline._uiElementIsland = null;
        }

        /// <summary>
        /// Embedded object's owner.
        /// </summary>
        internal override DependencyObject Element
        {
            get
            {
                return _uiElementIsland.Root;
            }
        }

        private UIElementIsland _uiElementIsland;
        private TextParagraph _para;
    }

    /// <summary>
    /// Stores information about figure embedded within a text paragraph.
    /// </summary>
    internal sealed class FigureObject : AttachedObject
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="dcp">
        /// Figure object's character position.
        /// </param>
        /// <param name="para">
        /// Paragraph associated with figure object.
        /// </param>
        internal FigureObject(int dcp, FigureParagraph para)
            : base(dcp, para)
        {
        }
    }

    /// <summary>
    /// Stores information about floater embedded within a text paragraph.
    /// </summary>
    internal sealed class FloaterObject : AttachedObject
    {
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="dcp">
        /// Floater object's character position.
        /// </param>
        /// <param name="para">
        /// Paragraph associated with floater object.
        /// </param>
        internal FloaterObject(int dcp, FloaterParagraph para)
            : base(dcp, para)
        {
        }
    }
}


text:
Various "sixth" chords can be used in place of subdominant (the IV chord).

- Italian sixth
    - V7 in IIb (without 5)
- French sixth
    - V7 in IIb (with b5)
    - connected to the blues pendulum
- German sixth
    - V7 in IIb (with normal 5)
- Neapolitan sixth
    - IIb triad
    - V in the mirror key
    - can be used over a minor or major chord
        - major: IIb/I or V/Vb or IV/VIb or I/IIb
        - minor: VIIb/I or IV/IV


text:
package com.vmware.upgrade.dsl.util;

import groovy.lang.Closure;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.vmware.upgrade.dsl.Processor;

/**
 * Aggregates zero or more {@link Processor} implementations.
 *
 * @author Zach Shepherd <shepherdz@vmware.com>
 * @version 1.0
 * @since 1.0
 */
public class AggregateProcessor implements Processor {
    private final Map<String, Closure<?>> keywordProcessors;
    private final List<Object> propertyProcessors;

    /**
     * Creates an {@link AggregateProcessor} based on the state of the delegates at
     * construction time
     *
     * @param processors
     */
    public AggregateProcessor(Processor ... processors) {
        final Map<String, Closure<?>> keywordProcessors = new HashMap<String, Closure<?>>();
        final List<Object> propertyProcessors = new ArrayList<Object>();
        for (Processor processor : processors) {
            keywordProcessors.putAll(processor.getKeywordProcessors());
            propertyProcessors.addAll(processor.getPropertyProcessors());
        }
        this.keywordProcessors = Collections.unmodifiableMap(keywordProcessors);
        this.propertyProcessors = Collections.unmodifiableList(propertyProcessors);
    }

    @Override
    public Map<String, Closure<?>> getKeywordProcessors() {
        return keywordProcessors;
    }

    @Override
    public List<?> getPropertyProcessors() {
        return propertyProcessors;
    }
}


text:
<?php

namespace app\lib\commands;

use app\lib\BaseCommand;
use app\lib\Log;
use app\lib\SftpHelper;
use yii\helpers\Console;
use Yii;
use Net_SFTP;
use yii\helpers\FileHelper;

class SftpGetCommand extends BaseCommand
{

    /** @var  Net_SFTP */
    private $_connection;
    /** @var  SftpHelper */
    private $_sftpHelper;

    private $_connectionId = '';
    private $_destPath = '';
    private $_overwrite = false;

    /**
     * @inheritdoc
     */
    public function run(& $cmdParams, & $params)
    {
        $controller = $this->controller;
        $taskRunner = $this->taskRunner;

        $res = true;
        $this->_connectionId = (!empty($cmdParams[0]) ? $cmdParams[0] : $this->_connectionId);
        $remotePath = (!empty($cmdParams[1]) ? $cmdParams[1] : []);
        $this->_destPath = (!empty($cmdParams[2]) ? $taskRunner->parsePath($cmdParams[2]) : '');
        $this->_overwrite = (!empty($cmdParams[3]) ? $cmdParams[3] : $this->_overwrite);
        // TODO: exclude / filter (?)

        if (empty($this->_connectionId) || empty($this->_destPath)) {
            Log::throwException('sftpGet: Please specify a valid connection id and destination directory');
        }

        if (empty($remotePath)) {
            Log::throwException('sftpGet: remotePath cannot be empty');
        }

        /** @noinspection PhpUndefinedMethodInspection (provided by the SftpConnectReqs Behavior) */
        $connParams = $controller->getConnectionParams($this->_connectionId);
        $controller->stdout(" ".$this->_connectionId." ", $connParams['sftpLabelColor'], Console::FG_BLACK);
        $controller->stdout(' Downloading to: ');
        $controller->stdout($this->_destPath, Console::FG_CYAN);

        if (!$controller->dryRun) {
            // the getConnection method is provided by the SftpConnectReqs Behavior
            /** @noinspection PhpUndefinedMethodInspection */
            $this->_connection = $controller->getConnection($this->_connectionId);
            $this->_sftpHelper = new SftpHelper($this->_connectionId, $this->_connection, $connParams);
        }

        $this->_get($remotePath);

        $controller->stdout("\n");
        return $res;
    }

    private function _get($remotePath, $destRelPathArr = []) {

        // Remove the first element from the $destRelPathArr since it corresponds to the destination path
        $destSubFoldersArr = $destRelPathArr;
        array_shift($destSubFoldersArr);
        $destRelPath = implode(DIRECTORY_SEPARATOR, $destSubFoldersArr);

        $localFolderName = basename($this->_destPath);
        $localFolderName .= (!empty($destRelPath) ? DIRECTORY_SEPARATOR.$destRelPath : '');

        $destPath = $this->_destPath;
        $destPath .= (!empty($destSubFoldersArr) ? DIRECTORY_SEPARATOR.$destRelPath : '');

        $this->controller->stdout("\n - {$localFolderName}\t <= {$remotePath}");

        if (!$this->controller->dryRun) {

            if ($this->_sftpHelper->isDir($remotePath)) {

                if (!is_dir($this->_destPath)) {
                    $this->controller->stdout("\n");
                    Log::throwException('sftpGet: remotePath is a directory, therefore destination has to be a directory too');
                }

                $list = $this->_sftpHelper->nlist($remotePath);
                $remoteDirName = basename($remotePath);
                $newSubDir = $destPath.DIRECTORY_SEPARATOR.$remoteDirName;
                $destRelPathArr[] = $remoteDirName;

                // Creating the sub-directory before recursion to allow creation of empty directories
                // (excluding the first level as it corresponds to the destination path)
                if (count($destRelPathArr) > 1 && !is_dir($newSubDir)) {
                    FileHelper::createDirectory($newSubDir);
                }

                foreach ($list as $item) {
                    if ($item !== '.' && $item !== '..') {
                        $this->_get($remotePath.'/'.$item, $destRelPathArr);
                    }
                }

            } elseif (!empty($destSubFoldersArr) || $this->_sftpHelper->fileExists($remotePath)) {
                // if $destSubFoldersArr is not empty it means that we've got the list of files
                // from the nlist command on the remote directory; therefore we don't need to check
                // if the file exists

                $destFile = $destPath;
                if (is_dir($destFile)) {
                    $destFile = $destPath.DIRECTORY_SEPARATOR.basename($remotePath);
                }

                if ($this->_overwrite || !file_exists($destFile)) {
                    $this->_sftpHelper->get($remotePath, $destFile);
                } else {
                    $this->controller->stdout(' [skipped]', Console::FG_PURPLE);
                }
            } else {
                $this->controller->stdout("\n");
                $this->controller->warn('Not found: '.$remotePath);
            }

        } else {
            $this->controller->stdout(' [dry run]', Console::FG_YELLOW);
        }

    }

}


text:
package org.ScripterRon.BitcoinCore;

import java.nio.ByteBuffer;

/**
 * A message is associated with a peer node and is sent or received using
 * the socket channel assigned to that peer.
 */
public class Message {

    /** The message buffer */
    private ByteBuffer buffer;

    /** The message restart buffer */
    private ByteBuffer restartBuffer;

    /** The associated peer */
    private Peer peer;

    /** The message command */
    private MessageHeader.MessageCommand command;

    /** Inventory message type */
    private int invType;

    /** Deferred restart index */
    private int restartIndex;

    /**
     * Creates an empty message for use by subclasses
     */
    protected Message() {
    }

    /**
     * Creates a new message
     *
     * @param       buffer          Message buffer
     * @param       peer            Associated peer or null for a broadcast message
     * @param       cmd             Message command
     */
    public Message(ByteBuffer buffer, Peer peer, MessageHeader.MessageCommand cmd) {
        this.buffer = buffer;
        this.peer = peer;
        this.command = cmd;
    }

    /**
     * Returns the peer associated with this message or null if this is a broadcast message
     *
     * @return      Peer
     */
    public Peer getPeer() {
        return peer;
    }

    /**
     * Sets the peer associated with this message
     *
     * @param       peer            Associated peer
     */
    public void setPeer(Peer peer) {
        this.peer = peer;
    }

    /**
     * Returns the message buffer
     *
     * @return                      Message buffer
     */
    public ByteBuffer getBuffer() {
        return buffer;
    }

    /**
     * Sets the message buffer
     *
     * @param       buffer          Message buffer
     */
    public void setBuffer(ByteBuffer buffer) {
        this.buffer = buffer;
    }

    /**
     * Returns the message restart buffer
     *
     * @return                      Restart buffer
     */
    public ByteBuffer getRestartBuffer() {
        return restartBuffer;
    }

    /**
     * Sets the message restart buffer
     *
     * @param       buffer          Restart buffer
     */
    public void setRestartBuffer(ByteBuffer buffer) {
        restartBuffer = buffer;
    }

    /**
     * Returns the message command
     *
     * @return                      Message command
     */
    public MessageHeader.MessageCommand getCommand() {
        return command;
    }

    /**
     * Sets the message command
     *
     * @param       cmd             Message command
     */
    public void setCommand(MessageHeader.MessageCommand cmd) {
        command = cmd;
    }

    /**
     * Returns the deferred restart index
     *
     * @return                      Restart index
     */
    public int getRestartIndex() {
        return restartIndex;
    }

    /**
     * Set the deferred restart index
     *
     * @param       restartIndex    Restart index
     */
    public void setRestartIndex(int restartIndex) {
        this.restartIndex = restartIndex;
    }

    /**
     * Return the inventory type
     *
     * @return                      Inventory type
     */
    public int getInventoryType() {
        return invType;
    }

    /**
     * Set the inventory type
     *
     * @param       invType         Inventory type
     */
    public void setInventoryType(int invType) {
        this.invType = invType;
    }

    /**
     * Creates a copy of this message
     *
     * A new ByteBuffer is created using the same byte array.  This allows multiple
     * output channels to process the message at the same time.
     *
     * @param       peer            Target peer
     * @return                      Message clone
     */
    public Message clone(Peer peer) {
        ByteBuffer newBuffer = (buffer!=null ? ByteBuffer.wrap(buffer.array()) : null);
        return new Message(newBuffer, peer, command);
    }
}


text:
import { PREV, NEXT, HIDE_VALUE, SHOW_VALUE } from './constants'

export default class Slide {

    constructor (parent, data, parentElement, showOnRender) {
        this.parent = parent
        this.data = data
        this.visible = showOnRender
        this.parentElement = parentElement
        this.defaultClasses = 'slide theme-' + this.data.theme
        if (this.data.mode) {
            this.defaultClasses += ' ' + this.data.mode
        }
        this.render()
    }

    render () {
        let classes = this.defaultClasses
        if (!this.visible) {
            classes += ' hidden'
        }

        let html = '';
        if (this.data.text) {
            html = `<h2>${this.data.text}</h2>`
        }
        html += `<img src="${this.data.image}" alt="${this.data.alt}" />`

        this.slide = document.createElement('li')
        this.slide.innerHTML = html
        this.slide.className = classes
        this.parentElement.appendChild(this.slide)
        this.caption = this.slide.querySelector('h2')
    }

    hide () {
        this.slide.className = this.defaultClasses + ' hidden'
    }

    show () {
        this.slide.className = this.defaultClasses
        if (this.parent.captionsShown) {
            this.showCaption()
        } else {
            this.hideCaption()
        }
    }

    toggleCaption () {
        if (this.caption) {
            if (this.caption.style.display === HIDE_VALUE) {
                this.showCaption()
            } else {
                this.hideCaption()
            }
        }
    }

    showCaption () {
        if (this.caption) {
            this.caption.style.display = SHOW_VALUE
        }
    }

    hideCaption () {
        if (this.caption) {
            this.caption.style.display = HIDE_VALUE
        }
    }
}


text:
/**
 * CriterionParameter.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.adwords.axis.v201601.cm;

/**
 * Base type of criterion parameters.
 */
public abstract class CriterionParameter  implements java.io.Serializable {
    /* Indicates that this instance is a subtype of CriterionParameter.
     * Although this field is returned in the response, it is ignored on
     * input
     *                 and cannot be selected. Specify xsi:type instead. */
    private java.lang.String criterionParameterType;

    public CriterionParameter() {
    }

    public CriterionParameter(
           java.lang.String criterionParameterType) {
           this.criterionParameterType = criterionParameterType;
    }

    /**
     * Gets the criterionParameterType value for this CriterionParameter.
     *
     * @return criterionParameterType   * Indicates that this instance is a subtype of CriterionParameter.
     * Although this field is returned in the response, it is ignored on
     * input
     *                 and cannot be selected. Specify xsi:type instead.
     */
    public java.lang.String getCriterionParameterType() {
        return criterionParameterType;
    }

    /**
     * Sets the criterionParameterType value for this CriterionParameter.
     *
     * @param criterionParameterType   * Indicates that this instance is a subtype of CriterionParameter.
     * Although this field is returned in the response, it is ignored on
     * input
     *                 and cannot be selected. Specify xsi:type instead.
     */
    public void setCriterionParameterType(java.lang.String criterionParameterType) {
        this.criterionParameterType = criterionParameterType;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof CriterionParameter)) return false;
        CriterionParameter other = (CriterionParameter) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.criterionParameterType==null && other.getCriterionParameterType()==null) ||
             (this.criterionParameterType!=null &&
              this.criterionParameterType.equals(other.getCriterionParameterType())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getCriterionParameterType() != null) {
            _hashCode += getCriterionParameterType().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(CriterionParameter.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "CriterionParameter"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("criterionParameterType");
        elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "CriterionParameter.Type"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
<?php

namespace Ruudk\Payment\MollieBundle\Form;

use Symfony\Component\Form\AbstractType;

class MollieType extends AbstractType
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @param string $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }
}


text:
FROM ubuntu:16.04

MAINTAINER Dockerfiles

# Install required packages and remove the apt packages cache when done.

RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y \
        git \
        python \
        python-dev \
        libpq-dev \
        python-setuptools \
        python-pip \
        nginx \
        supervisor \
        libmysqlclient-dev \
        sqlite3 && \
        pip install -U pip setuptools && \
        rm -rf /var/lib/apt/lists/*

# install uwsgi
RUN pip install uwsgi

# setup all the configfiles
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
COPY nginx-app.conf /etc/nginx/sites-available/default
COPY supervisor-app.conf /etc/supervisor/conf.d/

# COPY requirements.txt and RUN pip install BEFORE adding the rest of your code, this will cause Docker's caching mechanism
# to prevent re-installinig (all your) dependencies when you made a change a line or two in your app.

COPY requirements.txt /home/docker/code/SpearmintServer/
RUN pip install -r /home/docker/code/SpearmintServer/requirements.txt
COPY requirements2.txt /home/docker/code/SpearmintServer/
RUN pip --no-cache-dir install -r /home/docker/code/SpearmintServer/requirements2.txt

# add (the rest of) our code
COPY . /home/docker/code/
COPY secrets.json /home/docker/code/SpearmintServer/SpearmintServer/
ENV HOME /home/docker/code/SpearmintServer/
WORKDIR $HOME

RUN python manage.py collectstatic --noinput
RUN pip install git+http://github.com/acil-bwh/Spearmint.git@develop
RUN python setup.py install

EXPOSE 80
CMD ["supervisord", "-n"]


text:
LOGFILE=install.log
PATH=$PATH
export PATH
exec > >(tee $LOGFILE)
INSTALL_DIR="$( cd "$(dirname "$0")" ; pwd -P )"
BUILD_DIR=${INSTALL_DIR}/build_dir

# This is not the way to do this
PYTHON_PATH=/usr/lib/python2.7
PYTHON_REQUIREMENTS_PATH=requirements.txt

    ENV_VARIABLE="SYNCHRONIZED_LIGHTS_HOME=${INSTALL_DIR}"
exists=`grep -r "$ENV_VARIABLE" /etc/profile*`

# Root check
function check_uid {
  if [ "$EUID" -ne 0 ]; then
    echo "This must be run as root. Please re-run as 'sudo $0'"
    exit 1
  fi
  return 0
}

function log_on_error {
  # basic error reporting
  if [ $2 -ne 0 ]; then
    echo "Houston we have a problem....."
    echo "$1 failed with exit code $2"
    exit 1
  fi
}

check_uid

# Defaults to install where install.sh is located
pushd .
if [ -f $BUILD_DIR ]; then
  rm -rf $BUILD_DIR
fi

mkdir -p $BUILD_DIR
cd $BUILD_DIR

# update first
apt-get update

# Doesn't hurt to try to install things even if some are already installed
apt-get install -y git python-setuptools python-pip python-dev build-essential mercurial
pip install python-setuptools --upgrade

# Install python packages from pypi
popd
pip install -r $PYTHON_REQUIREMENTS_PATH
log_on_error "Installing required python packages..." $?

# install python-alsaaudio
apt-get install -y python-alsaaudio
log_on_error "Installing python-alsaaudio" $?

# install audio encoders
apt-get install -y lame flac faad vorbis-tools
log_on_error "Installing audio-encoders" $?

# install audio encoder ffmpeg (wheezy) or libav-tools (Jessie or OSMC)
version=$(cat /etc/*-release | grep 'VERSION_ID' | awk -F \" '{print $2}')
declare -i version

if [ $version -le 7 ] ; then
  AUDIO_DEODER=ffmpeg
  apt-get install -y ffmpeg
else
  AUDIO_DECODER=libav-tools
  apt-get install -y libav-tools

  # create symlink to avconv so the decoder can still work
  echo "creating symlink to avconv"
  ln -s /usr/bin/avconv /usr/bin/ffmpeg
fi
log_on_error "Installing $AUDIO_DECODER" $?

# install mpg123
apt-get install -y mpg123
log_on_error "Installing mpg123" $?

# Setup environment variables

if [ -z "$exists" ]; then
  echo "# Lightshow Pi Home" > /etc/profile.d/lightshowpi.sh
  echo "$ENV_VARIABLE" >> /etc/profile.d/lightshowpi.sh
  echo "export SYNCHRONIZED_LIGHTS_HOME" >> /etc/profile.d/lightshowpi.sh
  echo "" >> /etc/profile.d/lightshowpi.sh
  echo "# Add Lightshow Pi bin directory to path" >> /etc/profile.d/lightshowpi.sh
  echo "PATH=\$PATH:${INSTALL_DIR}/bin" >> /etc/profile.d/lightshowpi.sh
  echo "export PATH" >> /etc/profile.d/lightshowpi.sh

  # Force set this environment variable in this shell (as above doesn't take until reboot)
  export $ENV_VARIABLE
fi

KEEP_EN="Defaults	env_keep="SYNCHRONIZED_LIGHTS_HOME""
exists=`grep "$KEEP_EN" /etc/sudoers`

if [ -z "$exists" ]; then
  echo "$KEEP_EN" >> /etc/sudoers
fi

# Explain to installer how they can test to see if we are working
echo
echo "You may need to reboot your Raspberry Pi before running lightshowPi (sudo reboot)."
echo "Run the following command to test your installation and hardware setup (press CTRL-C to stop the test):"
echo
echo "sudo python $INSTALL_DIR/py/hardware_controller.py --state=flash"
echo


text:
package com.blochstech.bitcoincardterminal.scanner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;

@SuppressLint("NewApi")
public class DisplayUtils {
    @SuppressWarnings("deprecation") //Used correctly
	public static Point getScreenResolution(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point screenResolution = new Point();
        if (android.os.Build.VERSION.SDK_INT >= 13) {
            display.getSize(screenResolution);
        } else {
            screenResolution.set(display.getWidth(), display.getHeight());
        }

        return screenResolution;
    }

    @SuppressWarnings("deprecation")
	public static int getScreenOrientation(Context context)
    {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        int orientation = Configuration.ORIENTATION_UNDEFINED;
        int width, height;
        if (android.os.Build.VERSION.SDK_INT >= 13) {
	        Point point = new Point();
	        display.getSize(point);
	        width = point != null ? point.x : 0;
	        height = point != null ? point.y : 0;
        }else{
        	width = display.getWidth();
        	height = display.getHeight();
        }
        if(width==height && android.os.Build.VERSION.SDK_INT < 16){
            orientation = Configuration.ORIENTATION_SQUARE;
        } else{
            if(width <= height){
                orientation = Configuration.ORIENTATION_PORTRAIT;
            }else {
                orientation = Configuration.ORIENTATION_LANDSCAPE;
            }
        }
        return orientation;
    }

}


text:
/* Volteer family-specific configuration */
#include "charge_manager.h"
#include "charge_state.h"
#include "charger.h"
#include "common.h"
#include "driver/charger/isl9241_public.h"
#include "gpio.h"
#ifdef CONFIG_ZEPHYR
#include "usbc_config.h"
#endif
#include "usbc_ppc.h"
#include "util.h"

#define CPRINTSUSB(format, args...) cprints(CC_USBCHARGE, format, ##args)
#define CPRINTFUSB(format, args...) cprintf(CC_USBCHARGE, format, ##args)

/* Charger Chip Configuration */
const struct charger_config_t chg_chips[] = {
	{
		.i2c_port = I2C_PORT_CHARGER,
		.i2c_addr_flags = ISL9241_ADDR_FLAGS,
		.drv = &isl9241_drv,
	},
};

int board_set_active_charge_port(int port)
{
	int is_valid_port = (port >= 0 && port < CONFIG_USB_PD_PORT_MAX_COUNT);
	int i;

	if (port == CHARGE_PORT_NONE) {
		CPRINTSUSB("Disabling all charger ports");

		/* Disable all ports. */
		for (i = 0; i < ppc_cnt; i++) {
			/*
			 * Do not return early if one fails otherwise we can
			 * get into a boot loop assertion failure.
			 */
			if (ppc_vbus_sink_enable(i, 0))
				CPRINTSUSB("Disabling C%d as sink failed.", i);
		}

		return EC_SUCCESS;
	} else if (!is_valid_port) {
		return EC_ERROR_INVAL;
	}

	/* Check if the port is sourcing VBUS. */
	if (ppc_is_sourcing_vbus(port)) {
		CPRINTFUSB("Skip enable C%d", port);
		return EC_ERROR_INVAL;
	}

	CPRINTSUSB("New charge port: C%d", port);

	/*
	 * Turn off the other ports' sink path FETs, before enabling the
	 * requested charge port.
	 */
	for (i = 0; i < ppc_cnt; i++) {
		if (i == port)
			continue;

		if (ppc_vbus_sink_enable(i, 0))
			CPRINTSUSB("C%d: sink path disable failed.", i);
	}

	/* Enable requested charge port. */
	if (ppc_vbus_sink_enable(port, 1)) {
		CPRINTSUSB("C%d: sink path enable failed.", port);
		return EC_ERROR_UNKNOWN;
	}

	return EC_SUCCESS;
}

void board_overcurrent_event(int port, int is_overcurrented)
{
	/* Note that the level is inverted because the pin is active low. */
	switch (port) {
	case USBC_PORT_C0:
		gpio_set_level(GPIO_USB_C0_OC_ODL, !is_overcurrented);
		break;
	case USBC_PORT_C1:
		gpio_set_level(GPIO_USB_C1_OC_ODL, !is_overcurrented);
		break;
	}
}


text:
import{Component} from '@angular/core';
@Component({
    selector:'app-left-navigation',
    template: `
    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-4">
    leftcomponent
    </div>`
})
export class leftcomponent{

}


text: loads_scripts_with_improper_integrity_uri_scheme=true;


text:
package javax.swing.plaf.metal;

import java.awt.*;
import java.awt.event.*;
import javax.swing.plaf.basic.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.border.*;
import java.io.Serializable;

/**
 * JButton subclass to help out MetalComboBoxUI
 *

 * Warning:
 * Serialized objects of this class will not be compatible with
 * future Swing releases. The current serialization support is
 * appropriate for short term storage or RMI between applications running
 * the same version of Swing.  As of 1.4, support for long term storage
 * of all JavaBeans™
 * has been added to the java.beans package.
 * Please see {@link java.beans.XMLEncoder}.
 *
 * @see MetalComboBoxButton
 * @author Tom Santos
 */
public class MetalComboBoxButton extends JButton {
    protected JComboBox comboBox;
    protected JList listBox;
    protected CellRendererPane rendererPane;
    protected Icon comboIcon;
    protected boolean iconOnly = false;

    public final JComboBox getComboBox() { return comboBox;}
    public final void setComboBox( JComboBox cb ) { comboBox = cb;}

    public final Icon getComboIcon() { return comboIcon;}
    public final void setComboIcon( Icon i ) { comboIcon = i;}

    public final boolean isIconOnly() { return iconOnly;}
    public final void setIconOnly( boolean isIconOnly ) { iconOnly = isIconOnly;}

    MetalComboBoxButton() {
        super( "" );
        DefaultButtonModel model = new DefaultButtonModel() {
            public void setArmed( boolean armed ) {
                super.setArmed( isPressed() ? true : armed );
            }
        };
        setModel( model );
    }

    public MetalComboBoxButton( JComboBox cb, Icon i,
                                CellRendererPane pane, JList list ) {
        this();
        comboBox = cb;
        comboIcon = i;
        rendererPane = pane;
        listBox = list;
        setEnabled( comboBox.isEnabled() );
    }

    public MetalComboBoxButton( JComboBox cb, Icon i, boolean onlyIcon,
                                CellRendererPane pane, JList list ) {
        this( cb, i, pane, list );
        iconOnly = onlyIcon;
    }

    public boolean isFocusTraversable() {
        return false;
    }

    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);

        // Set the background and foreground to the combobox colors.
        if (enabled) {
            setBackground(comboBox.getBackground());
            setForeground(comboBox.getForeground());
        } else {
            setBackground(UIManager.getColor("ComboBox.disabledBackground"));
            setForeground(UIManager.getColor("ComboBox.disabledForeground"));
        }
    }

    public void paintComponent( Graphics g ) {
        boolean leftToRight = MetalUtils.isLeftToRight(comboBox);

        // Paint the button as usual
        super.paintComponent( g );

        Insets insets = getInsets();

        int width = getWidth() - (insets.left + insets.right);
        int height = getHeight() - (insets.top + insets.bottom);

        if ( height <= 0 || width <= 0 ) {
            return;
        }

        int left = insets.left;
        int top = insets.top;
        int right = left + (width - 1);
        int bottom = top + (height - 1);

        int iconWidth = 0;
        int iconLeft = (leftToRight) ? right : left;

        // Paint the icon
        if ( comboIcon != null ) {
            iconWidth = comboIcon.getIconWidth();
            int iconHeight = comboIcon.getIconHeight();
            int iconTop = 0;

            if ( iconOnly ) {
                iconLeft = (getWidth() / 2) - (iconWidth / 2);
                iconTop = (getHeight() / 2) - (iconHeight / 2);
            }
            else {
                if (leftToRight) {
                    iconLeft = (left + (width - 1)) - iconWidth;
                }
                else {
                    iconLeft = left;
                }
                iconTop = (top + ((bottom - top) / 2)) - (iconHeight / 2);
            }

            comboIcon.paintIcon( this, g, iconLeft, iconTop );

            // Paint the focus
            if ( comboBox.hasFocus() && (!MetalLookAndFeel.usingOcean() ||
                                         comboBox.isEditable())) {
                g.setColor( MetalLookAndFeel.getFocusColor() );
                g.drawRect( left - 1, top - 1, width + 3, height + 1 );
            }
        }

        if (MetalLookAndFeel.usingOcean()) {
            // With Ocean the button only paints the arrow, bail.
            return;
        }

        // Let the renderer paint
        if ( ! iconOnly && comboBox != null ) {
            ListCellRenderer renderer = comboBox.getRenderer();
            Component c;
            boolean renderPressed = getModel().isPressed();
            c = renderer.getListCellRendererComponent(listBox,
                                                      comboBox.getSelectedItem(),
                                                      -1,
                                                      renderPressed,
                                                      false);
            c.setFont(rendererPane.getFont());

            if ( model.isArmed() && model.isPressed() ) {
                if ( isOpaque() ) {
                    c.setBackground(UIManager.getColor("Button.select"));
                }
                c.setForeground(comboBox.getForeground());
            }
            else if ( !comboBox.isEnabled() ) {
                if ( isOpaque() ) {
                    c.setBackground(UIManager.getColor("ComboBox.disabledBackground"));
                }
                c.setForeground(UIManager.getColor("ComboBox.disabledForeground"));
            }
            else {
                c.setForeground(comboBox.getForeground());
                c.setBackground(comboBox.getBackground());
            }

            int cWidth = width - (insets.right + iconWidth);

            // Fix for 4238829: should lay out the JPanel.
            boolean shouldValidate = false;
            if (c instanceof JPanel)  {
                shouldValidate = true;
            }

            if (leftToRight) {
                rendererPane.paintComponent( g, c, this,
                                             left, top, cWidth, height, shouldValidate );
            }
            else {
                rendererPane.paintComponent( g, c, this,
                                             left + iconWidth, top, cWidth, height, shouldValidate );
            }
        }
    }

    public Dimension getMinimumSize() {
        Dimension ret = new Dimension();
        Insets insets = getInsets();
        ret.width = insets.left + getComboIcon().getIconWidth() + insets.right;
        ret.height = insets.bottom + getComboIcon().getIconHeight() + insets.top;
        return ret;
    }
}


text:
<?php

require_once "../../config.php";
require_once "header.php";
require_once "misc.php";
use Goutte\Client;

line_out("Grading PHP-Intro Assignment 5");

$url = getUrl('http://www.php-intro.com/assn/tracks');
$grade = 0;

error_log("ASSN05 ".$url);
line_out("Retrieving ".htmlent_utf8($url)."...");
flush();

$client = new Client();

$crawler = $client->request('GET', $url);

// Yes, one gigantic unindented try/catch block
$passed = 0;
$titlepassed = true;
try {

$html = $crawler->html();
togglePre("Show retrieved page",$html);

$retval = checkTitle($crawler);
if ( $retval !== true ) {
    error_out($retval);
    $titlepassed = false;
}

line_out("Looking for Add New link.");
$link = $crawler->selectLink('Add New')->link();
$url = $link->getURI();
line_out("Retrieving ".htmlent_utf8($url)."...");

$crawler = $client->request('GET', $url);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;

// Add new fail
line_out("Looking for the form with a 'Add New' submit button");
$form = $crawler->selectButton('Add New')->form();
line_out("Setting non-integer values in the plays and rating form fields and leaving title blank");
$form->setValues(array("plays" => "many", "rating" => "awesome"));
$crawler = $client->submit($form);
$passed++;

$html = $crawler->html();
togglePre("Show retrieved page",$html);
checkPostRedirect($client);

line_out("Expecting 'Bad value for title, plays, or rating'");
if ( strpos(strtolower($html), 'bad value') !== false ) {
    $passed++;
} else {
    error_out("Could not find 'Bad value for title, plays, or rating'");
}

line_out("Looking for Add New link.");
$link = $crawler->selectLink('Add New')->link();
$url = $link->getURI();
line_out("Retrieving ".htmlent_utf8($url)."...");

$crawler = $client->request('GET', $url);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;
line_out("Looking for the form with a 'Add New' submit button");
$form = $crawler->selectButton('Add New')->form();
$title = 'ACDC'.sprintf("%03d",rand(1,100));
$plays = rand(1,100);
$rating = rand(1,100);
line_out("Entering title=$title, plays=$plays, rating=$rating");
$form->setValues(array("title" => $title, "plays" => $plays, "rating" => $rating));
$crawler = $client->submit($form);
$passed++;

$html = $crawler->html();
togglePre("Show retrieved page",$html);
checkPostRedirect($client);

line_out("Looking '$title' entry");
$pos = strpos($html, $title);
$pos2 = strpos($html, "edit.php", $pos);
$body = substr($html,$pos,$pos2-$pos);
# echo "body=",htmlentities($body);
line_out("Looking for plays=$plays and rating=$rating");
if ( strpos($body,''.$plays) < 1 || strpos($body,''.$rating) < 1 ) {
    error_out("Could not find plays=$plays and rating=$rating");
} else {
    $passed++;
}

line_out("Looking for edit.php link associated with '$title' entry");
$pos3 = strpos($html, '"', $pos2);
$editlink = substr($html,$pos2,$pos3-$pos2);
line_out("Retrieving ".htmlent_utf8($editlink)."...");

$crawler = $client->request('GET', $editlink);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;

line_out("Looking for the form with a 'Update' submit button");
$form = $crawler->selectButton('Update')->form();
$plays = rand(1,100);
$rating = rand(1,100);
line_out("Editing title=$title, plays=$plays, rating=$rating");
$form->setValues(array("title" => $title, "plays" => $plays, "rating" => $rating));
$crawler = $client->submit($form);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;
checkPostRedirect($client);

// Delete...
line_out("Looking '$title' entry");
$pos = strpos($html, $title);
$pos2 = strpos($html, "delete.php", $pos);
$body = substr($html,$pos,$pos2-$pos);
# echo "body=",htmlentities($body);
line_out("Looking for plays=$plays and rating=$rating");
if ( strpos($body,''.$plays) < 1 || strpos($body,''.$rating) < 1 ) {
    error_out("Could not find plays=$plays and rating=$rating");
} else {
    $passed++;
}

line_out("Looking for delete.php link associated with '$title' entry");
$pos3 = strpos($html, '"', $pos2);
$editlink = substr($html,$pos2,$pos3-$pos2);
line_out("Retrieving ".htmlent_utf8($editlink)."...");

$crawler = $client->request('GET', $editlink);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;

// Do the Delete
line_out("Looking for the form with a 'Delete' submit button");
$form = $crawler->selectButton('Delete')->form();
$crawler = $client->submit($form);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;
checkPostRedirect($client);

line_out("Making sure '$title' has been deleted");
if ( strpos($html,$title) > 0 ) {
    error_out("Entry '$title' not deleted");
} else {
    $passed++;
}

line_out("Cleaning up old ACDC records...");
while (True ) {
    $pos = strpos($html, 'ACDC');
    if ( $pos < 1 ) break;
    $pos2 = strpos($html, "delete.php", $pos);
    if ( $pos2 < 1 ) break;
    $pos3 = strpos($html, '"', $pos2);
    if ( $pos3 < 1 ) break;
    $editlink = substr($html,$pos2,$pos3-$pos2);
    line_out("Retrieving ".htmlent_utf8($editlink)."...");

    $crawler = $client->request('GET', $editlink);
    $html = $crawler->html();
    togglePre("Show retrieved page",$html);
    $passed++;

    // Do the Delete
    line_out("Looking for the form with a 'Delete' submit button");
    $form = $crawler->selectButton('Delete')->form();
    $crawler = $client->submit($form);
    $html = $crawler->html();
    togglePre("Show retrieved page",$html);
    $passed++;
    checkPostRedirect($client);
}

line_out("Testing for HTML injection (proper use of htmlentities)...");
line_out("Looking for Add New link.");
$link = $crawler->selectLink('Add New')->link();
$url = $link->getURI();
line_out("Retrieving ".htmlent_utf8($url)."...");

$crawler = $client->request('GET', $url);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;

line_out("Looking for the form with a 'Add New' submit button");
$form = $crawler->selectButton('Add New')->form();
$title = 'AC<DC'.sprintf("%03d",rand(1,100));
$plays = rand(1,100);
$rating = rand(1,100);
line_out("Entering title=$title, plays=$plays, rating=$rating");
$form->setValues(array("title" => $title, "plays" => $plays, "rating" => $rating));
$crawler = $client->submit($form);
$passed++;

$html = $crawler->html();
togglePre("Show retrieved page",$html);
checkPostRedirect($client);

$pos = strpos($html, "AC<DC");
if ( $pos > 0 ) {
    $passed+=2;
} else {
    error_out("Found HTML Injection");
    throw new Exception("Found HTML Injection");
}
$pos2 = strpos($html, "delete.php", $pos);
line_out("Looking for delete.php link associated with '$title' entry");
$pos3 = strpos($html, '"', $pos2);
$editlink = substr($html,$pos2,$pos3-$pos2);
line_out("Retrieving ".htmlent_utf8($editlink)."...");

$crawler = $client->request('GET', $editlink);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;

$pos = strpos($html, "AC<DC");
if ( $pos > 0 ) {
    $passed+=2;
} else {
    error_out("Found HTML Injection");
    throw new Exception("Found HTML Injection");
}

line_out("Looking for the form with a 'Delete' submit button");
$form = $crawler->selectButton('Delete')->form();
$crawler = $client->submit($form);
$html = $crawler->html();
togglePre("Show retrieved page",$html);
$passed++;
checkPostRedirect($client);

} catch (Exception $ex) {
    error_out("The autograder did not find something it was looking for in your HTML - test ended.");
    error_log($ex->getMessage());
    error_log($ex->getTraceAsString());
    $detail = "This indicates the source code line where the test stopped.\n" .
        "It may not make any sense without looking at the source code for the test.\n".
        'Caught exception: '.$ex->getMessage()."\n".$ex->getTraceAsString()."\n";
    togglePre("Internal error detail.",$detail);
}

$perfect = 26;
$score = $passed * (1.0 / $perfect);
if ( $score < 0 ) $score = 0;
if ( $score > 1 ) $score = 1;
$scorestr = "Score = $score ($passed/$perfect)";
if ( $penalty === false ) {
    line_out("Score = $score ($passed/$perfect)");
} else {
    $score = $score * (1.0 - $penalty);
    line_out("Score = $score ($passed/$perfect) penalty=$penalty");
}

if ( ! $titlepassed ) {
    error_out("These pages do not have proper titles so this grade is not official");
    return;
}

if ( $score > 0.0 ) testPassed($score);


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsScreenManagerWin.h"
#include "nsScreenWin.h"

BOOL CALLBACK CountMonitors ( HMONITOR, HDC, LPRECT, LPARAM ioCount ) ;

nsScreenManagerWin :: nsScreenManagerWin ( )
  : mNumberOfScreens(0)
{
  // nothing to do. I guess we could cache a bunch of information
  // here, but we want to ask the device at runtime in case anything
  // has changed.
}

nsScreenManagerWin :: ~nsScreenManagerWin()
{
}

// addref, release, QI
NS_IMPL_ISUPPORTS1(nsScreenManagerWin, nsIScreenManager)

//
// CreateNewScreenObject
//
// Utility routine. Creates a new screen object from the given device handle
//
// NOTE: For this "single-monitor" impl, we just always return the cached primary
//        screen. This should change when a multi-monitor impl is done.
//
nsIScreen*
nsScreenManagerWin :: CreateNewScreenObject ( HMONITOR inScreen )
{
  nsIScreen* retScreen = nullptr;

  // look through our screen list, hoping to find it. If it's not there,
  // add it and return the new one.
  for ( unsigned i = 0; i < mScreenList.Length(); ++i ) {
    ScreenListItem& curr = mScreenList[i];
    if ( inScreen == curr.mMon ) {
      NS_IF_ADDREF(retScreen = curr.mScreen.get());
      return retScreen;
    }
  } // for each screen.

  retScreen = new nsScreenWin(inScreen);
  mScreenList.AppendElement ( ScreenListItem ( inScreen, retScreen ) );

  NS_IF_ADDREF(retScreen);
  return retScreen;
}

//
// ScreenForRect
//
// Returns the screen that contains the rectangle. If the rect overlaps
// multiple screens, it picks the screen with the greatest area of intersection.
//
// The coordinates are in pixels (not twips) and in screen coordinates.
//
NS_IMETHODIMP
nsScreenManagerWin :: ScreenForRect ( int32_t inLeft, int32_t inTop, int32_t inWidth, int32_t inHeight,
                                        nsIScreen **outScreen )
{
  if ( !(inWidth || inHeight) ) {
    NS_WARNING ( "trying to find screen for sizeless window, using primary monitor" );
    *outScreen = CreateNewScreenObject ( nullptr );    // addrefs
    return NS_OK;
  }

  RECT globalWindowBounds = { inLeft, inTop, inLeft + inWidth, inTop + inHeight };

  HMONITOR genScreen = ::MonitorFromRect( &globalWindowBounds, MONITOR_DEFAULTTOPRIMARY );

  *outScreen = CreateNewScreenObject ( genScreen );    // addrefs

  return NS_OK;

} // ScreenForRect

//
// GetPrimaryScreen
//
// The screen with the menubar/taskbar. This shouldn't be needed very
// often.
//
NS_IMETHODIMP
nsScreenManagerWin :: GetPrimaryScreen(nsIScreen** aPrimaryScreen)
{
  *aPrimaryScreen = CreateNewScreenObject ( nullptr );    // addrefs
  return NS_OK;

} // GetPrimaryScreen

//
// CountMonitors
//
// Will be called once for every monitor in the system. Just
// increments the parameter, which holds a ptr to a PRUin32 holding the
// count up to this point.
//
BOOL CALLBACK
CountMonitors ( HMONITOR, HDC, LPRECT, LPARAM ioParam )
{
  uint32_t* countPtr = reinterpret_cast<uint32_t*>(ioParam);
  ++(*countPtr);

  return TRUE; // continue the enumeration

} // CountMonitors

//
// GetNumberOfScreens
//
// Returns how many physical screens are available.
//
NS_IMETHODIMP
nsScreenManagerWin :: GetNumberOfScreens(uint32_t *aNumberOfScreens)
{
  if ( mNumberOfScreens )
    *aNumberOfScreens = mNumberOfScreens;
  else {
    uint32_t count = 0;
    BOOL result = ::EnumDisplayMonitors(nullptr, nullptr, (MONITORENUMPROC)CountMonitors, (LPARAM)&count);
    if (!result)
      return NS_ERROR_FAILURE;
    *aNumberOfScreens = mNumberOfScreens = count;
  }

  return NS_OK;

} // GetNumberOfScreens

NS_IMETHODIMP
nsScreenManagerWin :: ScreenForNativeWidget(void *aWidget, nsIScreen **outScreen)
{
  HMONITOR mon = MonitorFromWindow ((HWND) aWidget, MONITOR_DEFAULTTOPRIMARY);
  *outScreen = CreateNewScreenObject (mon);
  return NS_OK;
}