text:
describe("froala", function () {

    var $compile;
    var $rootScope;
    var element = null;
    var view = null;
    var elementHtml = null;
    var viewHtml = null;
    var froalaEditorStub = null;
    var froalaEditorOnStub = null;
    var froalaEditorOffStub = null;

    // Load the froala module, which contains the directive
    beforeEach(module('froala'));

    // Store references to $rootScope and $compile
    // so they are available to all tests in this describe block
    beforeEach(inject(function (_$compile_, _$rootScope_, froalaConfig) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;

        froalaConfig.placeholderText = 'Placeholder';
        elementHtml = "

";
        viewHtml = "

";
    }));

    var compileElement = function (extraSetup) {
        setupFroalaEditorStub();
        populateScope($rootScope);
        if (extraSetup && typeof extraSetup === 'function') {
            extraSetup();
        }

        element = $compile(elementHtml)($rootScope);
    };

    var compileViewElement = function () {
    	view = $compile(viewHtml)($rootScope);
    };

    var setupFroalaEditorStub = function () {
        froalaEditorStub = sinon.stub();
        froalaEditorOnStub = sinon.stub();
        froalaEditorOffStub = sinon.stub();

        froalaEditorStub.returns({
            data: function () {
                return {$el: {on: froalaEditorOnStub, off: froalaEditorOffStub}};
            }
        });

        angular.element.fn.froalaEditor = froalaEditorStub;
    };

    var populateScope = function (scope) {
        if (scope.froalaOptions === undefined) {
            scope.froalaOptions = {};
        }
        scope.froalaOptions.initOnClick = true;
        scope.content = '';
    };

    var createEditorInManualMode = function (moreFroalaOptions) {
        elementHtml = "

";
        compileElement(function () {
            $rootScope.initEditor = function (initControls) {
                $rootScope.initControls = initControls;

                $rootScope.froalaOptions = angular.extend($rootScope.froalaOptions, moreFroalaOptions);

            };
        });
    };

    it('Requires ngModel attribute', function () {
        expect(function () {
            $compile("

")($rootScope);
        }).toThrow();
    });

    it('Adds an ID to the html element', function () {
        compileElement();

        expect(element.attr('id')).toEqual('froala-0');
    });

    it('Combines the global and local configuration options', function () {
        compileElement();

        expect(froalaEditorStub.args[0][0].placeholderText).toEqual('Placeholder');
        expect(froalaEditorStub.args[0][0].initOnClick).toBeTruthy();
    });

    it('Uses default option values when no options are provided', function () {
        compileElement();

        expect(froalaEditorStub.args[0][0].immediateAngularModelUpdate).toBeFalsy();
    });

    it('Can overwrite default options', function () {
        $rootScope.froalaOptions = {immediateAngularModelUpdate: true};
        compileElement();

        expect(froalaEditorStub.args[0][0].immediateAngularModelUpdate).toBeTruthy();
    });

    it('Returns the instantiated editor in the options', function () {
        compileElement();

        expect($rootScope.froalaOptions.froalaEditor).toBeDefined();
    });

    it('Considers tags with whitespaces as empty content', function () {
        elementHtml = "<input froala='froalaOptions' ng-model='content' required/>";
        compileElement();

        $rootScope.content = '           ';
        $rootScope.$digest();

        expect(element.attr('class')).toContain('ng-invalid');
    });

    it('Registers the Key Up event', function () {
        $rootScope.froalaOptions = {immediateAngularModelUpdate: true};
        compileElement();

        expect(froalaEditorOnStub.args[0][0]).toEqual('keyup');
    });

    it('Does not register the Key Up event if immediateAngularModelUpdate is false', function () {
        $rootScope.froalaOptions = {immediateAngularModelUpdate: false};
        compileElement();

        expect(froalaEditorOnStub.args.length).toEqual(0);
    });

    it('Destroys editor when directive is destroyed', function () {
        compileElement();

        $rootScope.$destroy();

        expect(froalaEditorStub.args[1][0]).toEqual('destroy');
    });

    it('Updates the model after a key is released when option for immediate update is activated', function () {
        $rootScope.froalaOptions = {immediateAngularModelUpdate: true};
        compileElement(function () {
            froalaEditorStub.onSecondCall().returns('My String');
        });

        froalaEditorOnStub.callArgOn(1);

        expect($rootScope.content).toEqual('My String');
    });

    it('Updates the model after the froala editor content has changed', function () {
        compileElement(function () {
            froalaEditorStub.onSecondCall().returns('My String');
        });

        element.trigger('froalaEditor.contentChanged');

        expect($rootScope.content).toEqual('My String');
    });

    it('Updates the froala editor and reset the undo stack after the model changes', function () {
        compileElement();

        $rootScope.content = 'New Text';
        $rootScope.$digest();

        expect(froalaEditorStub.getCall(1).args[0]).toEqual('html.set');
        expect(froalaEditorStub.getCall(1).args[1]).toEqual('New Text');

        expect(froalaEditorStub.getCall(2).args[0]).toEqual('undo.reset');

    });

    it('Allows to register event handlers', function () {
        var callbackSpy = sinon.spy();
        compileElement(function () {
            $rootScope.froalaOptions.events = {
                'froalaEditor.focus': callbackSpy
            };
        });

        element.trigger('froalaEditor.focus');

        expect(callbackSpy.called).toBeTruthy();
    });

    it('Does not initialize the editor when in manual mode', function () {
        createEditorInManualMode();
        expect(froalaEditorStub.called).toBeFalsy();
    });

    it('Manually controls when the editor is instantiated', function () {
        createEditorInManualMode();

        $rootScope.initControls.initialize();

        expect(froalaEditorStub.called).toBeTruthy();
    });

    it('Manually controls when the editor is destroyed', function () {
        createEditorInManualMode();

        $rootScope.initControls.initialize();
        $rootScope.initControls.destroy();

        expect(froalaEditorStub.args[1][0]).toEqual('destroy');
    });

    it('Does not re-initialize the editor once instantiated', function () {
        createEditorInManualMode();

        $rootScope.initControls.initialize();
        $rootScope.initControls.initialize();

        expect(froalaEditorStub.callCount).toEqual(1);
    });

    it('Can re-initialize the editor after closing it', function () {
        createEditorInManualMode();

        $rootScope.initControls.initialize();
        $rootScope.initControls.destroy();
        $rootScope.initControls.initialize();

        expect(froalaEditorStub.callCount).toEqual(3); //init, close and init again
    });

    it('Returns the editor after initialing it', function () {
        createEditorInManualMode();

        $rootScope.initControls.initialize();

        expect($rootScope.initControls.getEditor()).toBeDefined();
    });

    it('Returns a NULL editor if it was not manually initialized', function () {
        createEditorInManualMode();

        expect($rootScope.initControls.getEditor()).toBeNull();
    });

    it('Allows create then destroy then create with options preserved', function() {
        var linkList = [
            {
                text: 'MSN',
                href: 'http://www.msn.com'
            },
            {
                text: 'NY Times',
                href: 'http://www.nytimes.com',
                rel: 'nofollow'
            },
            {
                displayText: 'Tellwise',
                href: 'http://www.tellwise.com',
                target: '_blank'
            },
            {
                text: 'Bing',
                displayText: 'Bing',
                href: 'http://www.bing.com',
                target: '_blank',
                rel: 'nofollow'
            }
        ];
        createEditorInManualMode({
            linkList: linkList
        });

        //
        // First initialize
        //
        $rootScope.initControls.initialize();
        expect($rootScope.initControls.getEditor()).toBeDefined();

        //
        // Destroy
        //
        $rootScope.initControls.destroy();

        //
        // Second initialize
        //
        $rootScope.initControls.initialize();
        expect($rootScope.initControls.getEditor()).toBeDefined();

        //
        // Would be nice to verify that the linkList is applied to froalaEditor
        //

    });

		it('Sets the view to the value of the model', function () {
				$rootScope.content = 'New Text';

				compileViewElement();
				$rootScope.$digest();

      	expect(view.html()).toEqual("New Text");
		});
});


text:
@interface FotoViewerTableViewController : UITableViewController

@end

redpajama_set_name: RedPajamaGithub


text:
import * as chalk from 'chalk'
import * as readline from 'readline'
import { exec } from 'child_process'

import {
  existsSync,
  readFileSync,
  writeFileSync,
  read
} from 'fs'

import { show } from './views/app'
import { MigrationRunner } from './tasks/migrate'
import { BackupRunner } from './tasks/backup'
import { Linter } from './tasks/lint'
import { MigrationDocument } from './tasks/migration/document';
import { EnvironmentConfig } from './lib/environment';
import { create } from './lib/database';
import { join } from 'path';

import {
  commandHelp,
  showSimpleHelp,
  detailedHelp
} from './lib/cli-help'

import { CredentialStore } from './lib/credential-store';

// todo: read some things
const version = 'v0.1 (alpha)'

const flag = (args, text) => {
  return args.indexOf(text) > -1
}

// one of the few mutable things in the file.
let hosts

/**
 * Extracts arg values of the form --arg-name=value
 * @param args argv from the process, but scoped to the specific sub-command
 * @param text the option flag to match
 */
const option = (args, text) => {
  const token = text + '=';

  for (let i = 0; i < args.length; i++) {
    const e = args[i];

    if (e.startsWith(token)) {
      const [_, val] = e.split('=')

      return val
    }
  }
}

const backup = (args) => {

  const [server, ...rest] = args
  const target = hosts.find(server)

  if (!target) {
    die(`Unknown server: ${server}, add to your hosts.yml file and run again`)
  }

  const options = {
    scriptPerObject: true,
    safe: true
  }

  if (rest) {
    options.scriptPerObject = flag(rest, '--script-per-object')
    options.safe = flag(rest, '--safe')
  }

  const db = create(target)

  db.getSchema()
    .then((schema) => {
      const runner = new BackupRunner(target)
      runner.on('log', (msg) => console.log(msg))
      runner.on('done', () => process.exit(0))

      runner.run(schema, options)
    })
}

const die = (message) => {
  console.log(chalk.red(message));
  process.exit(1)
}

const log = function (message) {
  const d = new Date()
  const date = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear()
  const time = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
  const ts = date + ' ' + time

  console.log(chalk.yellow(ts) + ': ' + message)
}

const migrate = (args) => {
  if (!args.length || args[0] === 'help') {
    die('dbm migrate <doc> <environment>')
  }

  function completer(line) {
    const completions = 'r retry s skip c cancel'.split(' ');
    const hits = completions.filter((c) => { return c.indexOf(line) === 0 });
    return [hits.length ? hits : completions, line];
  }

  const c: any = completer // ignore typechecking
  const rl = readline.createInterface(process.stdin, process.stdout, c)
  const [docfile, envName, ...rest] = args;

  const server = hosts.find(envName)
  const doc = new MigrationDocument(docfile)
  const runner = new MigrationRunner(doc, server)

  function prompt() {
    const failed = 'Step failed! (r)etry, (s)kip, (c)ancel (default: r)'
    rl.question(failed, (line) => {
      switch (line.toLowerCase()) {
        case 'r':
        case 'retry':
          runner.retry();
          break;

        case 's':
        case 'skip':
          runner.skip();
          break;

        case 'c':
        case 'cancel':
          runner.stop();
          break;

        default: prompt()
      }
    })
  }

  runner.on('error', function (err) {
    console.log(chalk.red(err))

    prompt()
  })

  runner.on('log', function (msg) {
    log(msg)
  })

  runner.on('done', function (msg) {
    rl.close()
  })

  // todo: explain steps.
  rl.question('Start migration?', function (answer) {
      answer === 'y' && runner.start()
      answer === 'n' && process.exit(0)
  })
}

const config = (args) => {
  const action = args.unshift()

  if (!action) {
    die('Unrecognized sub-action.')
  }

  const rl = readline.createInterface(process.stdin, process.stdout)

  console.log('DBM_HOME: ' + home)
  console.log('hosts: ')
  console.log(JSON.stringify(hosts.servers(), undefined, ' '));

  rl.question('enter passphrase: ', function (phrase) {

    // todo: if phrase is falsy, try non-encrypted
    const store = new CredentialStore({ encrypted: false })
    console.log('credentials: ')

    try {
      store.open(phrase)
      console.log(store.getAll())

      store.close();
    } catch (e) {
      console.log(chalk.red(e))
    }

    rl.close()
  })
}

const lint = (args) => {
  if (!args.length || args[0] === 'help') {
    die('dbm lint **/*.sql --rules=conf.yml --dump-ast')
  }

  const options = {
    rules: option(args, '--rules'),
    dumpAst: flag(args, '--dump-ast')
  }

  // todo: support globs
  const linter = new Linter(options);
  const file = readFileSync(args[0])
  linter.lint(file);
}

const analyze = (args) => {
  if (!args.length || args[0] === 'help') {
    die('dbm analyze some/server/db --config=analysis.yml --verbose')
  }
}

const compare = (args) => {
  if (!args.length || args[0] === 'help') {
    die('dbm compare dev/foo test/foo')
  }
}

const optimize = (args) => {
  if (!args.length || args[0] === 'help') {
    die('dbm optimize some/data/path --config=basic_optimizations.yml --verbose')
  }
}

const help = (args) => {
  if (args.length === 0) showDefaultHelp();

  const command = args.shift();
  const help = commandHelp[command]

  if (help) {
    console.log(chalk.bold(help.command))
    console.log(help.description)

    for (const example of help.examples) {
      console.log(chalk.italic(example))
    }
  }

  // else, unshift and see if we have command specific help
}

const initialize = (args) => {
  const rl = readline.createInterface(process.stdin, process.stdout)

  rl.question('Where would you to save things? (default: $HOME)', function (answer) {
    if (existsSync(answer)) {

      if (process.platform === 'win32') {
        exec(`setx DBM_HOME ${answer}`)
      } else {
        exec(`echo "export DBM_HOME=${answer}" >> ~/.bashrc`)
      }
    } else {
      die('No such directory.')
    }
  })
}

const showDefaultHelp = () => {
  console.log(` Dbm - ${version}`)
  console.log('commands:')

  showSimpleHelp((l) => console.log(l))

  process.exit(0)
}

// each of these commands needs some help info
const commands = {
  init: initialize,
  backup: backup,
  migrate: migrate,
  lint: lint,
  analyze: analyze,
  optimize: optimize,
  config: config,
  compare: compare,
  help: help,
  show: show
}

const home = process.env.DBM_HOME

const init = (args) => {
  const handler = commands[args[0]];

  if (!handler) {
    console.log(chalk.red('Unrecognized command: ' + args[0]))

    console.log('valid commands:')
    for (const key in commands) {
      console.log('  ' + key)
    }

    die('run "dbm help <command>" for usage info.')
  }

  console.log(args)
  handler(args.slice(1))
}

if (process.argv.length <= 2) {
  showDefaultHelp()
} else {
  if (!home) {
    die('Missing DBM_HOME environment variable.')
  }

  hosts = new EnvironmentConfig(join(home, 'hosts.yml'))

  // todo: keep track of any of our promises outstanding.
  // this is actually handled by the vscode debugger.
  const unhandledRejections = new Map();

  process.on('unhandledRejection', (reason, p) => {
    // todo: maybe a timestamp.
    unhandledRejections.set(p, reason);
  });

  process.on('rejectionHandled', (p) => {
    unhandledRejections.delete(p);
  });
}

init(process.argv.slice(2))


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/user_image"
        android:background="@drawable/user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text_view"
        android:text="歌诗图,cool"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/delete_image"
        android:background="@drawable/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


text:
package edu.hm.hafner.analysis.parser.pmd;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
 * Java Bean class for an error of the PMD format.
 *
 * @author Ullrich Hafner
 */
@SuppressWarnings({"InstanceVariableMayNotBeInitialized", "PMD.DataClass"})
public class PmdError {
    @CheckForNull
    private String filename;
    @CheckForNull
    private String msg;
    @CheckForNull
    private String description;

    @CheckForNull
    @SuppressFBWarnings("NM")
    public String getFilename() {
        return filename;
    }

    @SuppressFBWarnings("NM")
    public void setFilename(@CheckForNull final String filename) {
        this.filename = filename;
    }

    @CheckForNull
    public String getMsg() {
        return msg;
    }

    public void setMsg(@CheckForNull final String msg) {
        this.msg = msg;
    }

    @CheckForNull
    public String getDescription() {
        return description;
    }

    public void setDescription(@CheckForNull final String description) {
        this.description = description;
    }
}


text:
-------------------------------------------------------------------------------
-- <copyright company="Sherlock">
--     Copyright 2013 Sherlock. Licensed under the Apache License, Version 2.0.
-- </copyright>
-------------------------------------------------------------------------------

CREATE PROCEDURE [Tests].[GetTestApplicationsByApplicationId]
    @id INT
AS
    SELECT
        [pk_TestApplicationId]
    FROM [Tests].[TestApplication]
    WHERE [fk_ApplicationId] = @id


text:
local plpath = require 'pl.path'
local pldir  = require 'pl.dir'
local plfile = require 'pl.file'
local qconsts = require 'Q/UTILS/lua/q_consts'

-- START: Get and validate following environment variables
-- Q_ROOT
-- Q_BUILD_DIR
-- QC_FLAGS
-- Q_LINK_FLAGS
local q_root = qconsts.Q_ROOT
assert(q_root, "Do export Q_ROOT=/home/subramon/Q/ or some such")
final_h  = q_root .. "/include/"
final_so = q_root .. "/lib/"
local q_build_dir = qconsts.Q_BUILD_DIR
-- local dbg = require 'Q/UTILS/lua.debugger'
assert(plpath.isdir(q_build_dir), "Directory not found: " .. q_build_dir)
assert(plpath.isdir(final_h), "Directory not found: " .. final_h)
assert(plpath.isdir(final_so), "Directory not found: " .. final_so)

local QC_FLAGS = qconsts.QC_FLAGS
assert(QC_FLAGS ~= "", "QC_FLAGS not provided")

local Q_LINK_FLAGS = qconsts.Q_LINK_FLAGS
assert(Q_LINK_FLAGS ~= "", "Q_LINK_FLAGS not provided")
--
-- STOP: Get and validate needed environment variables

-- TODO P1: COMMENT: What does this function do?
local function clean_defs(file)
   local cmd = string.format("cat %s | grep -v '#include'| cpp | grep -v '^#'", file)
   local handle = io.popen(cmd)
   local res = handle:read("*a")
   handle:close()
   return res
end

-- Input: source file
-- Output: true if the word "struct" occurs in the file, false otherwise
local function is_struct_file(file)
  assert(plpath.isfile(file), "Could not find file " .. file)
  if string.match(plfile.read(file), "struct ") then
    return true
  else
    return false
  end
end

 local function add_h_files_to_list(
   list,
   file_list
   )
   assert(list)
   assert( file_list and ( type(file_list) == "table" ) )
   for i = 1, #file_list do
      list[#list + 1] = clean_defs(file_list[i])
   end
   return list
 end

local tgt_so = q_build_dir .. "/libq_core.so"
local tgt_h  = q_build_dir .. "/q_core.h"
local hdir   = q_build_dir .. "/include"
local cdir   = q_build_dir .. "/src"

----------Create q_core.h
local q_struct_files = {}
local q_h = {}
local q_h_files = {}
local q_c_files = {}
local q_h_set = {}
local h_files = pldir.getfiles(hdir, "*.h")
for num = 1, #h_files do
  local file_path = h_files[num]
  if is_struct_file(file_path) then
    q_struct_files[#q_struct_files + 1] = file_path
  else
    q_h_files[#q_h_files + 1] = file_path
  end
  q_h_set[file_path] = true
end

q_h = add_h_files_to_list(q_h, q_struct_files)
q_h = add_h_files_to_list(q_h, q_h_files)
q_h = table.concat(q_h, "\n")
plfile.write(tgt_h, q_h)
pldir.copyfile(tgt_h, final_h)
print("Copied " .. tgt_h .. " to " .. final_h)

----------Create q_core.so

local q_c_files = pldir.getfiles(cdir, "*.c")
local q_c = table.concat(q_c_files, " ")
--  "gcc %s %s -I %s %s -lgomp -pthread -shared -o %s",
local q_cmd = string.format("gcc %s %s -I %s %s -o %s",
  QC_FLAGS, q_c, hdir, Q_LINK_FLAGS, tgt_so)
q_cmd = "cd " .. cdir .. "; " .. q_cmd
local status = os.execute(q_cmd)
assert(status, "gcc failed")
assert(plpath.isfile(tgt_so), "Target " .. tgt_so .. " not created")
print("Successfully created " .. tgt_so)
pldir.copyfile(tgt_so, final_so)
print("Copied " .. tgt_so .. " to " .. final_so)


text:
![Happy housing](https://github.com/happyhousing/happyhousing/blob/master/homeful/media/images/Happyhousing_logo.png)

The purpose of this app is to help recent immigrants of Seattle find affordable housing close to either their workplace, home, or preferred living location.

This application was developed on from February 6, 2015 to February February 8, 2015 for the [Hack Housing: Empowering Smarter Decisions – A Weekend Hackathon](http://investors.zillow.com/releasedetail.cfm?ReleaseID=892685).

![Screen Shot](https://github.com/happyhousing/happyhousing/blob/master/homeful/media/images/Screen%20Shot%202015-02-08%20at%201.03.34%20PM.png)
Our app is live at http://hh-helptheworld.herokuapp.com/homeful/.

## Challenge and Approach

Our submission is to address the following Low Income Renter challenge #3:
- where are the multi-family communities that accept my rental voucher, and is there availability in the communities?-
- Simple, consumer-friendly solutions to narrow their options, find available units, submit necessary information and connect with service providers.
- They can find this site by visiting the public library, or a mobile site.

1.  Open our [HappyHousing webpage](http://hh-helptheworld.herokuapp.com/homeful/)
2.  Select language
3.  Enter zip code
4.  Select the number of rooms you need.

Our approach for satisfying this challenge was to:

- Analyze current low income housing opportunities such as HUD, Seattle public housing, and Section 8.
- for much of these opportunities we realize that there is a waiting list.
- We identified that our customers would like recommendations on housing near their work or home.
- The application can be customize to their preferred language
- We pulled from the [Multi Family Data](http://zillowhack.hud.opendata.arcgis.com/datasets/c55eb46fbc3b472cabd0c2a41f805261_0)
- We pulled from the [Fair Market Rent Data](http://zillowhack.hud.opendata.arcgis.com/datasets/e29dca94b6924766a124d7c767e03b75_0)
- We use the FMR to give the search an idea of the price range for the apartments
- We use the multi-family data to provide contact information and addresses to allow in person or telephone contact.
- we also added easy to understand images for reading challenged, and native language customization.

## Team Members

Our team is comprised of:

- [@qayshp](http://github.com/qayshp) - Qays Poonawala
- [@YasharF](http://github.com/YasharF) - Yashar Fakhari
- [@ega123](http://github.com/ega123) - Shiirevjamts Munkhbat
- [@alyeung](http://github.com/alyeung) - Allan Yeung
- [Tuvshin](http://github.com/JFKHD!!!!!#*!) - Tuvshin Erdenebaatar

## Technologies, APIs, and Datasets Utilized

We made use of:

- [django](http://djangoproject.com)
- python request library
- Heroku
- JSON library
- [Google Maps](https://mapsengine.google.com/map/u/0/)
- HTML5
- [JetStrap](https://jetstrap.com)
- Google Translate plug-in

- [Multi Family Data](http://zillowhack.hud.opendata.arcgis.com/datasets/c55eb46fbc3b472cabd0c2a41f805261_0)
- [Fair Market Rent Data](http://zillowhack.hud.opendata.arcgis.com/datasets/e29dca94b6924766a124d7c767e03b75_0)

## Contributing

In order to build and run our app:
1)  Download source to your github.
2)  setup a heroku account.
3)  link github to heroku for continuous build.
4)  open up your heroku weblink.

Our code is licensed under the [MIT License](LICENSE.md). Pull requests will be accepted to this repo, pending review and approval.


text:
FactoryBot.define do
  factory :tardy do
    occurred_at { Time.now }
  end
end


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <item android:id="@+id/action_now_playing" android:title="@string/action_now_playing"
        android:orderInCategory="1" android:showAsAction="always"
        android:visible="false"/>

    <item android:id="@+id/action_settings" android:title="@string/action_settings"
        android:orderInCategory="100" android:showAsAction="never" />

</menu>


text:
class Char(object):
    def __init__(self):
        # First Char
        raven = Character()
        raven.name = "Duncan McNeil"
        raven.code_name = "The Raven"
        raven.age = 57
        raven.descrip = "Hardly Human Headmaster"
        raven.missions = 1243
        raven.victory = 1241

        clio = Character()
        clio.name = "Laia Eavening"
        clio.code_name = "Clio"
        clio.age = 15
        clio.descrip = "Beloved Bookworm"
        clio.missions = 12
        clio.victory = 8

        qilin = Character()
        qilin.name = "Yvette Van De Voorst"
        qilin.code_name = "Qilin"
        qilin.age = 18
        qilin.descrip = "The Last Unciorn"
        qilin.missions = 47
        qilin.victory = 47

        toon = Character()
        toon.name = "Rudy DeMarca"
        toon.code_name = "Toon"
        toon.age = 15
        toon.descrip = "Artistic Intent"
        toon.missions = 23
        toon.victory = 18

        atlanta = Character()
        atlanta.name = "Vijana Ravana Romana"
        atlanta.code_name = "Atlanta"
        atlanta.age = 18
        atlanta.descrip = "Psychic Gypsy Werewolf"
        atlanta.missions = 19
        atlanta.victory = 18

class Character(object):
    def __init__(self):
        self.name = ""
        self.code_name = ""
        self.age = 0
        self.descrip = ""
        self.missions = 0
        self.victory = 0
        self.__status = "PC"

    def success_rate(self):
        sr = self.victory/self.missions
        return sr


text:
[Leaflet](https://github.com/Leaflet/Leaflet) canvas layer plugin that enables you to draw elements on the edge of the
canvas that normally are cutted.

Usually When you draw points that reside on the edge of a tile,

##Requirements

It requires Leaflet 0.7.x.

##Usage

	var padding = 30;

	//create a new paddedCanvas layer with tilePadding option
    var paddedCanvas = L.tileLayer.paddedCanvas({tilePadding: padding})

    paddedCanvas.drawTile = function (canvas, tilePoint, zoom) {

    // remember to pad always to your coordinates
    var x = 125 + padding,
        y = 255 + padding;

    	var ctx = canvas.getContext('2d');
    	ctx.beginPath();
    	ctx.arc(x, y, 20, 0, 2 * Math.PI);
    	ctx.fillStyle = "rgba(0, 255, 0, 0.5)";
    	ctx.fill();
    	ctx.lineWidth = 2;
    	ctx.strokeStyle = 'black';
    	ctx.stroke();
    };
    paddedCanvas.addTo(map);

##Demo

An example can be found within the `examples` subdirectory of the repository: [Zero or Padded Layer example](//accurat.github.io/Leaflet.TileLayer.PaddedCanvas)


text:
package es.tid.cosmos.infinity.common.hadoop

import org.apache.hadoop.fs.{FileStatus, Path => HadoopPath}
import org.apache.hadoop.fs.permission.FsPermission

import es.tid.cosmos.infinity.common.fs._
import es.tid.cosmos.infinity.common.permissions.PermissionsMask

/** This object provides implicits to bling Hadoop objects into their equivalent Infinity ones. */
object HadoopConversions {

  implicit class FsPermissionConversion(val permission: FsPermission) extends AnyVal {
    def toInfinity: PermissionsMask = PermissionsMask.fromShort(permission.toShort)
  }

  implicit class PermissionsMaskConversion(val permission: PermissionsMask) extends AnyVal {
    def toHadoop: FsPermission = new FsPermission(permission.toShort)
  }

  implicit class HadoopPathConversion(val path: HadoopPath) extends AnyVal {
    def toInfinity: Path = Path.absolute(path.toUri.getPath)
  }

  implicit class PathConversion(val path: Path) extends AnyVal {
    def toHadoop: HadoopPath = new HadoopPath(s"infinity:${path.toString}")
  }

  implicit class AbstractMetadataConversion(val metadata: AbstractMetadata) extends AnyVal {
    def toHadoop: FileStatus = new FileStatus(
      metadata.size,
      metadata.isDirectory,
      metadata.replication,
      metadata.blockSize,
      metadata.modificationTime.getTime,
      metadata.accessTime.fold(0l)(_.getTime),
      metadata.permissions.toHadoop,
      metadata.owner,
      metadata.group,
      metadata.path.toHadoop
    )
  }
}


text:
package org.arquillian.extension.governor.github.impl;

import org.arquillian.extension.governor.api.GovernorClientFactory;
import org.arquillian.extension.governor.github.configuration.GitHubGovernorConfiguration;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.jboss.arquillian.core.spi.Validate;

/**
 * @author Alex Soto
 */
public class GitHubGovernorClientFactory implements GovernorClientFactory<GitHubGovernorConfiguration, GitHubGovernorClient> {

    private GitHubGovernorConfiguration gitHubGovernorConfiguration;

    @Override
    public GitHubGovernorClient build(
            GitHubGovernorConfiguration governorConfiguration) throws Exception {
        Validate.notNull(governorConfiguration, "GitHub governor configuration has to be set.");
        this.gitHubGovernorConfiguration = governorConfiguration;

        final GitHubClient gitHubClient = new GitHubClient();
        if (this.gitHubGovernorConfiguration.getUsername() != null && this.gitHubGovernorConfiguration.getUsername().length() > 0 && this.gitHubGovernorConfiguration.getPassword() != null && this.gitHubGovernorConfiguration.getPassword().length() > 0) {
            gitHubClient.setCredentials(this.gitHubGovernorConfiguration.getUsername(), this.gitHubGovernorConfiguration.getPassword());
        }

        if (this.gitHubGovernorConfiguration.getToken() != null && this.gitHubGovernorConfiguration.getToken().length() > 0) {
            gitHubClient.setOAuth2Token(gitHubGovernorConfiguration.getToken());
        }

        final GitHubGovernorClient gitHubGovernorClient = new GitHubGovernorClient(gitHubClient, gitHubGovernorConfiguration);
        gitHubGovernorClient.setGovernorStrategy(new GitHubGovernorStrategy(this.gitHubGovernorConfiguration));

        return gitHubGovernorClient;
    }

}


text:
package io.zerodi.windbag.core;

import com.fasterxml.jackson.databind.SerializationFeature;
import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.assets.AssetsBundle;
import com.yammer.dropwizard.config.Bootstrap;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.views.ViewBundle;
import io.zerodi.windbag.api.resources.ServerConfigurationResource;
import io.zerodi.windbag.api.resources.ServerControlResource;
import io.zerodi.windbag.api.resources.WebAppController;
import io.zerodi.windbag.app.healthcheck.ServerDefinitionHealthCheck;
import io.zerodi.windbag.app.registry.ConnectionRegistryImpl;
import io.zerodi.windbag.core.protocol.ConnectionFactoryRegistry;

/**
 * Main class, spinning the core application.
 *
 * @author zerodi
 */
public class ApplicationService extends Service<ApplicationConfiguration> {

	public static void main(String[] args) throws
	                                       Exception {
		new ApplicationService().run(args);
	}

	@Override
	public void initialize(Bootstrap<ApplicationConfiguration> bootstrap) {
		bootstrap.setName("windbag");
		bootstrap.getObjectMapperFactory()
		         .enable(SerializationFeature.WRAP_ROOT_VALUE);

		bootstrap.addBundle(new AssetsBundle("/assets"));
		bootstrap.addBundle(new ViewBundle());
	}

	@Override
	public void run(ApplicationConfiguration configuration,
	                Environment environment) throws
	                                         Exception {
		ConnectionFactoryRegistry connectionFactoryRegistry = ConnectionFactoryRegistry.getInstance(configuration);
		ConnectionRegistryImpl connectionRegistry = ConnectionRegistryImpl.getInstance(connectionFactoryRegistry);

		environment.manage(connectionRegistry); // registry of open connections will need to be shut down along with the main application.

		environment.addResource(ServerConfigurationResource.getInstance(configuration));
		environment.addResource(ServerControlResource.getInstance(configuration,
		                                                          connectionRegistry));
		environment.addResource(WebAppController.getInstance());

		environment.addHealthCheck(ServerDefinitionHealthCheck.getInstance(configuration));
	}
}


text:
/* FASTGAP https://github.com/GustavoCostaW/FastGap */

(function (window) {
	//navigator object
	var Navigator = window.Navigator = {
		control: true,
		currentPage: '',
		isBack: false
	};
	//load page
	Navigator.loadPage = function (url) {
		//if string page is url
		if (typeof url == "string") {
			Navigator.currentPage = url;
		} else {
			// or page is data-url attr in menu ul li element
			Navigator.currentPage = $(this).data("url");
		}
		//start transition
		Transition.start();
	};

})(window);


text:
from .parsers import Parser
from .wrappers import ParserWrapper


text:
const sensors = require("./sensors/index.js");
const config = require("./config.js");
const db = require("./pushDestinations/gcpDatastore.js");
const pubnub = require("./pushDestinations/pubnub.js");
const schedule = require("node-schedule");

var currentNumber = 0;
var currentAverages = {};

sensors
	.load()
	.then(pubnub.connect())
	.then(db.connect())
	.then(function() {
		// read first measurement immediately
		setImmediate(readData);
		// read measurements on interval
		setInterval(readData, config.recordInterval);
		// send to GCP on cron interval
		schedule.scheduleJob(config.storeCron, function(fireDate) {
			if (currentNumber > 0) {
				Object.keys(currentAverages).forEach(key => {
					// Calculate averages
					currentAverages[key] = (
						currentAverages[key] / currentNumber
					).toFixed(config.decimalPlaces[key]);
				});
				currentAverages.time = fireDate;
				db.pushData(currentAverages); // Push averages to cloud datastore

				// Clear averages
				currentAverages = {};
				currentNumber = 0;
			}
		});
	})
	.catch(function(err) {
		console.error(err);
		return;
	});

function addAverages(values) {
	Object.keys(values).forEach(key => {
		if (key == "time") return;
		if (currentAverages[key]) {
			currentAverages[key] += parseFloat(values[key]);
		} else {
			currentAverages[key] = parseFloat(values[key]);
		}
	});
	currentNumber++;
}

function readData() {
	// read data from sensors
	sensors
		.run()
		.then(function(values) {
			values.time = new Date();
			pubnub.pushData(values);
			addAverages(values);
			console.log("Successfully logged data [" + values.time + "]");
		})
		.catch(function(err) {
			console.error(err);
			return;
		});
}


text:
package loadbalancer

import (
	"github.com/docker/infrakit/pkg/cli"
	logutil "github.com/docker/infrakit/pkg/log"
	"github.com/docker/infrakit/pkg/spi/loadbalancer"
)

var log = logutil.New("module", "cli/v0/loadbalancer")

func init() {
	cli.Register(loadbalancer.InterfaceSpec,
		[]cli.CmdBuilder{
			Routes,
			Backends,
		})
}


text:
namespace signalpp {

class AccountManager {
	std::unique_ptr<TextSecureServer> m_server;
	StorageContainer *m_storage = nullptr;

public:
    AccountManager(class StorageContainer *storage,
    					const std::string& url,
						const unsigned short ports[],
						const std::string& username,
						const std::string& password)
	: m_server(new TextSecureServer(url, username, password, ports))
	, m_storage(storage) {
    }

	inline void requestVoiceVerification(const std::string& number) {
	    m_server->requestVerificationVoice(number);
	}

	inline void requestSMSVerification(const std::string& number) {
	    m_server->requestVerificationSMS(number);
	}

	bool registerSingleDevice() {
		return false;
	}

	bool registerSecondDevice(std::function<void (const std::string&)> setProvisioningUrl,
								std::function<std::string(const std::string&)> confirmNumber);

	void refreshPreKeys() {}
	void createAccount(const std::string& number,
									const std::string& provisioningCode,
									ec_key_pair *identityKeyPair,
									const std::string& deviceName,
									const std::string& userAgent);
	prekey::result generateKeys(size_t count = 100);
};

} // namespace signalpp

#endif // _ACCOUNT_MANAGER_H_


text:
'use strict';

import GL from "gl-react";
import React, { Component }  from "react";

import {
    GPUImage3x3ConvolutionFilter
} from '../ImageProcessing/GPUImage3x3ConvolutionFilter';

export const GPUImageEmbossFilter = GL.createComponent(
    ({children, texelWidth, texelHeight, intensity})=>{
        return(
            <GPUImage3x3ConvolutionFilter
                texelWidth={texelWidth}
                texelHeight={texelHeight}
                convolutionMatrix={[-2.0 * intensity, -intensity, 0.0,
                                    -intensity, 1.0, intensity,
                                    0.0, intensity, 2.0 * intensity]}
                >
                {children}
            </GPUImage3x3ConvolutionFilter>
        );
    },
    {
        defaultProps: {
            intensity: 1.0,
        }
    }
);


text:
import Ember from 'ember';
import layout from '../templates/components/ttr-next-tetromino';
import tetrominos from '../utils/tetrominos';

const {
  Component,
  computed,
  inject
} = Ember;

export default Component.extend({
  layout: layout,
  classNames: ['ttr-tetromino'],
  tagName: 'g',
  attributeBindings: ['style'],

  style: computed('scale', 'type', function() {
    let scale = this.get('scale');
    let type = this.get('type');
    let center = tetrominos[type].nextCenter;
    let style = `transform: translate(${scale * center[0]}px, ${scale * center[1]}px);`;
    return Ember.String.htmlSafe(style);
  }),

  tetromino: inject.service(),
  bag: inject.service(),

  scale: computed.reads('tetromino.scale'),

  type: computed('bag.queue.lastObject', function() {
    return this.get('bag.queue.lastObject');
  }),

  positions: computed('type', function() {
    // TODO: copied code from tetromino service (make a mixin or other service?)
    let type = this.get('type');
    let data = tetrominos[type].positions;
    let positions = [];
    for (let i = 0, len = data[0].length; i < len; i++) {
      let position = {
        x: data[0][i],
        y: data[1][i]
      };
      positions.push(position);
    }
    return positions;
  }),
});


text:
require "spec_helper"

module Capistrano
  describe Configuration do
    let(:config) { Configuration.new }
    let(:servers) { stub }

    describe ".new" do
      it "accepts initial hash" do
        configuration = described_class.new(custom: "value")
        expect(configuration.fetch(:custom)).to eq("value")
      end
    end

    describe ".env" do
      it "is a global accessor to a single instance" do
        Configuration.env.set(:test, true)
        expect(Configuration.env.fetch(:test)).to be_truthy
      end
    end

    describe ".reset!" do
      it "blows away the existing `env` and creates a new one" do
        old_env = Configuration.env
        Configuration.reset!
        expect(Configuration.env).not_to be old_env
      end
    end

    describe "roles" do
      context "adding a role" do
        subject { config.role(:app, %w{server1 server2}) }

        before do
          Configuration::Servers.expects(:new).returns(servers)
          servers.expects(:add_role).with(:app, %w{server1 server2}, {})
        end

        it "adds the role" do
          expect(subject)
        end
      end
    end

    describe "setting and fetching" do
      subject { config.fetch(:key, :default) }

      context "set" do
        it "sets by value" do
          config.set(:key, :value)
          expect(subject).to eq :value
        end

        it "sets by block" do
          config.set(:key) { :value }
          expect(subject).to eq :value
        end

        it "raises an exception when given both a value and block" do
          expect { config.set(:key, :value) { :value } }.to raise_error(Capistrano::ValidationError)
        end
      end

      context "set_if_empty" do
        it "sets by value when none is present" do
          config.set_if_empty(:key, :value)
          expect(subject).to eq :value
        end

        it "sets by block when none is present" do
          config.set_if_empty(:key) { :value }
          expect(subject).to eq :value
        end

        it "does not overwrite existing values" do
          config.set(:key, :value)
          config.set_if_empty(:key, :update)
          config.set_if_empty(:key) { :update }
          expect(subject).to eq :value
        end
      end

      context "value is not set" do
        it "returns the default value" do
          expect(subject).to eq :default
        end
      end

      context "value is a proc" do
        subject { config.fetch(:key, proc { :proc }) }
        it "calls the proc" do
          expect(subject).to eq :proc
        end
      end

      context "value is a lambda" do
        subject { config.fetch(:key, -> { :lambda }) }
        it "calls the lambda" do
          expect(subject).to eq :lambda
        end
      end

      context "value inside proc inside a proc" do
        subject { config.fetch(:key, proc { proc { "some value" } }) }
        it "calls all procs and lambdas" do
          expect(subject).to eq "some value"
        end
      end

      context "value inside lambda inside a lambda" do
        subject { config.fetch(:key, -> { -> { "some value" } }) }
        it "calls all procs and lambdas" do
          expect(subject).to eq "some value"
        end
      end

      context "value inside lambda inside a proc" do
        subject { config.fetch(:key, proc { -> { "some value" } }) }
        it "calls all procs and lambdas" do
          expect(subject).to eq "some value"
        end
      end

      context "value inside proc inside a lambda" do
        subject { config.fetch(:key, -> { proc { "some value" } }) }
        it "calls all procs and lambdas" do
          expect(subject).to eq "some value"
        end
      end

      context "lambda with parameters" do
        subject { config.fetch(:key, ->(c) { c }).call(42) }
        it "is returned as a lambda" do
          expect(subject).to eq 42
        end
      end

      context "block is passed to fetch" do
        subject { config.fetch(:key, :default) { raise "we need this!" } }

        it "returns the block value" do
          expect { subject }.to raise_error(RuntimeError)
        end
      end

      context "validations" do
        before do
          config.validate :key do |_, value|
            raise Capistrano::ValidationError unless value.length > 3
          end
        end

        it "validates string without error" do
          config.set(:key, "longer_value")
        end

        it "validates block without error" do
          config.set(:key) { "longer_value" }
          expect(config.fetch(:key)).to eq "longer_value"
        end

        it "validates lambda without error" do
          config.set :key, -> { "longer_value" }
          expect(config.fetch(:key)).to eq "longer_value"
        end

        it "raises an exception on invalid string" do
          expect { config.set(:key, "sho") }.to raise_error(Capistrano::ValidationError)
        end

        it "raises an exception on invalid string provided by block" do
          config.set(:key) { "sho" }
          expect { config.fetch(:key) }.to raise_error(Capistrano::ValidationError)
        end

        it "raises an exception on invalid string provided by lambda" do
          config.set :key, -> { "sho" }
          expect { config.fetch(:key) }.to raise_error(Capistrano::ValidationError)
        end
      end

      context "appending" do
        subject { config.append(:linked_dirs, "vendor/bundle", "tmp") }

        it "returns appended value" do
          expect(subject).to eq ["vendor/bundle", "tmp"]
        end

        context "on non-array variable" do
          before { config.set(:linked_dirs, "string") }
          subject { config.append(:linked_dirs, "vendor/bundle") }

          it "returns appended value" do
            expect(subject).to eq ["string", "vendor/bundle"]
          end
        end
      end

      context "removing" do
        before :each do
          config.set(:linked_dirs, ["vendor/bundle", "tmp"])
        end

        subject { config.remove(:linked_dirs, "vendor/bundle") }

        it "returns without removed value" do
          expect(subject).to eq ["tmp"]
        end

        context "on non-array variable" do
          before { config.set(:linked_dirs, "string") }

          context "when removing same value" do
            subject { config.remove(:linked_dirs, "string") }

            it "returns without removed value" do
              expect(subject).to eq []
            end
          end

          context "when removing different value" do
            subject { config.remove(:linked_dirs, "othervalue") }

            it "returns without removed value" do
              expect(subject).to eq ["string"]
            end
          end
        end
      end
    end

    describe "keys" do
      subject { config.keys }

      before do
        config.set(:key1, :value1)
        config.set(:key2, :value2)
      end

      it "returns all set keys" do
        expect(subject).to match_array [:key1, :key2]
      end
    end

    describe "deleting" do
      before do
        config.set(:key, :value)
      end

      it "deletes the value" do
        config.delete(:key)
        expect(config.fetch(:key)).to be_nil
      end
    end

    describe "asking" do
      let(:question) { stub }
      let(:options) { Hash.new }

      before do
        Configuration::Question.expects(:new).with(:branch, :default, options)
                               .returns(question)
      end

      it "prompts for the value when fetching" do
        config.ask(:branch, :default, options)
        expect(config.fetch(:branch)).to eq question
      end
    end

    describe "setting the backend" do
      it "by default, is SSHKit" do
        expect(config.backend).to eq SSHKit
      end

      it "can be set to another class" do
        config.backend = :test
        expect(config.backend).to eq :test
      end

      describe "ssh_options for Netssh" do
        it "merges them with the :ssh_options variable" do
          config.set :format, :pretty
          config.set :log_level, :debug
          config.set :ssh_options, user: "albert"
          SSHKit::Backend::Netssh.configure { |ssh| ssh.ssh_options = { password: "einstein" } }
          config.configure_backend

          expect(
            config.backend.config.backend.config.ssh_options
          ).to include(user: "albert", password: "einstein")
        end
      end
    end

    describe "dry_run?" do
      it "returns false when using default backend" do
        expect(config.dry_run?).to eq(false)
      end

      it "returns true when using printer backend" do
        config.set :sshkit_backend, SSHKit::Backend::Printer

        expect(config.dry_run?).to eq(true)
      end
    end

    describe "custom filtering" do
      it "accepts a custom filter object" do
        filter = Object.new
        def filter.filter(servers)
          servers
        end
        config.add_filter(filter)
      end

      it "accepts a custom filter as a block" do
        config.add_filter { |servers| servers }
      end

      it "raises an error if passed a block and an object" do
        filter = Object.new
        def filter.filter(servers)
          servers
        end

        expect { config.add_filter(filter) { |servers| servers } }.to raise_error(ArgumentError)
      end

      it "raises an error if the filter lacks a filter method" do
        filter = Object.new
        expect { config.add_filter(filter) }.to raise_error(TypeError)
      end

      it "calls the filter method of a custom filter" do
        ENV.delete "ROLES"
        ENV.delete "HOSTS"

        servers = Configuration::Servers.new

        servers.add_host("test1")
        servers.add_host("test2")
        servers.add_host("test3")

        filtered_servers = servers.take(2)

        filter = mock("custom filter")
        filter.expects(:filter)
              .with { |subset| subset.is_a? Configuration::Servers }
              .returns(filtered_servers)

        config.add_filter(filter)
        expect(config.filter(servers)).to eq(filtered_servers)
      end
    end
  end
end


text:
#include "tensorflow/core/util/strided_slice_op.h"
#include "tensorflow/compiler/tf2xla/literal_util.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/mem.h"

namespace tensorflow {
namespace {

class StridedSliceOp : public XlaOpKernel {
 public:
  explicit StridedSliceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    const TensorShape input_shape = ctx->InputShape(0);

    TensorShape final_shape;
    gtl::InlinedVector<int64, 4> begin;
    gtl::InlinedVector<int64, 4> end;
    gtl::InlinedVector<int64, 4> strides;

    xla::Literal begin_literal, end_literal, strides_literal;
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &begin_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &end_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal));

    Tensor begin_tensor, end_tensor, strides_tensor;
    OP_REQUIRES_OK(
        ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor));
    OP_REQUIRES_OK(ctx,
                   LiteralToHostTensor(end_literal, index_type_, &end_tensor));
    OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_,
                                            &strides_tensor));

    TensorShape dummy_processing_shape;
    ShapeReadWriteFromTensorShape wrapped_final_shape(&final_shape);
    ShapeReadWriteFromTensorShape wrapped_dummy_processing_shape(
        &dummy_processing_shape);
    bool dummy = false;
    OP_REQUIRES_OK(
        ctx, ValidateStridedSliceOp(
                 &begin_tensor, &end_tensor, strides_tensor,
                 ShapeReadWriteFromTensorShape(&input_shape), begin_mask_,
                 end_mask_, ellipsis_mask_, new_axis_mask_, shrink_axis_mask_,
                 &wrapped_dummy_processing_shape, &wrapped_final_shape, &dummy,
                 &dummy, &dummy, &begin, &end, &strides));

    gtl::InlinedVector<int64, 4> dimensions_to_reverse;
    gtl::InlinedVector<int64, 4> slice_begin, slice_end;
    bool simple_strides = true;
    for (int i = 0; i < begin.size(); ++i) {
      simple_strides &= (std::abs(strides[i]) == 1);
      if (strides[i] > 0) {
        slice_begin.push_back(begin[i]);
        slice_end.push_back(end[i]);
      } else {
        // Negative stride: swap begin and end, add 1 because the interval
        // is semi-open, and mark the dimension to be reversed.
        slice_begin.push_back(end[i] + 1);
        slice_end.push_back(begin[i] + 1);
        dimensions_to_reverse.push_back(i);
      }
    }
    xla::ComputationDataHandle slice =
        ctx->builder()->Slice(ctx->Input(0), slice_begin, slice_end);
    if (!dimensions_to_reverse.empty()) {
      slice = ctx->builder()->Rev(slice, dimensions_to_reverse);
    }

    // If at least one of the strides is > 1 (or < -1) then use Slice
    // to pull out each of the strided slices, and Concat to put them
    // together again.
    if (!simple_strides) {
      // Re-adjust the begin and end now that the periphery has been
      // sliced away.
      for (int d = 0; d < strides.size(); ++d) {
        slice_end[d] -= slice_begin[d];
        slice_begin[d] = 0;
      }

      for (int d = 0; d < strides.size(); ++d) {
        int64 stride = std::abs(strides[d]);
        if (stride > 1) {
          std::vector<xla::ComputationDataHandle> to_concat;
          int64 end = slice_end[d];
          for (int64 i = 0; i < end; i += stride) {
            slice_begin[d] = i;
            slice_end[d] = i + 1;
            to_concat.push_back(
                ctx->builder()->Slice(slice, slice_begin, slice_end));
          }
          slice = ctx->builder()->ConcatInDim(to_concat, d);
          slice_begin[d] = 0;
          slice_end[d] = to_concat.size();
        }
      }
    }

    slice = ctx->builder()->Reshape(slice, final_shape.dim_sizes());
    ctx->SetOutput(0, slice);
  }

 private:
  int32 begin_mask_, end_mask_;
  int32 ellipsis_mask_, new_axis_mask_, shrink_axis_mask_;
  DataType index_type_;
};

REGISTER_XLA_OP(Name("StridedSlice"), StridedSliceOp);

class StridedSliceGradOp : public XlaOpKernel {
 public:
  explicit StridedSliceGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    TensorShape processing_shape, final_shape;
    gtl::InlinedVector<int64, 4> begin;
    gtl::InlinedVector<int64, 4> end;
    gtl::InlinedVector<int64, 4> strides;

    TensorShape input_shape;
    OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &input_shape));

    xla::Literal begin_literal, end_literal, strides_literal;
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &begin_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &end_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal));

    Tensor begin_tensor, end_tensor, strides_tensor;
    OP_REQUIRES_OK(
        ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor));
    OP_REQUIRES_OK(ctx,
                   LiteralToHostTensor(end_literal, index_type_, &end_tensor));
    OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_,
                                            &strides_tensor));

    bool dummy = false;
    ShapeReadWriteFromTensorShape wrapped_final_shape(&final_shape);
    ShapeReadWriteFromTensorShape wrapped_processing_shape(&processing_shape);
    OP_REQUIRES_OK(
        ctx, ValidateStridedSliceOp(
                 &begin_tensor, &end_tensor, strides_tensor,
                 ShapeReadWriteFromTensorShape(&input_shape), begin_mask_,
                 end_mask_, ellipsis_mask_, new_axis_mask_, shrink_axis_mask_,
                 &wrapped_processing_shape, &wrapped_final_shape, &dummy,
                 &dummy, &dummy, &begin, &end, &strides));

    // Check to make sure dy is consistent with the original slice
    const TensorShape dy_shape = ctx->InputShape(4);
    OP_REQUIRES(
        ctx, final_shape == dy_shape,
        errors::InvalidArgument("shape of dy was ", dy_shape.DebugString(),
                                " instead of ", final_shape.DebugString()));

    OP_REQUIRES(
        ctx, input_shape.dims() == processing_shape.dims(),
        errors::Internal(
            "input shape and processing shape must have same number of dims"));

    auto zero = XlaHelpers::Zero(ctx->builder(), ctx->expected_output_dtype(0));

    xla::ComputationDataHandle grad = ctx->Input(4);

    // Undo any new/shrink axes.
    grad = ctx->builder()->Reshape(grad, processing_shape.dim_sizes());

    // Pad the input gradients.
    gtl::InlinedVector<int64, 4> dimensions_to_reverse;
    xla::PaddingConfig padding_config;

    for (int i = 0; i < processing_shape.dims(); ++i) {
      auto* dims = padding_config.add_dimensions();
      if (strides[i] > 0) {
        dims->set_edge_padding_low(begin[i]);
        dims->set_interior_padding(strides[i] - 1);

        // Pad the upper dimension up to the expected input shape. (It's
        // not sufficient simply to use "end[i]" to compute the padding in
        // cases where the stride does not divide evenly into the interval
        // between begin[i] and end[i].)
        int64 size =
            dims->edge_padding_low() + processing_shape.dim_size(i) +
            (processing_shape.dim_size(i) - 1) * dims->interior_padding();
        dims->set_edge_padding_high(input_shape.dim_size(i) - size);
      } else {
        dimensions_to_reverse.push_back(i);
        dims->set_edge_padding_high(input_shape.dim_size(i) - begin[i] - 1);
        dims->set_interior_padding(-strides[i] - 1);

        // Pad the lower dimension up to the expected input shape.
        int64 size =
            dims->edge_padding_high() + processing_shape.dim_size(i) +
            (processing_shape.dim_size(i) - 1) * dims->interior_padding();
        dims->set_edge_padding_low(input_shape.dim_size(i) - size);
      }
    }
    if (!dimensions_to_reverse.empty()) {
      grad = ctx->builder()->Rev(grad, dimensions_to_reverse);
    }
    grad = ctx->builder()->Pad(grad, zero, padding_config);
    ctx->SetOutput(0, grad);
  }

 private:
  int32 begin_mask_, end_mask_;
  int32 ellipsis_mask_, new_axis_mask_, shrink_axis_mask_;
  DataType index_type_;
};

REGISTER_XLA_OP(Name("StridedSliceGrad"), StridedSliceGradOp);

class StridedSliceAssignOp : public XlaOpKernel {
 public:
  explicit StridedSliceAssignOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_));
    OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_));
  }

  void Compile(XlaOpKernelContext* ctx) override {
    TensorShape final_shape;
    gtl::InlinedVector<int64, 4> begin;
    gtl::InlinedVector<int64, 4> end;
    gtl::InlinedVector<int64, 4> strides;

    xla::Literal begin_literal, end_literal, strides_literal;
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &begin_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &end_literal));
    OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal));

    Tensor begin_tensor, end_tensor, strides_tensor;
    OP_REQUIRES_OK(
        ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor));
    OP_REQUIRES_OK(ctx,
                   LiteralToHostTensor(end_literal, index_type_, &end_tensor));
    OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_,
                                            &strides_tensor));

    DataType lhs_type;
    TensorShape lhs_shape;
    OP_REQUIRES_OK(ctx, ctx->GetVariableTypeAndShape(0, &lhs_type, &lhs_shape));

    const TensorShape rhs_shape = ctx->InputShape(4);

    TensorShape dummy_processing_shape;
    ShapeReadWriteFromTensorShape wrapped_final_shape(&final_shape);
    ShapeReadWriteFromTensorShape wrapped_dummy_processing_shape(
        &dummy_processing_shape);
    bool dummy = false;
    OP_REQUIRES_OK(
        ctx, ValidateStridedSliceOp(
                 &begin_tensor, &end_tensor, strides_tensor,
                 ShapeReadWriteFromTensorShape(&lhs_shape), begin_mask_,
                 end_mask_, ellipsis_mask_, new_axis_mask_, shrink_axis_mask_,
                 &wrapped_dummy_processing_shape, &wrapped_final_shape, &dummy,
                 &dummy, &dummy, &begin, &end, &strides));

    if (final_shape.num_elements() == 0 && rhs_shape.num_elements() == 0) {
      // DynamicUpdateSlice does not allow 0-element updates. We should probably
      // check that rhs_shape can be broadcast to final_shape, but that is
      // probably better handled when implementing broadcasting more generally.
      return;
    }

    // TODO(aselle): This check is too strong, we only should need
    // input_shape to be broadcastable to final_shape
    OP_REQUIRES(ctx, final_shape == rhs_shape,
                errors::Unimplemented(
                    "sliced l-value shape ", final_shape.DebugString(),
                    " does not match r-value shape ", rhs_shape.DebugString(),
                    ". Automatic broadcasting not yet implemented."));

    xla::ComputationDataHandle lhs;
    OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, &lhs));

    xla::ComputationDataHandle rhs = ctx->Input(4);

    gtl::InlinedVector<int64, 4> dimensions_to_reverse;
    gtl::InlinedVector<int64, 4> slice_begin, slice_dims;
    for (int i = 0; i < begin.size(); ++i) {
      // TODO(phawkins): implement strides != 1
      OP_REQUIRES(
          ctx, strides[i] == 1 || strides[i] == -1,
          errors::Unimplemented("Strides != 1 or -1 are not yet implemented"));
      if (strides[i] > 0) {
        slice_begin.push_back(begin[i]);
        slice_dims.push_back(end[i] - begin[i]);
      } else {
        // Negative stride: swap begin and end, add 1 because the interval
        // is semi-open, and mark the dimension to be reversed.
        slice_begin.push_back(end[i] + 1);
        slice_dims.push_back(begin[i] - end[i]);
        dimensions_to_reverse.push_back(i);
      }
    }

    if (!dimensions_to_reverse.empty()) {
      rhs = ctx->builder()->Rev(rhs, dimensions_to_reverse);
    }
    rhs = ctx->builder()->Reshape(rhs, slice_dims);

    if (lhs_shape.dims() == 0) {
      // TODO(b/38323843): DynamicUpdateSlice crashes on rank 0 inputs. Fix
      // and remove this workaround.
      lhs = rhs;
    } else {
      lhs = ctx->builder()->DynamicUpdateSlice(
          lhs, rhs, ctx->builder()->ConstantR1<int64>(slice_begin));
    }

    OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, lhs_type, lhs));
  }

 private:
  int32 begin_mask_, end_mask_;
  int32 ellipsis_mask_, new_axis_mask_, shrink_axis_mask_;
  DataType index_type_;
};

REGISTER_XLA_OP(Name("ResourceStridedSliceAssign"), StridedSliceAssignOp);

}  // namespace
}  // namespace tensorflow


text:
require 'spec_helper'

describe 'Fhir::Coding' do
  it 'should create coding by system_oid' do
    coding = Fhir::Coding.new(system: :rgb)
    coding.system.should == "urn:oid:RGB"
  end

  it 'should create coding by system' do
    coding = Fhir::Coding.new(system: 'ups')
    coding.system.should == "ups"
  end

  it 'test equality' do
    Fhir::Coding.new(system: 'ups').should == Fhir::Coding.new(system: 'ups')
  end

  it "#to_concept should convert to CodableConcept" do
    coding = Fhir::Coding.new(system: 'ups', code: 'ups', display: 'display')
    concept = coding.to_concept
    concept.should_not be_nil
    concept.should be_a(Fhir::CodeableConcept)
    concept.text.should == coding.display
    concept.coding.first.should == coding
  end
end


text:
from . agents import *
from random import randint

class hudrobotClass(Agent):
    def __init__(self, noCleans=10):
        Agent.__init__(self)
        self.name = 'Hudrobot'
        #self.img = 'minion' ## Immagine in base all'ID dell'agente
        self.actions = ['GoNorth', 'GoEast', 'GoSouth', 'GoWest'] # array direzionale
        self.perc_attuale = [55, 20, 5, 20] ## "%" non numerica dei movimenti possibili
        self.pos_prec = 999  # inizializzazione posizione "precedente"; 999 indica nessuna posizione
        self.grade = 'M' # indica se l'agente è master (M) o slave (S)
        self.designedPos = 1 # indica la direzione preferenziale nel calcolo "dell'euristica", inizializzato ad "Est"
        self.passed = 100 # contatore per lo stato "goal" (fittizio) indica il nuero di movimenti massimi esclusi i bump

        def k(pos, numb):
            # ridistribuisce le % per la posizione per il prossimo movimento (simulando una Euristica)
            # Prende la posizione da EVITARE più la percentuale di incremento per le altre direzioni
            # Il master "si sposta" in modo diretto alla posizione preferenziale, lo slave nel primo adiacente
            numb = numb/4
            resto = numb%4
            for i, x in enumerate(self.perc_attuale):
                if i != pos:
                    self.perc_attuale[i] += numb
                if i == self.designedPos: # determinata la posizione preferenziale
                    if self.grade == "M":
                        self.perc_attuale[i] += numb
                    else:
                        self.perc_attuale[((i+2)%4)] += numb

            self.perc_attuale[((pos+2)%4)] += resto

        def k2(pos, numb):
            # ridistribuisce le % per la posizione dopo un bump (simulando una Euristica)
            # Prende la posizione da EVITARE più la percentuale di incremento per le direzioni adiacenti
            # Il master "si sposta" in modo diretto alla posizione preferenziale, lo slave nel primo adiacente
            numb = numb/3
            resto = numb%3
            for i, x in enumerate(self.perc_attuale):
                if (i != pos and i != (pos+2)%4):
                    self.perc_attuale[i] += numb
                if i == self.designedPos: # determinata la posizione preferenziale
                    if self.grade == "M":
                        self.perc_attuale[i] += numb
                    else:
                        self.perc_attuale[((i+2)%4)] += numb

            self.perc_attuale[((pos+2)%4)] += resto

        def bumped(): # funzione che risponde al "bump"
            tempVal = self.perc_attuale[self.pos_prec]
            self.perc_attuale[self.pos_prec] = 0
            k2(self.pos_prec, tempVal) # esegue la k2 sulla direzione del bump
            return muovi()

        def spostato(): # funzione che risponde all'vento movimento su locazione pulita
            noMove= (self.pos_prec + 2)%4
            enumb = self.perc_attuale[noMove]/2
            self.perc_attuale[noMove] = self.perc_attuale[noMove]/2
            k(noMove, enumb) # esegue la k2 sulla direzione dettata in precedenza
            return muovi()

        def muovi(): # funzione che calcola il prossimo movimento
            # genera la posizione
            id1 = self.perc_attuale[0]
            id2 = id1 + self.perc_attuale[1]
            id3 = id2 + self.perc_attuale[2]
            id4 = id3 + self.perc_attuale[3]

            index = int(random.randint(1, int(id4)+1))  #  "rolled" index
            # identifica quale delle 4 in %, aggiornando il movimento "precedente" per l'istante k+1
            if (index >= 0 and index <id1 and self.perc_attuale[0] != 0): ## è loc 0
                self.pos_prec = 0
                return self.actions[0]
            if (index >= id1 and index <id2 and self.perc_attuale[1] != 0): # è loc 1
                self.pos_prec = 1
                return self.actions[1]
            if (index >= id2 and index <id3 and self.perc_attuale[2] != 0): # è loc 2
                self.pos_prec = 2
                return self.actions[2]
            if (index >= id3 and index <= id4 and self.perc_attuale[3] != 0): # è loc 3
                self.pos_prec = 3
                return self.actions[3]

        def amici(neighbors): #verifico quale agente è più vicino e applico delle modifiche alle K e K2
            # Go near first neighbor (Funzione di Mirco Tracolli)
            a_near = min([((agent_id, agent_class), pos)
                        for (agent_id, agent_class), pos in neighbors
                        if agent_id != self.id],
                        key=lambda obj: obj[1]  # select position as filter
                      )
            (agent_id, agent_class), pos = a_near # Ho l'agente più vicino

            if agent_id != self.id: #controllo che tipo o che agente è
                if agent_class == self.name: # amico
                    if (min(pos) == 0): # allora è a 0,0, sto sopra un vicino amico/nemico
                        if agent_id < self.id: # sono slave
                            self.grade = 'S'
                            #.img = 'maid' # aggiorno immagine
                            return true
                        else:
                            self.grade = 'M' # sono master, controllo se è la prima mossa
                            if self.pos_prec == 999: # anticipiamo l'avversario
                                return muovi()
                            else:
                                return spostato()
                else: # questo è un nemico
                    # if agent_class != self.name:
                    if (abs(pos[0]) >= abs(pos[1])): # allora la X è maggiore; mi muovo sulla X
                        if pos[0] < 0:
                            self.designedPos = 1 # la posizione designata è "est"
                        else:
                            self.designedPos =  3 # la posizione designata è "ovest"
                    else: # mi muovo sulla Y
                        if pos[1] < 0:
                            self.designedPos =  0 # la posizione designata è "nord"
                        else:
                            self.designedPos =  2 # la posizione designata è "sud"
                return true

        def sporco():
            return 'Suck' # è sporco, pulisce

        def program(status, bump, neighbors): ##print("*******************")
            if self.passed == 0: # raggiungo lo stato terminale
                return"NoOp"

            if not neighbors: #  ho vicini ?
                amici(neighbors) # verifico e applico le K

            if bump == 'Bump':  # avviene il bump?
                return bumped()

            if status == 'Dirty':  # è sporco ?
                return sporco()
            else:
                # se è pulito (!= 'Dirty')
                self.passed -=1
                return spostato()

        self.program = program


text:
"use strict";

/*
The entire merge sort relies on divide-and-conquer strategy working with an
array and subdividing array[p..r] interval into array[p..q] and array[q+1..r]
intervals during the division phase, then merging them again in sorted order
across the interval array[p..r].
*/

var mergeSort = module.exports = function mergeSort (array, p, r, ascending) {
    ascending = (typeof ascending === "undefined") ? true : ascending;
    p = (typeof p === "undefined") ? 0 : p;
    r = (typeof r === "undefined") ? array.length - 1 : r;
    if (p < r) {
        var q = Math.floor((p + r) / 2);
        mergeSort(array, p, q, ascending);
        mergeSort(array, q + 1, r, ascending);
        merge(array, p, q, r, ascending);
    }
    return array;
};

var merge = function merge (array, p, q, r, ascending) {
    ascending = (typeof ascending === "undefined") ? true : ascending;
    var lengthLeftArray  = q - p + 1;
    var lengthRightArray = r - q; // r - (q + 1) + 1; reduces to r - q;
    var left = [];
    var right = [];
    for (var leftIndex = 0; leftIndex < lengthLeftArray; leftIndex++) {
        left.push(array[p + leftIndex]);
    }
    for (var rightIndex = 0; rightIndex < lengthRightArray; rightIndex++) {
        right.push(array[q + 1 + rightIndex]);
    }
    var takeFromLeftArray;
    for (var k = p; k < r + 1; k++) {
        if (left.length == 0) {
            takeFromLeftArray = false;
        } else if (right.length == 0) {
            takeFromLeftArray = true;
        } else if (ascending) {
            takeFromLeftArray = left[0] <= right[0];
        } else {
            takeFromLeftArray = left[0] >= right[0];
        }

        array[k] = takeFromLeftArray ? left.shift() : right.shift();
    }
}


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

<title>com.tailf.notif (CONF API Version 6.6)</title>
<meta name="date" content="2018-03-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.tailf.notif

Package for subscription of asynchronous events.

See: Description

Class Summary

Class
Description

AuditNotification

Data structure for Audit events

CommitDiffNotification

Data structure for CommitDiff notifications.

CommitFailedNotification

Data structure for failing commit notifications.

CommitNotification

Data structure for simple commit notifications.

CommitProgressNotification

Data structure for commit progress notifications.

CommitQueueProgressNotification

Data structure for commit queue progress notifications.

ConfirmNotification

Data structure for Confirmed commit notifications.

ForwardNotification

Data structure for Forward agent events.

HaNotification

Data structure for High Availability notifications.

HealtCheckNotification

Data structure for HealtCheck notifications.

HeartbeatNotification

Data structure for Heartbeat notifications.

Notif

This class implements the Notifications API in Java.

Notification

Base class for notification data structures.

NotificationCfg

PackageReloadNotification

Data structure for PackageReload notifications.

ReopenLogsNotification

Data structure for ReopenLogs notifications.

SnmpaNotification

Data structure SNMP agent notifications.

SnmpaNotification.SnmpVar

Class representing a SNMP variable

SnmpaNotification.TrapInfo

Class representing trapinfo for a trap

SnmpaNotification.Varbind

Class representing a varbind for a trap

StreamNotification

Data structure for Stream notifications.

SubagentNotification

Data structure for subagent notifications.

SyslogNotification

Data structure for syslog notifications.

UpgradeNotification

Data structure for upgrade notifications.

UserSessNotification

Data structure for user session start/stop notifications.

Enum Summary

Enum
Description

NotificationType

Enum describing the different notification types available.

Exception Summary

Exception
Description

NotifException

Exceptions raised from the notif package

Package com.tailf.notif Description

Package for subscription of asynchronous events.

  The server can deliver various classes of events to subscribing
  applications. The architecture is based on notification sockets.
  The application(s) connect a notifications socket to the server.
  The application provide a bit mask indicating which types of events
  the application is interested in.

  The following is a list of the different asynchronous event classes that
  can be delivered from the server to the application(s)

NOTIF_AUDIT - Audit events.

NOTIF_COMMIT_DIFF - A complete diff compared to previous configuration.

NOTIF_COMMIT_FAILED - Failed commit events.

NOTIF_COMMIT_SIMPLE - Commit events.

NOTIF_COMMIT_PROGRESS - Commit in progress events.

NOTIF_CONFIRMED_COMMIT - Confirmed commit events.

NOTIF_FORWARD_INFO - Forward northbound agent events.

NOTIF_HA_INFO - Changes in ConfD/NCS's perception of the cluster
  configuration.

NOTIF_HEARTBEAT - Heartbeat events.

NOTIF_SNMPA - SNMP agent audit log.

NOTIF_SUBAGENT_INFO - Subagent related events.

NOTIF_SYSLOG - Syslog events.

NOTIF_UPGRADE_EVENT - Upgrade events.

NOTIF_USER_SESSION - Whenever a user session is started or stopped.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


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

<title>model.node.visual</title>
<meta name="date" content="2017-06-13">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

model.node.visual

Classes

CoordinateNode


text:
package factomapi

import (
	"encoding/hex"
	"fmt"

	"github.com/FactomProject/FactomCode/common"
	"github.com/FactomProject/FactomCode/database"
	"github.com/FactomProject/FactomCode/process"
	"github.com/FactomProject/btcd/wire"
	fct "github.com/FactomProject/factoid"
)

var (
	db     database.Db
	inMsgQ chan wire.FtmInternalMsg
)

func ChainHead(chainid string) (*common.Hash, error) {
	h, err := atoh(chainid)
	if err != nil {
		return nil, err
	}
	c, err := db.FetchHeadMRByChainID(h)
	if err != nil {
		return nil, fmt.Errorf("Chain not found")
	}
	return c, nil
}

func CommitChain(c *common.CommitChain) error {
	m := wire.NewMsgCommitChain()
	m.CommitChain = c
	inMsgQ <- m
	return nil
}

func CommitEntry(c *common.CommitEntry) error {
	m := wire.NewMsgCommitEntry()
	m.CommitEntry = c
	inMsgQ <- m
	return nil
}

func FactoidTX(t fct.ITransaction) error {
	m := new(wire.MsgFactoidTX)
	m.SetTransaction(t)
	inMsgQ <- m
	return nil
}

func DBlockByKeyMR(keymr string) (*common.DirectoryBlock, error) {
	key, err := atoh(keymr)
	if err != nil {
		return nil, err
	}
	r, err := db.FetchDBlockByMR(key)
	if err != nil {
		return r, fmt.Errorf("DBlock not found")
	}
	return r, nil
}

func DBlockHead() (*common.DirectoryBlock, error) {
	_, height, err := db.FetchBlockHeightCache()
	if err != nil {
		return nil, err
	}
	block, err := db.FetchDBlockByHeight(uint32(height))
	if err != nil {
		return nil, err
	}
	block.BuildKeyMerkleRoot()
	return block, nil
}

func EBlockByKeyMR(keymr string) (*common.EBlock, error) {
	h, err := atoh(keymr)
	if err != nil {
		return nil, err
	}
	r, err := db.FetchEBlockByMR(h)
	if err != nil {
		return r, fmt.Errorf("EBlock not found")
	}
	return r, nil
}

func ECBalance(eckey string) (uint32, error) {
	key := new([32]byte)
	if p, err := hex.DecodeString(eckey); err != nil {
		return 0, err
	} else {
		copy(key[:], p)
	}
	val, _ := process.GetEntryCreditBalance(key)
	return uint32(val), nil
}

func EntryByHash(hash string) (*common.Entry, error) {
	h, err := atoh(hash)
	if err != nil {
		return nil, err
	}
	r, err := db.FetchEntryByHash(h)
	if err != nil {
		return r, err
	}
	if r == nil {
		return r, fmt.Errorf("Entry not found")
	}
	return r, nil
}

func RevealEntry(e *common.Entry) error {
	m := wire.NewMsgRevealEntry()
	m.Entry = e
	inMsgQ <- m
	return nil
}

func SetDB(d database.Db) {
	db = d
}

func SetInMsgQueue(q chan wire.FtmInternalMsg) {
	inMsgQ = q
}

func atoh(a string) (*common.Hash, error) {
	h := common.NewHash()
	p, err := hex.DecodeString(a)
	if err != nil {
		return h, err
	}
	h.SetBytes(p)
	return h, nil
}


text:
"""Tests for dm_control.locomotion.soccer.soccer_ball."""

from absl.testing import absltest
from dm_control import composer
from dm_control import mjcf
from dm_control.entities import props
from dm_control.locomotion.soccer import soccer_ball
from dm_control.locomotion.soccer import team
import numpy as np

class SoccerBallTest(absltest.TestCase):

  def test_detect_hit(self):
    arena = composer.Arena()
    ball = soccer_ball.SoccerBall(radius=0.35, mass=0.045, name='test_ball')
    player = team.Player(
        team=team.Team.HOME,
        walker=props.Primitive(geom_type='sphere', size=(0.1,), name='home'))
    arena.add_free_entity(player.walker)
    ball.register_player(player)
    arena.add_free_entity(ball)

    random_state = np.random.RandomState(42)
    physics = mjcf.Physics.from_mjcf_model(arena.mjcf_model)
    physics.step()

    ball.initialize_episode(physics, random_state)
    ball.before_step(physics, random_state)
    self.assertEqual(ball.hit, False)
    self.assertEqual(ball.repossessed, False)
    self.assertEqual(ball.intercepted, False)
    self.assertIsNone(ball.last_hit)
    self.assertIsNone(ball.dist_between_last_hits)

    ball.after_substep(physics, random_state)
    ball.after_step(physics, random_state)

    self.assertEqual(ball.hit, True)
    self.assertEqual(ball.repossessed, True)
    self.assertEqual(ball.intercepted, True)
    self.assertEqual(ball.last_hit, player)
    # Only one hit registered.
    self.assertIsNone(ball.dist_between_last_hits)

  def test_has_tracking_cameras(self):
    ball = soccer_ball.SoccerBall(radius=0.35, mass=0.045, name='test_ball')
    expected_camera_names = ['ball_cam_near', 'ball_cam', 'ball_cam_far']
    camera_names = [cam.name for cam in ball.mjcf_model.find_all('camera')]
    self.assertCountEqual(expected_camera_names, camera_names)

  def test_damp_ratio_is_valid(self):
    with self.assertRaisesRegex(ValueError, 'Invalid `damp_ratio`.*'):
      soccer_ball.SoccerBall(damp_ratio=-0.5)

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


text:
    <script src="<?php echo URL; ?>js/application.js"></script>
</body>
</html>


text:
<!DOCTYPE html>
<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org">
<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1347322">

    text


text:
package org.jrimum.bopepo.banco;

import org.jrimum.bopepo.campolivre.CLMercantilDoBrasil;
import org.jrimum.bopepo.campolivre.CampoLivre;
import org.jrimum.bopepo.campolivre.NotSupportedCampoLivreException;
import org.jrimum.domkee.financeiro.banco.febraban.Titulo;

public class BancoMercantilDoBrasil extends AbstractBanco {

	public BancoMercantilDoBrasil() {
		super("389", "17184037000110", "BANCO MERCANTIL DO BRASIL S.A.", Segmento.BANCO_MULTIPLO);
	}

	@Override
	public CampoLivre createCampoLivre(final Titulo titulo) throws NotSupportedCampoLivreException {
		return CLMercantilDoBrasil.newCampoLivre(titulo);
	}

}


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

namespace fyiReporting.RDL
{
	///<summary>
	/// Runtime data structure representing the group hierarchy
	///</summary>
	internal class MatrixEntry
	{
        Row _r;                 // needed for sort
		Dictionary<string, MatrixEntry> _HashData;	// Hash table of data values
		List<MatrixEntry> _SortedData;	//  Sorted List version of the data
        string _hash;           // item that is used for hash
		BitArray _Rows;			// rows
		MatrixEntry _Parent;	// parent
		ColumnGrouping _ColumnGroup;	//   Column grouping
		RowGrouping _RowGroup;	// Row grouping
		int _FirstRow;			// First row in _Rows marked true
		int _LastRow;			// Last row in _Rows marked true
		int _rowCount;			//   we save the rowCount so we can delay creating bitArray
		int _StaticColumn=0;	// this is the index to which column to use (always 0 when dynamic)
		int _StaticRow=0;		// this is the index to which row to use (always 0 when dynamic)
		Rows _Data;				// set dynamically when needed

		internal MatrixEntry(Row r, string hash, MatrixEntry p, int rowCount)
		{
            _r = r;
            _hash = hash;
			_HashData = new Dictionary<string, MatrixEntry>();
			_ColumnGroup = null;
			_RowGroup = null;
			_SortedData = null;
			_Data = null;
			_rowCount = rowCount;
			_Rows = null;
			_Parent = p;
			_FirstRow = -1;
			_LastRow = -1;
		}

		internal Dictionary<string, MatrixEntry> HashData
		{
			get { return  _HashData; }
		}

		internal Rows Data
		{
			get { return _Data; }
			set { _Data = value; }
		}

        internal string HashItem
        {
            get { return _hash; }
        }
		internal List<MatrixEntry> GetSortedData(Report rpt)
		{
			if (_SortedData == null && _HashData != null && _HashData.Count > 0)
			{
				_SortedData = new List<MatrixEntry>(_HashData.Values);
                _SortedData.Sort(new MatrixEntryComparer(rpt, GetSortBy()));
				_HashData = null;		// we only keep one
			}

			return  _SortedData;
		}

		internal MatrixEntry Parent
		{
			get { return  _Parent; }
		}

		internal ColumnGrouping ColumnGroup
		{
			get { return  _ColumnGroup; }
			set {  _ColumnGroup = value; }
		}

		internal int StaticRow
		{
			get { return  _StaticRow; }
			set {  _StaticRow = value; }
		}

		internal int StaticColumn
		{
			get { return  _StaticColumn; }
			set {  _StaticColumn = value; }
		}

		internal RowGrouping RowGroup
		{
			get { return  _RowGroup; }
			set {  _RowGroup = value; }
		}

		internal int FirstRow
		{
			get { return  _FirstRow; }
			set
			{
				if (_FirstRow == -1)
					_FirstRow = value;
			}
		}

		internal int LastRow
		{
			get { return  _LastRow; }
			set
			{
				if (value >= _LastRow)
					_LastRow = value;
			}
		}

		internal BitArray Rows
		{
			get
			{
				if (_Rows == null)
					_Rows = new BitArray(_rowCount);

				return  _Rows;
			}
			set {  _Rows = value; }
		}

        internal Row R
        {
            get { return _r; }
        }

        Sorting GetSortBy()
        {
            MatrixEntry me=null;
            foreach (MatrixEntry m in this.HashData.Values)
            {   // just get the first one
                me = m;
                break;
            }
            if (me == null)
                return null;

            Sorting sb = null;
            if (me.RowGroup != null)
            {
                if (me.RowGroup.DynamicRows != null)
                    sb = me.RowGroup.DynamicRows.Sorting;
            }
            else if (me.ColumnGroup != null)
            {
                if (me.ColumnGroup.DynamicColumns != null)
                    sb = me.ColumnGroup.DynamicColumns.Sorting;
            }
            return sb;
        }

    }

    class MatrixEntryComparer : System.Collections.Generic.IComparer<MatrixEntry>
    {
        Report _rpt;
        Sorting _Sorting;

        public MatrixEntryComparer(Report rpt, Sorting s)
        {
            _rpt = rpt;
            _Sorting = s;
        }

		#region IComparer Members

        public int Compare(MatrixEntry m1, MatrixEntry m2)
        {
            if (_Sorting == null)
                return m1.HashItem.CompareTo(m2.HashItem);

            object o1 = null, o2 = null;
            TypeCode tc = TypeCode.Object;
            int rc;
            try
            {
                foreach (SortBy sb in _Sorting.Items)
                {
                    IExpr e = sb.SortExpression.Expr;
                    o1 = e.Evaluate(_rpt, m1.R);
                    o2 = e.Evaluate(_rpt, m2.R);
                    tc = e.GetTypeCode();
                    rc = Filter.ApplyCompare(tc, o1, o2);
                    if (rc != 0)
                        return sb.Direction == SortDirectionEnum.Ascending? rc : -rc;
                }
            }
            catch (Exception e)		// this really shouldn't happen
            {
                _rpt.rl.LogError(8,
                    string.Format("Matrix Sort rows exception\r\nArguments: {0} {1}\r\nTypecode: {2}\r\n{3}\r\n{4}",
                    o1, o2, tc.ToString(), e.Message, e.StackTrace));
                return m1.HashItem.CompareTo(m2.HashItem);
            }
            return 0;		    // treat as the same

        }

        #endregion
    }
}


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

<TITLE>
MassData
</TITLE>

<META NAME="keywords" CONTENT="org.jbox2d.collision.MassData class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.jbox2d.collision

Class MassData

java.lang.Object
  org.jbox2d.collision.MassData

public class MassData
extends java.lang.Object

Field Summary

 Vec2
center

 float
I

 float
mass

Constructor Summary

MassData()

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

mass

public float mass

center

public Vec2 center

I

public float I

Constructor Detail

MassData

public MassData()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD