text:
import unittest
from gameplay.rock import Rock
from gameplay.player import Player
from gameplay.bullet import Bullet
from gameplay.field import Field
from gameplay.game import Game
from gui.user_interface import UserInterface
from gui.bullet_ui import BulletUI
from gui.powerup_ui import PowerupUI, PowerupType

class RockTest(unittest.TestCase):
    def setUp(self):
        self.rock = Rock()

    def test_getting_initial_rock_speed(self):
        initial_speed = 50
        self.assertEqual(initial_speed, self.rock.rock_speed)

    def test_setting_new_rock_speed(self):
        new_speed = 60
        self.rock.set_speed(new_speed)
        self.assertEqual(new_speed, self.rock.rock_speed)

class PlayerTest(unittest.TestCase):
    def setUp(self):
        self.player = Player()

    def test_check_initial_player_invinciblity(self):
        self.assertEqual(False, self.player.is_player_invincible)
        self.assertNotEqual(True, self.player.is_player_invincible)

    def test_getting_initial_player_speed(self):
        initial_speed = 10
        self.assertEqual(initial_speed, self.player.player_speed)

    def test_setting_player_invinciblity(self):
        self.player.set_player_invinciblity()
        self.assertEqual(True, self.player.is_player_invincible)
        self.assertNotEqual(False, self.player.is_player_invincible)
        self.player.set_player_invinciblity()
        self.assertEqual(False, self.player.is_player_invincible)
        self.assertNotEqual(True, self.player.is_player_invincible)

class BulletTest(unittest.TestCase):
    def setUp(self):
        self.bullet = Bullet()

    def test_getting_initial_bullet_speed(self):
        initial_speed = 50
        self.assertEqual(initial_speed, self.bullet.bullet_speed)

    def test_setting_new_bullet_speed(self):
        new_speed = 60
        self.bullet.set_speed(new_speed)
        self.assertEqual(new_speed, self.bullet.bullet_speed)

class GameTest(unittest.TestCase):
    def setUp(self):
        self.field = Field(1080, 800)
        self.game = Game(self.field)

    def check_game_field_dimensions(self):
        game_dimensions = (self.field.width, self.field.height)
        self.assertEqual(game_dimensions, self.game.dimensions)

    def test_checking_is_game_lost(self):
        self.assertEqual(False, self.game.is_lost)

    def test_checking_is_game_won(self):
        self.assertEqual(False, self.game.is_won)

    def test_checking_is_game_paused(self):
        self.assertEqual(False, self.game.is_paused)

    def test_checking_is_game_running(self):
        self.assertEqual(True, self.game.is_running)

    def test_checking_is_game_lost_after_losing(self):
        self.game.lose()
        self.assertEqual(True, self.game.is_lost)
        self.assertEqual(False, self.game.is_running)

    def test_checking_is_game_won_after_winning(self):
        self.game.win()
        self.assertEqual(True, self.game.is_won)
        self.assertEqual(False, self.game.is_lost)
        self.assertEqual(False, self.game.is_running)

    def test_checking_is_game_paused_after_pausing(self):
        self.game.pause()
        self.assertEqual(True, self.game.is_paused)
        self.assertEqual(False, self.game.is_running)

    def test_checking_is_game_running_after_resuming(self):
        self.game.resume()
        self.assertEqual(False, self.game.is_paused)
        self.assertEqual(True, self.game.is_running)

    def test_setting_new_game_speed(self):
        new_speed = 300
        self.game.set_speed(new_speed)
        self.assertEqual(new_speed, self.game.game_speed)

    def test_setting_new_rock_speed(self):
        new_speed = 30
        self.game.set_rock_speed(new_speed)
        self.assertEqual(new_speed, self.game.rock_speed)

    def test_leveling_up(self):
        current_level = self.game.level
        self.game.level_up()
        self.assertEqual(current_level + 1, self.game.level)

    def test_getting_initial_game_speed(self):
        initial_speed = 630
        self.assertEqual(initial_speed, self.game.game_speed)

    def test_getting_initial_bullet_speed(self):
        initial_speed = 50
        self.assertEqual(initial_speed, self.game.bullet_speed)

    def test_getting_initial_rock_speed(self):
        initial_speed = 50
        self.assertEqual(initial_speed, self.game.rock_speed)

    def test_getting_initial_level_speed(self):
        initial_speed = 30000
        self.assertEqual(initial_speed, self.game.level_speed)

    def test_getting_initial_level(self):
        initial_level = 1
        self.assertEqual(initial_level, self.game.level)

    def test_get_rock(self):
        rock = self.field.rock
        self.assertEqual(rock, self.game.rock)

    def test_get_bullet(self):
        bullet = self.field.bullet
        self.assertEqual(bullet, self.game.bullet)

    def test_get_powerup(self):
        powerup = self.field.powerup
        self.assertEqual(powerup, self.game.powerup)

    def test_get_player(self):
        player = self.field.player
        self.assertEqual(player, self.game.player)

    def test_get_rocks(self):
        rocks = self.field.rocks
        self.assertEqual(rocks, self.game.rocks)

    def test_get_bullets(self):
        bullets = self.field.bullets
        self.assertEqual(bullets, self.game.bullets)

    def test_get_powerups(self):
        powerups = self.field.powerups
        self.assertEqual(powerups, self.game.powerups)

    def test_resetting_game(self):
        self.game.reset_game_values()
        self.assertEqual(630, self.game.game_speed)
        self.assertEqual(30000, self.game.level_speed)
        self.assertEqual(1, self.game.level)
        self.assertEqual(50, self.game.rock_speed)

class FieldTest(unittest.TestCase):
    def setUp(self):
        self.field = Field(1080, 800)

    def test_getting_initial_bullet_speed(self):
        initial_speed = 50
        self.assertEqual(initial_speed, self.field.bullet.bullet_speed)

    def test_getting_initial_rock_speed(self):
        initial_speed = 50
        self.assertEqual(initial_speed, self.field.rock.rock_speed)

    def test_getting_initial_player_speed(self):
        initial_speed = 10
        self.assertEqual(initial_speed, self.field.player.player_speed)

class GUITest(unittest.TestCase):
    field = Field(1080, 800)
    game = Game(field)
    ui = UserInterface(game)
    ui.main_loop()
    main_window = UserInterface.get_main_window()

    def test_check_main_window_dimensions(self):
        main_window_height = UserInterface.get_main_window().height
        main_window_width = UserInterface.get_main_window().width
        self.assertEqual(1080, main_window_height)
        self.assertEqual(800, main_window_width)

    def test_bullet_moving_to_target(self):
        self.field_ui = GUITest.main_window.field_ui
        self.player_ui = self.field_ui.player_ui
        self.bullet_ui = BulletUI(GUITest.main_window,
                                  GUITest.game, self.player_ui)
        initial_y = self.bullet_ui.y
        self.bullet_ui.move_to_target()
        self.assertGreater(initial_y, self.bullet_ui.y)

    def test_check_pausing_the_game(self):
        self.field_ui = GUITest.main_window.field_ui
        self.field_ui.pause_game()
        self.assertEqual(True, GUITest.game.is_paused)

    def test_check_resuming_the_game(self):
        self.field_ui = GUITest.main_window.field_ui
        self.field_ui.resume_game()
        self.assertEqual(True, GUITest.game.is_running)

    def test_check_leveling_up(self):
        self.game = GUITest.game
        current_level = self.game.level
        self.game.level_up()
        self.assertLess(current_level, self.game.level)

    def test_check_winning_the_game(self):
        GUITest.main_window.field_ui.win_the_game()
        self.assertEqual(True, GUITest.game.is_won)

    def test_check_powerup_dropping_down(self):
        self.field_ui = GUITest.main_window.field_ui
        self.powerup_ui = PowerupUI(GUITest.main_window, GUITest.game,
                                    PowerupType.player_invinciblility)
        initial_y = self.powerup_ui.y
        self.powerup_ui.drop_down()
        self.assertLess(initial_y, self.powerup_ui.y)

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


text:
package org.apache.storm.hdfs.bolt.rotation;

import org.apache.storm.tuple.Tuple;

public class TimedRotationPolicy implements FileRotationPolicy {

    private long interval;

    public TimedRotationPolicy(float count, TimeUnit units) {
        this.interval = (long) (count * units.getMilliSeconds());
    }

    protected TimedRotationPolicy(long interval) {
        this.interval = interval;
    }

    /**
     * Called for every tuple the HdfsBolt executes.
     *
     * @param tuple  The tuple executed.
     * @param offset current offset of file being written
     * @return true if a file rotation should be performed
     */
    @Override
    public boolean mark(Tuple tuple, long offset) {
        return false;
    }

    /**
     * Called after the HdfsBolt rotates a file.
     */
    @Override
    public void reset() {

    }

    @Override
    public FileRotationPolicy copy() {
        return new TimedRotationPolicy(this.interval);
    }

    public long getInterval() {
        return this.interval;
    }

    public static enum TimeUnit {

        SECONDS((long) 1000),
        MINUTES((long) 1000 * 60),
        HOURS((long) 1000 * 60 * 60),
        DAYS((long) 1000 * 60 * 60 * 24);

        private long milliSeconds;

        private TimeUnit(long milliSeconds) {
            this.milliSeconds = milliSeconds;
        }

        public long getMilliSeconds() {
            return milliSeconds;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  UIView+Utility.m
//  OPNFileReader
//
//  Created by Shota Takai on 2015/05/11.
//  Copyright (c) 2015年 NRI Netcom. All rights reserved.
//

#import "UIView+Utility.h"

@implementation UIView(Utility)

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (CGFloat)x
{
    return self.frame.origin.x;
}

- (CGFloat)y
{
    return self.frame.origin.y;
}

- (CGFloat)width
{
    return self.frame.size.width;
}

- (CGFloat)height
{
    return self.frame.size.height;
}

- (void)setX:(CGFloat)x
{
    CGRect rect = self.frame;
    rect.origin.x = x;
    [self setFrame:rect];
}

- (void)setY:(CGFloat)y
{
    CGRect rect = self.frame;
    rect.origin.y = y;
    [self setFrame:rect];
}

- (void)setWidth:(CGFloat)width
{
    CGRect rect = self.frame;
    rect.size.width = width;
    [self setFrame:rect];
}

- (void)setHeight:(CGFloat)height
{
    CGRect rect = self.frame;
    rect.size.height = height;
    [self setFrame:rect];
}

@end


text:
import {CommonModule, HashLocationStrategy, Location, LocationStrategy} from '@angular/common';
import {SpyLocation} from '@angular/common/testing';
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, Injectable, NgModule, TemplateRef, Type, ViewChild, ViewContainerRef} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import {ChildrenOutletContexts, Resolve, Router, RouterOutlet} from '@angular/router';
import {RouterTestingModule} from '@angular/router/testing';
import {of} from 'rxjs';
import {delay, mapTo} from 'rxjs/operators';

import {provideRouterForTesting} from '../testing/src/provide_router_for_testing';

describe('Integration', () => {
  describe('routerLinkActive', () => {
    it('should update when the associated routerLinks change - #18469', fakeAsync(() => {
         @Component({
           template: `
          {{firstLink}}

            {{secondLink}}

           `,
         })
         class LinkComponent {
           firstLink = 'link-a';
           secondLink = 'link-b';

           changeLinks(): void {
             const temp = this.secondLink;
             this.secondLink = this.firstLink;
             this.firstLink = temp;
           }
         }

         @Component({template: 'simple'})
         class SimpleCmp {
         }

         TestBed.configureTestingModule({
           imports: [RouterTestingModule.withRoutes(
               [{path: 'link-a', component: SimpleCmp}, {path: 'link-b', component: SimpleCmp}])],
           declarations: [LinkComponent, SimpleCmp]
         });

         const router: Router = TestBed.inject(Router);
         const fixture = createRoot(router, LinkComponent);
         const firstLink = fixture.debugElement.query(p => p.nativeElement.id === 'first-link');
         const secondLink = fixture.debugElement.query(p => p.nativeElement.id === 'second-link');
         router.navigateByUrl('/link-a');
         advance(fixture);

         expect(firstLink.nativeElement.classList).toContain('active');
         expect(secondLink.nativeElement.classList).not.toContain('active');

         fixture.componentInstance.changeLinks();
         fixture.detectChanges();
         advance(fixture);

         expect(firstLink.nativeElement.classList).not.toContain('active');
         expect(secondLink.nativeElement.classList).toContain('active');
       }));

    it('should not cause infinite loops in the change detection - #15825', fakeAsync(() => {
         @Component({selector: 'simple', template: 'simple'})
         class SimpleCmp {
         }

         @Component({
           selector: 'some-root',
           template: `

          <ng-container *ngTemplateOutlet="tpl"></ng-container>

        <router-outlet></router-outlet>
        <ng-template #tpl>

        </ng-template>`
         })
         class MyCmp {
           show: boolean = false;
         }

         @NgModule({
           imports: [CommonModule, RouterTestingModule],
           declarations: [MyCmp, SimpleCmp],
         })
         class MyModule {
         }

         TestBed.configureTestingModule({imports: [MyModule]});

         const router: Router = TestBed.inject(Router);
         const fixture = createRoot(router, MyCmp);
         router.resetConfig([{path: 'simple', component: SimpleCmp}]);

         router.navigateByUrl('/simple');
         advance(fixture);

         const instance = fixture.componentInstance;
         instance.show = true;
         expect(() => advance(fixture)).not.toThrow();
       }));

    it('should set isActive right after looking at its children -- #18983', fakeAsync(() => {
         @Component({
           template: `

            isActive: {{rla.isActive}}

            <ng-template let-data>
              link
            </ng-template>

            <ng-container #container></ng-container>

        `
         })
         class ComponentWithRouterLink {
           // TODO(issue/24571): remove '!'.
           @ViewChild(TemplateRef, {static: true}) templateRef!: TemplateRef<any>;
           // TODO(issue/24571): remove '!'.
           @ViewChild('container', {read: ViewContainerRef, static: true})
           container!: ViewContainerRef;

           addLink() {
             this.container.createEmbeddedView(this.templateRef, {$implicit: '/simple'});
           }

           removeLink() {
             this.container.clear();
           }
         }

         @Component({template: 'simple'})
         class SimpleCmp {
         }

         TestBed.configureTestingModule({
           imports: [RouterTestingModule.withRoutes([{path: 'simple', component: SimpleCmp}])],
           declarations: [ComponentWithRouterLink, SimpleCmp]
         });

         const router: Router = TestBed.inject(Router);
         const fixture = createRoot(router, ComponentWithRouterLink);
         router.navigateByUrl('/simple');
         advance(fixture);

         fixture.componentInstance.addLink();
         fixture.detectChanges();

         fixture.componentInstance.removeLink();
         advance(fixture);
         advance(fixture);

         expect(fixture.nativeElement.innerHTML).toContain('isActive: false');
       }));

    it('should set isActive with OnPush change detection - #19934', fakeAsync(() => {
         @Component({
           template: `

               isActive: {{rla.isActive}}

           `,
           changeDetection: ChangeDetectionStrategy.OnPush
         })
         class OnPushComponent {
         }

         @Component({template: 'simple'})
         class SimpleCmp {
         }

         TestBed.configureTestingModule({
           imports: [RouterTestingModule.withRoutes([{path: 'simple', component: SimpleCmp}])],
           declarations: [OnPushComponent, SimpleCmp]
         });

         const router: Router = TestBed.get(Router);
         const fixture = createRoot(router, OnPushComponent);
         router.navigateByUrl('/simple');
         advance(fixture);

         expect(fixture.nativeElement.innerHTML).toContain('isActive: true');
       }));
  });

  it('should not reactivate a deactivated outlet when destroyed and recreated - #41379',
     fakeAsync(() => {
       @Component({template: 'simple'})
       class SimpleComponent {
       }

       @Component({template: ` <router-outlet *ngIf="outletVisible" name="aux"></router-outlet> `})
       class AppComponent {
         outletVisible = true;
       }

       TestBed.configureTestingModule({
         imports: [RouterTestingModule.withRoutes(
             [{path: ':id', component: SimpleComponent, outlet: 'aux'}])],
         declarations: [SimpleComponent, AppComponent],
       });

       const router = TestBed.inject(Router);
       const fixture = createRoot(router, AppComponent);
       const componentCdr = fixture.componentRef.injector.get<ChangeDetectorRef>(ChangeDetectorRef);

       router.navigate([{outlets: {aux: ['1234']}}]);
       advance(fixture);
       expect(fixture.nativeElement.innerHTML).toContain('simple');

       router.navigate([{outlets: {aux: null}}]);
       advance(fixture);
       expect(fixture.nativeElement.innerHTML).not.toContain('simple');

       fixture.componentInstance.outletVisible = false;
       componentCdr.detectChanges();
       expect(fixture.nativeElement.innerHTML).not.toContain('simple');
       expect(fixture.nativeElement.innerHTML).not.toContain('router-outlet');

       fixture.componentInstance.outletVisible = true;
       componentCdr.detectChanges();
       expect(fixture.nativeElement.innerHTML).toContain('router-outlet');
       expect(fixture.nativeElement.innerHTML).not.toContain('simple');
     }));

  describe('useHash', () => {
    it('should restore hash to match current route - #28561', fakeAsync(() => {
         @Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`})
         class RootCmp {
         }

         @Component({template: 'simple'})
         class SimpleCmp {
         }
         @Component({template: 'one'})
         class OneCmp {
         }

         TestBed.configureTestingModule({
           imports: [RouterTestingModule.withRoutes([
             {path: '', component: SimpleCmp},
             {path: 'one', component: OneCmp, canActivate: ['returnRootUrlTree']}
           ])],
           declarations: [SimpleCmp, RootCmp, OneCmp],
           providers: [
             {
               provide: 'returnRootUrlTree',
               useFactory: (router: Router) => () => {
                 return router.parseUrl('/');
               },
               deps: [Router]
             },
           ],
         });

         const router = TestBed.inject(Router);
         const location = TestBed.inject(Location) as SpyLocation;

         router.navigateByUrl('/');
         // Will setup location change listeners
         const fixture = createRoot(router, RootCmp);

         location.simulateHashChange('/one');
         advance(fixture);

         expect(location.path()).toEqual('/');
         expect(fixture.nativeElement.innerHTML).toContain('one');
       }));
  });

  describe('duplicate navigation handling (#43447, #43446)', () => {
    let location: SpyLocation;
    let router: Router;
    let fixture: ComponentFixture<{}>;

    beforeEach(fakeAsync(() => {
      @Injectable()
      class DelayedResolve implements Resolve<{}> {
        resolve() {
          return of('').pipe(delay(1000), mapTo(true));
        }
      }
      @Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`})
      class RootCmp {
      }

      @Component({template: 'simple'})
      class SimpleCmp {
      }
      @Component({template: 'one'})
      class OneCmp {
      }
      TestBed.configureTestingModule({
        declarations: [SimpleCmp, RootCmp, OneCmp],
        imports: [RouterOutlet],
        providers: [
          DelayedResolve,
          provideRouterForTesting(
              [
                {path: '', component: SimpleCmp},
                {path: 'one', component: OneCmp, resolve: {x: DelayedResolve}}
              ],
              ),
          {provide: LocationStrategy, useClass: HashLocationStrategy},
        ],
      });

      router = TestBed.inject(Router);
      location = TestBed.inject(Location) as SpyLocation;

      router.navigateByUrl('/');
      // Will setup location change listeners
      fixture = createRoot(router, RootCmp);
    }));

    it('duplicate navigation to same url', fakeAsync(() => {
         location.simulateHashChange('/one');
         tick(100);
         location.simulateHashChange('/one');
         tick(1000);
         advance(fixture);

         expect(location.path()).toEqual('/one');
         expect(fixture.nativeElement.innerHTML).toContain('one');
       }));

    it('works with a duplicate popstate/hashchange navigation (as seen in firefox)',
       fakeAsync(() => {
         (location as any)._subject.emit({'url': 'one', 'pop': true, 'type': 'popstate'});
         tick(1);
         (location as any)._subject.emit({'url': 'one', 'pop': true, 'type': 'hashchange'});
         tick(1000);
         advance(fixture);

         expect(router.routerState.toString()).toContain(`url:'one'`);
         expect(fixture.nativeElement.innerHTML).toContain('one');
       }));
  });

  it('should not unregister outlet if a different one already exists #36711, 32453', async () => {
    @Component({
      template: `
      <router-outlet *ngIf="outlet1"></router-outlet>
      <router-outlet *ngIf="outlet2"></router-outlet>
      `,
    })
    class TestCmp {
      outlet1 = true;
      outlet2 = false;
    }

    @Component({template: ''})
    class EmptyCmp {
    }

    TestBed.configureTestingModule({
      imports: [CommonModule, RouterTestingModule.withRoutes([{path: '**', component: EmptyCmp}])],
      declarations: [TestCmp, EmptyCmp]
    });
    const fixture = TestBed.createComponent(TestCmp);
    const contexts = TestBed.inject(ChildrenOutletContexts);
    await TestBed.inject(Router).navigateByUrl('/');
    fixture.detectChanges();

    expect(contexts.getContext('primary')).toBeDefined();
    expect(contexts.getContext('primary')?.outlet).not.toBeNull();

    // Show the second outlet. Applications shouldn't really have more than one outlet but there can
    // be timing issues between destroying and recreating a second one in some cases:
    // https://github.com/angular/angular/issues/36711,
    // https://github.com/angular/angular/issues/32453
    fixture.componentInstance.outlet2 = true;
    fixture.detectChanges();
    expect(contexts.getContext('primary')?.outlet).not.toBeNull();

    fixture.componentInstance.outlet1 = false;
    fixture.detectChanges();
    // Destroying the first one show not clear the outlet context because the second one takes over
    // as the registered outlet.
    expect(contexts.getContext('primary')?.outlet).not.toBeNull();
  });
});

function advance<T>(fixture: ComponentFixture<T>): void {
  tick();
  fixture.detectChanges();
}

function createRoot<T>(router: Router, type: Type<T>): ComponentFixture<T> {
  const f = TestBed.createComponent(type);
  advance(f);
  router.initialNavigation();
  advance(f);
  return f;
}


text:
class Buffer {
  char* buffer_;
  int   storage_;
  int   length_;

  Buffer(const Buffer&);
  Buffer& operator =(const Buffer&);
public:
  enum {
    kDefaultStorage = 16 * 1024,
    kLimitedStorage = 1024 * 1024,
  };
  explicit Buffer(void);
  ~Buffer(void);

  inline const char* buffer(void) const
  {
    return buffer_;
  }

  inline int length(void) const
  {
    return length_;
  }

  inline char* free_buffer(void) const
  {
    return buffer_ + length_;
  }

  inline int free_length(void) const
  {
    return storage_ - length_;
  }

  inline int storage(void) const
  {
    return storage_;
  }
public:
  bool Init(int storage = kDefaultStorage);
  void Destroy(void);

  int Put(const char* buffer, int bytes);
  int Get(int bytes, char* buffer);
  int Increment(int bytes);
  int Decrement(int bytes);

  bool Regrow(void);
};

#endif  //! __BUFFER_HEADER_H__


text:
Collect.DataCleansingStepValueService = function() {
	Collect.AbstractService.apply(this, arguments);
	this.contextPath = "api/datacleansing/datacleansingstepvalues";
};

Collect.DataCleansingStepValueService.prototype = Object.create(Collect.AbstractService.prototype);


text:
namespace Scada.Admin.App.Forms
{
    partial class FrmTableImport
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.lblTable = new System.Windows.Forms.Label();
            this.cbTable = new System.Windows.Forms.ComboBox();
            this.gbSrcIDs = new System.Windows.Forms.GroupBox();
            this.chkSrcEndID = new System.Windows.Forms.CheckBox();
            this.chkSrcStartID = new System.Windows.Forms.CheckBox();
            this.numSrcEndID = new System.Windows.Forms.NumericUpDown();
            this.lblSrcEndID = new System.Windows.Forms.Label();
            this.numSrcStartID = new System.Windows.Forms.NumericUpDown();
            this.lblSrcStartID = new System.Windows.Forms.Label();
            this.lblSrcFile = new System.Windows.Forms.Label();
            this.btnImport = new System.Windows.Forms.Button();
            this.btnClose = new System.Windows.Forms.Button();
            this.txtSrcFile = new System.Windows.Forms.TextBox();
            this.btnBrowse = new System.Windows.Forms.Button();
            this.gbDestIDs = new System.Windows.Forms.GroupBox();
            this.chkDestStartID = new System.Windows.Forms.CheckBox();
            this.numDestEndID = new System.Windows.Forms.NumericUpDown();
            this.lblDestEndID = new System.Windows.Forms.Label();
            this.numDestStartID = new System.Windows.Forms.NumericUpDown();
            this.lblDestStartID = new System.Windows.Forms.Label();
            this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
            this.gbSrcIDs.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numSrcEndID)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.numSrcStartID)).BeginInit();
            this.gbDestIDs.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numDestEndID)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.numDestStartID)).BeginInit();
            this.SuspendLayout();
            //
            // lblTable
            //
            this.lblTable.AutoSize = true;
            this.lblTable.Location = new System.Drawing.Point(9, 9);
            this.lblTable.Name = "lblTable";
            this.lblTable.Size = new System.Drawing.Size(34, 13);
            this.lblTable.TabIndex = 0;
            this.lblTable.Text = "Table";
            //
            // cbTable
            //
            this.cbTable.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbTable.FormattingEnabled = true;
            this.cbTable.Location = new System.Drawing.Point(12, 25);
            this.cbTable.Name = "cbTable";
            this.cbTable.Size = new System.Drawing.Size(310, 21);
            this.cbTable.TabIndex = 1;
            //
            // gbSrcIDs
            //
            this.gbSrcIDs.Controls.Add(this.chkSrcEndID);
            this.gbSrcIDs.Controls.Add(this.chkSrcStartID);
            this.gbSrcIDs.Controls.Add(this.numSrcEndID);
            this.gbSrcIDs.Controls.Add(this.lblSrcEndID);
            this.gbSrcIDs.Controls.Add(this.numSrcStartID);
            this.gbSrcIDs.Controls.Add(this.lblSrcStartID);
            this.gbSrcIDs.Location = new System.Drawing.Point(12, 93);
            this.gbSrcIDs.Name = "gbSrcIDs";
            this.gbSrcIDs.Padding = new System.Windows.Forms.Padding(10, 3, 10, 10);
            this.gbSrcIDs.Size = new System.Drawing.Size(310, 65);
            this.gbSrcIDs.TabIndex = 5;
            this.gbSrcIDs.TabStop = false;
            this.gbSrcIDs.Text = "Source IDs";
            //
            // chkSrcEndID
            //
            this.chkSrcEndID.AutoSize = true;
            this.chkSrcEndID.Location = new System.Drawing.Point(158, 35);
            this.chkSrcEndID.Name = "chkSrcEndID";
            this.chkSrcEndID.Size = new System.Drawing.Size(15, 14);
            this.chkSrcEndID.TabIndex = 4;
            this.chkSrcEndID.UseVisualStyleBackColor = true;
            this.chkSrcEndID.CheckedChanged += new System.EventHandler(this.chkSrcEndID_CheckedChanged);
            //
            // chkSrcStartID
            //
            this.chkSrcStartID.AutoSize = true;
            this.chkSrcStartID.Location = new System.Drawing.Point(13, 35);
            this.chkSrcStartID.Name = "chkSrcStartID";
            this.chkSrcStartID.Size = new System.Drawing.Size(15, 14);
            this.chkSrcStartID.TabIndex = 1;
            this.chkSrcStartID.UseVisualStyleBackColor = true;
            this.chkSrcStartID.CheckedChanged += new System.EventHandler(this.chkSrcStartID_CheckedChanged);
            //
            // numSrcEndID
            //
            this.numSrcEndID.Enabled = false;
            this.numSrcEndID.Location = new System.Drawing.Point(179, 32);
            this.numSrcEndID.Maximum = new decimal(new int[] {
            2147483647,
            0,
            0,
            0});
            this.numSrcEndID.Name = "numSrcEndID";
            this.numSrcEndID.Size = new System.Drawing.Size(118, 20);
            this.numSrcEndID.TabIndex = 5;
            this.numSrcEndID.ValueChanged += new System.EventHandler(this.num_ValueChanged);
            //
            // lblSrcEndID
            //
            this.lblSrcEndID.AutoSize = true;
            this.lblSrcEndID.Location = new System.Drawing.Point(176, 16);
            this.lblSrcEndID.Name = "lblSrcEndID";
            this.lblSrcEndID.Size = new System.Drawing.Size(26, 13);
            this.lblSrcEndID.TabIndex = 3;
            this.lblSrcEndID.Text = "End";
            //
            // numSrcStartID
            //
            this.numSrcStartID.Enabled = false;
            this.numSrcStartID.Location = new System.Drawing.Point(34, 32);
            this.numSrcStartID.Maximum = new decimal(new int[] {
            2147483647,
            0,
            0,
            0});
            this.numSrcStartID.Name = "numSrcStartID";
            this.numSrcStartID.Size = new System.Drawing.Size(118, 20);
            this.numSrcStartID.TabIndex = 2;
            this.numSrcStartID.ValueChanged += new System.EventHandler(this.num_ValueChanged);
            //
            // lblSrcStartID
            //
            this.lblSrcStartID.AutoSize = true;
            this.lblSrcStartID.Location = new System.Drawing.Point(31, 16);
            this.lblSrcStartID.Name = "lblSrcStartID";
            this.lblSrcStartID.Size = new System.Drawing.Size(29, 13);
            this.lblSrcStartID.TabIndex = 0;
            this.lblSrcStartID.Text = "Start";
            //
            // lblSrcFile
            //
            this.lblSrcFile.AutoSize = true;
            this.lblSrcFile.Location = new System.Drawing.Point(9, 49);
            this.lblSrcFile.Name = "lblSrcFile";
            this.lblSrcFile.Size = new System.Drawing.Size(57, 13);
            this.lblSrcFile.TabIndex = 2;
            this.lblSrcFile.Text = "Source file";
            //
            // btnImport
            //
            this.btnImport.Location = new System.Drawing.Point(166, 235);
            this.btnImport.Name = "btnImport";
            this.btnImport.Size = new System.Drawing.Size(75, 23);
            this.btnImport.TabIndex = 7;
            this.btnImport.Text = "Import";
            this.btnImport.UseVisualStyleBackColor = true;
            this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
            //
            // btnClose
            //
            this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.btnClose.Location = new System.Drawing.Point(247, 235);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(75, 23);
            this.btnClose.TabIndex = 8;
            this.btnClose.Text = "Close";
            this.btnClose.UseVisualStyleBackColor = true;
            //
            // txtSrcFile
            //
            this.txtSrcFile.Location = new System.Drawing.Point(12, 65);
            this.txtSrcFile.Name = "txtSrcFile";
            this.txtSrcFile.Size = new System.Drawing.Size(229, 20);
            this.txtSrcFile.TabIndex = 3;
            //
            // btnBrowse
            //
            this.btnBrowse.Location = new System.Drawing.Point(247, 64);
            this.btnBrowse.Name = "btnBrowse";
            this.btnBrowse.Size = new System.Drawing.Size(75, 23);
            this.btnBrowse.TabIndex = 4;
            this.btnBrowse.Text = "Browse...";
            this.btnBrowse.UseVisualStyleBackColor = true;
            this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
            //
            // gbDestIDs
            //
            this.gbDestIDs.Controls.Add(this.chkDestStartID);
            this.gbDestIDs.Controls.Add(this.numDestEndID);
            this.gbDestIDs.Controls.Add(this.lblDestEndID);
            this.gbDestIDs.Controls.Add(this.numDestStartID);
            this.gbDestIDs.Controls.Add(this.lblDestStartID);
            this.gbDestIDs.Location = new System.Drawing.Point(12, 164);
            this.gbDestIDs.Name = "gbDestIDs";
            this.gbDestIDs.Padding = new System.Windows.Forms.Padding(10, 3, 10, 10);
            this.gbDestIDs.Size = new System.Drawing.Size(310, 65);
            this.gbDestIDs.TabIndex = 6;
            this.gbDestIDs.TabStop = false;
            this.gbDestIDs.Text = "Destination IDs";
            //
            // chkDestStartID
            //
            this.chkDestStartID.AutoSize = true;
            this.chkDestStartID.Location = new System.Drawing.Point(13, 35);
            this.chkDestStartID.Name = "chkDestStartID";
            this.chkDestStartID.Size = new System.Drawing.Size(15, 14);
            this.chkDestStartID.TabIndex = 1;
            this.chkDestStartID.UseVisualStyleBackColor = true;
            this.chkDestStartID.CheckedChanged += new System.EventHandler(this.chkDestStartID_CheckedChanged);
            //
            // numDestEndID
            //
            this.numDestEndID.Increment = new decimal(new int[] {
            0,
            0,
            0,
            0});
            this.numDestEndID.Location = new System.Drawing.Point(179, 32);
            this.numDestEndID.Maximum = new decimal(new int[] {
            2147483647,
            0,
            0,
            0});
            this.numDestEndID.Name = "numDestEndID";
            this.numDestEndID.ReadOnly = true;
            this.numDestEndID.Size = new System.Drawing.Size(118, 20);
            this.numDestEndID.TabIndex = 4;
            //
            // lblDestEndID
            //
            this.lblDestEndID.AutoSize = true;
            this.lblDestEndID.Location = new System.Drawing.Point(176, 16);
            this.lblDestEndID.Name = "lblDestEndID";
            this.lblDestEndID.Size = new System.Drawing.Size(26, 13);
            this.lblDestEndID.TabIndex = 3;
            this.lblDestEndID.Text = "End";
            //
            // numDestStartID
            //
            this.numDestStartID.Enabled = false;
            this.numDestStartID.Location = new System.Drawing.Point(34, 32);
            this.numDestStartID.Maximum = new decimal(new int[] {
            2147483647,
            0,
            0,
            0});
            this.numDestStartID.Name = "numDestStartID";
            this.numDestStartID.Size = new System.Drawing.Size(118, 20);
            this.numDestStartID.TabIndex = 2;
            this.numDestStartID.ValueChanged += new System.EventHandler(this.num_ValueChanged);
            //
            // lblDestStartID
            //
            this.lblDestStartID.AutoSize = true;
            this.lblDestStartID.Location = new System.Drawing.Point(31, 16);
            this.lblDestStartID.Name = "lblDestStartID";
            this.lblDestStartID.Size = new System.Drawing.Size(29, 13);
            this.lblDestStartID.TabIndex = 0;
            this.lblDestStartID.Text = "Start";
            //
            // openFileDialog
            //
            this.openFileDialog.Filter = "Tables (*.dat;*.xml)|*.dat;*.xml|All Files (*.*)|*.*";
            //
            // FrmTableImport
            //
            this.AcceptButton = this.btnImport;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.btnClose;
            this.ClientSize = new System.Drawing.Size(334, 270);
            this.Controls.Add(this.gbDestIDs);
            this.Controls.Add(this.btnBrowse);
            this.Controls.Add(this.txtSrcFile);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.btnImport);
            this.Controls.Add(this.lblSrcFile);
            this.Controls.Add(this.gbSrcIDs);
            this.Controls.Add(this.cbTable);
            this.Controls.Add(this.lblTable);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FrmTableImport";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Import Table";
            this.Load += new System.EventHandler(this.FrmTableImport_Load);
            this.gbSrcIDs.ResumeLayout(false);
            this.gbSrcIDs.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numSrcEndID)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.numSrcStartID)).EndInit();
            this.gbDestIDs.ResumeLayout(false);
            this.gbDestIDs.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numDestEndID)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.numDestStartID)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label lblTable;
        private System.Windows.Forms.ComboBox cbTable;
        private System.Windows.Forms.GroupBox gbSrcIDs;
        private System.Windows.Forms.Label lblSrcFile;
        private System.Windows.Forms.CheckBox chkSrcEndID;
        private System.Windows.Forms.CheckBox chkSrcStartID;
        private System.Windows.Forms.NumericUpDown numSrcEndID;
        private System.Windows.Forms.Label lblSrcEndID;
        private System.Windows.Forms.NumericUpDown numSrcStartID;
        private System.Windows.Forms.Label lblSrcStartID;
        private System.Windows.Forms.Button btnImport;
        private System.Windows.Forms.Button btnClose;
        private System.Windows.Forms.TextBox txtSrcFile;
        private System.Windows.Forms.Button btnBrowse;
        private System.Windows.Forms.GroupBox gbDestIDs;
        private System.Windows.Forms.CheckBox chkDestStartID;
        private System.Windows.Forms.NumericUpDown numDestEndID;
        private System.Windows.Forms.Label lblDestEndID;
        private System.Windows.Forms.NumericUpDown numDestStartID;
        private System.Windows.Forms.Label lblDestStartID;
        private System.Windows.Forms.OpenFileDialog openFileDialog;
    }
}


text: gennitor-mvn-repo


text:
package algorithm.lintcode.easy;

public class RemoveNthNodeFromEndOfList {
    public static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
            this.next = null;
        }
    }

    ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode emptyHead = new ListNode(0);
        emptyHead.next = head;
        ListNode target = emptyHead;
        ListNode pos = moveRight(emptyHead, n);
        while (isNotLastNode(pos)) {
            target = target.next;
            pos = pos.next;
        }
        removeNextNode(target);
        return emptyHead.next;
    }

    private ListNode moveRight(ListNode currentNode, int n) {
        ListNode target = currentNode;
        for (int i = 0; i < n; i++) {
            target = target.next;
        }
        return target;
    }

    private boolean isNotLastNode(ListNode node) {
        return node.next != null;
    }

    private void removeNextNode(ListNode currentNode) {
        currentNode.next = currentNode.next.next;
    }
}


text:
=head1 LICENSE

See the NOTICE file distributed with this work for additional information
regarding copyright ownership.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

Bio::EnsEMBL::Compara::HAL::HALXS::HALAdaptor

=cut

package Bio::EnsEMBL::Compara::HAL::HALXS::HALAdaptor;

use strict;
use warnings;
no warnings 'uninitialized';

BEGIN {
    use File::Spec;
    my ($volume, $directory, $file) = File::Spec->splitpath(__FILE__);
    unshift @INC, "$volume$directory/lib"; # path to HALXS.xs
    unshift @INC, "$volume$directory/blib/arch"; # path to built .so file
}

use Carp;
use ExtUtils::testlib;
use HALXS;

=head2 new

  Arg [1]    : list of args to super class constructor
  Example    : $ga_a = Bio::EnsEMBL::Compara::HAL::HALAdaptor->new("/tmp/test.hal");
  Description: Creates a new HALAdaptor from an lod.txt file or hal file.
  Returntype : none
  Exceptions : none

=cut

sub new {
    my($class, $path, $use_hal_genomes) = @_;
    my $self = {};
    bless $self, $class;
    unless (-r $path) {
        if (-e $path) {
            die "'$path' cannot be read";
        } else {
            die "'$path' doesn\'t exist";
        }
    }
    $self->{'hal_fd'} = HALXS::_open_hal($path);
    # if (defined $use_hal_genomes && $use_hal_genomes) {
    #     $self->{'use_hal_genomes'} = 1;
    # } else {
    #     $self->{'use_hal_genomes'} = 0;
    # }

    return $self;
}

# sub path {
#     my $self = shift;
#     return $self->{'path'};
# }

sub hal_filehandle {
    my $self = shift;
    return $self->{'hal_fd'};
}

sub genome_metadata {
    my ($self, $genome) = @_;
    return HALXS::_get_genome_metadata($self->{'hal_fd'}, $genome);
}

sub genomes {
    my $self = shift;
    return HALXS::_get_genome_names($self->{'hal_fd'});
}

sub seqs_in_genome {
    my ($self, $genome) = @_;
    return HALXS::_get_seqs_in_genome($self->{'hal_fd'}, $genome);
}

sub msa_blocks {
    my ( $self, $targets_str, $ref, $hal_seq_reg, $start, $end, $max_ref_gap, $max_block_length ) = @_;
    # Default values from hal2maf
    $max_ref_gap ||= 0;
    $max_block_length ||= 1000;
    confess "Need some target species" unless $targets_str;
    return HALXS::_get_multiple_aln_blocks( $self->{'hal_fd'}, $targets_str, $ref, $hal_seq_reg, $start, $end, $max_ref_gap, $max_block_length );
}

sub pairwise_blocks {
    my ( $self, $target, $ref, $hal_seq_reg, $start, $end, $target_seq_reg ) = @_;

    confess "Need the name of the target species" unless $target;
    my @blocks;
    if ( $target_seq_reg ){
        @blocks = HALXS::_get_pairwise_blocks_filtered($self->{'hal_fd'}, $target, $ref, $hal_seq_reg, $start, $end, $target_seq_reg);
    }
    else {
        @blocks = HALXS::_get_pairwise_blocks($self->{'hal_fd'}, $target, $ref, $hal_seq_reg, $start, $end);
    }

    return \@blocks;
}

1;


text:
#ifndef _SPOON_INTERFACE_FONT_H
#define _SPOON_INTERFACE_FONT_H

#include <types.h>
#include <spoon/support/String.h>

/** \ingroup interface
 *
 */
class Font
{
	public:
		Font( const char *fontName, const char fontFamily );

		int StringWidth(const char *string) const;
		int StringWidth(const char *string, int32 length) const;

		String	FontName();
		String	FontFamily();
		int		FontSize();
		unsigned int	FontFace();

		void	SetFace( unsigned int face );

	private:
		String 	_fontName;
		String 	_fontFamily;
		int		_fontSize;
		unsigned int	_fontFace;

};

#endif


text:
package team1;

import battlecode.common.RobotController;

public class Barracks extends Building  {

	public Barracks(RobotController rc) {
		super(rc);
		basic_turn_loop();
	}
}


text:
<?php

namespace Ticketmatic\Model;

use Ticketmatic\Json;

/**
 * Defines which fees are active for specific price types and sales channels.
 * It's possible to define a fixed fee and a percentage based fee. The default rule
 * (if none is specified for a specific sales channel) is always a fixed fee of 0.
 *
 * ## Help Center
 *
 * Full documentation can be found in the Ticketmatic Help Center
 * (https://apps.ticketmatic.com/#/knowledgebase/api/types/TicketfeeRules).
 */
class TicketfeeRules implements \jsonSerializable
{
    /**
     * Create a new TicketfeeRules
     *
     * @param array $data
     */
    public function __construct(array $data = array()) {
        foreach ($data as $key => $value) {
            $this->$key = $value;
        }
    }

    /**
     * The default ticket fee rule, one rule for each saleschannel.
     *
     * @var \Ticketmatic\Model\TicketfeeSaleschannelRule[]
     */
    public $default;

    /**
     * An array of exception rules for specific pricetypes.
     *
     * @var \Ticketmatic\Model\TicketfeeException[]
     */
    public $exceptions;

    /**
     * Unpack TicketfeeRules from JSON.
     *
     * @param object $obj
     *
     * @return \Ticketmatic\Model\TicketfeeRules
     */
    public static function fromJson($obj) {
        if ($obj === null) {
            return null;
        }

        return new TicketfeeRules(array(
            "default" => isset($obj->default) ? Json::unpackArray("TicketfeeSaleschannelRule", $obj->default) : null,
            "exceptions" => isset($obj->exceptions) ? Json::unpackArray("TicketfeeException", $obj->exceptions) : null,
        ));
    }

    /**
     * Serialize TicketfeeRules to JSON.
     *
     * @return array
     */
    public function jsonSerialize() {
        $result = array();
        if (!is_null($this->default)) {
            $result["default"] = $this->default;
        }
        if (!is_null($this->exceptions)) {
            $result["exceptions"] = $this->exceptions;
        }

        return $result;
    }
}


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2015 Google, All Rights reserved
// Copyright 2011-2015 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.components.runtime;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.google.appinventor.components.runtime.util.HoneycombUtil;
import com.google.appinventor.components.runtime.util.SdkLevel;

/**
 * This is a FrameLayout that displays all content by a scaled amount.
 * Paddding is adjusted such that scale * (size-padding) = size.
 * Code adjusted from Google example code found at:
 * http://developer.android.com/reference/android/view/ViewGroup.html
 */
public class ScaledFrameLayout extends ViewGroup {

  /** The amount of space used by children in the left gutter. */
  private int mLeftWidth;

  /** The amount of space used by children in the right gutter. */
  private int mRightWidth;

  /** These are used for computing child frames based on their gravity. */
  private final Rect mTmpContainerRect = new Rect();
  private final Rect mTmpChildRect = new Rect();

  private float mScale = 1.0f;

  public ScaledFrameLayout(Context context) {
    super(context);
  }

  public ScaledFrameLayout(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public ScaledFrameLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setClipChildren(false);
  }

  @Override
  protected void dispatchDraw(Canvas canvas) {
    canvas.save(Canvas.MATRIX_SAVE_FLAG);
    canvas.scale(mScale, mScale);
    super.dispatchDraw(canvas);
    canvas.restore();
  }

  @Override
  public ViewParent invalidateChildInParent(final int[] location,
                                            final Rect dirty) {
    // This function is overridden so that children properly invalidate
    // when scaling is in place.
    final int[] scaledLocation = { (int) (location[0] * mScale),
                                   (int) (location[1] * mScale) };

    final Rect scaledDirty = new Rect((int) (dirty.left * mScale),
                                      (int) (dirty.top * mScale), (int) (dirty.right * mScale),
                                      (int) (dirty.bottom * mScale));

    this.invalidate(scaledDirty);

    return super.invalidateChildInParent(scaledLocation, scaledDirty);
  }

  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
    // Modify the touch events so that children receive scaled touch events
    ev.setLocation(ev.getX() * (1f / mScale), ev.getY() * (1f / mScale));
    super.dispatchTouchEvent(ev);
    return true;
  }

  public void setScale(float scale) {
    mScale = scale;
    updatePadding(getWidth(), getHeight());
  }

  private void updatePadding(int width, int height) {
    // To maintain constant size, the padding is adjusted such that
    // scale * (size - padding) = size
    int paddingRight = (int)((width * (mScale - 1f)) / mScale);
    int paddingBottom = (int)((height * (mScale - 1f)) / mScale);
    setPadding(0, 0, paddingRight, paddingBottom);
  }

  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    updatePadding(w,h);
  }

  /**
   * Override because viewgroup does not scroll
   */
  @Override
  public boolean shouldDelayChildPressedState() {
    return false;
  }

  /**
   * Ask all children to measure themselves and compute the measurement of
   * this layout based on the children.
   */
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();

    mLeftWidth = 0;
    mRightWidth = 0;

    int maxHeight = 0;
    int maxWidth = 0;
    int childState = 0;

    for (int i = 0; i < count; i++) {
      final View child = getChildAt(i);
      if (child.getVisibility() != GONE) {
        measureChild(child, widthMeasureSpec, heightMeasureSpec);

        mLeftWidth += Math.max(maxWidth, child.getMeasuredWidth());

        maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
        if (SdkLevel.getLevel() >= SdkLevel.LEVEL_HONEYCOMB) {
          childState = HoneycombUtil.combineMeasuredStates(this, childState,
            HoneycombUtil.getMeasuredState(child));
        }
      }
    }

    maxWidth += mLeftWidth + mRightWidth;

    maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
    maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

    if (SdkLevel.getLevel() >= SdkLevel.LEVEL_HONEYCOMB) {
      setMeasuredDimension(
        HoneycombUtil.resolveSizeAndState(this, maxWidth, widthMeasureSpec, childState),
        HoneycombUtil.resolveSizeAndState(this, maxHeight, heightMeasureSpec,
          childState << HoneycombUtil.VIEWGROUP_MEASURED_HEIGHT_STATE_SHIFT));
    } else {
      setMeasuredDimension(
        resolveSize(maxWidth, widthMeasureSpec),
        resolveSize(maxHeight, heightMeasureSpec));
    }
  }

  /**
   * Position all children within this layout.
   */
  @Override
  protected void onLayout(boolean changed, int left, int top, int right,
                          int bottom) {
    final int count = getChildCount();

    int leftPos = getPaddingLeft();

    final int parentTop = getPaddingTop();
    final int parentBottom = bottom - top - getPaddingBottom();

    for (int i = 0; i < count; i++) {
      final View child = getChildAt(i);
      if (child.getVisibility() != GONE) {
        final int width = child.getMeasuredWidth();
        final int height = child.getMeasuredHeight();

        mTmpContainerRect.left = leftPos;
        mTmpContainerRect.right = leftPos;
        leftPos = mTmpContainerRect.right;
        mTmpContainerRect.top = parentTop;
        mTmpContainerRect.bottom = parentBottom;

        Gravity.apply(Gravity.TOP | Gravity.LEFT, width, height,
                      mTmpContainerRect, mTmpChildRect);

        child.layout(mTmpChildRect.left, mTmpChildRect.top,
                     mTmpChildRect.right, mTmpChildRect.bottom);
      }
    }
  }
}


text:
package javax.microedition.lcdui;

import com.francetelecom.rd.stubs.annotation.ClassDone;
@ClassDone
public final class Font extends Object {
    public static final int STYLE_PLAIN = 0;
    public static final int STYLE_BOLD = 1;
    public static final int STYLE_ITALIC = 2;
    public static final int STYLE_UNDERLINED = 4;
    public static final int SIZE_SMALL = 8;
    public static final int SIZE_MEDIUM = 0;
    public static final int SIZE_LARGE = 16;
    public static final int FACE_SYSTEM = 0;
    public static final int FACE_MONOSPACE = 32;
    public static final int FACE_PROPORTIONAL = 64;
    public static final int FONT_STATIC_TEXT = 0;
    public static final int FONT_INPUT_TEXT = 1;
    private static Font defaultfont = new Font();
    public static Font getFont(int a0) { return new Font(); }
    public static Font getDefaultFont() { return defaultfont; }
    public static Font getFont(int a0,int a1,int a2) { return new Font(); }
    public int getStyle(){ return 0;}
    public int getSize(){ return 0;}
    public int getFace(){ return 0;}
    public boolean isPlain(){ return true;}
    public boolean isBold(){ return true;}
    public boolean isItalic(){ return true;}
    public boolean isUnderlined(){ return true;}
    public int getHeight(){ return 0;}
    public int getBaselinePosition(){ return 0;}
    public int charWidth(char a0){ return 0;}
    public int charsWidth(char[] a0,int a1,int a2){ return 0;}
    public int stringWidth(String a0){ return 0;}
    public int substringWidth(String a0,int a1,int a2){ return 0;}
}


text:
#pragma once
#include <aws/workspaces/WorkSpaces_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace WorkSpaces
{
namespace Model
{

  /**
   *
Describes the Amazon Web Services accounts that have been granted permission
   * to use a shared image. For more information about sharing images, see
   * Share or Unshare a Custom WorkSpaces Image.

See Also:
   AWS
   * API Reference

   */
  class AWS_WORKSPACES_API ImagePermission
  {
  public:
    ImagePermission();
    ImagePermission(Aws::Utils::Json::JsonView jsonValue);
    ImagePermission& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline const Aws::String& GetSharedAccountId() const{ return m_sharedAccountId; }

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline bool SharedAccountIdHasBeenSet() const { return m_sharedAccountIdHasBeenSet; }

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline void SetSharedAccountId(const Aws::String& value) { m_sharedAccountIdHasBeenSet = true; m_sharedAccountId = value; }

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline void SetSharedAccountId(Aws::String&& value) { m_sharedAccountIdHasBeenSet = true; m_sharedAccountId = std::move(value); }

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline void SetSharedAccountId(const char* value) { m_sharedAccountIdHasBeenSet = true; m_sharedAccountId.assign(value); }

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline ImagePermission& WithSharedAccountId(const Aws::String& value) { SetSharedAccountId(value); return *this;}

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline ImagePermission& WithSharedAccountId(Aws::String&& value) { SetSharedAccountId(std::move(value)); return *this;}

    /**
     *
The identifier of the Amazon Web Services account that an image has been
     * shared with.

     */
    inline ImagePermission& WithSharedAccountId(const char* value) { SetSharedAccountId(value); return *this;}

  private:

    Aws::String m_sharedAccountId;
    bool m_sharedAccountIdHasBeenSet;
  };

} // namespace Model
} // namespace WorkSpaces
} // namespace Aws


text:
<?php

namespace Drupal\FunctionalJavascriptTests\Ajax;

use Drupal\FunctionalJavascriptTests\JavascriptTestBase;

/**
 * Tests AJAX responses.
 *
 * @group Ajax
 */
class AjaxTest extends JavascriptTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = ['ajax_test'];

  public function testAjaxWithAdminRoute() {
    \Drupal::service('theme_installer')->install(['stable', 'seven']);
    $theme_config = \Drupal::configFactory()->getEditable('system.theme');
    $theme_config->set('admin', 'seven');
    $theme_config->set('default', 'stable');
    $theme_config->save();

    $account = $this->drupalCreateUser(['view the administration theme']);
    $this->drupalLogin($account);

    // First visit the site directly via the URL. This should render it in the
    // admin theme.
    $this->drupalGet('admin/ajax-test/theme');
    $assert = $this->assertSession();
    $assert->pageTextContains('Current theme: seven');

    // Now click the modal, which should also use the admin theme.
    $this->drupalGet('ajax-test/dialog');
    $assert->pageTextNotContains('Current theme: stable');
    $this->clickLink('Link 8 (ajax)');
    $assert->assertWaitOnAjaxRequest();

    $assert->pageTextContains('Current theme: stable');
    $assert->pageTextNotContains('Current theme: seven');
  }

  /**
   * Test that AJAX loaded libraries are not retained between requests.
   *
   * @see https://www.drupal.org/node/2647916
   */
  public function testDrupalSettingsCachingRegression() {
    $this->drupalGet('ajax-test/dialog');
    $assert = $this->assertSession();
    $session = $this->getSession();

    // Insert a fake library into the already loaded library settings.
    $fake_library = 'fakeLibrary/fakeLibrary';
    $session->evaluateScript("drupalSettings.ajaxPageState.libraries = drupalSettings.ajaxPageState.libraries + ',$fake_library';");

    $libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
    // Test that the fake library is set.
    $this->assertContains($fake_library, $libraries);

    // Click on the AJAX link.
    $this->clickLink('Link 8 (ajax)');
    $assert->assertWaitOnAjaxRequest();

    // Test that the fake library is still set after the AJAX call.
    $libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
    $this->assertContains($fake_library, $libraries);

    // Reload the page, this should reset the loaded libraries and remove the
    // fake library.
    $this->drupalGet('ajax-test/dialog');
    $libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
    $this->assertNotContains($fake_library, $libraries);

    // Click on the AJAX link again, and the libraries should still not contain
    // the fake library.
    $this->clickLink('Link 8 (ajax)');
    $assert->assertWaitOnAjaxRequest();
    $libraries = $session->evaluateScript('drupalSettings.ajaxPageState.libraries');
    $this->assertNotContains($fake_library, $libraries);
  }

}


text:
class Motor {
public:

  Motor(int outputPin);
  ~Motor(){};

  void red()
  {
    showFlag(NO_HEAT_FLAG);
  };
  void green()
  {
    showFlag(HEAT_IN_PROGESS_FLAG);
  };
  void yellow()
  {
    showFlag(HEAT_ENDING_SOON_FLAG);
  };

  int flagInPosition() {
    return isInPosition;
  }

  int getFlagPosition();
  int getDesiredFlagPosition();

private:
  int flagPosition;
  int desiredFlagPosition;
  int isInPosition;
  void showFlag(int desiredFlag);
  static int output;

  // static const int FLAG_UPDATE = 0;
  static const int FLAG_RED = 1;
  static const int FLAG_GREEN = 2;
  static const int FLAG_YELLOW = 3;
  static const int FLAG_TICK_DURATION_MS = 300;

  static const int LED_FLAG_RED = A1;
  static const int LED_FLAG_GREEN = A2;
  static const int LED_FLAG_YELLOW = A3;

  // red flag
  static const int NO_HEAT_FLAG = 2;
  // green flag
  static const int HEAT_IN_PROGESS_FLAG = 3;
  // yellow flag
  static const int HEAT_ENDING_SOON_FLAG = 12;

};

#endif
// _MOTOR_H


text: Second header variant.


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\Planet;

class LoadPlanetData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $planets = array(
            array('name' => 'Mercury'),
            array('name' => 'Venus'),
            array('name' => 'Earth'),
            array('name' => 'Mars'),
            array('name' => 'Jupiter'),
            array('name' => 'Saturn'),
            array('name' => 'Uranus'),
            array('name' => 'Neptune'),
        );

        for ($i = 0; $i < count($planets); $i++) {
            $planet = new Planet();
            foreach ($planets[$i] as $field => $value) {
                $planet->{'set' . ucfirst($field)}($value);
            }

            $manager->persist($planet);
            $manager->flush();

            $this->addReference('planet-' . strtolower($planets[$i]['name']), $planet);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 1;
    }
}


text:
<?php

namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Http\Response;

class AuthenticationHelper extends AbstractPlugin
{
    protected $zfcUserAuthentication;
    protected $getResponse;

    public function __construct($auth)
    {
        $this->zfcUserAuthentication = $auth;
        $this->getResponse = new Response();
    }

    public function checkIdentity()
    {
        if ($this->zfcUserAuthentication->hasIdentity() === false) {
            $this->getController()->getResponse()->setStatusCode('401');
            //$this->getResponse->setStatusCode(401);

            return array(
                'code'    => '401',
                'errors'  => array(
                    'application' => 'Session not exist'
                )
            );
        } else {
            $this->getController()->getResponse()->setStatusCode('200');
            //$this->getResponse->setStatusCode(200);

            return array(
                'code'    => '200',
                'response' => array(
                    //'id'     => $this->zfcUserAuthentication->getIdentity()->getId(),
                    'action' => 'Session already exist',
                )
            );
        }
    }
}


text:
var SassPlotter = require('../');
var Assert = require('assert');
var path = require('path');
var _ = require('underscore');

var file_a = path.resolve('test/scss/a.scss');
var file_b = path.resolve('test/scss/b.scss');
var file_c = path.resolve('test/scss/c.scss');
var file_d = path.resolve('test/scss/d.scss');
var file_e = path.resolve('test/scss/e.scss');

describe('Constructor', function () {

  it('should have a `_plot` property object assigned', function () {
    var plotter;
    plotter = new SassPlotter();
    Assert(_.isObject(plotter._plot));
  });

  it('should parse given directory and build plot from it', function () {
    plot = new SassPlotter(path.resolve('test/scss'));
    Assert(_.isObject(plot._plot));
    Assert(!_.isEmpty(plot._plot));
  });

  describe('Options', function () {
    var plotWithOptions;
    it('should pass options to sass-import-resolve', function () {
      plot = new SassPlotter(path.resolve('test/scss'));
      plotWithOptions = new SassPlotter(path.resolve('test/scss'), {
        resolveScss : false
      });
      Assert.strictEqual(plot._plot[file_a].resolves.length / 2, plotWithOptions._plot[file_a].resolves.length);
      Assert.strictEqual(!!_(plot._plot[file_a].resolves).indexOf(file_b), _(plotWithOptions._plot[file_a].resolves).indexOf(file_b) === -1);
    });

  });

});


text:
/**
 * Utility function to append locale specific data to oForm payload object sent to /account/create endpoint
 *
 * @param {String} `data` string of form data encoded by oForm
 * @return {String} encoded locale string to be appended to the oForm `data` string in the oForm middleware
 */
function tld2locale(tld){
  switch(tld){
    case 'de': return 'de_DE';
    case 'fr': return 'fr_FR';
    case 'es': return 'es_ES';
    case 'jp': return 'ja_JP';
    default: return 'en_US';
  }
}

module.exports = function() {
  // extract TLD from current URL
  var tld = window.location.hostname.split('.').pop();
  return window.encodeURI('&locale=' + tld2locale(tld));
};


text:
package quickfix.field;
import quickfix.StringField;

public class CardExpDate extends StringField
{
  static final long serialVersionUID = 20050617;

  public static final int FIELD = 490;

  public CardExpDate()
  {
    super(490);
  }

  public CardExpDate(String data)
  {
     super(490, data);
  }

}


text:
<?php
namespace Apitude\User\OAuth\Entities;

use Doctrine\ORM\Mapping as ORM;
use Apitude\Core\Annotations\API;

/**
 * @ORM\Entity()
 * @ORM\Table(name="oauth_scope")
 * @package Apitude\User\Entities
 */
class OauthScope
{
    /**
     * @var string
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="id", type="string", length=32, options={"collation"="ascii_general_ci"})
     */
    private $id;

    /**
     * @var string
     * @ORM\Column(name="description", type="string", options={"collation"="ascii_general_ci"})
     */
    private $description;

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

    /**
     * @param string $id
     * @return OauthScope
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

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

    /**
     * @param string $description
     * @return OauthScope
     */
    public function setDescription($description)
    {
        $this->description = $description;
        return $this;
    }

}


text:
package org.apache.metamodel.query;

import org.apache.metamodel.util.AbstractNumberAggregateBuilder;

/**
 * Aggregate builder for the {@link FunctionType#AVG} function
 */
final class AverageAggregateBuilder extends AbstractNumberAggregateBuilder<Double> {

	public double _average;
	public int _numValues;

	@Override
	protected void add(Number number) {
		double total = _average * _numValues + number.doubleValue();
		_numValues++;
		_average = total / _numValues;
	}

	@Override
	public Double getAggregate() {
		return _average;
	}

}


text:
package com.vaadin.tests.elements.menubar;

import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;

/**
 *
 */
@SuppressWarnings("serial")
public class MenuBarUI extends AbstractTestUI {

    @Override
    protected void setup(VaadinRequest request) {
        addComponent(createDefaultMenuBar("", ""));
        addComponent(createDefaultMenuBar("2", ""));
        addComponent(createDefaultMenuBar("", "2"));
    }

    private MenuBar createDefaultMenuBar(String topLevelItemSuffix,
            String secondaryLevelItemSuffix) {
        MenuBar menuBar = new MenuBar();
        MenuItem file = menuBar.addItem("File" + topLevelItemSuffix, null);
        file.addItem("Open" + secondaryLevelItemSuffix, new MenuBarCommand());
        file.addItem("Save" + secondaryLevelItemSuffix, new MenuBarCommand());
        file.addItem("Save As.." + secondaryLevelItemSuffix,
                new MenuBarCommand());
        file.addSeparator();

        MenuItem export = file.addItem("Export.." + secondaryLevelItemSuffix,
                null);
        export.addItem("As PDF..." + secondaryLevelItemSuffix,
                new MenuBarCommand());
        export.addItem("As Doc..." + secondaryLevelItemSuffix,
                new MenuBarCommand());

        file.addSeparator();
        file.addItem("Exit" + secondaryLevelItemSuffix, new MenuBarCommand());

        MenuItem edit = menuBar.addItem("Edit" + topLevelItemSuffix, null);
        edit.addItem("Copy" + secondaryLevelItemSuffix, new MenuBarCommand());
        edit.addItem("Cut" + secondaryLevelItemSuffix, new MenuBarCommand());
        edit.addItem("Paste" + secondaryLevelItemSuffix, new MenuBarCommand());

        menuBar.addItem("Help" + topLevelItemSuffix, new MenuBarCommand());
        return menuBar;
    }

    @Override
    protected String getTestDescription() {
        return "UI used to validate MenuBarElement API";
    }

    @Override
    protected Integer getTicketNumber() {
        return 13364;
    }

    private class MenuBarCommand implements Command {

        @Override
        public void menuSelected(MenuItem selectedItem) {
        }

    }
}


text:
layout: post
title: Coerción
categories: serie js
permalink: serie/js/coercion
---

La Coerción o __Tipo de Conversión__ es el cambio de un tipo de datos a otro diferente. El tipo de conversión puede ser Implícita o Explícita, voy a describir sobre ambas y dar unos simples ejemplos.

# Explícita
El tipo de conversión Explícita es cuando cambiamos el tipo de dato por el lenguaje o por decir de una forma obvia.

## de Cadena de Carácteres a Números, de Números a Cadenas de Carácteres
Lo más usual en el tipo de conversión explícita, para coaccionar números y cadenas de carácteres utilizamos dos constructores nativos de __JavaScript__ que son __String()__ y __Number()__, en este caso no es necesario usar la palabra reservada __new__ ya que no vamos a crear objetos.

{% highlight javascript %}

var a = 20;
var b = '12';

String(a) // "20"
Number(b) // 12

{% endhighlight %}

es obvio el tipo de conversión, el constructor __String()__ coacciona cualquier valor a un valor primitivo de tipo cadena de carácteres pasando por la regla del __ToString__ y el constructor __Number()__ coacciona cualquier valor a un valor primitivo de tipo de número pasando por la regla del __ToNumber__.
Otras formas coerción explícita es usando el objeto global __toString()__ y en caso para los números el unario __+__, veamos el ejemplo:

{% highlight javascript %}

var a = 20;
var b = '12';

a.toString() // "20"
+b // 12

{% endhighlight %}

> La comunidad de __JavaScript__ toma el unario __+__ como un metodo de coerción muy explícita, teniendo en cuenta que __++__ o __--__ también coaccionan pero modifican el operando.

## Fecha a Número
EL operador unario __+__ también es de gran utilidad para coercer de Fecha a Número, el constructor global __Date()__ consigue la fecha en UTC (Universal Time Coordinate).

{% highlight javascript %}

var date = new Date();

+date // 1445821924634

{% endhighlight %}

y aun mas explícito puede ser el método __getTime()__ en el constructor global __Date()__, aunque el más preferible y recomendado es la función estática __Date.now()__  agregada en __EcmaScript5__.

{% highlight javascript %}

new Date().getTime() // 1445822462411
Date.now() // 1445822476015

{% endhighlight %}

## Parseando Cadenas Númericas
Como coaccionar cadenas a números pero con una poca diferencia a como lo hicimos arriba. Vamos a considerar:

{% highlight javascript %}

var a = '20';
var b = '12em';

Number(a) // 20
parseInt(a) // 20

Number(b) // NaN
parseInt(b) // 12

{% endhighlight %}

el __Number()__ coacciona solo si es una cadena númerica algo como __'12em'__ resulta __NaN__ (Not a Number) en cambio el método global __parseInt()__ comprueba que sea una cadena de carácteres y esta cadena debe comenzar por un número para lograr parsearlo a un entero.

## Booleanos
Ahora vamos a ver como coaccionar cualquier valor que no sea Booleano a Booleano, como los constructores globales __Number()__ y __String()__ para Booleanos tenemos el __Boolean()__, igual omitimos la palabra reservada __new__.

{% highlight javascript %}

var a = '0';
var b = [];
var c = {};
var d = '';
var e = 0;
var f = null;
var g;

Boolean(a) // true
Boolean(b) // true
Boolean(c) // true

Boolean(d) // false
Boolean(e) // false
Boolean(f) // false
Boolean(g) // false

{% endhighlight %}

claramente __Boolean()__ coacciona explícitamente, otra forma de coaccionar Booleanos explícitamente es con el unario __!__ (negación) similar al unario __+__ para los números.

{% highlight javascript %}

var a = '0';
var b = [];
var c = {};
var d = '';
var e = 0;
var f = null;
var g;

!!a // true
!!b // true
!!c // true

!!d // false
!!e // false
!!f // false
!!g // false

{% endhighlight %}

# Implícita
El tipo de conversión Implícita también llamado __Coerción__, es cuando cambiamos el tipo de dato por el compilador y de cualquier forma que no sea obvia.

## de Números a Cadena de Carácteres, de Cadena de Carácteres a Números
{% highlight javascript %}

var a = '10';
var b = '22';
var c = 33;
var d = 15;

a + b // "1022"
c + d // 48
a + c // "1033"
d + '' // "15"

// coercion de dos vectores a cadena
[2,3] + [5,5] // "2,35,5"

{% endhighlight %}

un poco extraño esto no? esto se basa por el operador __+__ que es de sumar y concatenar, en el ejemplo de arriba podemos ver como hacemos el tipo de conversión a cadenas de carácteres, ahora como pasamos de cadena a número?

{% highlight javascript %}

var a = '10';
a - 0 // 10

// coercion de dos vectores a numero
[5] - [3] // 2

{% endhighlight %}

el __-__ operador es es solo para substracción númerica, así forzamos de manera implícita cambiar a número.

## de Booleano a Número
{% highlight javascript %}

var a = true;
var b = false;

a + 1 // 2
a - 1 // 0
b + 1 // 1
a + a + a // 3

{% endhighlight %}

por lógica true equivale a 1 y false equivale a 0.

## Coerción de Booleanos
Con condicionales(if, while, do...while) podemos evaluar booleanos y retorna la declaración si es true, a veces forzandolo a que devuelva un valor booleano en específico.
{% highlight javascript %}

var a = 'Ninja';
var b;

if(a) {
	console.log('es true y por lo tanto se ejecuta este bloque de codigo');
}

if(!a) {
	console.log('lo forzamos a false y no se ejecuta este bloque de codigo, solo devuelve undefined');
}

while(b) {
	console.log('no se ejecuta')
}

{% endhighlight %}

los operadores __&&__ y __||__ igual que en otros lenguajes de programación pero en JavaScript se encuentra una pequeña diferencia, el valor a retorna no es necesariamente por un tipo de booleano, puede ser por alguna de las dos expresiones.

{% highlight javascript %}

var a = 'Ninja';
var b = 23;
var c = null;

a || b // "Ninja"
a && b // 23

a || c // "Ninja"
a && c // null

{% endhighlight %}

podemos denotar que en otros lenguajes estos operadores nos devuelve un valor booleano, en caso de __JavaScript__ (Ruby, Python también) nos devuelve el valor propio de la variable. Los operadores __||__ y __&&__ ejecutan una prueba de booleanos en los operandos, si el operador no es booleano se ejecuta la coerción con el __ToBoolean__. Para el operador __||__ si el resultado es __true__ retorna el valor del primer operando de lo contrario si es __false__ retorna el valor del segundo operando. Para el operador __&&__ lo inverso, si el resultado es __true__ retorna el valor del segundo operando de lo contario si es __false__ retorna el valor del primer operando.
También podemos usar el operador ternario (__? :__)

{% highlight javascript %}

var a = 'Ninja';
var b = 23;
var c = null;

a || b // "Ninja"
// equivalente a
a ? a : b  // "Ninja"

a && b // 23
// equivalente a
a ? b : a // 23

{% endhighlight %}

> con el operador ternario podemos omitir los valores __false__ y solo retornar los valores __true__.

Otro uso del operador es definir variables o argumentos predeterminados ya que en __JavaScript__ no se puede declarar argumentos predeterminados.

{% highlight javascript %}

var a = b || 'Ninja';

// o en un constructor
function Prueba(a, b) {
	this.a = a || 'Ninja';
	this.b = b || 20;
}

{% endhighlight %}

# Pérdida de igualdad e Igualdad estricta
Una preocupación de concepto sobre __JavaScript__ es la __Pérdida de igualdad (==)__ e __Igualdad estricta (===)__, esto es algo confuso para los que esten iniciando en el lenguaje y tiene que ver con la coerción, simplemente es asi: la pérdidad de igual (==) permite la coerción por esto comparar dos operandos con el mismo valor pero de diferente tipo de dato es __true__, y la igualdad estricta (===) no permite la coerción por lo tanto dos operandos con el mismo valor pero de diferente tipo de dato es __false__ porque la igualdad estricta evalua también el tipo de datos de los operandos. Para un mejor entendimiento vamos a ver unos ejemplos:

## Comparando con Cadenas de Carácteres
{% highlight javascript %}

var a = 20;
var b = '20';

a == b // true
a === b // false

{% endhighlight %}

como observamos la operación __a == b__ (perdida de igualdad) es true porque permite la coerción y la operación __a === b__ (igualdad estricta) es false porque no permite la coerción, el tipo de coerción que sucede en __a == b__ es que __b__ coerciona con __ToNumber__ si __a__ hubiese sido la cadena y __b__ el número se ejecuta igual el __ToNumber__ pero en este caso al valor de __a__.

## Comparando con Booleanos
Otro caso confuso es el de comparar con booleanos, veamos un simple ejemplo:

{% highlight javascript %}

var a = '20';
var b = true;

a == b // false
a === b // false

{% endhighlight %}

que pasa aqui? sabemos que la igualdad estricta es false, pero en la perdida de igualdad támbien resulta false pero porque si el valor de __a__ es una cadena que es true no? la razon es simple: si en una igualdad usando coerción existe un booleano se ejecuta el __ToNumber__ en este caso al operando __b__ que es un booleano de tipo __true__, sabemos que true es 1 entonces el __ToNumber(b)__ se ejecuta y lo coerciona a __1__ por lo tanto la operación es __'20' == 1__ también la denotamos el __'20'__ por __20__ entonces __20 == 1__ resulta __false__.

## Comparando Null y Undefined
Otro ejemplo es comparar __null__ y __undefined__ con perdida de igualdad (==).

{% highlight javascript %}

var a = null;
var b;

a == b // true
b == a // true

a == false // false
b == false // false
a == '' // false
b == '' // false
a == 0 // false
b == 0 // false

{% endhighlight %}

la igualdad entre __null__ y __undefined__ es seguro a __true__.

## Comparando Objetos
Los Objetos incluyendo funciones y vectores son comparados con simples valores primitivos, usando la perdida de igual (==) en un tipo de dato ya sea cadena o número y el otro tipo de dato un objeto se ejecuta el __ToPrimitive()__ al objeto, para tener un ejemplo mas claro:

{% highlight javascript %}

var a = 20;
var b = [20];
var c = Object(20);

a == b // true
a == c // true

{% endhighlight %}

como vemos la coerción ejecuta el __ToPrimitive__ al objeto pasandolo a un valor primitivo para evaluarlo con la cadena o un número.

# Conclusión
La Coerción en __JavaScript__ es un concepto muy confuso distinto a otro lenguajes de programación, es recomendado no usar la __coerción implícita__ a menos que estes al tanto de lo que haces y aunque no sea recomendado se le puede sacar provecho en algunos pocos casos, lo mejor es optar por la __coerción explícita__ ya que se define por el mismo lenguaje y más aun si estas trabajando con un grupo de trabajo, con este post espero que estes un poco más claro del estrecho concepto de la coerción en __JavaScript__.


text:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/crypto.h>
#include <linux/spinlock.h>
#include <crypto/algapi.h>
#include <crypto/aes.h>

#include <linux/io.h>
#include <linux/delay.h>

#include "geode-aes.h"

/* Static structures */

static void __iomem *_iobase;
static spinlock_t lock;

/* Write a 128 bit field (either a writable key or IV) */
static inline void
_writefield(u32 offset, void *value)
{
	int i;
	for (i = 0; i < 4; i++)
		iowrite32(((u32 *) value)[i], _iobase + offset + (i * 4));
}

/* Read a 128 bit field (either a writable key or IV) */
static inline void
_readfield(u32 offset, void *value)
{
	int i;
	for (i = 0; i < 4; i++)
		((u32 *) value)[i] = ioread32(_iobase + offset + (i * 4));
}

static int
do_crypt(void *src, void *dst, int len, u32 flags)
{
	u32 status;
	u32 counter = AES_OP_TIMEOUT;

	iowrite32(virt_to_phys(src), _iobase + AES_SOURCEA_REG);
	iowrite32(virt_to_phys(dst), _iobase + AES_DSTA_REG);
	iowrite32(len,  _iobase + AES_LENA_REG);

	/* Start the operation */
	iowrite32(AES_CTRL_START | flags, _iobase + AES_CTRLA_REG);

	do {
		status = ioread32(_iobase + AES_INTR_REG);
		cpu_relax();
	} while (!(status & AES_INTRA_PENDING) && --counter);

	/* Clear the event */
	iowrite32((status & 0xFF) | AES_INTRA_PENDING, _iobase + AES_INTR_REG);
	return counter ? 0 : 1;
}

static unsigned int
geode_aes_crypt(struct geode_aes_op *op)
{
	u32 flags = 0;
	unsigned long iflags;
	int ret;

	if (op->len == 0)
		return 0;

	/* If the source and destination is the same, then
	 * we need to turn on the coherent flags, otherwise
	 * we don't need to worry
	 */

	flags |= (AES_CTRL_DCA | AES_CTRL_SCA);

	if (op->dir == AES_DIR_ENCRYPT)
		flags |= AES_CTRL_ENCRYPT;

	/* Start the critical section */

	spin_lock_irqsave(&lock, iflags);

	if (op->mode == AES_MODE_CBC) {
		flags |= AES_CTRL_CBC;
		_writefield(AES_WRITEIV0_REG, op->iv);
	}

	if (!(op->flags & AES_FLAGS_HIDDENKEY)) {
		flags |= AES_CTRL_WRKEY;
		_writefield(AES_WRITEKEY0_REG, op->key);
	}

	ret = do_crypt(op->src, op->dst, op->len, flags);
	BUG_ON(ret);

	if (op->mode == AES_MODE_CBC)
		_readfield(AES_WRITEIV0_REG, op->iv);

	spin_unlock_irqrestore(&lock, iflags);

	return op->len;
}

/* CRYPTO-API Functions */

static int geode_setkey_cip(struct crypto_tfm *tfm, const u8 *key,
		unsigned int len)
{
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);
	unsigned int ret;

	op->keylen = len;

	if (len == AES_KEYSIZE_128) {
		memcpy(op->key, key, len);
		return 0;
	}

	if (len != AES_KEYSIZE_192 && len != AES_KEYSIZE_256) {
		/* not supported at all */
		tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
		return -EINVAL;
	}

	/*
	 * The requested key size is not supported by HW, do a fallback
	 */
	op->fallback.cip->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK;
	op->fallback.cip->base.crt_flags |= (tfm->crt_flags & CRYPTO_TFM_REQ_MASK);

	ret = crypto_cipher_setkey(op->fallback.cip, key, len);
	if (ret) {
		tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK;
		tfm->crt_flags |= (op->fallback.cip->base.crt_flags & CRYPTO_TFM_RES_MASK);
	}
	return ret;
}

static int geode_setkey_blk(struct crypto_tfm *tfm, const u8 *key,
		unsigned int len)
{
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);
	unsigned int ret;

	op->keylen = len;

	if (len == AES_KEYSIZE_128) {
		memcpy(op->key, key, len);
		return 0;
	}

	if (len != AES_KEYSIZE_192 && len != AES_KEYSIZE_256) {
		/* not supported at all */
		tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
		return -EINVAL;
	}

	/*
	 * The requested key size is not supported by HW, do a fallback
	 */
	op->fallback.blk->base.crt_flags &= ~CRYPTO_TFM_REQ_MASK;
	op->fallback.blk->base.crt_flags |= (tfm->crt_flags & CRYPTO_TFM_REQ_MASK);

	ret = crypto_blkcipher_setkey(op->fallback.blk, key, len);
	if (ret) {
		tfm->crt_flags &= ~CRYPTO_TFM_RES_MASK;
		tfm->crt_flags |= (op->fallback.blk->base.crt_flags & CRYPTO_TFM_RES_MASK);
	}
	return ret;
}

static int fallback_blk_dec(struct blkcipher_desc *desc,
		struct scatterlist *dst, struct scatterlist *src,
		unsigned int nbytes)
{
	unsigned int ret;
	struct crypto_blkcipher *tfm;
	struct geode_aes_op *op = crypto_blkcipher_ctx(desc->tfm);

	tfm = desc->tfm;
	desc->tfm = op->fallback.blk;

	ret = crypto_blkcipher_decrypt_iv(desc, dst, src, nbytes);

	desc->tfm = tfm;
	return ret;
}
static int fallback_blk_enc(struct blkcipher_desc *desc,
		struct scatterlist *dst, struct scatterlist *src,
		unsigned int nbytes)
{
	unsigned int ret;
	struct crypto_blkcipher *tfm;
	struct geode_aes_op *op = crypto_blkcipher_ctx(desc->tfm);

	tfm = desc->tfm;
	desc->tfm = op->fallback.blk;

	ret = crypto_blkcipher_encrypt_iv(desc, dst, src, nbytes);

	desc->tfm = tfm;
	return ret;
}

static void
geode_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);

	if (unlikely(op->keylen != AES_KEYSIZE_128)) {
		crypto_cipher_encrypt_one(op->fallback.cip, out, in);
		return;
	}

	op->src = (void *) in;
	op->dst = (void *) out;
	op->mode = AES_MODE_ECB;
	op->flags = 0;
	op->len = AES_MIN_BLOCK_SIZE;
	op->dir = AES_DIR_ENCRYPT;

	geode_aes_crypt(op);
}

static void
geode_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
{
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);

	if (unlikely(op->keylen != AES_KEYSIZE_128)) {
		crypto_cipher_decrypt_one(op->fallback.cip, out, in);
		return;
	}

	op->src = (void *) in;
	op->dst = (void *) out;
	op->mode = AES_MODE_ECB;
	op->flags = 0;
	op->len = AES_MIN_BLOCK_SIZE;
	op->dir = AES_DIR_DECRYPT;

	geode_aes_crypt(op);
}

static int fallback_init_cip(struct crypto_tfm *tfm)
{
	const char *name = tfm->__crt_alg->cra_name;
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);

	op->fallback.cip = crypto_alloc_cipher(name, 0,
				CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK);

	if (IS_ERR(op->fallback.cip)) {
		printk(KERN_ERR "Error allocating fallback algo %s\n", name);
		return PTR_ERR(op->fallback.cip);
	}

	return 0;
}

static void fallback_exit_cip(struct crypto_tfm *tfm)
{
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);

	crypto_free_cipher(op->fallback.cip);
	op->fallback.cip = NULL;
}

static struct crypto_alg geode_alg = {
	.cra_name			=	"aes",
	.cra_driver_name	=	"geode-aes",
	.cra_priority		=	300,
	.cra_alignmask		=	15,
	.cra_flags			=	CRYPTO_ALG_TYPE_CIPHER |
							CRYPTO_ALG_NEED_FALLBACK,
	.cra_init			=	fallback_init_cip,
	.cra_exit			=	fallback_exit_cip,
	.cra_blocksize		=	AES_MIN_BLOCK_SIZE,
	.cra_ctxsize		=	sizeof(struct geode_aes_op),
	.cra_module			=	THIS_MODULE,
	.cra_u				=	{
		.cipher	=	{
			.cia_min_keysize	=	AES_MIN_KEY_SIZE,
			.cia_max_keysize	=	AES_MAX_KEY_SIZE,
			.cia_setkey			=	geode_setkey_cip,
			.cia_encrypt		=	geode_encrypt,
			.cia_decrypt		=	geode_decrypt
		}
	}
};

static int
geode_cbc_decrypt(struct blkcipher_desc *desc,
		  struct scatterlist *dst, struct scatterlist *src,
		  unsigned int nbytes)
{
	struct geode_aes_op *op = crypto_blkcipher_ctx(desc->tfm);
	struct blkcipher_walk walk;
	int err, ret;

	if (unlikely(op->keylen != AES_KEYSIZE_128))
		return fallback_blk_dec(desc, dst, src, nbytes);

	blkcipher_walk_init(&walk, dst, src, nbytes);
	err = blkcipher_walk_virt(desc, &walk);
	op->iv = walk.iv;

	while ((nbytes = walk.nbytes)) {
		op->src = walk.src.virt.addr,
		op->dst = walk.dst.virt.addr;
		op->mode = AES_MODE_CBC;
		op->len = nbytes - (nbytes % AES_MIN_BLOCK_SIZE);
		op->dir = AES_DIR_DECRYPT;

		ret = geode_aes_crypt(op);

		nbytes -= ret;
		err = blkcipher_walk_done(desc, &walk, nbytes);
	}

	return err;
}

static int
geode_cbc_encrypt(struct blkcipher_desc *desc,
		  struct scatterlist *dst, struct scatterlist *src,
		  unsigned int nbytes)
{
	struct geode_aes_op *op = crypto_blkcipher_ctx(desc->tfm);
	struct blkcipher_walk walk;
	int err, ret;

	if (unlikely(op->keylen != AES_KEYSIZE_128))
		return fallback_blk_enc(desc, dst, src, nbytes);

	blkcipher_walk_init(&walk, dst, src, nbytes);
	err = blkcipher_walk_virt(desc, &walk);
	op->iv = walk.iv;

	while ((nbytes = walk.nbytes)) {
		op->src = walk.src.virt.addr,
		op->dst = walk.dst.virt.addr;
		op->mode = AES_MODE_CBC;
		op->len = nbytes - (nbytes % AES_MIN_BLOCK_SIZE);
		op->dir = AES_DIR_ENCRYPT;

		ret = geode_aes_crypt(op);
		nbytes -= ret;
		err = blkcipher_walk_done(desc, &walk, nbytes);
	}

	return err;
}

static int fallback_init_blk(struct crypto_tfm *tfm)
{
	const char *name = tfm->__crt_alg->cra_name;
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);

	op->fallback.blk = crypto_alloc_blkcipher(name, 0,
			CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK);

	if (IS_ERR(op->fallback.blk)) {
		printk(KERN_ERR "Error allocating fallback algo %s\n", name);
		return PTR_ERR(op->fallback.blk);
	}

	return 0;
}

static void fallback_exit_blk(struct crypto_tfm *tfm)
{
	struct geode_aes_op *op = crypto_tfm_ctx(tfm);

	crypto_free_blkcipher(op->fallback.blk);
	op->fallback.blk = NULL;
}

static struct crypto_alg geode_cbc_alg = {
	.cra_name		=	"cbc(aes)",
	.cra_driver_name	=	"cbc-aes-geode",
	.cra_priority		=	400,
	.cra_flags			=	CRYPTO_ALG_TYPE_BLKCIPHER |
						CRYPTO_ALG_KERN_DRIVER_ONLY |
						CRYPTO_ALG_NEED_FALLBACK,
	.cra_init			=	fallback_init_blk,
	.cra_exit			=	fallback_exit_blk,
	.cra_blocksize		=	AES_MIN_BLOCK_SIZE,
	.cra_ctxsize		=	sizeof(struct geode_aes_op),
	.cra_alignmask		=	15,
	.cra_type			=	&crypto_blkcipher_type,
	.cra_module			=	THIS_MODULE,
	.cra_u				=	{
		.blkcipher	=	{
			.min_keysize	=	AES_MIN_KEY_SIZE,
			.max_keysize	=	AES_MAX_KEY_SIZE,
			.setkey			=	geode_setkey_blk,
			.encrypt		=	geode_cbc_encrypt,
			.decrypt		=	geode_cbc_decrypt,
			.ivsize			=	AES_IV_LENGTH,
		}
	}
};

static int
geode_ecb_decrypt(struct blkcipher_desc *desc,
		  struct scatterlist *dst, struct scatterlist *src,
		  unsigned int nbytes)
{
	struct geode_aes_op *op = crypto_blkcipher_ctx(desc->tfm);
	struct blkcipher_walk walk;
	int err, ret;

	if (unlikely(op->keylen != AES_KEYSIZE_128))
		return fallback_blk_dec(desc, dst, src, nbytes);

	blkcipher_walk_init(&walk, dst, src, nbytes);
	err = blkcipher_walk_virt(desc, &walk);

	while ((nbytes = walk.nbytes)) {
		op->src = walk.src.virt.addr,
		op->dst = walk.dst.virt.addr;
		op->mode = AES_MODE_ECB;
		op->len = nbytes - (nbytes % AES_MIN_BLOCK_SIZE);
		op->dir = AES_DIR_DECRYPT;

		ret = geode_aes_crypt(op);
		nbytes -= ret;
		err = blkcipher_walk_done(desc, &walk, nbytes);
	}

	return err;
}

static int
geode_ecb_encrypt(struct blkcipher_desc *desc,
		  struct scatterlist *dst, struct scatterlist *src,
		  unsigned int nbytes)
{
	struct geode_aes_op *op = crypto_blkcipher_ctx(desc->tfm);
	struct blkcipher_walk walk;
	int err, ret;

	if (unlikely(op->keylen != AES_KEYSIZE_128))
		return fallback_blk_enc(desc, dst, src, nbytes);

	blkcipher_walk_init(&walk, dst, src, nbytes);
	err = blkcipher_walk_virt(desc, &walk);

	while ((nbytes = walk.nbytes)) {
		op->src = walk.src.virt.addr,
		op->dst = walk.dst.virt.addr;
		op->mode = AES_MODE_ECB;
		op->len = nbytes - (nbytes % AES_MIN_BLOCK_SIZE);
		op->dir = AES_DIR_ENCRYPT;

		ret = geode_aes_crypt(op);
		nbytes -= ret;
		ret =  blkcipher_walk_done(desc, &walk, nbytes);
	}

	return err;
}

static struct crypto_alg geode_ecb_alg = {
	.cra_name			=	"ecb(aes)",
	.cra_driver_name	=	"ecb-aes-geode",
	.cra_priority		=	400,
	.cra_flags			=	CRYPTO_ALG_TYPE_BLKCIPHER |
						CRYPTO_ALG_KERN_DRIVER_ONLY |
						CRYPTO_ALG_NEED_FALLBACK,
	.cra_init			=	fallback_init_blk,
	.cra_exit			=	fallback_exit_blk,
	.cra_blocksize		=	AES_MIN_BLOCK_SIZE,
	.cra_ctxsize		=	sizeof(struct geode_aes_op),
	.cra_alignmask		=	15,
	.cra_type			=	&crypto_blkcipher_type,
	.cra_module			=	THIS_MODULE,
	.cra_u				=	{
		.blkcipher	=	{
			.min_keysize	=	AES_MIN_KEY_SIZE,
			.max_keysize	=	AES_MAX_KEY_SIZE,
			.setkey			=	geode_setkey_blk,
			.encrypt		=	geode_ecb_encrypt,
			.decrypt		=	geode_ecb_decrypt,
		}
	}
};

static void geode_aes_remove(struct pci_dev *dev)
{
	crypto_unregister_alg(&geode_alg);
	crypto_unregister_alg(&geode_ecb_alg);
	crypto_unregister_alg(&geode_cbc_alg);

	pci_iounmap(dev, _iobase);
	_iobase = NULL;

	pci_release_regions(dev);
	pci_disable_device(dev);
}

static int geode_aes_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
	int ret;
	ret = pci_enable_device(dev);
	if (ret)
		return ret;

	ret = pci_request_regions(dev, "geode-aes");
	if (ret)
		goto eenable;

	_iobase = pci_iomap(dev, 0, 0);

	if (_iobase == NULL) {
		ret = -ENOMEM;
		goto erequest;
	}

	spin_lock_init(&lock);

	/* Clear any pending activity */
	iowrite32(AES_INTR_PENDING | AES_INTR_MASK, _iobase + AES_INTR_REG);

	ret = crypto_register_alg(&geode_alg);
	if (ret)
		goto eiomap;

	ret = crypto_register_alg(&geode_ecb_alg);
	if (ret)
		goto ealg;

	ret = crypto_register_alg(&geode_cbc_alg);
	if (ret)
		goto eecb;

	printk(KERN_NOTICE "geode-aes: GEODE AES engine enabled.\n");
	return 0;

 eecb:
	crypto_unregister_alg(&geode_ecb_alg);

 ealg:
	crypto_unregister_alg(&geode_alg);

 eiomap:
	pci_iounmap(dev, _iobase);

 erequest:
	pci_release_regions(dev);

 eenable:
	pci_disable_device(dev);

	printk(KERN_ERR "geode-aes:  GEODE AES initialization failed.\n");
	return ret;
}

static struct pci_device_id geode_aes_tbl[] = {
	{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_LX_AES), } ,
	{ 0, }
};

MODULE_DEVICE_TABLE(pci, geode_aes_tbl);

static struct pci_driver geode_aes_driver = {
	.name = "Geode LX AES",
	.id_table = geode_aes_tbl,
	.probe = geode_aes_probe,
	.remove = geode_aes_remove,
};

module_pci_driver(geode_aes_driver);

MODULE_AUTHOR("Advanced Micro Devices, Inc.");
MODULE_DESCRIPTION("Geode LX Hardware AES driver");
MODULE_LICENSE("GPL");


text:
package net.kuujo.vertigo.io.group;

import net.kuujo.vertigo.io.Input;

import org.vertx.java.core.Handler;

/**
 * Input groups represent collections of input messages.

 *
 * In order for an input group to receive messages, an output group
 * of the same name must have sent messages from the other side of
 * the connection. Each time an output group is created a corresponding
 * input group will be created on the other side of the connection.

 *
 * Input groups use a very particular order of operations. When a new
 * group message is received on an input connection, the connection will
 * create a corresponding input group. The group will not receive any
 * messages until it has registered a message handler. Once a message
 * handler has been registered, the input group will notify the
 * corresponding output group that it's prepared to accept messages.
 * This allows time for input groups to call asynchronous APIs during
 * setup.

 *
 * Input group messages will be received in strong order just as all
 * other Vertigo messages. The input group uses the underlying connection
 * to validate message ordering. This ordering helps guarantee that
 * all child groups will be ended before the parent is ended. This allows
 * inputs to reliably create and destroy state using start and end handlers.
 *
 * @author Jordan Halterman
 */
public interface InputGroup extends MessageGroup<InputGroup>, Input<InputGroup> {

  /**
   * Registers a start handler on the group.
   *
   * @param handler A handler to be called when the group is started.
   * @return The input group.
   */
  <T> InputGroup startHandler(Handler<T> handler);

  /**
   * Registers an end handler on the group.
   *
   * @param handler A handler to be called when the group is ended.
   * @return The input group.
   */
  <T> InputGroup endHandler(Handler<T> handler);

}


text:
package com.intellij.spring.model.highlighting.jam;

import com.intellij.find.findUsages.FindUsagesHandler;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.spring.model.jam.utils.SpringJamUtils;
import com.intellij.spring.model.jam.javaConfig.SpringJavaExternalBean;
import com.intellij.spring.model.xml.DomSpringBean;
import javax.annotation.Nonnull;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SpringJavaBeanReferencesFindUsagesHandler extends FindUsagesHandler {
  private final DomSpringBean mySpringBean;

  public SpringJavaBeanReferencesFindUsagesHandler(final DomSpringBean springBean) {
    super(springBean.getIdentifyingPsiElement());
    mySpringBean = springBean;
  }

  @Nonnull
  public PsiElement[] getSecondaryElements() {
    final List<SpringJavaExternalBean> list = SpringJamUtils.findExternalBeanReferences(mySpringBean);

    Set<PsiElement> psiElements = new HashSet<PsiElement>();

    for (SpringJavaExternalBean externalBean : list) {
      final PsiMethod method = externalBean.getPsiElement();
      if (method != null) {
         psiElements.add(method);
      }
    }
    return psiElements.toArray(new PsiElement[psiElements.size()]);
  }
}