text:
package org.ligerbots.steamworks;

import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.GenericHID.Hand;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.command.InstantCommand;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import java.util.Arrays;
import java.util.List;
import org.ligerbots.steamworks.FieldMap.FieldSide;
import org.ligerbots.steamworks.Robot.AutoMode;
import org.ligerbots.steamworks.commands.AlignBoilerAndShootCommand;
import org.ligerbots.steamworks.commands.CameraFeedCommand;
import org.ligerbots.steamworks.commands.ClimberEngageRatchetCommand;
import org.ligerbots.steamworks.commands.CompressorCommand;
import org.ligerbots.steamworks.commands.DriveDistanceCommand;
import org.ligerbots.steamworks.commands.DrivePathCommand;
import org.ligerbots.steamworks.commands.DriveToFeederCommand;
import org.ligerbots.steamworks.commands.DriveToGearCommand;
import org.ligerbots.steamworks.commands.FeederBackOutCommand;
import org.ligerbots.steamworks.commands.GearCommand;
import org.ligerbots.steamworks.commands.HumanPlayerCommunicationCommand;
import org.ligerbots.steamworks.commands.HumanPlayerCommunicationCommand.RequestedFeed;
import org.ligerbots.steamworks.commands.IntakeCommand;
import org.ligerbots.steamworks.commands.ManualControlWithTriggerCommand;
import org.ligerbots.steamworks.commands.ManualControlWithTriggerCommand.ManualControlType;
import org.ligerbots.steamworks.commands.ShiftCommand;
import org.ligerbots.steamworks.commands.ShooterFeederCommand;
import org.ligerbots.steamworks.commands.SlideCommandGroup;
import org.ligerbots.steamworks.commands.TurnCommand;
import org.ligerbots.steamworks.subsystems.DriveTrain;
import org.ligerbots.steamworks.subsystems.GearManipulator.Position;
import org.ligerbots.steamworks.subsystems.Pneumatics.CompressorState;
import org.ligerbots.steamworks.subsystems.Vision;
import org.ligerbots.steamworks.subsystems.Vision.StreamType;
import org.ligerbots.steamworks.triggers.JoystickPov;
import org.ligerbots.steamworks.triggers.JoystickPov.Direction;
import org.slf4j.LoggerFactory;

/**
 * This class is the glue that binds the controls on the physical operator interface to the commands
 * and command groups that allow control of the robot.
 */
public class OperatorInterface {
  public static final int AUTO_MODE_GEAR_SHOOT = 0;
  public static final int AUTO_MODE_HOPPER_SHOOT = 1;
  public static final int AUTO_MODE_NONE = 2;

  public XboxController xboxController;
  public Joystick farmController;

  SendableChooser<AutoMode> autoMode;
  SendableChooser<FieldSide> startingPosition;
  SendableChooser<FieldSide> gearLiftPosition;

  /**
   * This is where we set up the operator interface.
   */
  public OperatorInterface() {
    autoMode = new SendableChooser<>();
    populateSelect(autoMode, AutoMode.class);
    SmartDashboard.putData("Auto mode", autoMode);

    startingPosition = new SendableChooser<>();
    populateSelect(startingPosition, FieldSide.class);
    SmartDashboard.putData("Auto start position", startingPosition);

    gearLiftPosition = new SendableChooser<>();
    populateSelect(gearLiftPosition, FieldSide.class);
    SmartDashboard.putData("Auto gear lift position", gearLiftPosition);

    xboxController = new XboxController(0);
    farmController = new Joystick(1);

    final ShooterFeederCommand manualShootCommand = new ShooterFeederCommand(true);
    final AlignBoilerAndShootCommand autoShootCommand = new AlignBoilerAndShootCommand();
    final GearCommand manualGearCommand = new GearCommand();
    final DriveToGearCommand autoGearCommand = new DriveToGearCommand();
    final DriveToFeederCommand driveToFeeder = new DriveToFeederCommand();

    // Xbox main controls
    JoystickButton xboxAButton = new JoystickButton(xboxController, 1);
    xboxAButton.whenPressed(autoShootCommand);

    JoystickButton xboxBButton = new JoystickButton(xboxController, 2);
    xboxBButton.whenPressed(driveToFeeder);

    JoystickButton xboxXButton = new JoystickButton(xboxController, 3);
    xboxXButton.whileHeld(manualShootCommand);

    JoystickButton xboxYButton = new JoystickButton(xboxController, 4);
    xboxYButton.whenPressed(autoGearCommand);

    JoystickButton xboxLeftBumper = new JoystickButton(xboxController, 5);
    xboxLeftBumper.whenPressed(new ShiftCommand(DriveTrain.ShiftType.DOWN));

    JoystickButton xboxRightBumper = new JoystickButton(xboxController, 6);
    xboxRightBumper.whenPressed(new ShiftCommand(DriveTrain.ShiftType.UP));

    JoystickButton xboxMenuButton = new JoystickButton(xboxController, 7);
    xboxMenuButton.whenPressed(new IntakeCommand());

    JoystickButton xboxStartButton = new JoystickButton(xboxController, 8);
    xboxStartButton.whenPressed(new ClimberEngageRatchetCommand());

    JoystickPov povTriggerRight = new JoystickPov(xboxController, Direction.EAST);
    povTriggerRight.whenPressed(new SlideCommandGroup(2.0, true));

    JoystickPov povTriggerLeft = new JoystickPov(xboxController, Direction.WEST);
    povTriggerLeft.whenPressed(new SlideCommandGroup(2.0, false));

    if (isFarmControllerPresent()) {
      LoggerFactory.getLogger(OperatorInterface.class).info("Farm controller found!");

      // camera 1, 2, 3
      // intake on, off
      // gearmech closed, feed, open
      // drive to 3 inches for feeder
      // LEDs gear, fuel, none
      // duplicate manual shoot, auto shoot, manual gear, auto gear
      // manual RPM / feeder fiddling with 28 + stick

      // CAMERAS
      JoystickButton gearCam = new JoystickButton(farmController, 22);
      gearCam.whenPressed(new CameraFeedCommand(StreamType.GEAR_CAM));

      JoystickButton boilerCam = new JoystickButton(farmController, 23);
      boilerCam.whenPressed(new CameraFeedCommand(StreamType.BOILER_CAM));

      JoystickButton boilerFrontCam = new JoystickButton(farmController, 24);
      boilerFrontCam.whenPressed(new CameraFeedCommand(StreamType.BOILER_CAM_FRONT));

      // INTAKE
      JoystickButton intakeOn = new JoystickButton(farmController, 18);
      intakeOn.whenPressed(new IntakeCommand(true));

      JoystickButton intakeOff = new JoystickButton(farmController, 17);
      intakeOff.whenPressed(new IntakeCommand(false));

      // GEARMECH
      JoystickButton gearmechClosed = new JoystickButton(farmController, 1);
      gearmechClosed.whenPressed(new GearCommand(Position.CLOSED));

      JoystickButton gearmechReceive = new JoystickButton(farmController, 2);
      gearmechReceive.whenPressed(new GearCommand(Position.RECEIVE_GEAR));

      JoystickButton gearmechDeliver = new JoystickButton(farmController, 3);
      gearmechDeliver.whenPressed(new GearCommand(Position.DELIVER_GEAR));

      // drive to 6 inches
      JoystickButton driveToGearFeed = new JoystickButton(farmController, 6);
      driveToGearFeed.whenPressed(driveToFeeder);

      // LEDs
      JoystickButton ledsOff = new JoystickButton(farmController, 11);
      ledsOff.whenPressed(new HumanPlayerCommunicationCommand(RequestedFeed.NONE));

      JoystickButton ledsGear = new JoystickButton(farmController, 13);
      ledsGear.whenPressed(new HumanPlayerCommunicationCommand(RequestedFeed.GEAR));

      JoystickButton ledsFuel = new JoystickButton(farmController, 15);
      ledsFuel.whenPressed(new HumanPlayerCommunicationCommand(RequestedFeed.FUEL));

      // For testing turns
      JoystickButton turn5 = new JoystickButton(farmController, 12);
      turn5.whenPressed(new TurnCommand(1.0, 0.5));

      JoystickButton turn2 = new JoystickButton(farmController, 14);
      turn2.whenPressed(new TurnCommand(2.0, 0.5));

      JoystickButton turn30 = new JoystickButton(farmController, 16);
      turn30.whenPressed(new TurnCommand(30.0, 3.0));

      // duplicated controls
      JoystickButton manualShoot = new JoystickButton(farmController, 4);
      manualShoot.whileHeld(manualShootCommand);

      JoystickButton autoShoot = new JoystickButton(farmController, 5);
      autoShoot.whenPressed(autoShootCommand);

      JoystickButton manualGear = new JoystickButton(farmController, 9);
      manualGear.whenPressed(manualGearCommand);

      JoystickButton autoGear = new JoystickButton(farmController, 10);
      autoGear.whenPressed(autoGearCommand);

      // climb
      JoystickButton climb = new JoystickButton(farmController, 21);
      climb.whenPressed(new ClimberEngageRatchetCommand());
    } else {
      LoggerFactory.getLogger(OperatorInterface.class).info("(No farm controller found)");
    }

    SmartDashboard.putData(new InstantCommand("ForceOverrideRatchetEngage") {
      @Override
      public void execute() {
        Robot.driveTrain.engageClimberRatchet();
      }
    });

    SmartDashboard.putData(new CompressorCommand(CompressorState.TOGGLE));
    SmartDashboard.putData(new TurnCommand(45.0, RobotMap.AUTO_TURN_ACCEPTABLE_ERROR));
    SmartDashboard.putData(new TurnCommand(90.0, RobotMap.AUTO_TURN_ACCEPTABLE_ERROR));
    SmartDashboard.putData(new TurnCommand(180.0, RobotMap.AUTO_TURN_ACCEPTABLE_ERROR));
    SmartDashboard.putData(new DriveDistanceCommand(12 * 5));
    SmartDashboard.putData(new DriveDistanceCommand(12 * 10));
    SmartDashboard.putData(new DriveToGearCommand());

    SmartDashboard.putData(new ClimberEngageRatchetCommand());

    SmartDashboard.putData(new FeederBackOutCommand());

    SmartDashboard.putData(new CameraFeedCommand(Vision.StreamType.TOGGLE));

    SmartDashboard.putData(new AlignBoilerAndShootCommand());

    FieldPosition startPosition = FieldMap.getRed().startingPositions[0];
    List<FieldPosition> testCtrl =
        Arrays.asList(startPosition.add(-1, 0), startPosition, startPosition.add(60, 0),
            startPosition.add(60, -60), startPosition.add(120, -60), startPosition.add(121, -60));
    List<FieldPosition> testWaypoint = FieldMap.generateCatmullRomSpline(testCtrl);
    SmartDashboard.putData(new DrivePathCommand(testWaypoint));

    for (ManualControlType type : ManualControlWithTriggerCommand.ManualControlType.values()) {
      SmartDashboard.putData("ManualControl_" + type.toString(),
          new ManualControlWithTriggerCommand(type));
    }

    SmartDashboard.putData(new InstantCommand("ZeroSensors") {
      {
        setRunWhenDisabled(true);
      }

      @Override
      public void execute() {
        Robot.driveTrain.zeroSensors();
      }
    });

    SmartDashboard.putData(new InstantCommand("Auto Calculations") {
      {
        setRunWhenDisabled(true);
      }

      @Override
      public void execute() {
        LoggerFactory.getLogger(OperatorInterface.class).info("Auto calc test");
        FieldMap.navigateStartToGearLift(getStartingPosition(), getGearLiftPosition());
      }
    });
  }

  private <T extends Enum<?>> void populateSelect(SendableChooser<T> chooser, Class<T> options) {
    boolean first = true;
    for (T value : options.getEnumConstants()) {
      if (first) {
        first = false;
        chooser.addDefault(value.toString(), value);
      } else {
        chooser.addObject(value.toString(), value);
      }
    }
  }

  public double getThrottle() {
    return -xboxController.getY(GenericHID.Hand.kLeft);
  }

  public double getTurn() {
    return -xboxController.getX(GenericHID.Hand.kRight);
  }

  /**
   * Every command that implements automatic behavior should check this in isFinished(). This method
   * returns true if
   *

   *
The left (throttle) stick button is pressed, or

   *
Throttle is applied beyond 0.5

   *

   *
   * @return True if the above conditions are met.
   */
  public boolean isCancelled() {
    // just to be safe. The controller could fall down or something.
    if (DriverStation.getInstance().isAutonomous()) {
      return false;
    }
    return getThrottle() > 0.5 || getThrottle() < -0.5
        || xboxController.getStickButton(GenericHID.Hand.kLeft) || farmController.getRawButton(28);
  }

  public boolean isQuickTurn() {
    return xboxController.getStickButton(GenericHID.Hand.kRight);
  }

  public AutoMode getAutoMode() {
    return autoMode.getSelected();
  }

  public FieldSide getStartingPosition() {
    return startingPosition.getSelected();
  }

  public FieldSide getGearLiftPosition() {
    return gearLiftPosition.getSelected();
  }

  public double getTriggerValue() {
    return xboxController.getTriggerAxis(Hand.kRight) - xboxController.getTriggerAxis(Hand.kLeft);
  }

  /**
   * Detects whether we have a farm controller.
   *
   * @return True if present. Currently, always true
   */
  public boolean isFarmControllerPresent() {
    return true;
    // we had problems with a startup check last year
    // return (farmController.getButtonCount() > 10);
  }

}


text:
import os
import sys

import py_entitymatching  as mg

p = mg.get_install_path()
datasets_path = os.sep.join([p, 'datasets', 'example_datasets'])

class TimeBlockTablesElectronics:
    timeout = 20000.0

    def setup(self):
        path_for_A = os.sep.join([datasets_path, 'electronics', 'A.csv'])
        path_for_B = os.sep.join([datasets_path, 'electronics', 'B.csv'])
        try:
            self.A = mg.read_csv_metadata(path_for_A)
            mg.set_key(self.A, 'ID')
            self.B = mg.read_csv_metadata(path_for_B)
            mg.set_key(self.B, 'ID')
            self.feature_table = mg.get_features_for_blocking(self.A, self.B)
        except AssertionError:
            print("Dataset \'electronics\' not found. Please visit the project "
                  "website to download the dataset.")
            raise SystemExit

    def teardown(self):
        del self.A
        del self.B
        del self.feature_table

    def time_block_tables_name_cos(self):
        rb = mg.RuleBasedBlocker()
        rb.add_rule(['Name_Name_cos_dlm_dc0_dlm_dc0(ltuple,rtuple) < 0.3'],
                    self.feature_table)
        rb.block_tables(self.A, self.B, ['Name'], ['Name'])

    def time_block_tables_features_jac(self):
        rb = mg.RuleBasedBlocker()
        rb.add_rule(['Features_Features_jac_qgm_3_qgm_3(ltuple,rtuple) < 0.6'],
                    self.feature_table)
        rb.block_tables(self.A, self.B, ['Features'], ['Features'])

class TimeBlockTablesAnime:
    timeout = 10000.0

    def setup(self):
        path_for_A = os.sep.join([datasets_path, 'anime', 'A.csv'])
        path_for_B = os.sep.join([datasets_path, 'anime', 'B.csv'])
        try:
            self.A = mg.read_csv_metadata(path_for_A)
            mg.set_key(self.A, 'ID')
            self.B = mg.read_csv_metadata(path_for_B)
            mg.set_key(self.B, 'ID')
            self.feature_table = mg.get_features_for_blocking(self.A, self.B)
        except AssertionError:
            print("Dataset \'anime\' not found. Please visit the project "
                  "website to download the dataset.")
            raise SystemExit

    def teardown(self):
        del self.A
        del self.B
        del self.feature_table

    def time_block_tables(self):
        rb = mg.RuleBasedBlocker()
        rb.add_rule(['Title_Title_jac_qgm_3_qgm_3(ltuple,rtuple) < 0.4'],
                    self.feature_table)
        rb.block_tables(self.A, self.B, ['Title'], ['Title'])

class TimeBlockTablesBooks:
    timeout = 10000.0

    def setup(self):
        path_for_A = os.sep.join([datasets_path, 'books', 'A.csv'])
        path_for_B = os.sep.join([datasets_path, 'books', 'B.csv'])
        try:
            self.A = mg.read_csv_metadata(path_for_A)
            mg.set_key(self.A, 'ID')
            self.B = mg.read_csv_metadata(path_for_B)
            mg.set_key(self.B, 'ID')
            self.feature_table = mg.get_features_for_blocking(self.A, self.B)
            self.rb = mg.RuleBasedBlocker()
        except AssertionError:
            print("Dataset \'beer\' not found. Please visit the project "
                  "website to download the dataset.")
            raise SystemExit

    def teardown(self):
        del self.A
        del self.B
        del self.feature_table
        del self.rb

    def time_block_tables(self):
        self.rb.add_rule(['ISBN13_ISBN13_exm(ltuple, rtuple) < 0.4'],
                         self.feature_table)
        self.rb.block_tables(self.A, self.B,
                             ['Title','Author','ISBN13','Publisher','Publication_Date'],
                             ['Title','Author','ISBN13','Publisher','Publication_Date'])

class TimeBlockTablesMovies:
    timeout = 10000.0

    def setup(self):
        path_for_A = os.sep.join([datasets_path, 'movies', 'A.csv'])
        path_for_B = os.sep.join([datasets_path, 'movies', 'B.csv'])
        try:
            self.A = mg.read_csv_metadata(path_for_A)
            mg.set_key(self.A, 'id')
            self.B = mg.read_csv_metadata(path_for_B)
            mg.set_key(self.B, 'id')
            self.feature_table = mg.get_features_for_blocking(self.A, self.B)
        except AssertionError:
            print("Dataset \'movies\' not found. Please visit the project "
                  "website to download the dataset.")
            raise SystemExit

    def teardown(self):
        del self.A
        del self.B
        del self.feature_table

    def time_block_tables(self):
        rb = mg.RuleBasedBlocker()
        rb.add_rule(['movie_name_movie_name_jac_qgm_3_qgm_3(ltuple,rtuple) < 0.6'],
                    self.feature_table)
        rb.block_tables(self.A, self.B,
                        ['movie_name','year','directors','actors','critic_rating','genre','pg_rating','duration'],
                        ['movie_name','year','directors','actors','movie_rating','genre','duration'])

class TimeBlockCandsetRestaurants:
    timeout = 600.0

    def setup(self):
        path_for_A = os.sep.join([datasets_path, 'restaurants', 'A.csv'])
        path_for_B = os.sep.join([datasets_path, 'restaurants', 'B.csv'])
        try:
            A = mg.read_csv_metadata(path_for_A)
            mg.set_key(A, 'ID')
            B = mg.read_csv_metadata(path_for_B)
            mg.set_key(B, 'ID')
            ob = mg.OverlapBlocker()
            self.C = ob.block_tables(A, B, 'ADDRESS', 'ADDRESS', overlap_size=4,
			         l_output_attrs=['NAME', 'PHONENUMBER', 'ADDRESS'],
                                 r_output_attrs=['NAME', 'PHONENUMBER', 'ADDRESS'])
            feature_table = mg.get_features_for_blocking(A,B)
            self.rb = mg.RuleBasedBlocker()
            self.rb.add_rule(['ADDRESS_ADDRESS_jac_qgm_3_qgm_3(ltuple,rtuple) < 0.44'],
                         feature_table)
        except AssertionError:
            print("Dataset \'beer\' not found. Please visit the project "
                  "website to download the dataset.")
            raise SystemExit

    def teardown(self):
        del self.C
        del self.rb

    def time_block_candset(self):
        self.rb.block_candset(self.C)

class TimeBlockCandsetEbooks:
    timeout = 600.0

    def setup(self):
        path_for_A = os.sep.join([datasets_path, 'ebooks', 'A.csv'])
        path_for_B = os.sep.join([datasets_path, 'ebooks', 'B.csv'])
        try:
            A = mg.read_csv_metadata(path_for_A)
            mg.set_key(A, 'record_id')
            B = mg.read_csv_metadata(path_for_B)
            mg.set_key(B, 'record_id')
            ob = mg.OverlapBlocker()
            self.C = ob.block_tables(A, B, 'title', 'title', overlap_size=2,
                                 rem_stop_words = True,
                                 l_output_attrs=['title', 'author', 'publisher', 'date'],
                                 r_output_attrs=['title', 'author', 'publisher', 'date'])
            feature_table = mg.get_features_for_blocking(A,B)
            self.rb = mg.RuleBasedBlocker()
            self.rb.add_rule(['date_date_lev_sim(ltuple, rtuple) < 0.6'], feature_table)
        except AssertionError:
            print("Dataset \'beer\' not found. Please visit the project "
                  "website to download the dataset.")
            raise SystemExit

    def teardown(self):
        del self.C
        del self.rb

    def time_block_candset(self):
        self.rb.block_candset(self.C)

redpajama_set_name: RedPajamaGithub


text:
$rootPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) -ChildPath ('..\..\..\..\') -Resolve
Remove-Module PoShMon -ErrorAction SilentlyContinue
Import-Module (Join-Path $rootPath -ChildPath "PoShMon.psd1")

$o365TeamsConfigPath = [Environment]::GetFolderPath("MyDocuments") + "\o365TeamsConfig.json"

Describe "Send-RepairNotifications" {

   InModuleScope PoShMon {

        It "Should send notifications to the specified channels (email, Pushbullet, O365 Teams)" {

            $poShMonConfiguration = New-PoShMonConfiguration {
                            General `
                                -EnvironmentName 'SharePoint' `
                                -MinutesToScanHistory 60 `
                                -PrimaryServerName 'APPServer1' `
                                -ConfigurationName SpFarmPosh `
                                -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests'
                            Notifications -When All {
                                Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com"
                                Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID"
                                O365Teams -TeamsWebHookUrl "http://teams.office.com/theapi"
                            }
                        }

            $repairOutput = @(
                @{
                    "SectionHeader" = "Repair 1"
                    "RepairResult" = "Something Important Was Done"
                }
            )

            Mock -CommandName Send-EmailRepairMessage -ModuleName PoShMon -Verifiable -MockWith {
                return
            }
            Mock -CommandName Send-PushbulletRepairMessage -ModuleName PoShMon -Verifiable -MockWith {
                return
            }
            Mock -CommandName Send-O365TeamsRepairMessage -ModuleName PoShMon -MockWith {
                return
            }

            $actual = Send-RepairNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks $repairOutput -Verbose

            Assert-VerifiableMock
            Assert-MockCalled -CommandName Send-O365TeamsRepairMessage -Times 1
        }
    }
}
Describe "Send-RepairNotifications-New-Scope" {

   InModuleScope PoShMon {
        It "Should send notifications to ONLY the specified channels (email, Pushbullet, O365 Teams)" {

            #$o365TeamsConfig = Get-Content -Raw -Path $o365TeamsConfigPath | ConvertFrom-Json

            $poShMonConfiguration = New-PoShMonConfiguration {
                            General `
                                -EnvironmentName 'SharePoint' `
                                -MinutesToScanHistory 60 `
                                -PrimaryServerName 'APPServer1' `
                                -ConfigurationName SpFarmPosh `
                                -TestsToSkip 'SPServerStatus','WindowsServiceState','SPFailingTimerJobs','SPDatabaseHealth','SPSearchHealth','SPDistributedCacheHealth','WebTests'
                            Notifications -When All {
                                Email -ToAddress "hilton@email.com" -FromAddress "all@jones.com" -SmtpServer "smtp.company.com"
                                Pushbullet -AccessToken "TestAccessToken" -DeviceId "TestDeviceID"
                            }
                        }

            $repairOutput = @(
                @{
                    "SectionHeader" = "Repair 1"
                    "RepairResult" = "Something Important Was Done"
                }
            )

            Mock -CommandName Send-EmailRepairMessage -ModuleName PoShMon -Verifiable -MockWith {
                return
            }
            Mock -CommandName Send-PushbulletRepairMessage -ModuleName PoShMon -Verifiable -MockWith {
                return
            }
            Mock -CommandName Send-O365TeamsRepairMessage -ModuleName PoShMon -MockWith {
                return
            }

            $actual = Send-RepairNotifications $poShMonConfiguration $poShMonConfiguration.Notifications.Sinks $repairOutput -Verbose

            Assert-VerifiableMock
            Assert-MockCalled -CommandName Send-O365TeamsRepairMessage -Times 0
        }
    }
}


text:
RSpec.describe Dry::Monitor::Rack::Middleware do
  subject(:middleware) { Dry::Monitor::Rack::Middleware.new(notifications).new(rack_app) }

  let(:notifications) do
    Dry::Monitor::Notifications.new(:test)
  end

  let(:rack_app) do
    double(:rack_app)
  end

  let(:log_file_path) do
    SPEC_ROOT.join('test_logs/middleware.log')
  end

  let(:rack_logger) do
    Dry::Monitor::Rack::Logger.new(Dry::Monitor::Logger.new(log_file_path))
  end

  let(:env) do
    { 'REQUEST_METHOD' => 'GET',
      'PATH_INFO' => '/hello-world',
      'REMOTE_ADDR' => '0.0.0.0',
      'QUERY_STRING' => query_params }
  end

  let(:query_params) do
    %w[
      _csrf=123456
      password=secret
      user[password]=secret
      others[][password]=secret1
      others[][password]=secret2
      foo=bar
      one=1
      ids[]=1
      ids[]=2
    ].join('&')
  end

  describe '#call' do
    before do
      File.open(log_file_path, 'w').close
      rack_logger.attach(middleware)
    end

    it 'triggers start/stop events for with a rack request' do
      expect(rack_app).to receive(:call).with(env).and_return([200, :total_success])

      status, response = middleware.call(env)

      expect(status).to be(200)
      expect(response).to be(:total_success)

      log_file_content = File.read(log_file_path)

      expect(log_file_content).to include('Started GET "/hello-world"')
      expect(log_file_content).to include('Finished GET "/hello-world"')
      expect(log_file_content).to include('Query parameters {"_csrf"=>"[FILTERED]", "password"=>"[FILTERED]", "user"=>{"password"=>"[FILTERED]"}, "others"=>[{"password"=>"[FILTERED]"}, {"password"=>"[FILTERED]"}], "foo"=>"bar", "one"=>"1", "ids"=>["1", "2"]}')
    end
  end

  describe '#on' do
    it 'subscribe a listener to a specific request event' do
      captured = []

      middleware.on(:error) do |event|
        captured << event[:exception]
        captured << event[:env]
      end

      exception = 'oops'
      env = { 'REQUEST_METHOD' => 'GET' }

      middleware.instrument(:error, exception: exception, env: env)

      expect(captured).to eql([exception, env])
    end
  end

  describe 'rack logger' do
    before do
      File.open(log_file_path, 'w').close
      rack_logger.attach(middleware)
    end

    it 'logs exceptions' do
      exception = double(:exception, message: 'oops', backtrace: ['/some/path.rb'])

      middleware.instrument(:error, exception: exception, env: env)

      log_file_content = File.read(log_file_path)

      expect(log_file_content).to include('oops')
      expect(log_file_content).to include('/some/path.rb')
    end
  end
end


text:
package executables;

import java.util.ArrayList;

import gedi.app.Gedi;
import gedi.centeredDiskIntervalTree.CenteredDiskIntervalTreeStorage;
import gedi.core.data.annotation.Transcript;
import gedi.core.data.reads.AlignedReadsDataFactory;
import gedi.core.data.reads.DefaultAlignedReadsData;
import gedi.core.data.reads.ReadCountMode;
import gedi.core.genomic.Genomic;
import gedi.core.reference.Strandness;
import gedi.core.region.ImmutableReferenceGenomicRegion;
import gedi.core.region.intervalTree.MemoryIntervalTreeStorage;
import gedi.util.ArrayUtils;
import gedi.util.FileUtils;
import gedi.util.StringUtils;
import gedi.util.functions.EI;
import gedi.util.functions.ExtendedIterator;
import gedi.util.functions.IterateIntoSink;
import gedi.util.userInteraction.progress.ConsoleProgress;

public class SplitExonicCIT {
	public static void main(String[] args) {
		try {
			start(args);
		} catch (UsageException e) {
			usage("An error occurred: "+e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			System.err.println("An error occurred: "+e.getMessage());
			e.printStackTrace();
		}
	}

	private static void usage(String message) {
		System.err.println();
		if (message!=null){
			System.err.println(message);
			System.err.println();
		}
		System.err.println("SplitExonicCIT <Options> <cit-file>");
		System.err.println();
		System.err.println("Options:");
		System.err.println(" -g <genome1 genome2 ...>\t\t\tGenome names");
		System.err.println(" -cit <cit file>\t\t\tTranscript CITs");
		System.err.println(" -p\t\t\tShow progress");
		System.err.println(" -nthreads <n>\t\t\tNumber of threads");
		System.err.println(" -h\t\t\tShow this message");
		System.err.println();
	}

	private static class UsageException extends Exception {
		public UsageException(String msg) {
			super(msg);
		}
	}

	private static int checkMultiParam(String[] args, int index, ArrayList<String> re) throws UsageException {
		while (index<args.length && !args[index].startsWith("-"))
			re.add(args[index++]);
		return index-1;
	}
	private static String checkParam(String[] args, int index) throws UsageException {
		if (index>=args.length || args[index].startsWith("-")) throw new UsageException("Missing argument for "+args[index-1]);
		return args[index];
	}
	private static int checkIntParam(String[] args, int index) throws UsageException {
		String re = checkParam(args, index);
		if (!StringUtils.isInt(re)) throw new UsageException("Must be an integer: "+args[index-1]);
		return Integer.parseInt(args[index]);
	}

	public static void start(String[] args) throws Exception {
		Gedi.startup(true);

		MemoryIntervalTreeStorage<Transcript> trans = new MemoryIntervalTreeStorage<Transcript>(Transcript.class);
		boolean progress = true;
		boolean nosrna = false;
		int nthreads = Runtime.getRuntime().availableProcessors();
		boolean simplify = false;
		Strandness strandness = Strandness.Unspecific;

		int i;
		for (i=0; i<args.length; i++) {

			if (args[i].equals("-g")) {
				ArrayList<String> gnames = new ArrayList<>();
				i = checkMultiParam(args, ++i, gnames);
				trans.fill(Genomic.get(gnames).getTranscripts());
			}
			if (args[i].equals("-cit")) {
				trans.fill(new CenteredDiskIntervalTreeStorage<Transcript>(checkParam(args, ++i)));
			}
			else if (args[i].equals("-p"))
				progress = true;
			else if (args[i].equals("-nosRNA"))
				nosrna = true;
			else if (args[i].equals("-strandness"))
				strandness = Strandness.valueOf(checkParam(args, ++i));
			else if (args[i].equals("-s"))
				simplify = true;
			else if (args[i].equals("-nthreads"))
				nthreads = checkIntParam(args, ++i);
			else if (args[i].equals("-h")) {
				usage(null);
				System.exit(0);
			}
			else
				break;
		}

		if (i+1!=args.length)
			usage("Specify CIT file!");

		CenteredDiskIntervalTreeStorage<DefaultAlignedReadsData> in = new CenteredDiskIntervalTreeStorage<>(args[i]);
		CenteredDiskIntervalTreeStorage<DefaultAlignedReadsData> exonic = new CenteredDiskIntervalTreeStorage<>(FileUtils.getExtensionSibling(args[i],"exonic.cit"),in.getType());
		CenteredDiskIntervalTreeStorage<DefaultAlignedReadsData> other = new CenteredDiskIntervalTreeStorage<>(FileUtils.getExtensionSibling(args[i],"nonexonic.cit"),in.getType());

		IterateIntoSink<ImmutableReferenceGenomicRegion<DefaultAlignedReadsData>> exonicSink = new IterateIntoSink<>(exonic::fill);
		IterateIntoSink<ImmutableReferenceGenomicRegion<DefaultAlignedReadsData>> otherSink = new IterateIntoSink<>(other::fill);

		boolean usimplify = simplify;
		boolean unosrna = nosrna;
		Strandness ustrandness = strandness;
		in.ei()
			.iff(progress, ei->ei.progress(new ConsoleProgress(System.err), (int)in.size(), l->l.toLocationString()))
			.parallelized(nthreads, 4096, ei->ei.map(r->{
				if (usimplify)
					r = simplify(r);
				if (r==null)
					return 1;
				if (testExonic(r,trans,ustrandness,unosrna))
					exonicSink.accept(r);
				else
					otherSink.accept(r);
				return 1;
			}))
			.drain();

		exonicSink.finish();
		otherSink.finish();

		exonic.setMetaData(in.getMetaData());
		other.setMetaData(in.getMetaData());
	}

	private static ImmutableReferenceGenomicRegion<DefaultAlignedReadsData> simplify(
			ImmutableReferenceGenomicRegion<DefaultAlignedReadsData> r) {

		if (r.getData().hasGeometry())
			throw new RuntimeException("No simplify for paired end!");

		int[] c = r.getData().getTotalCountsForConditionsInt(ReadCountMode.Unique);
		if (ArrayUtils.sum(c)==0) return null;
		return new ImmutableReferenceGenomicRegion<>(r.getReference(), r.getRegion(), AlignedReadsDataFactory.createSimple(c, r.getData().hasNonzeroInformation()));
	}

	private static boolean testExonic(ImmutableReferenceGenomicRegion<DefaultAlignedReadsData> r,
			MemoryIntervalTreeStorage<Transcript> trans, Strandness strandness, boolean nosrna) {

		if (r.getData().hasGeometry())
			throw new RuntimeException("Not for for paired end!");
		if (r.getRegion().getNumParts()>1) return true;

		ExtendedIterator<ImmutableReferenceGenomicRegion<Transcript>> it = EI.empty();
		if (!strandness.equals(Strandness.Antisense))
			it = it.chain(trans.ei(r));
		if (!strandness.equals(Strandness.Sense))
			it = it.chain(trans.ei(r.toOppositeStrand()));

		if (nosrna)
			it = it.filter(t->!issRNA(t));

		for (ImmutableReferenceGenomicRegion<Transcript> t : it.loop()) {
			if (r.getRegion().intersect(t.getRegion()).getTotalLength()>=r.getRegion().getTotalLength()-10)
				return true;
		}
		return false;
	}

	public static boolean issRNA(ImmutableReferenceGenomicRegion<Transcript> t) {
		return t.getData().issRNA(t);
	}

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.senac.kkcommerce.service;

import br.edu.senac.kkcommerce.dao.PedidosClienteDetalhesDAO;
import br.edu.senac.kkcommerce.dao.IDaoBase;
import br.edu.senac.kkcommerce.model.PedidosClienteDetalhes;
import java.util.ArrayList;

import java.util.List;

/**
 *
 * @author While True
 */

public class PedidosClienteDetalhesService extends ServiceBase {

    public PedidosClienteDetalhesService() {
        super(new PedidosClienteDetalhesDAO());
    }

    public List<PedidosClienteDetalhes> listar(int carrinho_id) throws Exception {
        ArrayList<PedidosClienteDetalhes> retorno = new ArrayList<>();
        ArrayList<PedidosClienteDetalhes> pedido = (ArrayList<PedidosClienteDetalhes>) dao.listar();

         for (PedidosClienteDetalhes p : pedido) {
            if (p.getCarrinho_id()== carrinho_id) {
                retorno.add(p);
            }
        }
        return retorno;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
     xmlns:util="http://www.springframework.org/schema/util"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
             http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
                         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<!-- 下面标签内建的就是 FormattingConversionServiceFactoryBean 所以 Spring MVC 对处理方法的入参绑定就支持注解驱动的功能-->
	<mvc:annotation-driven />
	<context:component-scan base-package="cn.bjfu.springdao.web.controller" />
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory
		 静态资源的处理 提供 rest 风格的URL 提供可能	cache-period 静态资源在客户浏览器的缓存时间-->
	<mvc:resources mapping="/resources/**" location="/resources/" cache-period="31536000"/>
	<!--
        - Message source for this context, loaded from localized "messages_xx" files.
        - Files are stored inside src/main/resources
    -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    	<property name="basename" value="messages/messages"/>
    </bean>

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- CommonsMultipartResolver -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="1024000000"></property>
	</bean>

	<!-- Spring MVC HttpMessageConverter<T> 自定义之后则覆盖默认的值-->
	<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters" ref="messageConverters" />
	</bean>
	默认配置以下四个
	<util:list id="messageConverters">
		<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter" />
		<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
		<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
		<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
		<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
	</util:list> -->

	<!-- <bean id="xmlMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
		<property name="streamDriver">
			<bean class="com.thoughtworks.xstream.io.xml.StaxDriver" />
		</property>
	</bean>

	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	</bean> -->

	<!-- <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="10" />
		<bean id="blogListExcel" class="cn.tramp.iblog.docview.BlogListExcelView" />
		<bean id="blogListPdf" class="cn.tramp.iblog.docview.BlogListPdfView" />
		<bean id="userListExcel" class="cn.tramp.iblog.docview.UserListExcelView" />
	<bean id="userListPdf" class="cn.tramp.iblog.docview.UserListPdfView" /> -->
</beans>


text:
New Work Advocate

I write and speak about the Future of Work and how to build the next generation of organizations.

            {% for post in site.posts %}

{{ post.title }}

{{ post.subtitle }}

            {% endfor %}


text:
package com.greenpepper.extensions.dynabeans;

import org.apache.commons.beanutils.DynaBean;

import com.greenpepper.reflect.Message;

public class DynaPropertyReader extends Message {

    private final DynaBean bean;
    private final String propertyName;

    public DynaPropertyReader(DynaBean bean, String propertyName) {
        this.bean = bean;
        this.propertyName = propertyName;
    }

    public int getArity() {
        return 0;
    }

    public Object send(String... args) throws Exception {
        return bean.get(propertyName);
    }
}


text:
"use strict";

const weave = require( '..' )
const garden = require( 'gardens' ).createScope( 'weave.bind' )

const chalk = require( 'chalk' )
const http = require( 'http' )
const https = require( 'https' )

weave._bindings = {}

class Binding {
  constructor( port, serverOptions ) {
    if ( !port ) throw garden.error( 'Not given a port to link to!' )
    if ( typeof port !== 'number' ) throw garden.typeerror( 'Argument port must be a number!' )
    if ( port < 1 || port > 0xFFFF ) throw garden.error( `${port} is not a valid port number.` )

    // If a binding for this port already exists,
    if ( weave._bindings[ port ] ) throw garden.error( 'Port already has a binding!' )

    let secure = serverOptions && serverOptions.key && serverOptions.cert

    Object.assign( this, {
      server: ( secure ? https : http ).createServer( serverOptions ),
      port, attachments: [], cachedMatches: {}
    })

    this.server.on( 'error', error => {
      throw garden.catch( error, 'Unable to bind to port, likely insufficient access.\n'
        + `${chalk.green( 'Did you remember to ' )} sudo${chalk.green( '?' )}` )
    })

    // Begin listening for requests
    void [ 'request', 'upgrade' ].forEach( event =>
      this.server.on( event, ( ...connection ) => new weave.Exchange( secure, ...connection ) ) )

    // Export binding, and listen to server
    weave._bindings[ port ] = this
    this.server.listen( port )
  }
}

weave.Binding = Binding


text:
package it.finsiel.siged.mvc.presentation.action.amministrazione;

import it.finsiel.siged.constant.ReturnValues;
import it.finsiel.siged.mvc.business.AmministrazioneDelegate;
import it.finsiel.siged.mvc.presentation.actionform.amministrazione.TitoloDestinatarioForm;
import it.finsiel.siged.mvc.vo.IdentityVO;

import java.util.Collection;

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

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 * Implementation of <strong>Action </strong> to create a new
 * TitoloDestinatario.
 *
 *
 *
 */

public final class TitoloDestinatarioAction extends Action {

    static Logger logger = Logger.getLogger(TitoloDestinatarioAction.class
            .getName());

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionMessages errors = new ActionMessages();

        HttpSession session = request.getSession(true);

        IdentityVO titoloVO = new IdentityVO();

        TitoloDestinatarioForm titoloDestinatarioForm = (TitoloDestinatarioForm) form;

        if (form == null) {
            logger.info("Creating new TitoloDestinatarioForm");
            form = new TitoloDestinatarioForm();
            session.setAttribute(mapping.getAttribute(), form);
        }

        logger.info("Siamo entrati in TitoloDestinatarioAction");

        if (!errors.isEmpty()) {
            saveErrors(request, errors);
            logger.info("Ci sono errori... Riga 56");
            return (mapping.findForward("input"));
        }

        AmministrazioneDelegate td = AmministrazioneDelegate.getInstance();
        Collection titoli = td.getElencoTitoliDestinatario();
        if (titoli != null) {
            titoloDestinatarioForm.setTitoli(titoli);
        }

        if (request.getParameter("btnModifica") != null
                && request.getParameter("id") == null) {
            errors.add("titolo", new ActionMessage("selezione.obbligatoria",
                    "il titolo", ""));

        } else if (request.getParameter("btnModifica") != null
                && request.getParameter("id") != null) {
            int id = Integer.parseInt(request.getParameter("id"));
            titoloVO = td.getTitoloDestinatario(id);
            titoloDestinatarioForm.setId(id);
            titoloDestinatarioForm.setDescrizione(titoloVO.getDescription());
            return (mapping.findForward("titolo"));
        } else if (request.getParameter("btnCancella") != null
                && request.getParameter("id") != null) {
            errors = titoloDestinatarioForm.validate(mapping, request);
            int id = Integer.parseInt(request.getParameter("id"));
            boolean esiste = esisteInProtocolloDestinatari(id);

            if (esiste) {
                errors
                        .add(
                                "titolo",
                                new ActionMessage("record_non_cancellabile",
                                        "il titolo",
                                        ": esiste almeno un destinatario protocollato che fa riferimento ad esso."));
                saveErrors(request, errors);
                return (mapping.findForward("input"));
            } else {
                // Verificare l'esistenza di vincoli nella tabella
                // Storia_Protocollo_Destinatari
                esiste = esisteInStoriaProtocolloDestinatari(id);
                if (esiste) {
                    errors
                            .add(
                                    "titolo",
                                    new ActionMessage(
                                            "record_non_cancellabile",
                                            "il titolo",
                                            ": nell'archivio storico destinatari esiste almeno un destinatario protocollato che fa riferimento ad esso."));
                    saveErrors(request, errors);
                    return (mapping.findForward("input"));
                } else {
                    // Verificare l'esistenza di vincoli nella tabella
                    // Invio_classificati_destinatari
                    esiste = esisteInInvioClassificatiDestinatari(id);
                    if (esiste) {
                        errors
                                .add(
                                        "titolo",
                                        new ActionMessage(
                                                "record_non_cancellabile",
                                                "il titolo",
                                                ": nella tabella di invio classificati destinatari esiste almeno un destinatario protocollato che fa riferimento ad esso."));
                        saveErrors(request, errors);
                        return (mapping.findForward("input"));
                    } else {
                        // Verificare l'esistenza di vincoli nella tabella
                        // Invio_fascicoli_destinatari
                        esiste = esisteInInvioFascicoliDestinatari(id);
                        if (esiste) {
                            errors
                                    .add(
                                            "titolo",
                                            new ActionMessage(
                                                    "record_non_cancellabile",
                                                    "il titolo",
                                                    ": nella tabella di invio fascicoli destinatari esiste almeno un destinatario protocollato che fa riferimento ad esso."));
                            saveErrors(request, errors);
                            return (mapping.findForward("input"));
                        } else {
                            // Posso eliminare il titolo, poiché non ci sono
                            // vincoli
                            boolean eliminato = false;
                            eliminato = td.deleteTitolo(id);
                            if (eliminato) {
                                errors
                                        .add(
                                                "titolo",
                                                new ActionMessage(
                                                        "cancellazione_ok",
                                                        "il titolo",
                                                        ": nella tabella di invio fascicoli destinatari esiste almeno un destinatario protocollato che fa riferimento ad esso."));
                                saveErrors(request, errors);

                            }
                            titoloDestinatarioForm.setTitoli(td
                                    .getElencoTitoliDestinatario());
                            titoloDestinatarioForm.setId(0);

                        }
                    }
                }

            }

            return (mapping.findForward("input"));
        } else if (request.getParameter("btnSalva") != null) {
            // validazione dei dati
            errors = titoloDestinatarioForm.validate(mapping, request);
            if (!errors.isEmpty()) {
                saveErrors(request, errors);
                return mapping.findForward("input");
            }
            // fine validazioni
            titoloVO.setId(titoloDestinatarioForm.getId());
            titoloVO.setDescription(titoloDestinatarioForm.getDescrizione());
            titoloVO = td.salvaTitoloDestinatario(titoloVO);
            // titoloDestinatarioForm.setTitoli(td.getElencoTitoliDestinatario());

            if (titoloVO.getReturnValue() == ReturnValues.SAVED) {
                titoloDestinatarioForm.setTitoli(td
                        .getElencoTitoliDestinatario());
                titoloDestinatarioForm.setId(0);
                return (mapping.findForward("input"));
            } else {
                errors.add("registrazione_titolo", new ActionMessage(
                        "record_non_inseribile", "il titolo",
                        ": ne esiste già uno identico"));
                saveErrors(request, errors);
                return (mapping.findForward("titolo"));
            }

        } else if (request.getParameter("btnNuovo") != null) {
            titoloDestinatarioForm.setId(0);
            return (mapping.findForward("titolo"));
        }

        logger.info("Execute TitoliDestinatario");

        return mapping.getInputForward();

    }

    private boolean esisteInProtocolloDestinatari(int id) {
        boolean esiste = false;
        AmministrazioneDelegate ad = AmministrazioneDelegate.getInstance();
        esiste = ad.esisteTitoloInProtocolloDestinatari(id);
        return esiste;
    }

    private boolean esisteInStoriaProtocolloDestinatari(int id) {
        boolean esiste = false;
        AmministrazioneDelegate ad = AmministrazioneDelegate.getInstance();
        esiste = ad.esisteTitoloInStoriaProtDest(id);
        return esiste;
    }

    private boolean esisteInInvioClassificatiDestinatari(int id) {
        boolean esiste = false;
        AmministrazioneDelegate ad = AmministrazioneDelegate.getInstance();
        esiste = ad.esisteInInvioClassificatiProtDest(id);
        return esiste;
    }

    private boolean esisteInInvioFascicoliDestinatari(int id) {
        boolean esiste = false;
        AmministrazioneDelegate ad = AmministrazioneDelegate.getInstance();
        esiste = ad.esisteInInvioFascicoliDestinatari(id);
        return esiste;
    }

}


text:
/* global FileReader FormData XMLHttpRequest */
import React from "react";
import PropTypes from "prop-types";
import ImmutablePropTypes from "react-immutable-proptypes";
import LightComponent from "ui-lib/light_component";
import Input from "react-toolbox/lib/input";
import {
    Form as TAForm,
    Section as TASection
} from "ui-components/type_admin";
import { Header } from "ui-components/layout";
import { isTokenValidForAccess } from "auth/lib/util";
import Notification from "ui-observables/notification";

class UserUploadAvatar extends LightComponent {
    constructor(props) {
        super(props);
        this.state = {
            avatarFilename: "",
            avatarFile: false,
            avatarPreviewData: false
        };
    }

    async _onConfirm() {
        const user = this._getUser();

        // Prepare form data
        const formData = new FormData();
        formData.append("avatar", this.state.avatarFile);

        // Prepare AJAX request
        const request = new XMLHttpRequest();
        request.addEventListener("load", () => {
            if (request.status === 200) {
                Notification.instance.publish("Avatar uploaded!");
            } else {
                Notification.instance.publish(`Avatar upload failed with status ${request.status}!`, "warning");
            }
        });
        request.addEventListener("error", () => {
            Notification.instance.publish(`Avatar upload failed with status ${request.status}!`, "warning");
        });
        request.addEventListener("abort", () => {
            Notification.instance.publish("Avatar upload aborted!", "warning");
        });
        request.open("POST", `/userrepo/useravatar/${user._id}/upload`);

        // Submit AJAX request
        request.send(formData);
    }

    async _onCancel() {
        this.context.router.goBack();
    }

    _confirmAllowed() {
        const user = this._getUser();
        const inputsValid = this.state.avatarFilename.length > 0 &&
            !!this.state.avatarFile;

        return user && inputsValid;
    }

    _getUser(props = null) {
        props = props || this.props;

        return props.parentItems.find((item) => item.type === "userrepo.user");
    }

    _onAvatarFilenameChange(avatarFilename, event) {
        const avatarFile = event.target.files[0];
        this.setState({
            avatarFilename,
            avatarFile
        });
        const reader = new FileReader();
        reader.onload = (e) =>
            this.setState({ avatarPreviewData: e.target.result });
        reader.readAsDataURL(avatarFile);
    }

    render() {
        this.log("render", this.props, this.state);

        const signedInUserPriv = this.props.activeUser.has("priv") && this.props.activeUser.get("priv").toJS();
        // Check that we have access to update teams
        let accessError;
        try {
            isTokenValidForAccess(signedInUserPriv, "userrepo.useravatar", "upload");
        } catch (error) {
            accessError = error.message;
        }

        const user = this._getUser();

        return (
            <TASection
                breadcrumbs={this.props.breadcrumbs}
                controls={this.props.controls}
                menuItems={this.props.menuItems}
            >
                <Choose>
                    <When condition={ accessError }>

{accessError}

                    </When>
                    <When condition={ user }>
                        <TAForm
                            confirmAllowed={this._confirmAllowed()}
                            confirmText={"Upload"}
                            primaryText={`Upload avatar for ${user.name}`}
                            onConfirm={() => this._onConfirm()}
                            onCancel={() => this._onCancel()}
                        >

                                Note that page needs to be reloaded
                                for changes to take effect.

                            <Input
                                type="file"
                                label="Choose avatar image"
                                name="avatarFile"
                                value={this.state.avatarFilename}
                                onChange={(value, event) => this._onAvatarFilenameChange(value, event)}
                                floating={false}
                                required={true}
                            />
                            <If condition={this.state.avatarPreviewData}>

                            </If>
                        </TAForm>
                    </When>
                </Choose>
            </TASection>
        );
    }
}

UserUploadAvatar.propTypes = {
    theme: PropTypes.object,
    parentItems: PropTypes.array.isRequired,
    pathname: PropTypes.string.isRequired,
    breadcrumbs: PropTypes.array.isRequired,
    controls: PropTypes.array.isRequired,
    menuItems: PropTypes.array.isRequired,
    activeUser: ImmutablePropTypes.map.isRequired
};

UserUploadAvatar.contextTypes = {
    router: PropTypes.object.isRequired
};

export default UserUploadAvatar;


text:
package com.pungwe.db.io.store;

import com.pungwe.db.io.serializers.DBDocumentSerializer;
import com.pungwe.db.io.volume.MemoryVolume;
import com.pungwe.db.io.volume.Volume;
import com.pungwe.db.types.BasicDBDocument;
import com.pungwe.db.types.DBDocument;
import com.pungwe.db.types.Header;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by 917903 on 13/02/2015.
 */
public class DirectStoreTest {

	Volume volume;
	Volume recVolume;
	DirectStore store;

	@Before
	public void setupBuffer() throws Exception {
		volume = new MemoryVolume(false);
		recVolume = new MemoryVolume(false);
		store = new DirectStore(volume, recVolume);
	}

	@Test
	public void testPut() throws Exception {
		BasicDBDocument object = new BasicDBDocument();
		object.put("_id", 1l);
		object.put("key", "value");
		long position = store.put(object, new DBDocumentSerializer());
		assert position > -1 : "Position should be greater than -1";

	}

	@Test
	public void testGet() throws Exception {
		BasicDBDocument object = new BasicDBDocument();
		object.put("_id", 1l);
		object.put("key", "value");
		long position = store.put(object, new DBDocumentSerializer());
		assert position > -1 : "Position should be greater than -1";
		DBDocument result = store.get(position, new DBDocumentSerializer());
		assertNotNull(result);
		assertEquals(object.get("_id"), result.get("_id"));

	}

	@Test
	public void testUpdate() throws Exception {
		BasicDBDocument object = new BasicDBDocument();
		object.put("_id", 1l);
		object.put("key", "value");
		long position = store.put(object, new DBDocumentSerializer());
		assert position > -1 : "Position should be greater than -1";

		object.put("key", "new value");
		long newPosition = store.update(position, object, new DBDocumentSerializer());

		assert newPosition == position : "Update should be at the same position";

		DBDocument newObject = store.get(newPosition, new DBDocumentSerializer());
		assertEquals(newObject.get("key"), "new value");

	}

	@Test
	public void testGetHeader() throws Exception {
		// We probably need more here
		Header header = store.getHeader();
		assert header.getPosition() > 0l : "Header is still at 0";
		assertEquals(DirectStore.class.getName(), header.getStore());
	}

	@Test
	public void tesRemove() throws Exception {
		BasicDBDocument object = new BasicDBDocument();
		object.put("_id", 1l);
		object.put("key", "value");
		long position = store.put(object, new DBDocumentSerializer());
		store.remove(position);
	}

	@Test
	public void testCommit() throws Exception {
		// Does nothing
	}

	@Test
	public void testRollback() throws Exception {
		// Does nothing
	}

	@Test
	public void testIsClosed() throws Exception {
		assertFalse(store.isClosed());
		store.close();
		assertTrue(store.isClosed());
	}

	@Test
	public void testLock() throws Exception {
		// do nothing for now
	}

	@Test
	public void testUnlock() throws Exception {
		// do nothing for now
	}

	@Test
	public void testIsAppendOnly() throws Exception {
		assert !store.isAppendOnly(); // just to get line coverage
	}

	@Test
	public void testAlloc() throws Exception {
		// already tested
	}
}


text:
package bixie.translation.soot;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import bixie.Options;
import bixie.boogie.ProgramFactory;
import bixie.boogie.ast.Attribute;
import bixie.boogie.ast.expression.Expression;
import bixie.boogie.ast.expression.IdentifierExpression;
import bixie.boogie.ast.statement.Statement;
import bixie.boogie.type.BoogieType;
import bixie.translation.GlobalsCache;
import bixie.util.Log;
import soot.Local;
import soot.Scene;
import soot.SootClass;
import soot.SootField;
import soot.SootMethod;
import soot.Trap;
import soot.TrapManager;
import soot.Unit;
import soot.jimple.StaticFieldRef;
import soot.jimple.Stmt;
import soot.tagkit.LineNumberTag;
import soot.tagkit.SourceFileTag;
import soot.tagkit.SourceLnNamePosTag;
import soot.tagkit.Tag;

/**
 * @author schaef
 *
 */
public class TranslationHelpers {

	public static Statement havocEverything(SootProcedureInfo procInfo,
			SootValueSwitch valueswitch) {
		LinkedList<IdentifierExpression> havoc_var = new LinkedList<IdentifierExpression>();
		for (IdentifierExpression id : procInfo.getLocalVariables()) {
			havoc_var.add(id);
		}
		for (IdentifierExpression id : procInfo.getOutParamters()) {
			havoc_var.add(id);
		}
		for (StaticFieldRef sr : procInfo.usedStaticFields) {
			sr.apply(valueswitch);
			IdentifierExpression ide = (IdentifierExpression) valueswitch
					.getExpression();
			havoc_var.add(ide);
		}

		havoc_var.add(SootPrelude.v().getHeapVariable());
		return GlobalsCache
				.v()
				.getPf()
				.mkHavocStatement(
						new Attribute[] {},
						havoc_var.toArray(new IdentifierExpression[havoc_var
								.size()]));
	}

	public static void getReachableTraps(Unit s, SootMethod m,
			List<Trap> out_traps, List<Trap> out_finally) {
		if (m.getActiveBody() == null) {
			throw new RuntimeException("cannot look into " + m.getSignature());
		}
		out_traps.addAll(TrapManager.getTrapsAt(s, m.getActiveBody()));

		SootClass throwable = Scene.v().loadClass("java.lang.Throwable",
				SootClass.SIGNATURES);

		Unit trap_begin = null;
		Unit trap_end = null;
		SootClass trap_exception = null;
		// Unit trap_handler = null;
		for (Trap trap : new LinkedList<Trap>(out_traps)) {
			if (trap.getBeginUnit() == trap_begin
					&& trap.getEndUnit() == trap_end
					&& trap.getException() == trap_exception) {
				out_traps.remove(trap);
				if (trap.getException() == throwable) {
					// in that case the second trap was most likely
					// of type "any" and thus is a finally block, but
					// soot translated that into Throwable.
					out_finally.add(trap);
					// System.err.println("unreachable finally "+GlobalsCache.v().getUnitLabel((Stmt)
					// trap.getHandlerUnit()));
					// System.err.println("\t\t"+GlobalsCache.v().getUnitLabel((Stmt)
					// trap_handler));
				}
			} else {
				// everything fine.
			}
			trap_begin = trap.getBeginUnit();
			trap_end = trap.getEndUnit();
			trap_exception = trap.getException();
			// trap_handler = trap.getHandlerUnit();
		}

	}

	public static Statement mkLocationAssertion(Stmt s) {
		return mkLocationAssertion(s, false, null);
	}

	public static Statement mkLocationAssertion(Stmt s,
			boolean forceCloneAttribute) {
		return mkLocationAssertion(s, forceCloneAttribute, null);
	}

	public static Statement mkLocationAssertion(Stmt s,
			boolean forceCloneAttribute, String comment) {
		return GlobalsCache
				.v()
				.getPf()
				.mkAssertStatement(
						javaLocation2Attribute(s, forceCloneAttribute, comment),
						GlobalsCache.v().getPf().mkBooleanLiteral(true));
	}

	public static final HashSet<Stmt> clonedFinallyBlocks = new HashSet<Stmt>();

	public static Attribute[] javaLocation2Attribute(Stmt s) {
		return javaLocation2Attribute(s, false, null);
	}

	public static Attribute[] javaLocation2Attribute(Stmt s,
			boolean forceCloneAttribute, String comment) {
		return javaLocation2Attribute(s.getTags(),
				clonedFinallyBlocks.contains(s) || forceCloneAttribute, comment);
	}

	public static Attribute[] javaLocation2Attribute(List<Tag> list) {
		return javaLocation2Attribute(list, false, null);
	}

	private static String getFileName(SootClass sc) {
		if (sc.hasOuterClass() && sc.getOuterClass()!=sc)
			return getFileName(sc.getOuterClass());
		String filename = null;
		for (Tag t_ : sc.getTags()) {
			if (t_ instanceof SourceFileTag) {
				filename = ((SourceFileTag) t_).getSourceFile();
				if (((SourceFileTag) t_).getAbsolutePath() != null) {
					filename = ((SourceFileTag) t_).getAbsolutePath();
				}
				if (filename!=null) break;
			} else if (t_ instanceof SourceLnNamePosTag) {
				if (((SourceLnNamePosTag) t_).getFileName()!=null) {
					filename = ((SourceLnNamePosTag) t_).getFileName();
				}
				// don't break, mybe there is still a source file tag.
			}
		}

		if (filename==null) {
			//try to make a name up.
			filename = sc.getName()+".java";
		}

		File srcFile = new File(filename);

		if (!srcFile.exists() && Options.v().getSrcFilesString()!=null) {
			final String expectedName = sc.getPackageName().replace(".", File.separator) + File.separator + filename;
			srcFile = findSourceFile(expectedName);
			if (srcFile==null || !srcFile.exists()) {
				Log.debug("Source file not found: "+filename + ".\nCheck your settings.");
			} else {
				filename = srcFile.getAbsolutePath();
			}
		}

		return filename;
	}

	public static void reset() {
		sourceFiles.clear();
	}

	private static Map<String, File> sourceFiles = new HashMap<String,File>();

	private static File findSourceFile(String expectedName) {
		if (!sourceFiles.containsKey(expectedName)) {
			File f = null;
			for (String s: Options.v().getSrcFilesString()) {
				if (s.contains(expectedName)) {
					f = new File(s);
					if (!f.exists()) {
						throw new RuntimeException("Bug");
					}
					break;
				}
			}
			sourceFiles.put(expectedName, f);
		}
		return sourceFiles.get(expectedName);
	}

	public static Statement createClonedAttribAssert() {
		ProgramFactory pf = GlobalsCache.v().getPf();
		Attribute[] res = new Attribute[] { pf
				.mkCustomAttribute(ProgramFactory.Cloned) };
		return pf.mkAssertStatement(res, pf.mkBooleanLiteral(true));
	}

	public static Attribute[] javaLocation2Attribute(List<Tag> list,
			boolean isCloned, String comment) {
		// if the taglist is empty return no location
		int startln, endln, startcol, endcol;

		startln = -1;
		endln = -1;
		startcol = -1;
		endcol = -1;
		String filename = null;

		if (GlobalsCache.v().currentMethod != null) {
			filename = getFileName(GlobalsCache.v().currentMethod
					.getDeclaringClass());
		}

		for (Tag tag : list) {
			if (tag instanceof LineNumberTag) {
				startln = ((LineNumberTag) tag).getLineNumber();
				break;
			} else if (tag instanceof SourceLnNamePosTag) {
				if (filename == null) {
					filename = ((SourceLnNamePosTag) tag).getFileName();
				}
				startln = ((SourceLnNamePosTag) tag).startLn();
				endln = ((SourceLnNamePosTag) tag).endLn();
				startcol = ((SourceLnNamePosTag) tag).startPos();
				endcol = ((SourceLnNamePosTag) tag).endPos();
				break;
			} else if (tag instanceof SourceFileTag) {
				if (filename == null) {
					filename = ((SourceFileTag) tag).getSourceFile();
					if (((SourceFileTag) tag).getAbsolutePath() != null) {
						filename = ((SourceFileTag) tag).getAbsolutePath();
					}
				}
				break;
			} else {
				// Log.info("Tag ignored: " + tag.getClass().toString());
			}
		}

		if (filename == null && startln == -1 && endln == -1 && startcol == -1
				&& endcol == -1) {
			return new Attribute[0];
		}

		if (filename == null && GlobalsCache.v().currentMethod != null) {
			filename = GlobalsCache.v().currentMethod.getDeclaringClass()
					.getName();
		}

		ProgramFactory pf = GlobalsCache.v().getPf();
		Attribute loc = pf.mkLocationAttribute(filename, startln, endln,
				startcol, endcol);

		Attribute[] res;
		if (isCloned) {
			if (comment!=null)  {
				res = new Attribute[] { loc,
						pf.mkCustomAttribute(ProgramFactory.Cloned), pf.mkCommentAttribute(comment)};

			} else {
				res = new Attribute[] { loc,
						pf.mkCustomAttribute(ProgramFactory.Cloned) };
			}
		} else {
			if (comment!=null)  {
				res = new Attribute[] { loc, pf.mkCommentAttribute(comment) };
			} else {
				res = new Attribute[] { loc };
			}
		}

		return res;
	}

	public static String getQualifiedName(SootClass c) {
		StringBuilder sb = new StringBuilder();
		sb.append(c.getName());
		return replaceIllegalChars(sb.toString());
	}

	public static String getQualifiedName(SootMethod m) {
		StringBuilder sb = new StringBuilder();
		sb.append(m.getReturnType().toString() + "$");
		sb.append(m.getDeclaringClass().getName() + "$");
		sb.append(m.getName() + "$");
		sb.append(m.getNumber());
		return replaceIllegalChars(sb.toString());
	}

	public static String getQualifiedName(Local l) {
		// TODO: check if the name is really unique
		StringBuilder sb = new StringBuilder();
		sb.append(replaceIllegalChars(l.getName()));

		sb.append(l.getNumber());
		return sb.toString();
	}

	public static String getQualifiedName(StaticFieldRef f) {
		return getQualifiedName(f.getField());
	}

	public static String getQualifiedName(SootField f) {
		StringBuilder sb = new StringBuilder();
		sb.append(f.getType() + "$");
		sb.append(f.getDeclaringClass().getName() + "$");
		sb.append(f.getName());
		sb.append(f.getNumber());
		return replaceIllegalChars(sb.toString());
	}

	public static String replaceIllegalChars(String s) {
		String ret = s.replace("<", "$la$");
		ret = ret.replace("@", "$at$");
		ret = ret.replace(">", "$ra$");
		ret = ret.replace("[", "$lp$");
		ret = ret.replace("]", "$rp$");
		ret = ret.replace("/", "$_$");
		ret = ret.replace(";", "$");
		return ret;
	}

	/**
	 * This is a helper function to cast between bool and int if soot does not
	 * distinguish them. TODO: extend to ref if necessary
	 *
	 * @param expr
	 * @param target
	 * @return
	 */
	public static Expression castBoogieTypes(Expression expr, BoogieType target) {
		if (expr.getType() == target) {
			return expr;
		} else if (expr.getType() == GlobalsCache.v().getPf().getIntType()
				&& target == GlobalsCache.v().getPf().getBoolType()) {
			return SootPrelude.v().intToBool(expr);
		} else if (expr.getType() == GlobalsCache.v().getPf().getBoolType()
				&& target == GlobalsCache.v().getPf().getIntType()) {
			return SootPrelude.v().boolToInt(expr);
		} else if (expr.getType() == GlobalsCache.v().getPf().getIntType()
				&& target == GlobalsCache.v().getPf().getRealType()) {
			return SootPrelude.v().intToReal(expr);
		} else if (expr.getType() == GlobalsCache.v().getPf().getRealType()
				&& target == GlobalsCache.v().getPf().getIntType()) {
			return SootPrelude.v().realToInt(expr);
		} else if (expr.getType() == SootPrelude.v().getReferenceType()
				&& target == GlobalsCache.v().getPf().getBoolType()) {
			return SootPrelude.v().refToBool(expr);
		} else if (expr == SootPrelude.v().getNullConstant()
				&& target == GlobalsCache.v().getPf().getRealType()) {
			return GlobalsCache.v().getPf().mkRealLiteral("0.0");
		} else if (expr == SootPrelude.v().getNullConstant()
				&& target == GlobalsCache.v().getPf().getIntType()) {
			return GlobalsCache.v().getPf().mkIntLiteral("0");
		}

		throw new RuntimeException("Cannot cast "
				+ expr.toString()
				+ " from: "
				+ ((expr.getType() == null) ? "null" : expr.getType()
						.getClass().toString()) + " to "
				+ target.getClass().toString());
		// return expr;
	}

}


text:
// Copyright (C) 2013 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 25.2
description: >
    Yield expressions are valid yield expression operands.
---*/

function* g() {
  yield yield 1;
}
var iter = g();
var result;

result = iter.next();
assert.sameValue(result.value, 1, 'First result `value`');
assert.sameValue(result.done, false, 'First result `done` flag');

result = iter.next(3);
assert.sameValue(result.value, 3, 'Second result `value`');
assert.sameValue(result.done, false, 'Second result `done` flag');

result = iter.next();
assert.sameValue(result.value, undefined, 'Final result `value`');
assert.sameValue(result.done, true, 'Final result `done`flag');


text:
import express from 'express'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import _ from 'lodash'

import router from './routes'
import config from './config'

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.header('Access-Control-Allow-Headers', 'x-access-token, content-type');
    next();
};

const app = express()
mongoose.Promise = global.Promise
mongoose.connect(config.database.url)

// configure app to use bodyParser()
// this will let us get the data from a POST

// allow CORS
app.use(allowCrossDomain);

//  do not check for authorization if OPTIONS
app.options('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.header('Access-Control-Allow-Headers', 'x-access-token, content-type');
    res.send(200);
});

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

const port = process.env.PORT || 3000

app.use('/api', router)
app.listen(port)

console.log(`Listening on port ${port}`)


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
     <!-- When selected, use grey -->
    <item android:drawable="@drawable/button_nomusic"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/button_music"
        android:state_checked="false"/>

</selector>
<!-- From: file:/home/quiin/Development/android/AndroidstudioProjects/GCrusher/app/src/main/res/drawable-xhdpi/check.xml -->


text:
<?xml version="1.0" encoding="iso-8859-1"?>

<project name="example" default="deploy">

    <property file="../../../config/common.properties"/>
    <import file="../../../config/common.xml" />

    <target name="deploy" depends="init,build_war,deploy_war" />
    <target name="undeploy" depends="init,undeploy_war,clean" />

    <target name="init">
        <property name="example_name" value="userTxExample" />
    </target>
</project>


text:
namespace weblayer {

namespace {

// Ignores origin security check. DownloadManagerImpl will provide its own
// implementation when InProgressDownloadManager object is passed to it.
bool IgnoreOriginSecurityCheck(const GURL& url) {
  return true;
}

void BindWakeLockProvider(
    mojo::PendingReceiver<device::mojom::WakeLockProvider> receiver) {
  content::GetDeviceService().BindWakeLockProvider(std::move(receiver));
}

}  // namespace

class ResourceContextImpl : public content::ResourceContext {
 public:
  ResourceContextImpl() = default;
  ~ResourceContextImpl() override = default;

 private:
  DISALLOW_COPY_AND_ASSIGN(ResourceContextImpl);
};

BrowserContextImpl::BrowserContextImpl(ProfileImpl* profile_impl,
                                       const base::FilePath& path)
    : profile_impl_(profile_impl),
      path_(path),
      resource_context_(new ResourceContextImpl()),
      download_delegate_(BrowserContext::GetDownloadManager(this)) {
  CreateUserPrefService();

  BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
      this);
}

BrowserContextImpl::~BrowserContextImpl() {
  NotifyWillBeDestroyed(this);

  BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
      this);
}

base::FilePath BrowserContextImpl::GetDefaultDownloadDirectory() {
  // Note: if we wanted to productionize this on Windows/Linux, refactor
  // src/chrome's GetDefaultDownloadDirectory.
  base::FilePath download_dir;
#if defined(OS_ANDROID)
  base::android::GetDownloadsDirectory(&download_dir);
#elif defined(OS_WIN)
  base::win::ScopedCoMem<wchar_t> path_buf;
  if (SUCCEEDED(
          SHGetKnownFolderPath(FOLDERID_Downloads, 0, nullptr, &path_buf))) {
    download_dir = base::FilePath(path_buf.get());
  } else {
    NOTREACHED();
  }
#else
  download_dir = base::nix::GetXDGUserDirectory("DOWNLOAD", "Downloads");
#endif
  return download_dir;
}

#if !defined(OS_ANDROID)
std::unique_ptr<content::ZoomLevelDelegate>
BrowserContextImpl::CreateZoomLevelDelegate(const base::FilePath&) {
  return nullptr;
}
#endif  // !defined(OS_ANDROID)

base::FilePath BrowserContextImpl::GetPath() {
  return path_;
}

bool BrowserContextImpl::IsOffTheRecord() {
  return path_.empty();
}

content::DownloadManagerDelegate*
BrowserContextImpl::GetDownloadManagerDelegate() {
  return &download_delegate_;
}

content::ResourceContext* BrowserContextImpl::GetResourceContext() {
  return resource_context_.get();
}

content::BrowserPluginGuestManager* BrowserContextImpl::GetGuestManager() {
  return nullptr;
}

storage::SpecialStoragePolicy* BrowserContextImpl::GetSpecialStoragePolicy() {
  return nullptr;
}

content::PushMessagingService* BrowserContextImpl::GetPushMessagingService() {
  return nullptr;
}

content::StorageNotificationService*
BrowserContextImpl::GetStorageNotificationService() {
  return nullptr;
}

content::SSLHostStateDelegate* BrowserContextImpl::GetSSLHostStateDelegate() {
  return StatefulSSLHostStateDelegateFactory::GetForBrowserContext(this);
}

content::PermissionControllerDelegate*
BrowserContextImpl::GetPermissionControllerDelegate() {
  return PermissionManagerFactory::GetForBrowserContext(this);
}

content::ClientHintsControllerDelegate*
BrowserContextImpl::GetClientHintsControllerDelegate() {
  return ClientHintsFactory::GetForBrowserContext(this);
}

content::BackgroundFetchDelegate*
BrowserContextImpl::GetBackgroundFetchDelegate() {
  return nullptr;
}

content::BackgroundSyncController*
BrowserContextImpl::GetBackgroundSyncController() {
  return nullptr;
}

content::BrowsingDataRemoverDelegate*
BrowserContextImpl::GetBrowsingDataRemoverDelegate() {
  return nullptr;
}

download::InProgressDownloadManager*
BrowserContextImpl::RetriveInProgressDownloadManager() {
  // Override this to provide a connection to the wake lock service.
  auto* download_manager = new download::InProgressDownloadManager(
      nullptr, path_,
      path_.empty()
          ? nullptr
          : GetDefaultStoragePartition(this)->GetProtoDatabaseProvider(),
      base::BindRepeating(&IgnoreOriginSecurityCheck),
      base::BindRepeating(&content::DownloadRequestUtils::IsURLSafe),
      base::BindRepeating(&BindWakeLockProvider));

#if defined(OS_ANDROID)
  download_manager->set_default_download_dir(GetDefaultDownloadDirectory());
#endif

  return download_manager;
}

content::ContentIndexProvider* BrowserContextImpl::GetContentIndexProvider() {
  return nullptr;
}

void BrowserContextImpl::CreateUserPrefService() {
  auto pref_registry = base::MakeRefCounted<user_prefs::PrefRegistrySyncable>();
  RegisterPrefs(pref_registry.get());

  PrefServiceFactory pref_service_factory;
  if (IsOffTheRecord()) {
    pref_service_factory.set_user_prefs(
        base::MakeRefCounted<InMemoryPrefStore>());
  } else {
    pref_service_factory.set_user_prefs(base::MakeRefCounted<JsonPrefStore>(
        path_.Append(FILE_PATH_LITERAL("Preferences"))));
  }
  {
    // Creating the prefs service may require reading the preferences from disk.
    base::ScopedAllowBlocking allow_io;
    user_pref_service_ = pref_service_factory.Create(pref_registry);
  }
  // Note: UserPrefs::Set also ensures that the user_pref_service_ has not
  // been set previously.
  user_prefs::UserPrefs::Set(this, user_pref_service_.get());
}

void BrowserContextImpl::RegisterPrefs(
    user_prefs::PrefRegistrySyncable* pref_registry) {
  // This pref is used by captive_portal::CaptivePortalService (as well as other
  // potential use cases in the future, as it is used for various purposes
  // through //chrome).
  pref_registry->RegisterBooleanPref(
      embedder_support::kAlternateErrorPagesEnabled, true);

  StatefulSSLHostStateDelegate::RegisterProfilePrefs(pref_registry);
  HostContentSettingsMap::RegisterProfilePrefs(pref_registry);
  safe_browsing::RegisterProfilePrefs(pref_registry);
  security_state::RegisterProfilePrefs(pref_registry);
  language::LanguagePrefs::RegisterProfilePrefs(pref_registry);
  translate::TranslatePrefs::RegisterProfilePrefs(pref_registry);
  pref_registry->RegisterBooleanPref(
      prefs::kOfferTranslateEnabled, true,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#if defined(OS_ANDROID)
  cdm::MediaDrmStorageImpl::RegisterProfilePrefs(pref_registry);
  permissions::GeolocationPermissionContextAndroid::RegisterProfilePrefs(
      pref_registry);
#endif

  BrowserContextDependencyManager::GetInstance()
      ->RegisterProfilePrefsForServices(pref_registry);
}

class BrowserContextImpl::WebLayerVariationsClient
    : public variations::VariationsClient {
 public:
  explicit WebLayerVariationsClient(content::BrowserContext* browser_context)
      : browser_context_(browser_context) {}

  ~WebLayerVariationsClient() override = default;

  bool IsIncognito() const override {
    return browser_context_->IsOffTheRecord();
  }

  std::string GetVariationsHeader() const override {
    return variations::VariationsHttpHeaderProvider::GetInstance()
        ->GetClientDataHeader(IsSignedIn());
  }

 private:
  bool IsSignedIn() const {
    // TODO(weblayer-dev): Update when signin is supported.
    return false;
  }

  content::BrowserContext* browser_context_;
};

variations::VariationsClient* BrowserContextImpl::GetVariationsClient() {
  if (!weblayer_variations_client_) {
    weblayer_variations_client_ =
        std::make_unique<WebLayerVariationsClient>(this);
  }
  return weblayer_variations_client_.get();
}

}  // namespace weblayer


text:
const webpackMerge = require('webpack-merge')
  , path = require('path')
  , fs = require('fs')
  , helpers = require('../../config/helpers')
  , projectConfig = require('./project.config')

/*
 * Webpack Constants
 */

module.exports = function (options) {

  var config;
  var env;

  switch (process.env.NODE_ENV) {
    case 'test':
      config = require('../../config/webpack.test');
      env = 'test';
      break;
    case 'prod':
    case 'production':
      config = require('../../config/webpack.prod');
      env = 'production';
      break;
    case 'dev':
    case 'development':
    default:
      config = require('../../config/webpack.dev');
      env = 'development';
      break;
  }

  options = webpackMerge(projectConfig, options || {});
  options['env'] = env;

  var webpackConfig = config(options);

  // console.log(webpackConfig);
  var mergeFile = helpers.root('webpack/webpack.merge.js')
  if (fs.existsSync(mergeFile)) {
    var exConfig = require(mergeFile);
    webpackConfig = webpackMerge(webpackConfig, exConfig(options));
  }

  // console.log(webpackConfig);

  return webpackConfig;
};


text:
#ifndef _SGWDYNSPEED_SGWDYNSPEED_H
#define _SGWDYNSPEED_SGWDYNSPEED_H

/* Plugin includes */

/* OLSR includes */

/* System includes */
#include <stdbool.h>

/*
 * Global
 */

/** The long plugin name */
#define SGWDYNSPEED_PLUGIN_NAME_LONG			"OLSRD Smart Gateway Dynamic Speed plugin"

/** The short plugin name / abbreviation */
#define SGWDYNSPEED_PLUGIN_ABBR					"SGWDYNSPEED"

/*
 *  Interface
 */

bool initSgwDynSpeed(void);
void stopSgwDynSpeed(void);

void sgwDynSpeedError(bool useErrno, const char *format, ...) __attribute__ ((format(printf, 2, 3)));

#endif /* _SGWDYNSPEED_SGWDYNSPEED_H */


text:
using System;
using ObjCRuntime;

namespace OpenId.AppAuth
{
	[Native]
	public enum ErrorCode : long
	{
		InvalidDiscoveryDocument = -2,
		UserCanceledAuthorizationFlow = -3,
		ProgramCanceledAuthorizationFlow = -4,
		NetworkError = -5,
		ServerError = -6,
		JSONDeserializationError = -7,
		TokenResponseConstructionError = -8,
		SafariOpenError = -9,
		BrowserOpenError = -10,
		TokenRefreshError = -11,
		RegistrationResponseConstructionError = -12,
		JSONSerializationError = -13,
	}

	[Native]
	public enum ErrorCodeOAuth : long
	{
		InvalidRequest = -2,
		UnauthorizedClient = -3,
		AccessDenied = -4,
		UnsupportedResponseType = -5,
		InvalidScope = -6,
		ServerError = -7,
		TemporarilyUnavailable = -8,
		InvalidClient = -9,
		InvalidGrant = -10,
		UnsupportedGrantType = -11,
		InvalidRedirectUri = -12,
		InvalidClientMetadata = -13,
		ClientError = -0xEFFF,
		Other = -0xF000
	}

	[Native]
	public enum ErrorCodeOAuthAuthorization : long
	{
		InvalidRequest = ErrorCodeOAuth.InvalidRequest,
		UnauthorizedClient = ErrorCodeOAuth.UnauthorizedClient,
		AccessDenied = ErrorCodeOAuth.AccessDenied,
		UnsupportedResponseType = ErrorCodeOAuth.UnsupportedResponseType,
		AuthorizationInvalidScope = ErrorCodeOAuth.InvalidScope,
		ServerError = ErrorCodeOAuth.ServerError,
		TemporarilyUnavailable = ErrorCodeOAuth.TemporarilyUnavailable,
		ClientError = ErrorCodeOAuth.ClientError,
		Other = ErrorCodeOAuth.Other
	}

	[Native]
	public enum ErrorCodeOAuthToken : long
	{
		InvalidRequest = ErrorCodeOAuth.InvalidRequest,
		InvalidClient = ErrorCodeOAuth.InvalidClient,
		InvalidGrant = ErrorCodeOAuth.InvalidGrant,
		UnauthorizedClient = ErrorCodeOAuth.UnauthorizedClient,
		UnsupportedGrantType = ErrorCodeOAuth.UnsupportedGrantType,
		InvalidScope = ErrorCodeOAuth.InvalidScope,
		ClientError = ErrorCodeOAuth.ClientError,
		Other = ErrorCodeOAuth.Other
	}

	[Native]
	public enum ErrorCodeOAuthRegistration : long
	{
		InvalidRequest = ErrorCodeOAuth.InvalidRequest,
		InvalidRedirectURI = ErrorCodeOAuth.InvalidRedirectUri,
		InvalidClientMetadata = ErrorCodeOAuth.InvalidClientMetadata,
		ClientError = ErrorCodeOAuth.ClientError,
		Other = ErrorCodeOAuth.Other
	}
}


text:
package pv3199.util;

/**
 * A binary tree stored in the form of a binary tree. This array is NOT self balancing.
 *
 * @param <E> a comparable data type
 */
public final class BinaryArray<E extends Comparable<E>> extends HeapImpl<E> {
	/**
	 * Constructs a BinaryArray with a default capacity of 7.
	 */
	public BinaryArray() {
		super();
	}

	/**
	 * Constructs a BinaryArray with a <i>desired</i> initial capacity. The
	 * given capacity is not always ensured because binary array's capacity must
	 * be some positive power of 2 minus 1. As such, the initial capacity is
	 * "rounded" down to the nearest such size.
	 *
	 * @param initialCapacity the desired initial capacity of the binary array.
	 */
	public BinaryArray(int initialCapacity) {
		super(initialCapacity);
	}

	@Override
	public void add(E e) {
		if (e == null) {
			throw new NullPointerException("nulls not allowed");
		}

		// get the best parent node index
		int parent = bestParent(e, 0);

		// if the parent index is less than 0, then we are adding the root
		// to the tree; otherwise we must insert this element to the left
		// subtree or right subtree of the parent node if the element is
		// less than or equal to the parent or greater than the parent
		// (respectively)
		if (parent < 0) {
			set(0, e);
		} else {
			// if the supposed left index of this parent is out of bounds,
			// the binary array must grow in size (we don't need to check
			// for the right index because the left index is less than the
			// right index
			if (refLeft(parent) >= this.data.length) {
				grow();
			}

			// insert element appropriately
			if (e.compareTo(get(parent)) <= 0) {
				setLeft(parent, e);
			} else {
				setRight(parent, e);
			}
		}
	}

	/**
	 * Gets the index of the best parent node for a given element.
	 *
	 * @param e the element to add.
	 * @param node the current node.
	 * @return the index of the best parent node for an element.
	 */
	private int bestParent(E e, int node) {
		// if the node doesn't exist, then return -1 (this should only
		// happen when the binary array is empty
		if (!exists(node)) {
			return -1;
		}

		// get the compare result, and get the left and right node indices of "node"
		int compare = e.compareTo(get(node));
		int left = refLeft(node);
		int right = refRight(node);

		if (compare <= 0 && exists(left)) {
			// best parent resides in the left subtree
			return bestParent(e, left);
		} else if (compare > 0 && exists(right)) {
			// best parent resides in right subtree
			return bestParent(e, right);
		} else {
			// this is the best parent
			return node;
		}
	}

	/**
	 * Checks if the binary array has an element.
	 *
	 * @param e the element.
	 * @return true if the array has the element.
	 */
	public boolean contains(E e) {
		return get(e, 0) >= 0;
	}

	/**
	 * Gets the index of an element.
	 *
	 * @param e the element.
	 * @param node the current node.
	 * @return the index of the element; -1 if not found
	 */
	private int get(E e, int node) {
		if (!exists(node)) {
			// node doesn't exist aka not found
			return -1;
		} else if (e.compareTo(get(node)) == 0) {
			// this is the node, return this index
			return node;
		} else if (e.compareTo(get(node)) < 0) {
			// node resides in left subtree
			return get(e, refLeft(node));
		} else {
			// node resides in right subtree
			return get(e, refRight(node));
		}
	}

	/**
	 * Removes an element from the binary array.
	 *
	 * @param e the element to remove.
	 * @return true if the element was removed (only possible if the
	 * element existed in the array).
	 */
	public boolean remove(E e) {
		// get the index of the element
		int node = get(e, 0);

		if (node < 0) {
			// node DNE
			return false;
		}

		remove(node);

		return true;
	}

	/**
	 * Removes a node from the binary array. 3 possible cases:
	 * node is a leaf, has only one child, or has two children.
	 *
	 * @param node the node index to remove.
	 */
	private void remove(int node) {
		if (isLeaf(node)) {
			leafRemoval(node);
		} else if (isSingle(node)) {
			singleRemoval(node);
		} else {
			doubleRemoval(node);
		}
	}

	/**
	 * Removes a leaf node.
	 *
	 * @param node the leaf node.
	 */
	private void leafRemoval(int node) {
		this.data[node] = null;

		/*if (node == 0) {
			// node is root, set root to null
			this.data[0] = null;
		} else {
			// get parent of node (it must have one since it's not the root)
			int parent = refParent(node);

			// if the left child of this parent is the node, set that
			// child to be null; similarly if it's the right child
			if (refLeft(parent) == node) {
				setLeft(parent, null);
			} else {
				setRight(parent, null);
			}
		}*/
	}

	/**
	 * Removes a node with only one child.
	 *
	 * @param node the node with only child.
	 */
	private void singleRemoval(int node) {
		// get parent of this node
		int parent = refParent(node);
		// get the only child of this node
		int child = exists(refRight(node)) ? refRight(node) : refLeft(node);

		if (node == 0) {
			// node is root, set root to be node's child
			this.data[0] = get(child);
		} else {
			// if node is right child of parent, set right child of parent
			// to be the only child of node; similarly if it's the left child
			if (refRight(parent) == node) {
				setRight(parent, get(child));
			} else {
				setLeft(parent, get(child));
			}
		}

		remove(child);

		// set the child index of this node to be null
		// this.data[child] = null;
	}

	/**
	 * Removes a node with two children.
	 *
	 * @param node the node with two children.
	 */
	private void doubleRemoval(int node) {
		// getting the smallest node on the right subtree of node
		int minSubRight = refRight(node);

		while (exists(refLeft(minSubRight))) {
			minSubRight = refLeft(minSubRight);
		}

		// set the node index to be it's smallest node on it's right subtree
		set(node, get(minSubRight));

		// remove minSubRight from tree appropriately (if it's leaf or single-child node)
		if (isLeaf(minSubRight)) {
			leafRemoval(minSubRight);
		} else {
			singleRemoval(minSubRight);
		}
	}
}