text:
import {Errors} from "../../../src/comm_system/constants";
import {ActionDispatcher} from "../../../src/comm_system/ActionDispatcher";

import Chai = require("chai");
var expect = Chai.expect;

describe('ActionDispatcher', function() {

    var actionDispatcher:any = new ActionDispatcher();
    var throws;

    beforeEach(function (done) {
        throws = null;
        done();
    });

    var actionNumber:number = 0;
    function registerAction(handler,handlerContext?):string
    {
        var action:string = "action"+actionNumber;
        actionDispatcher.registerAction("action"+actionNumber,handler,handlerContext);
        actionNumber++;
        return action;
    }

    describe("registerAction",()=>{
        it('should throw an error when registering action with actionName not of type string', function(done) {
            throws = function() {
                actionDispatcher.registerAction({});
            };
            expect(throws).to.throw(Errors.ERROR_REGISTERING_ACTION_NAME_NOT_TYPE_STRING);

            throws = function() {
                actionDispatcher.registerAction();
            };
            expect(throws).to.throw(Errors.ERROR_REGISTERING_ACTION_NAME_NOT_TYPE_STRING);

            throws = function() {
                actionDispatcher.registerAction(null);
            };
            expect(throws).to.throw(Errors.ERROR_REGISTERING_ACTION_NAME_NOT_TYPE_STRING);

            done();
        });

        it('should throw an error when no handler is passed, while registering an action', function(done) {

            throws = function() {
                actionDispatcher.registerAction("action");
            };

            expect(throws).to.throw(Errors.ERROR_REGISTERING_ACTION_NO_HANDLER_GIVEN);

            throws = function() {
                actionDispatcher.registerAction("event",null);
            };

            expect(throws).to.throw(Errors.ERROR_REGISTERING_ACTION_NO_HANDLER_GIVEN);

            done();
        });

        it('should throw an error when handler is not of type function, while registering an action', function(done) {

            throws = function() {
                actionDispatcher.registerAction("event",{});
            };

            expect(throws).to.throw(Errors.ERROR_REGISTERING_ACTION_HANDLER_NOT_TYPE_FUNCTION);
            done();
        });

        it('should throw an error when handler is already set for the action', function(done) {

            actionDispatcher.registerAction("event",function(){});
            throws = function() {
                actionDispatcher.registerAction("event",function(){});
            };

            expect(throws).to.throw(Errors.ERROR_REGISTERING_ACTION_ONLY_ONE_HANDLER_ALLOWED);
            done();
        });
    });

    describe("unregisterAction",()=>{
        it('should throw an error when trying to un-register from an action not of type string', function(done) {
            throws = function() {
                actionDispatcher.unregisterAction({});
            };
            expect(throws).to.throw(Errors.ERROR_UNREGISTERING_ACTION_NAME_NOT_TYPE_STRING);

            throws = function() {
                actionDispatcher.unregisterAction();
            };
            expect(throws).to.throw(Errors.ERROR_UNREGISTERING_ACTION_NAME_NOT_TYPE_STRING);

            throws = function() {
                actionDispatcher.unregisterAction(null);
            };
            expect(throws).to.throw(Errors.ERROR_UNREGISTERING_ACTION_NAME_NOT_TYPE_STRING);

            done();
        });

        it('should throw an error when no handler is passed while un-registering to an anction', function(done) {

            throws = function() {
                actionDispatcher.unregisterAction("event");
            };

            expect(throws).to.throw(Errors.ERROR_UNREGISTERING_ACTION_NO_HANDLER_GIVEN);

            throws = function() {
                actionDispatcher.unregisterAction("event",null);
            };

            expect(throws).to.throw(Errors.ERROR_UNREGISTERING_ACTION_NO_HANDLER_GIVEN);

            done();
        });

        it('should throw an error when trying to un-register with handler not of type function', function(done) {

            throws = function() {
                actionDispatcher.unregisterAction("event",{});
            };
            expect(throws).to.throw(Errors.ERROR_UNREGISTERING_ACTION_HANDLER_NOT_TYPE_FUNCTION);
            done();
        });

        it('should successfully unregister action', function(done) {

            function handler():void
            {

            }
            actionDispatcher.registerAction("action",handler);
            actionDispatcher.unregisterAction("action",handler);
            expect(actionDispatcher.hasAction("action")).to.equal(false);
            done();
        });
    });

    describe("perform",()=>{
        it('should throw an error when taking action name not of type string', function(done) {

            throws = function() {
                actionDispatcher.perform({});
            };
            expect(throws).to.throw(Errors.ERROR_TAKING_ACTION_ACTION_NAME_NOT_TYPE_STRING);
            done();
        });

        it('should successfully call any handler associated with the action', function(done) {

            var handler = function(data){
                done();
            };

            var action = registerAction(handler);

            actionDispatcher.perform(action);
        });

        it('should successfully call handler associated with the action, with appropriate parameters', function(done) {

            var paramA = "A";
            var paramB = {};
            var handler = function(param1,param2){

                expect(arguments.length).to.equal(2);
                expect(param1).to.equal(paramA);
                expect(param2).to.equal(paramB);
                done();
            };

            var action = registerAction(handler);

            actionDispatcher.perform(action,paramA,paramB);

        });

        it('should call the handler with right context if the context is passed while registering', function(done) {

            var handlerContext ={};
            var paramA = "A";
            var paramB = {};
            var handler = function(param1,param2){

                expect(this).to.equal(handlerContext);
                done();
            };

            var action = registerAction(handler,handlerContext);

            actionDispatcher.perform(action,paramA,paramB);

        });

        it('should call the handler with undefined context if no context is passed while registering', function(done) {

            var handler = function(){

                expect(this).to.equal(undefined);
                done();
            };

            var action = registerAction(handler);
            actionDispatcher.perform(action);

        });

        it('should return a promise, when handler returns a promise', function(done) {

            var handler = function(data){
                return new Promise(function(){});
            };
            var action = registerAction(handler);

            var result = actionDispatcher.perform(action, "humm");

            expect(result instanceof Promise).to.equal(true);
            done();
        });

        it('should return a promise, when handler returns a value', function(done) {

            var handler = function(data){
                return true;
            };
            var action = registerAction(handler);

            var result = actionDispatcher.perform(action, "humm");

            expect(result instanceof Promise).to.equal(true);
            done();
        });

        it('should reject with error if handler throws error', function(done) {

            var handler = function(data){
                throw new Error("yay");
            };
            var action = registerAction(handler);

            var result = actionDispatcher.perform(action, "humm");

            expect(result instanceof Promise).to.equal(true);

            result.then(null,(error)=>{
                expect(error).to.be.instanceof(Error);
                expect(error.message).to.equal("yay");
                done();
            })

        });
    });

    describe("hasAction",()=>{
        it('should return true if action registered', function(done) {
            var action = registerAction(function(){});

            expect(actionDispatcher.hasAction(action)).to.equal(true);
            done();
        });

        it('should return false if no action registered', function(done) {
            expect(actionDispatcher.hasAction("ewrwer")).to.equal(false);
            done();
        });
    });

});


text:
<?php
/**
 * This is the model class for table "cat_dependencia".
 *
 * The followings are the available columns in table 'cat_dependencia':
 * @property string $id_cat_dependencia
 * @property string $cat_dependencia
 * @property string $persona_creacion
 * @property string $fecha_creacion
 * @property string $persona_modificacion
 * @property string $fecha_modificacion
 * @property integer $activo
 *
 * The followings are the available model relations:
 * @property CatAreaDependencia[] $catAreaDependencias
 * @property ServidorPublico[] $servidorPublicos
 */
class CatDependencia extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return CatDependencia the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'cat_dependencia';
    }

    /**
     * @return Validaciones de modelo
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('cat_dependencia', 'required'),
            array('activo', 'numerical', 'integerOnly' => true),
            array('cat_dependencia', 'length', 'max' => 200),
            array('persona_creacion, persona_modificacion', 'length', 'max' => 20),
            array('fecha_creacion, fecha_modificacion', 'safe'),

            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id_cat_dependencia, cat_dependencia, persona_creacion, fecha_creacion, persona_modificacion, fecha_modificacion, activo\n', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'catAreaDependencias' => array(self::HAS_MANY, 'CatAreaDependencia', 'id_cat_dependencia'),
            'servidorPublicos' => array(self::HAS_MANY, 'ServidorPublico', 'id_cat_dependencia'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id_cat_dependencia' => 'Cat Dependencia',
            'cat_dependencia' => 'Cat Dependencia',
            'persona_creacion' => 'Persona Creacion',
            'fecha_creacion' => 'Fecha Creacion',
            'persona_modificacion' => 'Persona Modificacion',
            'fecha_modificacion' => 'Fecha Modificacion',
            'activo' => 'Activo',
        );
    }

    /**
     * @return array para Combobox
     */
    public function comboBox()
    {

        return CHtml::listData(CatDependencia::model()->findAll(),
            'id_cat_dependencia', 'cat_dependencia');

    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */

    public function search()
    {

        $criteria = new CDbCriteria();
        $criteria->compare('cat_dependencia', $this->cat_dependencia, true);

        $criteria->compare('activo', 1);
        Yii::app()->session['CatDependenciaCriteria'] = $criteria;

        return new CActiveDataProvider($this, array(
                'criteria' => $criteria,
                'pagination' => array(
                    'pageSize' => 20),
            )
        );

    }
}

redpajama_set_name: RedPajamaGithub


text:
import smbus

# ===========================================================================
# Adafruit_I2C Base Class
# ===========================================================================

class Adafruit_I2C :

  def __init__(self, address, bus=0, debug=False):
    self.address = address
    self.bus = smbus.SMBus(bus)
    self.debug = debug

  def reverseByteOrder(self, data):
    "Reverses the byte order of an int (16-bit) or long (32-bit) value"
    # Courtesy Vishal Sapre
    dstr = hex(data)[2:].replace('L','')
    byteCount = len(dstr[::2])
    val = 0
    for i, n in enumerate(range(byteCount)):
      d = data & 0xFF
      val |= (d << (8 * (byteCount - i - 1)))
      data >>= 8
    return val

  def write8(self, reg, value):
    "Writes an 8-bit value to the specified register/address"
    try:
      self.bus.write_byte_data(self.address, reg, value)
      if (self.debug):
        print("I2C: Wrote 0x%02X to register 0x%02X" % (value, reg))
    except IOError  as err:
      print( "Error accessing 0x%02X: Check your I2C address" % self.address)
      return -1

  def writeList(self, reg, list):
    "Writes an array of bytes using I2C format"
    try:
      self.bus.write_i2c_block_data(self.address, reg, list)
    except IOError  as err:
      print( "Error accessing 0x%02X: Check your I2C address" % self.address)
      return -1

  def readU8(self, reg):
    "Read an unsigned byte from the I2C device"
    try:
      result = self.bus.read_byte_data(self.address, reg)
      if (self.debug):
        print( "I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % (self.address, result & 0xFF, reg))
      return result
    except IOError as err:
      print( "Error accessing 0x%02X: Check your I2C address" % self.address)
      return -1

  def readS8(self, reg):
    "Reads a signed byte from the I2C device"
    try:
      result = self.bus.read_byte_data(self.address, reg)
      if (self.debug):
        print( "I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % (self.address, result & 0xFF, reg))
      if (result > 127):
        return result - 256
      else:
        return result
    except IOError as err:
      print( "Error accessing 0x%02X: Check your I2C address" % self.address)
      return -1

  def readU16(self, reg):
    "Reads an unsigned 16-bit value from the I2C device"
    try:
      hibyte = self.bus.read_byte_data(self.address, reg)
      result = (hibyte << 8) + self.bus.read_byte_data(self.address, reg+1)
      if (self.debug):
        print( "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg))
      return result
    except IOError as err:
      print("Error accessing 0x%02X: Check your I2C address" % self.address)
      return -1

  def readS16(self, reg):
    "Reads a signed 16-bit value from the I2C device"
    try:
      hibyte = self.bus.read_byte_data(self.address, reg)
      if (hibyte > 127):
        hibyte -= 256
      result = (hibyte << 8) + self.bus.read_byte_data(self.address, reg+1)
      if (self.debug):
        print( "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg))
      return result
    except IOError as err:
      print( "Error accessing 0x%02X: Check your I2C address" % self.address)
      return -1


text:
package com.example.ashut.getitnow;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class SignUpActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        final EditText name,email,pwd,phn,address;
        name = (EditText)findViewById(R.id.etName);
        email = (EditText)findViewById(R.id.etEmail);
        pwd = (EditText)findViewById(R.id.etPassword);
        phn = (EditText)findViewById(R.id.etPhn);
        address = (EditText)findViewById(R.id.etAddress);

        final Button reset,signup;
        reset=(Button)findViewById(R.id.bReset);
        signup=(Button)findViewById(R.id.bSignUp);
        reset.setOnClickListener(new TextView.OnClickListener(){
            @Override
            public void onClick(View v) {
                name.setText("");
                email.setText("");
                pwd.setText("");
                phn.setText("");
            }
        });

    }
    public void signUp(View v){
        Intent i=new Intent(SignUpActivity.this,MainActivity.class);
        startActivity(i);
    }

}


text:
package io.spine.server.storage.datastore;

import com.google.cloud.datastore.Entity;
import com.google.common.collect.ImmutableMultimap;
import io.spine.client.CompositeFilter.CompositeOperator;
import io.spine.client.Filter;
import io.spine.server.entity.storage.Column;
import io.spine.server.entity.storage.CompositeQueryParameter;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.Map;
import java.util.function.Predicate;

import static io.spine.client.OperatorEvaluator.eval;
import static io.spine.util.Exceptions.newIllegalArgumentException;

/**
 * Test if a Datastore entity matches query parameters.
 */
final class EntityColumnPredicate implements Predicate<Entity> {

    private final FilterAdapter adapter;
    private final Iterable<CompositeQueryParameter> queryParams;

    EntityColumnPredicate(Iterable<CompositeQueryParameter> queryParams,
                          FilterAdapter adapter) {
        this.adapter = adapter;
        this.queryParams = queryParams;
    }

    @Override
    @SuppressWarnings("FallThrough") // defines strategy for default and faulty values.
    public boolean test(@Nullable Entity entity) {
        if (entity == null) {
            return false;
        }
        for (CompositeQueryParameter filter : queryParams) {
            boolean match;
            CompositeOperator operator = filter.operator();
            switch (operator) {
                case ALL:
                    match = checkAll(filter.filters(), entity);
                    break;
                case EITHER:
                    match = checkEither(filter.filters(), entity);
                    break;

                // Fall through to default strategy for the `default` and `faulty` enum values.
                case UNRECOGNIZED:
                case CCF_CO_UNDEFINED:
                default:
                    throw newIllegalArgumentException(
                            "Composite operator %s is invalid.", operator
                    );
            }
            if (!match) {
                return false;
            }
        }
        return true;
    }

    private boolean checkAll(ImmutableMultimap<Column, Filter> filters, Entity entity) {
        for (Map.Entry<Column, Filter> filter : filters.entries()) {
            Column column = filter.getKey();
            boolean matches = checkSingleParam(filter.getValue(), entity, column);
            if (!matches) {
                return false;
            }
        }
        return true;
    }

    private boolean checkEither(ImmutableMultimap<Column, Filter> filters, Entity entity) {
        for (Map.Entry<Column, Filter> filter : filters.entries()) {
            Column column = filter.getKey();
            boolean matches = checkSingleParam(filter.getValue(), entity, column);
            if (matches) {
                return true;
            }
        }
        return filters.isEmpty();
    }

    private boolean checkSingleParam(Filter filter, Entity entity, Column column) {
        String columnName = column.name()
                                  .value();
        if (!entity.contains(columnName)) {
            return false;
        }
        Object actual = entity.getValue(columnName)
                              .get();
        Object expected = adapter.toValue(column, filter)
                                 .get();

        boolean result = eval(actual, filter.getOperator(), expected);
        return result;
    }
}


text:
package com.microsoft.azure.management.loganalytics.v2020_08_01;

import rx.Observable;
import com.microsoft.azure.management.loganalytics.v2020_08_01.implementation.WorkspacePurgesInner;
import com.microsoft.azure.arm.model.HasInner;

/**
 * Type representing WorkspacePurges.
 */
public interface WorkspacePurges extends HasInner<WorkspacePurgesInner> {
    /**
     * Gets status of an ongoing purge operation.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param purgeId In a purge status request, this is the Id of the operation the status of which is returned.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<WorkspacePurgeStatusResponse> getPurgeStatusAsync(String resourceGroupName, String workspaceName, String purgeId);

    /**
     * Purges data in an Log Analytics workspace by a set of user-defined filters.
    In order to manage system resources, purge requests are throttled at 50 requests per hour. You should batch the execution of purge requests by sending a single command whose predicate includes all user identities that require purging. Use the in operator to specify multiple identities. You should run the query prior to using for a purge request to verify that the results are expected.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param workspaceName The name of the workspace.
     * @param body Describes the body of a request to purge data in a single table of an Log Analytics Workspace
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    Observable<WorkspacePurgeResponse> purgeAsync(String resourceGroupName, String workspaceName, WorkspacePurgeBody body);

}


text:
#import "RCTDefines.h"

#if RCT_DEV

#import <dlfcn.h>

#import <mach/mach.h>

#import "RCTBridge.h"
#import "RCTDevMenu.h"
#import "RCTFPSGraph.h"
#import "RCTInvalidating.h"
#import "RCTJavaScriptExecutor.h"
#import "RCTRootView.h"
#import "RCTSparseArray.h"
#import "RCTUIManager.h"

static NSString *const RCTPerfMonitorKey = @"RCTPerfMonitorKey";

typedef BOOL (*RCTJSCSetOptionType)(const char *);

static BOOL RCTJSCSetOption(const char *option)
{
  static RCTJSCSetOptionType setOption;
  static dispatch_once_t onceToken;

  dispatch_once(&onceToken, ^{
    /**
     * JSC private C++ static method to toggle options at runtime
     *
     * JSC::Options::setOptions - JavaScriptCore/runtime/Options.h
     */
    setOption = dlsym(RTLD_DEFAULT, "_ZN3JSC7Options9setOptionEPKc");

    if (RCT_DEBUG && setOption == NULL) {
      RCTLogWarn(@"The symbol used to enable JSC runtime options is not available in this iOS version");
    }
  });

  if (setOption) {
    return setOption(option);
  } else {
    return NO;
  }
}

static vm_size_t RCTGetResidentMemorySize(void)
{
  struct task_basic_info info;
  mach_msg_type_number_t size = sizeof(info);
  kern_return_t kerr = task_info(mach_task_self(),
                                 TASK_BASIC_INFO,
                                 (task_info_t)&info,
                                 &size);
  if (kerr != KERN_SUCCESS) {
    return 0;
  }

  return info.resident_size;
}

@class RCTDevMenuItem;

@interface RCTPerfMonitor : NSObject <RCTBridgeModule, RCTInvalidating>

@property (nonatomic, strong, readonly) RCTDevMenuItem *devMenuItem;
@property (nonatomic, strong, readonly) UIPanGestureRecognizer *gestureRecognizer;
@property (nonatomic, strong, readonly) UIView *container;
@property (nonatomic, strong, readonly) UILabel *memory;
@property (nonatomic, strong, readonly) UILabel *heap;
@property (nonatomic, strong, readonly) UILabel *views;
@property (nonatomic, strong, readonly) RCTFPSGraph *jsGraph;
@property (nonatomic, strong, readonly) RCTFPSGraph *uiGraph;
@property (nonatomic, strong, readonly) UILabel *jsGraphLabel;
@property (nonatomic, strong, readonly) UILabel *uiGraphLabel;

@end

@implementation RCTPerfMonitor {
  RCTDevMenuItem *_devMenuItem;
  UIPanGestureRecognizer *_gestureRecognizer;
  UIView *_container;
  UILabel *_memory;
  UILabel *_heap;
  UILabel *_views;
  UILabel *_uiGraphLabel;
  UILabel *_jsGraphLabel;

  RCTFPSGraph *_uiGraph;
  RCTFPSGraph *_jsGraph;

  CADisplayLink *_uiDisplayLink;
  CADisplayLink *_jsDisplayLink;

  NSUInteger _heapSize;

  dispatch_queue_t _queue;
  dispatch_io_t _io;
  int _stderr;
  int _pipe[2];
  NSString *_remaining;
}

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE()

- (void)invalidate
{
  [self hide];
}

- (RCTDevMenuItem *)devMenuItem
{
  if (!_devMenuItem) {
    __weak __typeof__(self) weakSelf = self;
    _devMenuItem =
      [RCTDevMenuItem toggleItemWithKey:RCTPerfMonitorKey
                                  title:@"Show Perf Monitor"
                          selectedTitle:@"Hide Perf Monitor"
                                handler:
                                ^(BOOL selected) {
                                  if (selected) {
                                    [weakSelf show];
                                  } else {
                                    [weakSelf hide];
                                  }
                                }];
  }

  return _devMenuItem;
}

- (UIPanGestureRecognizer *)gestureRecognizer
{
  if (!_gestureRecognizer) {
    _gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                 action:@selector(gesture:)];
  }

  return _gestureRecognizer;
}

- (UIView *)container
{
  if (!_container) {
    _container = [[UIView alloc] initWithFrame:CGRectMake(10, 25, 180, 50)];
    _container.backgroundColor = UIColor.whiteColor;
    _container.layer.borderWidth = 2;
    _container.layer.borderColor = [UIColor grayColor].CGColor;
    [_container addGestureRecognizer:self.gestureRecognizer];
  }

  return _container;
}

- (UILabel *)memory
{
  if (!_memory) {
    _memory = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 44, 50)];
    _memory.font = [UIFont systemFontOfSize:12];
    _memory.numberOfLines = 3;
    _memory.textAlignment = NSTextAlignmentCenter;
  }

  return _memory;
}

- (UILabel *)heap
{
  if (!_heap) {
    _heap = [[UILabel alloc] initWithFrame:CGRectMake(44, 0, 44, 50)];
    _heap.font = [UIFont systemFontOfSize:12];
    _heap.numberOfLines = 3;
    _heap.textAlignment = NSTextAlignmentCenter;
  }

  return _heap;
}

- (UILabel *)views
{
  if (!_views) {
    _views = [[UILabel alloc] initWithFrame:CGRectMake(88, 0, 44, 50)];
    _views.font = [UIFont systemFontOfSize:12];
    _views.numberOfLines = 3;
    _views.textAlignment = NSTextAlignmentCenter;
  }

  return _views;
}

- (RCTFPSGraph *)uiGraph
{
  if (!_uiGraph) {
    _uiGraph = [[RCTFPSGraph alloc] initWithFrame:CGRectMake(134, 14, 40, 30)
                                            color:[UIColor lightGrayColor]];
  }
  return _uiGraph;
}

- (RCTFPSGraph *)jsGraph
{
  if (!_jsGraph) {
    _jsGraph = [[RCTFPSGraph alloc] initWithFrame:CGRectMake(178, 14, 40, 30)
                                            color:[UIColor lightGrayColor]];
  }
  return _jsGraph;
}

- (UILabel *)uiGraphLabel
{
  if (!_uiGraphLabel) {
    _uiGraphLabel = [[UILabel alloc] initWithFrame:CGRectMake(134, 3, 40, 10)];
    _uiGraphLabel.font = [UIFont systemFontOfSize:11];
    _uiGraphLabel.textAlignment = NSTextAlignmentCenter;
    _uiGraphLabel.text = @"UI";
  }

  return _uiGraphLabel;
}

- (UILabel *)jsGraphLabel
{
  if (!_jsGraphLabel) {
    _jsGraphLabel = [[UILabel alloc] initWithFrame:CGRectMake(178, 3, 38, 10)];
    _jsGraphLabel.font = [UIFont systemFontOfSize:11];
    _jsGraphLabel.textAlignment = NSTextAlignmentCenter;
    _jsGraphLabel.text = @"JS";
  }

  return _jsGraphLabel;
}

- (dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

- (void)setBridge:(RCTBridge *)bridge
{
  _bridge = bridge;

  [_bridge.devMenu addItem:self.devMenuItem];
}

- (void)show
{
  if (_container) {
    return;
  }

  [self.container addSubview:self.memory];
  [self.container addSubview:self.heap];
  [self.container addSubview:self.views];
  [self.container addSubview:self.uiGraph];
  [self.container addSubview:self.uiGraphLabel];

  [self redirectLogs];

  RCTJSCSetOption("logGC=1");

  [self updateStats];

  UIWindow *window = [UIApplication sharedApplication].delegate.window;
  [window addSubview:self.container];

  _uiDisplayLink = [CADisplayLink displayLinkWithTarget:self
                                               selector:@selector(threadUpdate:)];
  [_uiDisplayLink addToRunLoop:[NSRunLoop mainRunLoop]
                       forMode:NSRunLoopCommonModes];

  id<RCTJavaScriptExecutor> executor = [_bridge valueForKey:@"javaScriptExecutor"];
  if ([executor isKindOfClass:NSClassFromString(@"RCTContextExecutor")]) {
    self.container.frame = (CGRect) {
      self.container.frame.origin, {
        self.container.frame.size.width + 44,
        self.container.frame.size.height
      }
    };
    [self.container addSubview:self.jsGraph];
    [self.container addSubview:self.jsGraphLabel];
    [executor executeBlockOnJavaScriptQueue:^{
      _jsDisplayLink = [CADisplayLink displayLinkWithTarget:self
                                                   selector:@selector(threadUpdate:)];
      [_jsDisplayLink addToRunLoop:[NSRunLoop currentRunLoop]
                           forMode:NSRunLoopCommonModes];
    }];
  }
}

- (void)hide
{
  if (!_container) {
    return;
  }

  [self.container removeFromSuperview];
  _container = nil;
  _jsGraph = nil;
  _uiGraph = nil;

  RCTJSCSetOption("logGC=0");

  [self stopLogs];

  [_uiDisplayLink invalidate];
  [_jsDisplayLink invalidate];

  _uiDisplayLink = nil;
  _jsDisplayLink = nil;
}

- (void)redirectLogs
{
  _stderr = dup(STDERR_FILENO);

  if (pipe(_pipe) != 0) {
    return;
  }

  dup2(_pipe[1], STDERR_FILENO);
  close(_pipe[1]);

  __weak __typeof__(self) weakSelf = self;
  _queue = dispatch_queue_create("com.facebook.react.RCTPerfMonitor", DISPATCH_QUEUE_SERIAL);
  _io = dispatch_io_create(
    DISPATCH_IO_STREAM,
    _pipe[0],
    _queue,
    ^(__unused int error) {});

  dispatch_io_set_low_water(_io, 20);

  dispatch_io_read(
    _io,
    0,
    SIZE_MAX,
    _queue,
    ^(__unused bool done, dispatch_data_t data, __unused int error) {
      if (!data) {
        return;
    }

      dispatch_data_apply(
        data,
        ^bool(
          __unused dispatch_data_t region,
          __unused size_t offset,
          const void *buffer,
          size_t size
        ) {
          write(_stderr, buffer, size);

          NSString *log = [[NSString alloc] initWithBytes:buffer
                                                   length:size
                                                 encoding:NSUTF8StringEncoding];
          [weakSelf parse:log];
          return true;
        });
    });
}

- (void)stopLogs
{
  dup2(_stderr, STDERR_FILENO);
  dispatch_io_close(_io, 0);
}

- (void)parse:(NSString *)log
{
  static NSRegularExpression *GCRegex;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    NSString *pattern = @"\\[GC: (Eden|Full)Collection, (?:Skipped copying|Did copy), ([\\d\\.]+) (\\wb), ([\\d.]+) (\\ws)\\]";
    GCRegex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                        options:0
                                                          error:nil];
  });

  if (_remaining) {
    log = [_remaining stringByAppendingString:log];
    _remaining = nil;
  }

  NSArray *lines = [log componentsSeparatedByString:@"\n"];
  if (lines.count == 1) { // no newlines
    _remaining = log;
    return;
  }

  for (NSString *line in lines) {
    NSTextCheckingResult *match = [GCRegex firstMatchInString:line options:0 range:NSMakeRange(0, line.length)];
    if (match) {
      NSString *heapSizeStr = [line substringWithRange:[match rangeAtIndex:2]];
      _heapSize = [heapSizeStr integerValue];
    }
  }
}

- (void)updateStats
{
  RCTSparseArray *views = [_bridge.uiManager valueForKey:@"viewRegistry"];
  NSUInteger viewCount = views.count;
  NSUInteger visibleViewCount = 0;
  for (UIView *view in views.allObjects) {
    if (view.window || view.superview.window) {
      visibleViewCount++;
    }
  }

  double mem = (double)RCTGetResidentMemorySize() / 1024 / 1024;
  self.memory.text  =[NSString stringWithFormat:@"RAM\n%.2lf\nMB", mem];
  self.heap.text = [NSString stringWithFormat:@"JSC\n%.2lf\nMB", (double)_heapSize / 1024];
  self.views.text = [NSString stringWithFormat:@"Views\n%lu\n%lu", (unsigned long)visibleViewCount, (unsigned long)viewCount];

  __weak __typeof__(self) weakSelf = self;
  dispatch_after(
    dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)),
    dispatch_get_main_queue(),
    ^{
      __strong __typeof__(weakSelf) strongSelf = weakSelf;
      if (strongSelf && strongSelf->_container.superview) {
        [strongSelf updateStats];
      }
    });
}

- (void)gesture:(UIPanGestureRecognizer *)gestureRecognizer
{
  CGPoint translation = [gestureRecognizer translationInView:self.container.superview];
  self.container.center = CGPointMake(
    self.container.center.x + translation.x,
    self.container.center.y + translation.y
  );
  [gestureRecognizer setTranslation:CGPointMake(0, 0)
                             inView:self.container.superview];
}

- (void)threadUpdate:(CADisplayLink *)displayLink
{
  RCTFPSGraph *graph = displayLink == _jsDisplayLink ? _jsGraph : _uiGraph;
  [graph onTick:displayLink.timestamp];
}

@end

#endif


text:
<inline model='parameter.name' action='update'></inline>

<messages></messages>

      Typ
      <inline-select model='parameter.type' action='update' options="options"></inline-select>

      Hodnoty

        <form ng-show="updateCodebook">
          <fieldset class="well">

              {{$index + 1}}. <input type="text" ng-model="value.value" ui-event="{ keyup : 'check()' }">

          </fieldset>

<input value="Upravit" class="btn btn-primary" ng-click="updateCodebook=false;update()">

        </form>

{{value}}

Smazat


text:
namespace dom_distiller {

extern const char kEntryIdKey[];
extern const char kUrlKey[];
extern const char kCssPath[];

}  // namespace dom_distiller

#endif  // COMPONENTS_DOM_DISTILLER_CORE_URL_CONSTANTS_H_


text:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/include/autoprepend.php');
/*
	$Id: validerInscription.php,v 1.1 2013-09-30 09:42:18 raphael Exp $
	$Author: raphael $

	$Log: validerInscription.php,v $
	Revision 1.1  2013-09-30 09:42:18  raphael
	*** empty log message ***

	Revision 1.6  2013-03-01 10:28:18  pierre
	*** empty log message ***

	Revision 1.5  2012-07-31 14:24:50  pierre
	*** empty log message ***

	Revision 1.4  2009-02-16 16:24:18  pierre
	*** empty log message ***

	Revision 1.3  2009-02-16 15:33:37  pierre
	*** empty log message ***

	Revision 1.2  2009-02-16 15:28:05  pierre
	*** empty log message ***

	Revision 1.1  2009-02-16 14:56:09  pierre
	*** empty log message ***

	Revision 1.2  2008/03/04 14:54:19  pierre
	*** empty log message ***

	Revision 1.1  2006/04/12 07:25:22  sylvie
	*** empty log message ***

	Revision 1.1  2004/06/01 14:25:19  ddinside
	ajout petites annonce dont gardes finies
	newslettrer

	Revision 1.1  2004/05/18 13:47:12  ddinside
	creation module petites annonces

*/
include_once($_SERVER['DOCUMENT_ROOT'].'/include/cms-inc/PetitesAnnonces/include_pa.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/include/cms-inc/mail_lib.php');

activateMenu('gestionPA');  //permet de dérouler le menu contextuellement

if (!( (strlen($_GET['id'])>0) && ($_GET['id']>0) )) {
	die("Appel incorrect à la fonctionnalité.");
}

$status = ' ';
$inscrit = new Inscript($_GET['id']);

if(!strlen($_GET['action'])>0)
	$_GET['action'] = 'valider';
if($_GET['action']=='valider') {
	if($inscrit->validate()) $status = "Validation enregistrée.";
} elseif($_GET['action']=='invalider') {
	if($inscrit->unvalidate()) $status = "Inscrit invalidé.";
} elseif($_GET['action']=='supprimer') {
	if($inscrit->delete()) $status = "Inscrit supprimé.";
}
if($_GET['action']!='supprimer') {
?>

Petites annonces - Liste des inscrits - validation

<?php echo $status; ?>

   Date d'inscription
   Validé
   Email
   Nom
   Prénom
   Tel
   Adresse
   Code Postal
   Ville

   <?php echo from_dbdate_TIMESTAMP_WITH_TIME_ZONE($inscrit->dateInscription); ?>
   <?php echo ($inscrit->valide) ? "oui" : "non" ; ?>
   <?php echo $inscrit->mail; ?>
   <?php echo $inscrit->nom; ?>
   <?php echo $inscrit->prenom; ?>
   <?php echo $inscrit->telephone; ?>
   <?php echo $inscrit->adresse; ?>
   <?php echo $inscrit->codePostal; ?>
   <?php echo $inscrit->ville; ?>

<?php
} else {
?>

<?php echo $status; ?>

<?php
}
?>

Retour à la liste des inscrits


text:
namespace SDKTemplate
{
    /// <summary>
    /// Display animation metrics.
    /// </summary>
    [Windows::Foundation::Metadata::WebHostHidden]
    public ref class Scenario5_Clear sealed
    {
    public:
        Scenario5_Clear();
    private:
        MainPage^ rootPage;
        void PickPlaylistButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
    };
}


text:
import testtools as tt

from openstack_env import main

class TestOpenstackEnv(tt.TestCase):
    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main()


text:
{-# LANGUAGE RecordWildCards #-}
module GHCJS.DOM.JSFFI.SQLError (
    module Generated
  , SQLErrorCode(..)
  , SQLException(..)
  , throwSQLException
) where

import Control.Exception (Exception, throwIO)
import Control.Monad.IO.Class (MonadIO(..))

import GHCJS.DOM.JSFFI.Generated.SQLError as Generated

data SQLErrorCode = SQLErrorUnknown
                  | SQLErrorDatabase
                  | SQLErrorVersion
                  | SQLErrorTooLarge
                  | SQLErrorQuota
                  | SQLErrorSyntax
                  | SQLErrorConstraint
                  | SQLErrorTimeout
                  deriving (Show, Eq, Enum)
data SQLException = SQLException { sqlErrorCode :: SQLErrorCode, sqlErrorMessage :: String } deriving (Show, Eq)

instance Exception SQLException

throwSQLException :: MonadIO m => SQLError -> m a
throwSQLException error = do
    sqlErrorCode <- (toEnum . subtract 1 . fromIntegral) <$> getCode error
    sqlErrorMessage <- getMessage error
    liftIO $ throwIO (SQLException{..})


text:
var util     =   require('util');
var spawn    =   require('child_process').spawn;
var child    =   spawn('python',['-u','-i']);
var cmdQueue =   new Array();

child.stdout.on('data', handleStdout);
child.stderr.on('data', handleStderr);
child.on('exit', handleExit);

function handleStdout(data) {
  var datastr = data.toString('utf8');
  var finished = false;
  if (datastr.match(/Command Start\n/)) {
    datastr = datastr.replace(/Command Start\n/,'');
  }
  if (datastr.match(/Command End\n/)) {
    datastr = datastr.replace(/Command End\n/,'');
    finished = true;
  }
  if (cmdQueue.length > 0) {
    cmdQueue[0].data+=datastr;
  }
  if (finished) {
    cmd = cmdQueue.shift();
    if (cmd && cmd.command) {
      if (undefined != typeof cmd.callback) {
        cmd.callback(null, cmd.data);
        processQueue();
      }
    }
  }
};

function handleStderr(data) {
  processQueue();
};

function processQueue() {
  if (cmdQueue.length > 0 && cmdQueue[0].state === 'pending') {
    cmdQueue[0].state = 'processing';
    child.stdin.write(cmdQueue[0].command, encoding='utf8');
  }
};

function handleExit(code) {
  console.log('child process exited with code ' + code);
  process.exit();
};

this.shell = function (command, callback) {
  command = 'print "Command Start"; ' + command + '\nprint "Command End"';
  if (command.charAt[command.length-1]!='\n') command += '\n';
  cmdQueue.push({'command':command, 'callback':callback, 'data': '', state: 'pending'});
  processQueue();
};


text:
#ifndef __CCDATA_H__
#define __CCDATA_H__

#include "platform/CCPlatformMacros.h"
#include "CCObject.h"

NS_CC_BEGIN

class CC_DLL Data : public Object
{
public:
    Data(unsigned char *pBytes, const unsigned long nSize);
    Data(Data *pData);
    ~Data();

    static Data* create(unsigned char *pBytes, const unsigned long nSize)
    {
        Data* pRet = new Data(pBytes, nSize);
        if (pRet)
        {
            pRet->autorelease();
        }
        return pRet;
    }

    unsigned char* getBytes() const;
    unsigned long getSize() const;

    /* override functions */
    virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); }

private:
    unsigned char* _bytes;
    unsigned long _size;
};

NS_CC_END

#endif // __CCDATA_H__


text:
#import "EBConditionLock.h"
#import <pthread.h>
#import <sys/time.h>
#import <EBFoundation/EBFoundation.h>

#define EBExactlyOneBitSet(x) ((x) > 0 && ((x) & ((x) - 1)) == 0)
#define EBAtLeastOneBitSet(x) ((x) != 0)

@implementation EBConditionLock
{
    pthread_mutex_t _pthreadMutex;
    pthread_cond_t _pthreadCondition;
}

#pragma mark - Creation -
- (id)initWithCondition: (uint64_t)condition
{
        NSParameterAssert(EBExactlyOneBitSet(condition));

    if (!(self = [super init]))
        return nil;

    _condition = condition;

    int pthreadResult = pthread_mutex_init(&_pthreadMutex, nil);
        EBAssertOrRecover(!pthreadResult, return nil);

    pthreadResult = pthread_cond_init(&_pthreadCondition, nil);
        EBAssertOrRecover(!pthreadResult, return nil);

    return self;
}

- (id)init
{
    EBRaise(@"%@ cannot be initialized via %@!", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    return nil;
}

- (void)dealloc
{
    int pthreadResult = 0;

    pthreadResult = pthread_cond_destroy(&_pthreadCondition);
        EBAssertOrRecover(!pthreadResult, EBNoOp);

    pthreadResult = pthread_mutex_destroy(&_pthreadMutex);
        EBAssertOrRecover(!pthreadResult, EBNoOp);
}

#pragma mark - Methods -
- (void)lock
{
    [self lockOnConditions: UINT64_MAX];
}

- (void)unlock
{
    [self unlockWithCondition: _condition];
}

- (void)lockOnConditions: (uint64_t)conditions
{
        NSParameterAssert(EBAtLeastOneBitSet(conditions));

    /* Lock the mutex */
    int pthreadResult = pthread_mutex_lock(&_pthreadMutex);
        EBAssertOrBail(!pthreadResult);

    while (!(_condition & conditions))
    {
        pthreadResult = pthread_cond_wait(&_pthreadCondition, &_pthreadMutex);
            EBAssertOrBail(!pthreadResult);
    }
}

- (void)unlockWithCondition: (uint64_t)condition
{
        NSParameterAssert(EBExactlyOneBitSet(condition));

    _condition = condition;

    /* Relinquish the lock */
    int pthreadResult = pthread_mutex_unlock(&_pthreadMutex);
        EBAssertOrBail(!pthreadResult);

    /* Let other threads know that the condition changed! */
    pthreadResult = pthread_cond_broadcast(&_pthreadCondition);
        EBAssertOrBail(!pthreadResult);
}

@end


text:
<?php

namespace Sylius\Bundle\CoreBundle\Form\Type\Checkout;

use Doctrine\Common\Collections\ArrayCollection;
use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * Checkout payment step form type.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class PaymentStepType extends AbstractResourceType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $notBlank = new NotBlank();
        $notBlank->message = 'sylius.checkout.payment_method.not_blank';

        $builder
            ->add('paymentMethod', 'sylius_payment_method_choice', array(
                'label'          => 'sylius.form.checkout.payment_method',
                'expanded'       => true,
                'property_path'  => 'lastPayment.method',
                'order_items' => $options['order_items'],
                'constraints'    => array(
                    $notBlank
                )
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        parent::setDefaultOptions($resolver);
        $resolver->setDefaults(array(
            'order_items' => new ArrayCollection(),
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sylius_checkout_payment';
    }
}


text:
package wrangler

import (
	"fmt"

	"github.com/youtube/vitess/go/vt/key"
	"github.com/youtube/vitess/go/vt/tabletmanager/actionnode"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topo/topoproto"
	"github.com/youtube/vitess/go/vt/topotools"
	"golang.org/x/net/context"

	querypb "github.com/youtube/vitess/go/vt/proto/query"
	topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)

// Tablet related methods for wrangler

// InitTablet creates or updates a tablet. If no parent is specified
// in the tablet, and the tablet has a slave type, we will find the
// appropriate parent. If createShardAndKeyspace is true and the
// parent keyspace or shard don't exist, they will be created.  If
// allowUpdate is true, and a tablet with the same ID exists, just update it.
// If a tablet already exists, and has a different keyspace / shard,
// allowDifferentShard must be set to accept the update.
// If a tablet is created as master, and there is already a different
// master in the shard, allowMasterOverride must be set.
func (wr *Wrangler) InitTablet(ctx context.Context, tablet *topodatapb.Tablet, allowMasterOverride, allowDifferentShard, createShardAndKeyspace, allowUpdate bool) error {
	if err := topo.TabletComplete(tablet); err != nil {
		return err
	}

	// get the shard, possibly creating it
	var err error
	var si *topo.ShardInfo

	if createShardAndKeyspace {
		// create the parent keyspace and shard if needed
		si, err = topotools.GetOrCreateShard(ctx, wr.ts, tablet.Keyspace, tablet.Shard)
	} else {
		si, err = wr.ts.GetShard(ctx, tablet.Keyspace, tablet.Shard)
		if err == topo.ErrNoNode {
			return fmt.Errorf("missing parent shard, use -parent option to create it, or CreateKeyspace / CreateShard")
		}
	}

	// get the shard, checks a couple things
	if err != nil {
		return fmt.Errorf("cannot get (or create) shard %v/%v: %v", tablet.Keyspace, tablet.Shard, err)
	}
	if !key.KeyRangeEqual(si.KeyRange, tablet.KeyRange) {
		return fmt.Errorf("shard %v/%v has a different KeyRange: %v != %v", tablet.Keyspace, tablet.Shard, si.KeyRange, tablet.KeyRange)
	}
	if tablet.Type == topodatapb.TabletType_MASTER && si.HasMaster() && !topoproto.TabletAliasEqual(si.MasterAlias, tablet.Alias) && !allowMasterOverride {
		return fmt.Errorf("creating this tablet would override old master %v in shard %v/%v, use allow_master_override flag", topoproto.TabletAliasString(si.MasterAlias), tablet.Keyspace, tablet.Shard)
	}

	// update the shard record if needed
	if err := wr.updateShardCellsAndMaster(ctx, si, tablet.Alias, tablet.Type, allowMasterOverride); err != nil {
		return err
	}

	err = wr.ts.CreateTablet(ctx, tablet)
	if err == topo.ErrNodeExists && allowUpdate {
		// Try to update then
		oldTablet, err := wr.ts.GetTablet(ctx, tablet.Alias)
		if err != nil {
			return fmt.Errorf("failed reading existing tablet %v: %v", topoproto.TabletAliasString(tablet.Alias), err)
		}

		// Check we have the same keyspace / shard, and if not,
		// require the allowDifferentShard flag.
		if (oldTablet.Keyspace != tablet.Keyspace || oldTablet.Shard != tablet.Shard) && !allowDifferentShard {
			return fmt.Errorf("old tablet has shard %v/%v, cannot override with shard %v/%v unless allow_different_shard is set", oldTablet.Keyspace, oldTablet.Shard, tablet.Keyspace, tablet.Shard)
		}

		*(oldTablet.Tablet) = *tablet
		if err := wr.ts.UpdateTablet(ctx, oldTablet); err != nil {
			return fmt.Errorf("failed updating tablet %v: %v", topoproto.TabletAliasString(tablet.Alias), err)
		}
	}

	// now update the replication data
	if err := topo.UpdateTabletReplicationData(ctx, wr.ts, tablet); err != nil {
		return fmt.Errorf("failed updating tablet replication data for %v: %v", topoproto.TabletAliasString(tablet.Alias), err)
	}
	return nil
}

// DeleteTablet removes a tablet from a shard.
// - if allowMaster is set, we can Delete a master tablet (and clear
// its record from the Shard record if it was the master).
// - if skipRebuild is set, we do not rebuild the serving graph.
func (wr *Wrangler) DeleteTablet(ctx context.Context, tabletAlias *topodatapb.TabletAlias, allowMaster, skipRebuild bool) error {
	// load the tablet, see if we'll need to rebuild
	ti, err := wr.ts.GetTablet(ctx, tabletAlias)
	if err != nil {
		return err
	}
	rebuildRequired := ti.IsInServingGraph()
	wasMaster := ti.Type == topodatapb.TabletType_MASTER
	if wasMaster && !allowMaster {
		return fmt.Errorf("cannot delete tablet %v as it is a master, use allow_master flag", topoproto.TabletAliasString(tabletAlias))
	}

	// remove the record and its replication graph entry
	if err := topotools.DeleteTablet(ctx, wr.ts, ti.Tablet); err != nil {
		return err
	}

	// update the Shard object if the master was scrapped
	if wasMaster {
		actionNode := actionnode.UpdateShard()
		lockPath, err := wr.lockShard(ctx, ti.Keyspace, ti.Shard, actionNode)
		if err != nil {
			return err
		}

		// read the shard with the lock
		si, err := wr.ts.GetShard(ctx, ti.Keyspace, ti.Shard)
		if err != nil {
			return wr.unlockShard(ctx, ti.Keyspace, ti.Shard, actionNode, lockPath, err)
		}

		// update it if the right alias is there
		if topoproto.TabletAliasEqual(si.MasterAlias, tabletAlias) {
			si.MasterAlias = nil

			// write it back
			if err := wr.ts.UpdateShard(ctx, si); err != nil {
				return wr.unlockShard(ctx, ti.Keyspace, ti.Shard, actionNode, lockPath, err)
			}
		} else {
			wr.Logger().Warningf("Deleting master %v from shard %v/%v but master in Shard object was %v", topoproto.TabletAliasString(tabletAlias), ti.Keyspace, ti.Shard, si.MasterAlias)
		}

		// and unlock
		if err := wr.unlockShard(ctx, ti.Keyspace, ti.Shard, actionNode, lockPath, err); err != nil {
			return err
		}
	}

	// and rebuild the original shard if needed
	if !rebuildRequired {
		wr.Logger().Infof("Rebuild not required")
		return nil
	}
	if skipRebuild {
		wr.Logger().Warningf("Rebuild required, but skipping it")
		return nil
	}
	_, err = wr.RebuildShardGraph(ctx, ti.Keyspace, ti.Shard, []string{ti.Alias.Cell})
	return err
}

// ChangeSlaveType changes the type of tablet and recomputes all
// necessary derived paths in the serving graph, if necessary.
//
// Note we don't update the master record in the Shard here, as we
// can't ChangeType from and out of master anyway.
func (wr *Wrangler) ChangeSlaveType(ctx context.Context, tabletAlias *topodatapb.TabletAlias, tabletType topodatapb.TabletType) error {
	// Load tablet to find endpoint, and keyspace and shard assignment.
	ti, err := wr.ts.GetTablet(ctx, tabletAlias)
	if err != nil {
		return err
	}

	// ask the tablet to make the change
	if err := wr.tmc.ChangeType(ctx, ti, tabletType); err != nil {
		return err
	}

	// if the tablet was or is serving, rebuild the serving graph
	if ti.IsInServingGraph() || topo.IsInServingGraph(tabletType) {
		if _, err := wr.RebuildShardGraph(ctx, ti.Tablet.Keyspace, ti.Tablet.Shard, []string{ti.Tablet.Alias.Cell}); err != nil {
			return err
		}
	}

	return nil
}

// same as ChangeType, but assume we already have the shard lock,
// and do not have the option to force anything.
func (wr *Wrangler) changeTypeInternal(ctx context.Context, tabletAlias *topodatapb.TabletAlias, dbType topodatapb.TabletType) error {
	ti, err := wr.ts.GetTablet(ctx, tabletAlias)
	if err != nil {
		return err
	}
	rebuildRequired := ti.IsInServingGraph()

	// change the type
	if err := wr.tmc.ChangeType(ctx, ti, dbType); err != nil {
		return err
	}

	// rebuild if necessary
	if rebuildRequired {
		_, err = wr.RebuildShardGraph(ctx, ti.Keyspace, ti.Shard, []string{ti.Alias.Cell})
		if err != nil {
			return err
		}
	}
	return nil
}

// ExecuteFetchAsDba executes a query remotely using the DBA pool
func (wr *Wrangler) ExecuteFetchAsDba(ctx context.Context, tabletAlias *topodatapb.TabletAlias, query string, maxRows int, wantFields, disableBinlogs bool, reloadSchema bool) (*querypb.QueryResult, error) {
	ti, err := wr.ts.GetTablet(ctx, tabletAlias)
	if err != nil {
		return nil, err
	}
	return wr.tmc.ExecuteFetchAsDba(ctx, ti, query, maxRows, wantFields, disableBinlogs, reloadSchema)
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
    public class OperatorKeywordRecommenderTests : KeywordRecommenderTests
    {
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAtRoot_Interactive()
        {
            await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterClass_Interactive()
        {
            await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterGlobalStatement_Interactive()
        {
            await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
        {
            await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotInUsingAlias()
        {
            await VerifyAbsenceAsync(
@"using Foo = $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotInEmptyStatement()
        {
            await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterImplicit()
        {
            await VerifyKeywordAsync(
@"class Foo {
    public static implicit $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterExplicit()
        {
            await VerifyKeywordAsync(
@"class Foo {
    public static explicit $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotAfterType()
        {
            await VerifyAbsenceAsync(
@"class Foo {
    int $$");
        }

        [WorkItem(542271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542271")]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterPublicStaticType()
        {
            await VerifyAbsenceAsync(
@"class Foo {
    public static int $$");
        }

        [WorkItem(542271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542271")]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterPublicStaticExternType()
        {
            await VerifyAbsenceAsync(
@"class Foo {
    public static extern int $$");
        }

        [WorkItem(542271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542271")]
        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestAfterGenericType()
        {
            await VerifyAbsenceAsync(
@"class Foo {
    public static IList<int> $$");
        }

        [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
        public async Task TestNotInInterface()
        {
            await VerifyAbsenceAsync(
@"interface Foo {
    public static int $$");
        }
    }
}


text:
<?php

namespace Lthrt\CCSBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CityType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(
        FormBuilderInterface $builder,
        array                $options
    ) {
        $builder
            ->add('active')
            ->add('name')
            ->add('county')
            ->add('state')
            ->add('zip');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Lthrt\CCSBundle\Entity\City',
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'lthrt_CCSBundle_city';
    }
}


text:
package org.apache.airavata.workflow.tracking;

import java.net.URI;

import org.apache.airavata.workflow.tracking.common.InvocationContext;
import org.apache.airavata.workflow.tracking.common.InvocationEntity;
import org.apache.airavata.workflow.tracking.common.WorkflowTrackingContext;
import org.apache.xmlbeans.XmlObject;

/**
 * Utility to create and send Lead provenance related notification messages. this tracks files used, produced, and
 * transfered by this application, application begin and end.
 *
 * <pre>
 *          appStarted(A1)
 *          fileConsumed(F1)
 *          fileProduced(F2)
 *          appFinishedSuccess(A1, F2) | appFinishedFailed(A1, ERR)
 *          flush()
 * </pre>
 */

public interface ServiceNotifier extends GenericNotifier {

    /**
     * send a message indicating the service has been instantiated and will accept messages henceforth.
     *
     * @param serviceID
     *            an URI that identifies the service instance
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void serviceInitialized(WorkflowTrackingContext context, URI serviceID, String... descriptionAndAnnotation);

    /**
     * send a message indicating the service instance has terminated and will not accept or generate any future
     * messages.
     *
     * @param serviceID
     *            an URI that identifies the service instance
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void serviceTerminated(WorkflowTrackingContext context, URI serviceID, String... descriptionAndAnnotation);

    /**
     * Method serviceInvoked. This service instance has received a message from the initiator to start executing.
     *
     * @param receiver
     *            identity of this service invocation
     * @param initiator
     *            identity of entity that invoked this service
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     * @return an InvocationContext that encapsulates this invocation. This object should be passed to any notification
     *         that is generated as part of this invocation.
     *
     */
    public InvocationContext serviceInvoked(WorkflowTrackingContext context, InvocationEntity receiver,
            String... descriptionAndAnnotation);

    /**
     * Method serviceInvoked. This service instance has received a message from the initiator to start executing.
     *
     * @param receiver
     *            identity of this service invocation
     * @param initiator
     *            identity of entity that invoked this service
     * @param header
     *            the context for this invocation (soap:header)
     * @param body
     *            the message received that has the actions and inputs (soap:body)
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     * @return an InvocationContext that encapsulates this invocation. This object should be passed to any notification
     *         that is generated as part of this invocation.
     *
     */
    public InvocationContext serviceInvoked(WorkflowTrackingContext wtcontext, InvocationEntity initiator,
            XmlObject header, XmlObject body, String... descriptionAndAnnotation);

    /**
     * Method sendingResult. Return the result of the invocation back to the initiator of the invocation. This happens
     * when a request-response pattern is followed.
     *
     * @param context
     *            the context for this invocation as returned by serviceInvoked
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void sendingResult(WorkflowTrackingContext wtcontext, InvocationContext context,
            String... descriptionAndAnnotation);

    /**
     * Method sendingResult. Return the result of the invocation back to the initiator of the invocation. This happens
     * when a request-response pattern is followed.
     *
     * @param context
     *            the context for this invocation as returned by serviceInvoked
     * @param header
     *            the context for the response to the invocation (soap:header)
     * @param body
     *            the message that is sent as output of the invocation (soap:body)
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void sendingResult(WorkflowTrackingContext wtcontext, InvocationContext context, XmlObject header,
            XmlObject body, String... descriptionAndAnnotation);

    /**
     * Method sendingFault. Return a fault as the response to the invocation, sent back to the initiator of the
     * invocation. This happens when a request-response pattern is followed.
     *
     * @param context
     *            the context for this invocation as returned by serviceInvoked
     * @param error
     *            human readable description of the failure to be sent with the message
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     *
     */
    public void sendingFault(WorkflowTrackingContext wtcontext, InvocationContext context,
            String... descriptionAndAnnotation);

    /**
     * Method sendingFault. Return a fault as the response to the invocation, sent back to the initiator of the
     * invocation. This happens when a request-response pattern is followed.
     *
     * @param context
     *            the context for this invocation as returned by serviceInvoked
     * @param header
     *            the context for the response to the invocation (soap:header)
     * @param fault
     *            the fault that is sent as output of the invocation (soap:fault)
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void sendingFault(WorkflowTrackingContext wtcontext, InvocationContext context, XmlObject header,
            XmlObject faultBody, String... descriptionAndAnnotation);

    /**
     * send sendingResponseSucceeded message. Acknowledges that the response to this invocation was successfully sent to
     * the initator of the invocation.
     *
     * @param context
     *            the context for this invocation as returned by serviceInvoked
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void sendingResponseSucceeded(WorkflowTrackingContext wtcontext, InvocationContext context,
            String... descriptionAndAnnotation);

    /**
     * send sendingResponseSucceeded message. Acknowledges that the response to this invocation could not be sent to the
     * initator of the invocation. Can be a local failure or a remote failure.
     *
     * @param context
     *            the context for this invocation as returned by serviceInvoked
     * @param error
     *            human readable description of the failure to be sent with the message
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void sendingResponseFailed(WorkflowTrackingContext wtcontext, InvocationContext context,
            String... descriptionAndAnnotation);

    /**
     * send sendingResponseSucceeded message. Acknowledges that the response to this invocation could not be sent to the
     * initator of the invocation. Can be a local failure or a remote failure.
     *
     * @param context
     *            the context for this invocation as returned by serviceInvoked
     * @param trace
     *            a throwable that has the trace for the error
     * @param descriptionAndAnnotation
     *            optional vararg. The first element is used as the human readable description for this notification.
     *            The subsequent strings need to be serialized XML fragments that are added as annotation to the
     *            notification.
     *
     */
    public void sendingResponseFailed(WorkflowTrackingContext wtcontext, InvocationContext context, Throwable trace,
            String... descriptionAndAnnotation);

}


text:
USING_DGR2;

extern Logger* g_local_logger;

__BCONF_BEGIN__
extern ULONG g_lock_num;
extern ULONG g_configurator_num;

HRESULT BlackConfiguratorFactory::QueryInterface(const IID& iid, void **ppv){
    if (iid == IID_IUnknown){
        *ppv = (IUnknown *) this;
        ((IUnknown *)(*ppv))->AddRef();
    } else if (iid == IID_IClassFactory){
        *ppv = (IClassFactory *) this;
        ((IClassFactory *)(*ppv))->AddRef();
    } else {
        *ppv = NULL;
        return E_NOINTERFACE;
    }
    return S_OK;
}

BlackConfiguratorFactory::BlackConfiguratorFactory()
    :ref_num_(0){
    SXLOG_INF(g_local_logger) << _X("New BlackConfiguratorFactory Object Created!") << LBT << END;
}

BlackConfiguratorFactory::~BlackConfiguratorFactory(){
    SXLOG_INF(g_local_logger) << _X("BlackConfiguratorFactory Object Destroy!") << LBT << END;
}

HRESULT BlackConfiguratorFactory::LockServer(BOOL block){
    block ? g_lock_num++ : g_lock_num--;
    return NOERROR;
}

HRESULT BlackConfiguratorFactory::CreateInstance(IUnknown* pUnknownOuter, const IID& iid, void **ppv){
    *ppv = NULL;
    HRESULT hr = E_OUTOFMEMORY;
    if (NULL != pUnknownOuter)
        return CLASS_E_NOAGGREGATION;
    BlackConfigurator * new_configurator = new BlackConfigurator();
    if (NULL == new_configurator)
        return hr;
    hr = new_configurator->QueryInterface(iid, ppv);
    if (hr != S_OK) {
        g_configurator_num--; // Reference count g_cDictionary be added in constructor
        delete new_configurator;
    }
    return hr;
}

ULONG BlackConfiguratorFactory::Release(){
    ref_num_--;
    if (ref_num_ == 0) {
        delete this;
        return 0;
    }
    return  ref_num_;
}

ULONG BlackConfiguratorFactory::AddRef(){
    return  ++ref_num_;
}
__BCONF_END__


text:
package avs.models;

import avs.utils.Animator;
import avs.utils.Textures;

import java.util.ArrayList;
import java.awt.image.*;
import java.awt.*;

import javax.swing.*;

public class Kopiko extends Plant implements Runnable{
	private Energy e;

    public Kopiko(Textures texx) {
		super(41, 102, 50, texx);
        this.animation = texx.getKopikoStaticArray();
		this.anim = new Animator(5, animation);
	}

	public void tick(){
        this.anim.setImages(animation);
		this.anim.runAnimation();
	}

	public void run(){
		try{
            while (this.isAlive()) {
                Thread.sleep(10*1000);
                animation = texx.getKopikoEmittingArray();
                Thread.sleep(500);
                Game.getInstance().createEnergy(this);
                animation = texx.getKopikoStaticArray();
            }
		}catch(InterruptedException e){
			return;
		}
	}

	public void render (Graphics g){
		this.anim.drawAnimation(g,getX(),getY(),width,height,0);
	}

	public int getHeight(){
		return this.height;
	}
}


text:
'use strict';

const { Suite } = require('./helpers');
const { getHashCodeFrom } = require('../dist/src');

const run = async () => {
    const str6 = Array.from({ length: 6 }, () => 'a').join('');
    const str26 = Array.from({ length: 26 }, () => 'a').join('');
    const str36 = Array.from({ length: 36 }, () => 'a').join('');
    const singleObj = { a: 1 };
    const multiObj = {
        a: 1,
        b: 2,
        c: 3,
        d: 4,
        e: 5,
        f: 6,
        g: 7
    };
    const arrSingleObj = [singleObj];
    const arrMultiObj = [multiObj];

    const multiArrSingleObj = Array.from({ length: 5 }, () => singleObj);
    const multiArrMultiObj = Array.from({ length: 5 }, () => multiObj);

    return Suite('getHashCodeFrom')
        .add('with a 6 character string', {
            fn() {
                getHashCodeFrom(str6);
            }
        })
        .add('with a 26 character string', {
            fn() {
                getHashCodeFrom(str26);
            }
        })
        .add('with a 36 character string', {
            fn() {
                getHashCodeFrom(str36);
            }
        })
        .add('with a single property object', {
            fn() {
                getHashCodeFrom(singleObj);
            }
        })
        .add('with a multiple property object', {
            fn() {
                getHashCodeFrom(multiObj);
            }
        })
        .add('with an array with a single property object', {
            fn() {
                getHashCodeFrom(arrSingleObj);
            }
        })
        .add('with an array with a multiple property object', {
            fn() {
                getHashCodeFrom(arrMultiObj);
            }
        })
        .add('with a multi-item array with a single prop obj', {
            fn() {
                getHashCodeFrom(multiArrSingleObj);
            }
        })
        .add('with a multi-item array with a multi-prop obj', {
            fn() {
                getHashCodeFrom(multiArrMultiObj);
            }
        })
        .run({
            async: true,
            initCount: 2,
            maxTime: 20,
        });
};

if (require.main === module) {
    run().then((suite) => {
        suite.on('complete', () => {});
    });
} else {
    module.exports = run;
}


text:
package com.kulinr.android.ui;

import android.os.Bundle;

/**
 * Created by bobbyadiprabowo on 01/02/14.
 */
public class TasteChooseActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
}


text:
"use strict";

tsApp.controller('EntryListCtrl', function ($scope, EntryDataService) {

    $scope.allEntriesView = true;

    $scope.entries = EntryDataService.getAllEntries();

    // $scope.getBookOrder = function(book) {
    //     return book.title;
    // };
    //
    // EntryDataService.getAllEntries().then(function(res) {
    //     $scope.entries = res.data;
    // }, function(error) {
    //     console.log('An error occurred!', error);
    // });
});


text:
CrystalBanker [![Build Status](https://travis-ci.org/CrystalCraftMC/CrystalKills.svg)](https://travis-ci.org/CrystalCraftMC/CrystalKills)
=============

This Spigot plugin will convert Minecraft XP orbs into bottles and bottles into XP orbs for your players!


text:
$NetBSD: patch-lib_rubygems_dependency__installer.rb,v 1.3 2014/02/19 15:52:05 taca Exp $

* Add install_root option for pkgsrc's rubygems support.

--- lib/rubygems/dependency_installer.rb.orig	2013-11-13 02:59:08.000000000 +0000
+++ lib/rubygems/dependency_installer.rb
@@ -50,6 +50,7 @@ class Gem::DependencyInstaller
   # :format_executable:: See Gem::Installer#initialize.
   # :ignore_dependencies:: Don't install any dependencies.
   # :install_dir:: See Gem::Installer#install.
+  # :install_root:: See Gem::Installer#install.
   # :prerelease:: Allow prerelease versions.  See #install.
   # :security_policy:: See Gem::Installer::new and Gem::Security.
   # :user_install:: See Gem::Installer.new
@@ -57,12 +58,14 @@ class Gem::DependencyInstaller
   # :build_args:: See Gem::Installer::new

   def initialize(options = {})
-    @install_dir = options[:install_dir] || Gem.dir
-
     if options[:install_dir] then
+      @install_dir = options[:install_dir]
+
       # HACK shouldn't change the global settings, needed for -i behavior
       # maybe move to the install command?  See also github #442
       Gem::Specification.dirs = @install_dir
+    else
+      @install_dir = Gem.dir
     end

     options = DEFAULT_OPTIONS.merge options
@@ -91,7 +94,12 @@ class Gem::DependencyInstaller
     @installed_gems = []
     @toplevel_specs = nil

-    @cache_dir = options[:cache_dir] || @install_dir
+    @install_root = options[:install_root] || ""
+    install_dir = @install_dir
+    unless @install_root.nil? or @install_root.empty?
+      install_dir = File.join(@install_root, install_dir)
+    end
+    @cache_dir = options[:cache_dir] || install_dir

     # Set with any errors that SpecFetcher finds while search through
     # gemspecs for a dep
@@ -371,6 +379,7 @@ class Gem::DependencyInstaller
                                 :format_executable   => @format_executable,
                                 :ignore_dependencies => @ignore_dependencies,
                                 :install_dir         => @install_dir,
+                                :install_root        => @install_root,
                                 :security_policy     => @security_policy,
                                 :user_install        => @user_install,
                                 :wrappers            => @wrappers,


text:
package effectivejava.chapter7;

//import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.stream.Stream;

import org.junit.Test;

public class Item45Tests {
	private static final BigInteger TWO = BigInteger.valueOf(2);
	/**
	 * Finds first x mersenne primes. Mersenne primes are of the form (2^p - 1) where p is a prime.
	 */
	@Test
	public void findMersennePrimes() {
		Stream.iterate(TWO, BigInteger::nextProbablePrime)
			.map(prime -> TWO.pow(prime.intValueExact()).subtract(BigInteger.ONE))
			.filter(maybePrime -> maybePrime.isProbablePrime(50))
			.limit(15)
			.forEach(System.out::println);
	}
}


text:
'use strict';

/*
 * Defining the Package
 */
var Module = require('meanio').Module;
var Comments = new Module('comments');

/*
 * All MEAN packages require registration
 * Dependency injection is used to define required modules
 */
Comments.register(function(app, auth, database, socket) {
  var io = socket.io; // note this is the socket object set in mean-socket and not the generic socket.io
  io.sockets.on('connection', function(socket) {
    socket.on('commentCreated', function(comment) {
      socket.broadcast.emit('commentCreated', {
        comment: comment
      });
    });

    socket.on('commentDeleted', function(comment) {
      socket.broadcast.emit('commentDeleted', {
        comment: comment
      });
    });

    socket.on('commentUpdated', function(comment) {
      socket.broadcast.emit('commentUpdated', {
        comment: comment
      });
    });
  });
  Comments.routes(app, auth, database);

  // //We are adding a link to the main menu for all authenticated users
  // Comments.menus.add({
  //   title: 'comments help page',
  //   link: 'comments help page',
  //   roles: ['authenticated'],
  //   menu: 'main'
  // });

  Comments.aggregateAsset('js', '../lib/angular-elastic/elastic.js');
  Comments.aggregateAsset('js', '../lib/angular-emoticons/javascripts/angular-emoticons.js');
  Comments.aggregateAsset('js', '../lib/angular-timeago/src/timeAgo.js');
  Comments.aggregateAsset('js', '../lib/ment.io/dist/mentio.js');
  Comments.aggregateAsset('js', '../lib/Autolinker.js/dist/Autolinker.min.js');
  Comments.aggregateAsset('css', '../lib/ment.io/ment.io/styles.css');
  Comments.aggregateAsset('css', '../lib/angular-emoticons/stylesheets/angular-emoticons.css');
  Comments.aggregateAsset('css', '../css/comments.css');

  Comments.angularDependencies(['yaru22.angular-timeago', 'emoticonizeFilter', 'monospaced.elastic', 'mentio', 'mean.socket']);

  return Comments;
});


text:
<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="author" content="minimo">
        <meta name="viewport" content="width=device-width, user-scalable=no" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

        <title>test</title>
        <link rel="apple-touch-icon-precomposed" href="icon.png" />

        <script src="src/Benri.js"></script>
        <script src="src/cordova/CdvDeviceEvents.js"></script>
        <script src="src/cordova/CdvAdmob.js"></script>
        <script src="src/cordova/CdvGameCenter.js"></script>
        <script src="src/cordova/CdvSNS.js"></script>

        <script src="src/libs/mt.js"></script>
        <script src="src/libs/tmlib.js"></script>
        <script src="src/libs/tmlib.custom.js"></script>
        <script src="src/libs/outlinelabel.js"></script>
        <script src="src/libs/touches.js"></script>
        <script src="src/libs/button.js"></script>
        <script src="src/libs/soundset.js"></script>

        <script src="src/main.js"></script>
        <script src="src/Application.js"></script>
        <script src="src/assets.js"></script>
        <script src="src/Card.js"></script>
        <script src="src/CardDeck.js"></script>

        <script src="src/scene/LoadingScene.js"></script>
        <script src="src/scene/MainScene.js"></script>
        <script src="src/scene/PauseScene.js"></script>
        <script src="src/scene/TitleScene.js"></script>
        <script src="src/scene/CreditScene.js"></script>
        <script src="src/scene/SettingScene.js"></script>
        <script src="src/scene/GameoverScene.js"></script>
    </head>

    <body>
        <canvas id="world"></canvas>
    </body>
</html>