text:
$(function () {
  [$('#conferences'), $('#earlier')].forEach(function (table) {
    table.DataTable({
      autoWidth: false,
      columnDefs: [
        { responsivePriority: 1, targets: -2 }, /* event title */
        { responsivePriority: 2, targest: 0  }, /* start date */
        { responsivePriority: 3, targets: -1 }  /* event location */
      ],
      pageLength: 50,
      responsive: true
    });
  });
  $('#topics').DataTable({
    autoWidth: false,
    pageLength: 25,
    responsive: true
  });

//$(document).ready(function(){
    var availableTags = [];
    var mapping = {}

    $.getJSON("/search.json", function( result ) {
        //console.log(result);
        //console.log(result.length)
        mapping = result;
        for (var key in result) {
            if (result.hasOwnProperty(key)) {
                availableTags.push(key);
            }
        }
        availableTags.sort();
        //console.log(availableTags);

    //    $('#q').css('display', 'inline');
        $('#search').css('display', 'inline-block');
        $( "#q" ).autocomplete({
          source: availableTags
        });
        $('#search').submit(function(e) {
            console.log('submit');
            var term = $('#q').val();
            e.preventDefault();
            if (mapping[term]) {
                window.location.href = mapping[term];
            }
        });

    });

    // Append a Twitter logo after every quote and make it Tweetable
    $('q').each(function( item ) {
        console.log( $(this).text() );
        var status = encodeURIComponent( $(this).text() + ' ' + window.location.href );
        var event_twitter = $('#event_twitter').val()
        if (event_twitter) {
            status += ' @' + event_twitter;
        }
        var speaker_twitters = $('#speaker_twitters').val();
        if (speaker_twitters) {
            status += speaker_twitters;
        }

        var html = '';
        $(this).append(html);
    })

});

// vim: expandtab


text:
CKEDITOR.plugins.setLang( 'language', 'de', {
	button: 'Sprache stellen',
	remove: 'Sprache entfernen'
} );

redpajama_set_name: RedPajamaGithub


text:
package com.salesforce.dataloader.ui;

import com.salesforce.dataloader.config.Config;
import com.salesforce.dataloader.model.LoginCriteria;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;

/**
 * LoginAdvancedControl is used to connect to SF with a sessionid
 */
public class LoginAdvancedControl extends Composite {
    private final Text loginUrl;
    private final Button loginButton;
    private final Text sessionId;
    private final AuthenticationRunner authenticator;
    private final Label loginLabel;
    private final Text userName;

    public LoginAdvancedControl(Composite parent, int style, AuthenticationRunner authenticator) {
        super(parent, style);
        this.authenticator = authenticator;

        Grid12 grid = new Grid12(this, 40, 20);

        grid.createLabel(4, Labels.getString("SettingsPage.username"));
        userName = grid.createText(6, SWT.BORDER | SWT.FILL, authenticator.getConfig().getString(Config.USERNAME));
        grid.createPadding(2);

        grid.createLabel(4, Labels.getString("SettingsPage.sessionId"));
        sessionId = grid.createText(6, SWT.BORDER, authenticator.getConfig().getString(Config.SFDC_INTERNAL_SESSION_ID));
        grid.createPadding(2);

        grid.createLabel(4, Labels.getString("SettingsPage.instServerUrl"));
        loginUrl = grid.createText(6, SWT.BORDER, authenticator.getConfig().getString(Config.ENDPOINT));
        grid.createPadding(2);

        loginLabel = grid.createLabel(10, "");
        loginButton = grid.createButton(2, SWT.PUSH | SWT.FILL, Labels.getString("SettingsPage.login"));
        loginButton.addListener(SWT.Selection, this::loginButton_Clicked);
    }

    private void loginButton_Clicked(Event event) {
        LoginCriteria criteria = new LoginCriteria(LoginCriteria.Advanced);
        criteria.setInstanceUrl(loginUrl.getText());
        criteria.setSessionId(sessionId.getText());
        criteria.setUserName(userName.getText());
        authenticator.login(criteria, loginLabel::setText);
    }
}


text:
using namespace clang;
using namespace llvm;
using namespace tooling;

cl::opt<std::string> build_path(cl::Positional, cl::desc("<build-path>"));
cl::list<std::string> source_paths(cl::Positional, cl::desc("<source0> [... <sourceN>]"), cl::OneOrMore);

  static void
InitCompilationDatabase(std::shared_ptr<CompilationDatabase>& compilations)
{
  if (!compilations)
  {
    std::string error_message;
    compilations.reset(CompilationDatabase::loadFromDirectory(build_path, error_message));
    if (!compilations)
      llvm::report_fatal_error(error_message);
  }
}

int main(int argc, const char **argv)
{
  llvm::sys::PrintStackTraceOnErrorSignal();

  std::shared_ptr<CompilationDatabase> compilations(FixedCompilationDatabase::loadFromCommandLine(argc, argv));
  cl::ParseCommandLineOptions(argc, argv);

  InitCompilationDatabase(compilations);

  tooling::RefactoringTool tool(*compilations, source_paths);
  ast_matchers::MatchFinder finder;

  ClassMembersPrinter& printer = GenerateSerialization(tool, finder);

  std::unique_ptr<clang::tooling::FrontendActionFactory> frontendAction(newFrontendActionFactory(&finder));

  int res = tool.run(frontendAction.get());
  WriteMetaInfo(printer);

  return res;
}


text:
namespace Tigwi.UI.Models
{
    using System;

    using Tigwi.UI.Models.Storage;

    /// <summary>
    /// The interface specification for a user repository.
    /// </summary>
    public interface IUserRepository
    {
        #region Public Methods and Operators

        /// <summary>
        /// Creates a new user with the given credentials.
        /// </summary>
        /// <param name="login">
        /// The desired login.
        /// </param>
        /// <param name="email">
        /// The desired email address.
        /// </param>
        /// <param name="password">
        /// The hashed password.
        /// </param>
        /// <returns>
        /// A <see cref="IUserModel"/> representing the newly created user.
        /// </returns>
        /// <exception cref="DuplicateUserException">
        /// When there is already a user with the given credentials.
        /// </exception>
        IUserModel Create(string login, string email, byte[] password);

        /// <summary>
        /// Deletes the given user and replaces it with a shallow "Deleted" object.
        /// </summary>
        /// <param name="user">
        /// The user to delete.
        /// </param>
        void Delete(IUserModel user);

        /// <summary>
        /// Finds a user with the given Id.
        /// </summary>
        /// <param name="userId">
        /// The Id of the user to retrieve.
        /// </param>
        /// <returns>
        /// A <see cref="IUserModel"/> representing the user with the given Id.
        /// </returns>
        IUserModel Find(Guid userId);

        /// <summary>
        /// Finds a user with the given login.
        /// </summary>
        /// <param name="login">
        /// The login identifying the user to retrieve.
        /// </param>
        /// <returns>
        /// A <see cref="IUserModel"/> representing the user with the given login.
        /// </returns>
        /// <exception cref="UserNotFoundException">
        /// When there is no user with the given login.
        /// </exception>
        IUserModel Find(string login);

        bool TryFind(string login, out IUserModel user);

        bool Exists(string login);

        #endregion
    }
}


text:
module Searchlogic
  module Modifiers
    class Md5 < Base
      class << self
        def return_type
          :string
        end
      end
    end
  end
end


text:
package pl.grzegorz2047.survivalcg.guild.relation;

/**
 * Created by grzegorz2047 on 30.12.2015.
 */
public class Relation {

    public Relation(String who, String withWho, Status state){
        this.who = who;
        this.withWho = withWho;
        this.startDate = System.currentTimeMillis();
        this.expireDate = (120 * 1000) + System.currentTimeMillis();
        this.state = state;
    }

    private String who;
    private String withWho;
    private long startDate;
    private long expireDate;
    private boolean expired;

    public String getWho() {
        return who;
    }

    public void setWho(String who) {
        this.who = who;
    }

    public boolean isExpired() {
        return expired;
    }

    public void setExpired(boolean expired) {
        this.expired = expired;
    }

    public enum Status { ALLY, ENEMY }

    private Status state;

    public String getWithWho() {
        return withWho;
    }

    public void setWithWho(String withWho) {
        this.withWho = withWho;
    }

    public long getStartDate() {
        return startDate;
    }

    public void setStartDate(long startDate) {
        this.startDate = startDate;
    }

    public long getExpireDate() {
        return expireDate;
    }

    public void setExpireDate(long expireDate) {
        this.expireDate = expireDate;
    }

    public Status getState() {
        return state;
    }

    public void setState(Status state) {
        this.state = state;
    }

}


text:
class AddMoreColumnsToProjects < ActiveRecord::Migration
  def change
    add_column :projects, :photocopy, :text
    add_column :projects, :photocopy_copyright, :text
  end
end


text:
import ModelView = require('../controls/Model');
import PropertiesView = require('../controls/PropertiesView');
import WebGLView = require('../controls/WebGLView');

import ASEModel = require('./../services/ASEModel');
import GeomObject = require('./../services/GeomObject');
import Model = require('../scene/Model');
import Bone = require('../scene/Bone');
import Mesh = require('../scene/Mesh');

class Application {
    private model: Model = new Model();
    private modelView: ModelView = null;
    private propsView: PropertiesView = null;
    private glView: WebGLView = null;

    private _debugMode: boolean = false;

    constructor() {
        document.addEventListener('DOMContentLoaded', () => {
            this.glView = new WebGLView(this.model);
            this.modelView = new ModelView(this.model, this.glView);
            this.propsView = new PropertiesView(this.model, this.modelView);

            document.querySelector('#openASE').addEventListener('click', () => {
                ipc.send('open-ase');
            });

            ipc.on('open-ase', (event: string) => {
                this.model.clear();
                let model: ASEModel = JSON.parse(event);
                model.geomObjects.forEach((geomObject: GeomObject) => {
                    if (geomObject.mesh.vertices.length === 1) {
                        this.model.add(new Bone(geomObject));
                    } else {
                        this.model.add(new Mesh(geomObject));
                    }
                });
            });
        });
    }

    get debugMode(): boolean {
        return this._debugMode;
    }

    set debugMode(debugMode: boolean) {
        this._debugMode = debugMode;
    }

    debug(): void {
        this._debugMode = true;
    }
}

export = Application;


text:
import { MeshModel, ScatterModel, VolumeModel } from "..";

// some helper functions to quickly create widgets

export
async function create_model_ipyvolume(manager, name: string, id: string, args: object) {
    return create_model(manager, "ipyvolume", `${name}Model`, `${name}View`, id, args);
}

export
async function create_model_bqplot(manager, name: string, id: string, args: object) {
    return create_model(manager, "bqplot", `${name}Model`, name, id, args);
}

export
async function create_model(manager, module: string, model: string, view: string, id: string, args = {}) {
    const model_widget = await manager.new_widget({
            model_module: module,
            model_name: model,
            model_module_version : "*",
            view_module: module,
            view_name: view,
            view_module_version: "*",
            model_id: id,
    }, args );
    return model_widget;
}

export
async function create_linear_scale(manager, scale_name, min, max) {
    return await create_model_bqplot(manager, "LinearScale", scale_name, {
        min, max, _view_module_version: "*", _view_module: "bqplot"});
}

export
async function create_log_scale(manager, scale_name, min, max) {
    return await create_model_bqplot(manager, "LogScale", scale_name, {
        min, max, _view_module_version: "*", _view_module: "bqplot"});
}

export
async function create_color_scale(manager, scale_name, min, max) {
    return await create_model_bqplot(manager, "ColorScale", scale_name, {
        min, max, colors: ["#f00", "#0f0", "#00f"], _view_module_version: "*", _view_module: "bqplot"});
}

export
async function create_view(manager, model, options = {}) {
    const view = await manager.create_view(model, options);
    return view;
}

export
async function create_widget(manager, name: string, id: string, args: object) {
    const model = await create_model_ipyvolume(manager, name, id, args);
    const view = await manager.create_view(model);
    await manager.display_view(undefined, view);
    return {model, view};
}

export
async function create_figure(manager, markModel) {
    const layout = await create_model(manager, "@jupyter-widgets/base", "LayoutModel", "LayoutView", "layout_figure1", {_dom_classes: "", width: "400px", height: "500px"});

    let figureModel;
    const scale_x = await create_linear_scale(manager, "scale_x", 0, 1);
    const scale_y = await create_log_scale(manager, "scale_y", 0.1, 1000);
    // const scale_y = await create_linear_scale(manager, "scale_y", 0, 1);
    const scale_z = await create_linear_scale(manager, "scale_z", 0, 1);
    const scales = {x: "IPY_MODEL_scale_x", y: "IPY_MODEL_scale_y", z: "IPY_MODEL_scale_z"};
    try {
        figureModel = await create_model_ipyvolume(manager, "Figure", "figure1", {
            layout: "IPY_MODEL_layout_figure1",
            scatters: markModel instanceof ScatterModel ? [`IPY_MODEL_${markModel.model_id}`] : [],
            meshes: markModel instanceof MeshModel ? [`IPY_MODEL_${markModel.model_id}`] : [],
            volumes: markModel instanceof VolumeModel ? [`IPY_MODEL_${markModel.model_id}`] : [],
            animation: 0,
            scales,
        });
    } catch (e) {
        console.error("error", e);
    }
    const figure  = await create_view(manager, figureModel);
    await manager.display_view(undefined, figure);
    return figure;
}

export
async function create_figure_scatter(manager, x, y, z, extra = {}) {
    const layout = await create_model(manager, "@jupyter-widgets/base", "LayoutModel", "LayoutView", "layout_figure1", {_dom_classes: "", width: "400px", height: "500px"});

    const scatterModel = await create_model_ipyvolume(manager, "Scatter", "scatter1", {
        x, y, z, ...extra, _view_module_version: "*", _view_module: "ipyvolume"});
    const figure  = await create_figure(manager, scatterModel);
    await manager.display_view(undefined, figure);
    return {figure, scatter: await figure.scatter_views[scatterModel.cid]};
}

export
async function create_figure_mesh_triangles(manager, x, y, z, triangles, extra = {}) {
    const layout = await create_model(manager, "@jupyter-widgets/base", "LayoutModel", "LayoutView", "layout_figure1", {_dom_classes: "", width: "400px", height: "500px"});

    const meshModel = await create_model_ipyvolume(manager, "Mesh", "mesh1", {
        x, y, z, triangles, color: "red", ...extra, _view_module_version: "*", _view_module: "ipyvolume"});
    const figure  = await create_figure(manager, meshModel);
    await manager.display_view(undefined, figure);
    return {figure, mesh: await figure.mesh_views[meshModel.cid]};
}

const tf_data = new Uint8Array([0, 0, 128, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 0, 0, 0, 128, 63]);

export
async function create_transfer_function(manager) {
    const layout = await create_model(manager, "@jupyter-widgets/base", "LayoutModel", "LayoutView", "layout_tf_1", {_dom_classes: ""});

    const tfModel = await create_model_ipyvolume(manager, "TransferFunction", "tf1", {
        _dom_classes: [],
        layout: "IPY_MODEL_layout_tf_1",
        rgba: {
            data: tf_data,
            dtype: "float32",
            shape: [2, 4],
        }},
    );
    return tfModel;
}

export
async function create_figure_volume(manager, data, extent, transfer_function) {
    const layout = await create_model(manager, "@jupyter-widgets/base", "LayoutModel", "LayoutView", "layout_figure1", {_dom_classes: "", width: "400px", height: "500px"});

    const material = await create_model(manager, "jupyter-threejs", `ShaderMaterialModel`, 'ShaderMaterial', 'shader1', {});
    const volumeModel = await create_model_ipyvolume(manager, "Volume", "volume1", {
        data, extent, material: "IPY_MODEL_" + String(material.model_id), tf: "IPY_MODEL_" + String(transfer_function.model_id), _view_module_version: "*", _view_module: "ipyvolume"});
    const figure  = await create_figure(manager, volumeModel);
    await manager.display_view(undefined, figure);
    return {figure, volume: await figure.mesh_views[volumeModel.cid]};
}

export
function data_float32(ar) {
    return { dtype: "float32", data: new Float32Array([...ar]), shape: [ar.length] };
}
export
function data_uint32(ar) {
    return { dtype: "uint32", data: new Uint32Array([...ar]), shape: [ar.length]  };
}


text:
**td_load>** operator loads data from storages, databases, or services.

    +step1:
      td_load>: config/guessed.yml
      database: prod
      table: raw

## Examples

  * [Examples](https://github.com/treasure-data/workflow-examples/tree/master/td_load)

## Secrets

When you set those parameters, use [digdag secrets command](https://docs.digdag.io/command_reference.html#secrets).

* **td.apikey**: API_KEY

  The Treasure Data API key to use when submitting Treasure Data bulk load jobs.

## Options

* **td_load>**: FILE.yml

  Path to a YAML template file. This configuration needs to be guessed using td command. If you saved DataConnector job on Treasure Data, you can use [Unique ID](https://tddocs.atlassian.net/wiki/spaces/PD/pages/1083717/Creating+a+YAML+Incremental+Data+Transfer+File#Configuring-your-Unique-ID-Incremental-Data-Transfer) instead of YAML path.

  Examples:

  ```
  td_load>: imports/load.yml
  ```

  ```
  td_load>: unique_id
  ```

* **database**: NAME

  Name of the database load data to.

  Examples:

  ```
  database: my_database
  ```

* **table**: NAME

  Name of the table load data to.

  Examples:

  ```
  table: my_table
  ```

* **endpoint**: ADDRESS

  API endpoint (default: api.treasuredata.com).

* **use_ssl**: BOOLEAN

  Enable SSL (https) to access to the endpoint (default: true).

## Output parameters

* **td.last_job_id** or **td.last_job.id**

  The job id this task executed.

  Examples:

  ```
  52036074
  ```

* **td.last_job.num_records**

  The number of records of this job output.

  Examples:

  ```
  10
  ```


text:
(function() {
  'use strict';

  Polymer({
    is: 'gr-admin-group-list',
    _legacyUndefinedCheck: true,

    properties: {
      /**
       * URL params passed from the router.
       */
      params: {
        type: Object,
        observer: '_paramsChanged',
      },

      /**
       * Offset of currently visible query results.
       */
      _offset: Number,
      _path: {
        type: String,
        readOnly: true,
        value: '/admin/groups',
      },
      _hasNewGroupName: Boolean,
      _createNewCapability: {
        type: Boolean,
        value: false,
      },
      _groups: Array,

      /**
       * Because  we request one more than the groupsPerPage, _shownGroups
       * may be one less than _groups.
       * */
      _shownGroups: {
        type: Array,
        computed: 'computeShownItems(_groups)',
      },

      _groupsPerPage: {
        type: Number,
        value: 25,
      },

      _loading: {
        type: Boolean,
        value: true,
      },
      _filter: String,
    },

    behaviors: [
      Gerrit.ListViewBehavior,
    ],

    attached() {
      this._getCreateGroupCapability();
      this.fire('title-change', {title: 'Groups'});
      this._maybeOpenCreateOverlay(this.params);
    },

    _paramsChanged(params) {
      this._loading = true;
      this._filter = this.getFilterValue(params);
      this._offset = this.getOffsetValue(params);

      return this._getGroups(this._filter, this._groupsPerPage,
          this._offset);
    },

    /**
     * Opens the create overlay if the route has a hash 'create'
     *
     * @param {!Object} params
     */
    _maybeOpenCreateOverlay(params) {
      if (params && params.openCreateModal) {
        this.$.createOverlay.open();
      }
    },

    _computeGroupUrl(id) {
      return Gerrit.Nav.getUrlForGroup(id);
    },

    _getCreateGroupCapability() {
      return this.$.restAPI.getAccount().then(account => {
        if (!account) { return; }
        return this.$.restAPI.getAccountCapabilities(['createGroup'])
            .then(capabilities => {
              if (capabilities.createGroup) {
                this._createNewCapability = true;
              }
            });
      });
    },

    _getGroups(filter, groupsPerPage, offset) {
      this._groups = [];
      return this.$.restAPI.getGroups(filter, groupsPerPage, offset)
          .then(groups => {
            if (!groups) {
              return;
            }
            this._groups = Object.keys(groups)
                .map(key => {
                  const group = groups[key];
                  group.name = key;
                  return group;
                });
            this._loading = false;
          });
    },

    _refreshGroupsList() {
      this.$.restAPI.invalidateGroupsCache();
      return this._getGroups(this._filter, this._groupsPerPage,
          this._offset);
    },

    _handleCreateGroup() {
      this.$.createNewModal.handleCreateGroup().then(() => {
        this._refreshGroupsList();
      });
    },

    _handleCloseCreate() {
      this.$.createOverlay.close();
    },

    _handleCreateClicked() {
      this.$.createOverlay.open();
    },

    _visibleToAll(item) {
      return item.options.visible_to_all === true ? 'Y' : 'N';
    },
  });
})();


text:
using System;
using System.Collections.Generic;
using System.Linq;
using BlueSheep.Common.Protocol.Types;
using BlueSheep.Common.IO;
using BlueSheep.Engine.Types;

namespace BlueSheep.Common.Protocol.Messages
{
    public class PrismInfoJoinLeaveRequestMessage : Message
    {
        public new const uint ID =5844;
        public override uint ProtocolID
        {
            get { return ID; }
        }

        public bool join;

        public PrismInfoJoinLeaveRequestMessage()
        {
        }

        public PrismInfoJoinLeaveRequestMessage(bool join)
        {
            this.join = join;
        }

        public override void Serialize(BigEndianWriter writer)
        {
            writer.WriteBoolean(join);
        }

        public override void Deserialize(BigEndianReader reader)
        {
            join = reader.ReadBoolean();
        }

    }

}


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */

namespace Piwik\Updates;

use Piwik\Common;
use Piwik\Updater;
use Piwik\Updates;
use Piwik\Updater\Migration\Factory as MigrationFactory;

/**
 * Update for version 2.13.1.
 */
class Updates_2_13_1 extends Updates
{
    /**
     * @var MigrationFactory
     */
    private $migration;

    public function __construct(MigrationFactory $factory)
    {
        $this->migration = $factory;
    }

    /**
     * Here you can define one or multiple SQL statements that should be executed during the update.
     * @return Updater\Migration[]
     */
    public function getMigrations(Updater $updater)
    {
        $optionTable = Common::prefixTable('option');
        $removeEmptyDefaultReportsSql = "delete from `$optionTable` where option_name like '%defaultReport%' and option_value=''";

        return array(
            $this->migration->db->sql($removeEmptyDefaultReportsSql)
        );
    }

    /**
     * Here you can define any action that should be performed during the update. For instance executing SQL statements,
     * renaming config entries, updating files, etc.
     */
    public function doUpdate(Updater $updater)
    {
        $updater->executeMigrations(__FILE__, $this->getMigrations($updater));
    }
}


text:
<?php

/** @file
* @brief
*/

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access directly to this file");
}

/**
 * Notification Class
**/
class Notification extends CommonDBTM {

// MAILING TYPE
   //Notification to a user (sse mailing users type below)
   const USER_TYPE             = 1;
   //Notification to users of a profile
   const PROFILE_TYPE          = 2;
   //Notification to users of a group
   const GROUP_TYPE            = 3;
   //Notification to the people in charge of the database synchronisation
   const MAILING_TYPE          = 4;
   //Notification to the supervisor of a group
   const SUPERVISOR_GROUP_TYPE = 5;
   //Notification to all users of a group except supervisor
   const GROUP_WITHOUT_SUPERVISOR_TYPE = 6;

   // MAILING USERS TYPE

   //Notification to the GLPI global administrator
   const GLOBAL_ADMINISTRATOR                = 1;
   //Notification to the technicial who's assign to a ticket
   const ASSIGN_TECH                         = 2;
   //Notification to the owner of the item
   const AUTHOR                              = 3;
   //Notification to the technician previously in charge of the ticket
   const OLD_TECH_IN_CHARGE                  = 4;
   //Notification to the technician in charge of the item
   const ITEM_TECH_IN_CHARGE                 = 5;
   //Notification to the item's user
   const ITEM_USER                           = 6;
   //Notification to the ticket's recipient
   const RECIPIENT                           = 7;
   //Notificartion to the ticket's assigned supplier
   const SUPPLIER                            = 8;
   //Notification to the ticket's assigned group
   const ASSIGN_GROUP                        = 9;
   //Notification to the supervisor of the ticket's assigned group
   const SUPERVISOR_ASSIGN_GROUP             = 10;
   //Notification to the entity administrator
   const ENTITY_ADMINISTRATOR                = 11;
   //Notification to the supervisor of the ticket's requester group
   const SUPERVISOR_REQUESTER_GROUP          = 12;
   //Notification to the ticket's requester group
   const REQUESTER_GROUP                     = 13;
   //Notification to the ticket's validation approver
   const VALIDATION_APPROVER                 = 14;
   //Notification to the ticket's validation requester
   const VALIDATION_REQUESTER                = 15;
   //Notification to the task assigned user
   const TASK_ASSIGN_TECH                    = 16;
   //Notification to the task author
   const TASK_AUTHOR                         = 17;
   //Notification to the followup author
   const FOLLOWUP_AUTHOR                     = 18;
   //Notification to the user
   const USER                                = 19;
   //Notification to the ticket's observer group
   const OBSERVER_GROUP                      = 20;
   //Notification to the ticket's observer user
   const OBSERVER                            = 21;
   //Notification to the supervisor of the ticket's observer group
   const SUPERVISOR_OBSERVER_GROUP           = 22;
   //Notification to the group of technicians in charge of the item
   const ITEM_TECH_GROUP_IN_CHARGE           = 23;
   // Notification to the ticket's assigned group without supervisor
   const ASSIGN_GROUP_WITHOUT_SUPERVISOR     = 24;
   //Notification to the ticket's requester group without supervisor
   const REQUESTER_GROUP_WITHOUT_SUPERVISOR  = 25;
   //Notification to the ticket's observer group without supervisor
   const OBSERVER_GROUP_WITHOUT_SUPERVISOR   = 26;
   // Notification to manager users
   const MANAGER_USER                        = 27;
   // Notification to manager groups
   const MANAGER_GROUP                       = 28;
   // Notification to supervisor of manager group
   const MANAGER_GROUP_SUPERVISOR            = 29;
   // Notification to manager group without supervisor
   const MANAGER_GROUP_WITHOUT_SUPERVISOR    = 30;
   // Notification to team users
   const TEAM_USER                           = 31;
   // Notification to team groups
   const TEAM_GROUP                          = 32;
   // Notification to supervisor of team groups
   const TEAM_GROUP_SUPERVISOR               = 33;
   // Notification to team groups without supervisor
   const TEAM_GROUP_WITHOUT_SUPERVISOR       = 34;
   // Notification to team contacts
   const TEAM_CONTACT                        = 35;
   // Notification to team suppliers
   const TEAM_SUPPLIER                       = 36;

   // From CommonDBTM
   public $dohistory = true;

   static $rightname = 'notification';

   static function getTypeName($nb=0) {
      return _n('Notification', 'Notifications', $nb);
   }

   /**
    *  @see CommonGLPI::getMenuContent()
    *
    *  @since version 0.85
   **/
   static function getMenuContent() {
      global $CFG_GLPI;

      $menu = array();

      if (Notification::canView()
          || Config::canView()) {
         $menu['title']                                      = _n('Notification', 'Notifications', Session::getPluralNumber());
         $menu['page']                                       = '/front/setup.notification.php';
         $menu['options']['notification']['title']           = _n('Notification', 'Notifications', Session::getPluralNumber());
         $menu['options']['notification']['page']            = '/front/notification.php';
         $menu['options']['notification']['links']['add']    = '/front/notification.form.php';
         $menu['options']['notification']['links']['search'] = '/front/notification.php';

         $menu['options']['config']['title'] = __('Setup');
         $menu['options']['config']['page']  = '/front/notificationmailsetting.form.php';

         $menu['options']['notificationtemplate']['title']
                        = _n('Notification template', 'Notification templates', Session::getPluralNumber());
         $menu['options']['notificationtemplate']['page']
                        = '/front/notificationtemplate.php';
         $menu['options']['notificationtemplate']['links']['add']
                        = '/front/notificationtemplate.form.php';
         $menu['options']['notificationtemplate']['links']['search']
                        = '/front/notificationtemplate.php';

      }
      if (count($menu)) {
         return $menu;
      }
      return false;
   }

   function defineTabs($options=array()) {

      $ong = array();
      $this->addDefaultFormTab($ong);
      $this->addStandardTab('NotificationTarget', $ong, $options);
      $this->addStandardTab('Log', $ong, $options);

      return $ong;
   }

   function showForm($ID, $options=array()) {
      global $CFG_GLPI;

      $this->initForm($ID, $options);
      $this->showFormHeader($options);

      echo "
" . __('Name') . "	";
      echo "";
      Html::autocompletionTextField($this, "name");
      echo "	";

      echo "".__('Comments')."	";
      echo "<textarea cols='45' rows='9' name='comment' >".
             $this->fields["comment"]."</textarea>
";

      echo "
" . __('Active') . "	";
      echo "";
      Dropdown::showYesNo('is_active', $this->fields['is_active']);
      echo "
";

      echo "
" . __('Type') . "	";
      echo "";
      if (!Session::haveRight(static::$rightname, UPDATE)) {
         $itemtype = $this->fields['itemtype'];
         echo $itemtype::getTypeName(1);
         $rand ='';
      } else if (Config::canUpdate()
          && ($this->getEntityID() == 0)) {
         $rand = Dropdown::showItemTypes('itemtype', $CFG_GLPI["notificationtemplates_types"],
                                          array('value' => $this->fields['itemtype']));
      } else {
         $rand = Dropdown::showItemTypes('itemtype',
                                         array_diff($CFG_GLPI["notificationtemplates_types"],
                                                    array('Crontask', 'DBConnection', 'User')),
                                         array('value' => $this->fields['itemtype']));
      }

      $params = array('itemtype' => '__VALUE__');
      Ajax::updateItemOnSelectEvent("dropdown_itemtype$rand", "show_events",
                                    $CFG_GLPI["root_doc"]."/ajax/dropdownNotificationEvent.php",
                                    $params);
      Ajax::updateItemOnSelectEvent("dropdown_itemtype$rand", "show_templates",
                                    $CFG_GLPI["root_doc"]."/ajax/dropdownNotificationTemplate.php",
                                    $params);
      echo "
";

      echo "
" . __('Notification method') . "	";
      echo "";
      self::dropdownMode(array('value'=>$this->fields['mode']));
      echo "
";

      echo "
" . NotificationEvent::getTypeName(1) . "	";
      echo "";
      NotificationEvent::dropdownEvents($this->fields['itemtype'],
                                        array('value'=>$this->fields['event']));
      echo "
";

      echo "
". NotificationTemplate::getTypeName(1)."	";
      echo "";
      NotificationTemplate::dropdownTemplates('notificationtemplates_id', $this->fields['itemtype'],
                                              $this->fields['notificationtemplates_id']);
      echo "
";

      $this->showFormButtons($options);
      return true;
   }

   /**
    * @since version 0.84
    *
    * @param $field
    * @param $values
    * @param $options   array
   **/
   static function getSpecificValueToDisplay($field, $values, array $options=array()) {

      if (!is_array($values)) {
         $values = array($field => $values);
      }
      switch ($field) {
         case 'event':
            if (isset($values['itemtype']) && !empty($values['itemtype'])) {
               return NotificationEvent::getEventName($values['itemtype'],$values[$field]);
            }
            break;

         case 'mode':
            return self::getMode($values[$field]);
      }
      return parent::getSpecificValueToDisplay($field, $values, $options);
   }

   /**
    * @since version 0.84
    *
    * @param $field
    * @param $name               (default '')
    * @param $values             (default '')
    * @param $options      array
   **/
   static function getSpecificValueToSelect($field, $name='', $values='', array $options=array()) {

      if (!is_array($values)) {
         $values = array($field => $values);
      }
      $options['display'] = false;

      switch ($field) {
         case 'event' :
            if (isset($values['itemtype'])
                && !empty($values['itemtype'])) {
               $options['value'] = $values[$field];
               $options['name']  = $name;
               return NotificationEvent::dropdownEvents($values['itemtype'],$options);
            }
            break;

         case 'mode' :
            $options['value'] = $values[$field];
            $options['name']  = $name;
            return self::dropdownMode($options);
      }
      return parent::getSpecificValueToSelect($field, $name, $values, $options);
   }

   function getSearchOptions() {

      $tab                       = array();
      $tab['common']             = __('Characteristics');

      $tab[1]['table']           = $this->getTable();
      $tab[1]['field']           = 'name';
      $tab[1]['name']            = __('Name');
      $tab[1]['datatype']        = 'itemlink';
      $tab[1]['massiveaction']   = false;

      $tab[2]['table']           = $this->getTable();
      $tab[2]['field']           = 'event';
      $tab[2]['name']            = _n('Event', 'Events', 1);
      $tab[2]['massiveaction']   = false;
      $tab[2]['datatype']        = 'specific';
      $tab[2]['additionalfields'] = array('itemtype');

      $tab[3]['table']           = $this->getTable();
      $tab[3]['field']           = 'mode';
      $tab[3]['name']            = __('Notification method');
      $tab[3]['massiveaction']   = false;
      $tab[3]['datatype']        = 'specific';
      $tab[3]['searchtype']      = array('equals', 'notequals');

      $tab[4]['table']           = 'glpi_notificationtemplates';
      $tab[4]['field']           = 'name';
      $tab[4]['name']            = _n('Notification template', 'Notification templates', Session::getPluralNumber());
      $tab[4]['datatype']        = 'itemlink';

      $tab[5]['table']           = $this->getTable();
      $tab[5]['field']           = 'itemtype';
      $tab[5]['name']            = __('Type');
      $tab[5]['datatype']        = 'itemtypename';
      $tab[5]['itemtype_list']   = 'notificationtemplates_types';
      $tab[5]['massiveaction']   = false;

      $tab[6]['table']           = $this->getTable();
      $tab[6]['field']           = 'is_active';
      $tab[6]['name']            = __('Active');
      $tab[6]['datatype']        = 'bool';

      $tab[16]['table']          = $this->getTable();
      $tab[16]['field']          = 'comment';
      $tab[16]['name']           = __('Comments');
      $tab[16]['datatype']       = 'text';

      $tab[80]['table']          = 'glpi_entities';
      $tab[80]['field']          = 'completename';
      $tab[80]['name']           = __('Entity');
      $tab[80]['massiveaction']  = false;
      $tab[80]['datatype']       = 'dropdown';

      $tab[86]['table']          = $this->getTable();
      $tab[86]['field']          = 'is_recursive';
      $tab[86]['name']           = __('Child entities');
      $tab[86]['datatype']       = 'bool';

      return $tab;
   }

   function canViewItem() {

      if ((($this->fields['itemtype'] == 'Crontask')
           || ($this->fields['itemtype'] == 'DBConnection'))
          && !Config::canView()) {
          return false;
      }
      return Session::haveAccessToEntity($this->getEntityID(), $this->isRecursive());
   }

   /**
    * Is the current user have right to update the current notification ?
    *
    * @return boolean
   **/
   function canCreateItem() {

      if ((($this->fields['itemtype'] == 'Crontask')
           || ($this->fields['itemtype'] == 'DBConnection'))
          && !Config::canUpdate()) {
          return false;
      }
      return Session::haveAccessToEntity($this->getEntityID());
   }

   /**
    * Display a dropdown with all the available notification modes
    *
    * @param $options array of options
   **/
   static function dropdownMode($options) {

      $p['name']    = 'mode';
      $p['display'] = true;
      $p['value']   = '';

      if (is_array($options) && count($options)) {
         foreach ($options as $key => $val) {
            $p[$key] = $val;
         }
      }

      return Dropdown::showFromArray($p['name'], self::getModes(), $p);
   }

   /**
    * Get notification method label (email only for the moment)
    *
    * @param $mode the mode to use
    *
    * @return the mode's label
   **/
   static function getMode($mode) {

      $tab = self::getModes();
      if (isset($tab[$mode])) {
         return $tab[$mode];
      }
      return NOT_AVAILABLE;
   }

   /**
    * Get notification method label (email only for the moment)
    *
    * @since versin 0.84
    *
    * @return the mode's label
   **/
   static function getModes() {
      return array('mail' => __('Email'));
   }

   function cleanDBonPurge() {
      global $DB;

      $query = "DELETE
                FROM `glpi_notificationtargets`
                WHERE `notifications_id` = '".$this->fields['id']."'";
      $DB->query($query);
   }

   /**
    * @param $mailing_options
   **/
   static function send($mailing_options) {

      $mail = new NotificationMail();
      $mail->sendNotification($mailing_options);
//       $mail->ClearAddresses();
   }

   /**
    * Get the mailing signature for the entity
    *
    * @param $entity
   **/
   static function getMailingSignature($entity) {
      global $DB, $CFG_GLPI;

      foreach ($DB->request('glpi_entities', array('id' => $entity)) as $data) {
         if (!empty($data['mailing_signature'])) {
            return $data['mailing_signature'];
         }
      }
      return $CFG_GLPI['mailing_signature'];
   }

   /**
    * @param $event
    * @param $itemtype
    * @param $entity
   **/
   static function getNotificationsByEventAndType($event, $itemtype, $entity) {
      global $DB;

      $query = "SELECT `glpi_notifications`.*
                FROM `glpi_notifications`
                LEFT JOIN `glpi_entities`
                  ON (`glpi_entities`.`id` = `glpi_notifications`.`entities_id`)
                WHERE `glpi_notifications`.`itemtype` = '$itemtype'
                      AND `glpi_notifications`.`event` = '$event' ".
                      getEntitiesRestrictRequest("AND", "glpi_notifications", 'entities_id',
                                                 $entity, true) ."
                      AND `glpi_notifications`.`is_active`='1'
                ORDER BY `glpi_entities`.`level` DESC";

      return $DB->request($query);
   }

}
?>


text:
require 'foodie'

describe Foodie::Food do
  it "broccoli is gross" do
    Foodie::Food.portray("Broccoli").should eql("Gross!")
  end

  it "anything else is delicious" do
    Foodie::Food.portray("Not Broccoli").should eql("Delicious!")
  end

  it "pluralizes a word" do
    Foodie::Food.pluralize("Tomato").should eql("Tomatoes")
  end
end


text:
require 'app/models/concerns/status'

class RedBall
  include Mongoid::Document

  field :status, type: Status
end


text:
package cn.mejhwu.service.impl;

import cn.mejhwu.beans.User;
import cn.mejhwu.dao.UserDao;
import cn.mejhwu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author: jhwu
 * E-mail: mejhwu@163.com
 * Date: 17-4-8
 * Time: 下午4:38.
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	public User queryUser(User user) {
		return userDao.queryUser(user);
	}
}


text:
package com.onsemi.matrix.android.testlogic;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import com.eclipsesource.restfuse.HttpJUnitRunner;

import org.junit.runner.manipulation.NoTestsRemainException;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

public class ExtendedHttpJUnitRunner extends HttpJUnitRunner {
    private String name;

    private List<Test> tests;
    private Hashtable<Test, Boolean> executableTests;

    private List<String> ignoredTests = null;

    private RunnerGroup runnerGroup;

	public ExtendedHttpJUnitRunner(String name, Class<?> klass) throws InitializationError {
		super(klass);

        this.name = name;

        this.tests = new ArrayList<>();
        this.executableTests = new Hashtable<>();

        List<FrameworkMethod> methods = this.getChildren();

        for(FrameworkMethod method : methods) {
            String methodName = this.describeChild(method).getMethodName();
            this.tests.add(new Test(methodName));
        }
	}

    public void setRunnerGroup(RunnerGroup runnerGroup) {
        this.runnerGroup = runnerGroup;
    }

    public RunnerGroup getRunnerGroup() {
        return this.runnerGroup;
    }

	public List<Test> getTests() {
		return this.tests;
	}

    public String getName() {
        return this.name;
    }

    public void updateTest(String methodName, Status status, String error) {
        for(int i = 0; i < this.tests.size(); i++) {
            if (this.tests.get(i).getMethodName().compareTo(methodName) == 0) {
                this.tests.get(i).setStatus(status);
                this.tests.get(i).setError(error);

                if(runnerGroup != null)
                    runnerGroup.notifyObservers();
            }
        }
    }

    public void run(RunNotifier notifier, Configuration configuration) throws NoTestsRemainException {
        if (configuration.getExecutableTest() != null) {
            this.executableTests.put(configuration.getExecutableTest(), false);
        } else {
            this.executableTests.clear();
        }

        if (configuration.getIgnoredTests() != null) {
            this.ignoredTests = configuration.getIgnoredTests();
        }

        super.run(notifier);

        if (configuration.getExecutableTest() != null) {
            this.executableTests.remove(configuration.getExecutableTest());
        }

        if (configuration.getIgnoredTests() != null) {
            this.ignoredTests = null;
        }
    }

    @Override
    public void runChild(FrameworkMethod method, RunNotifier notifier) {
        String methodName = method.getName();

        if (this.ignoredTests != null ) {
            for(String ignoredTest : this.ignoredTests) {
                if(ignoredTest.compareTo(methodName) == 0) {
                    return;
                }
            }
        }

        if (this.executableTests.isEmpty()) {
            super.runChild(method, notifier);
            return;
        }

        for(Test executableTest : this.executableTests.keySet()) {
            if (executableTest.getMethodName().compareTo(methodName) == 0 &&
                    !this.executableTests.get(executableTest)) {
                super.runChild(method, notifier);

                this.executableTests.put(executableTest, true);

                return;
            }
        }
    }
}


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

namespace MOE.Common.Models.Repositories
{
    public class SignalEventCountAggregationRepository : ISignalEventCountAggregationRepository
    {
        private readonly SPM _db;

        public SignalEventCountAggregationRepository()
        {
            _db = new SPM();
        }

        public SignalEventCountAggregationRepository(SPM context)
        {
            _db = context;
        }

        public int GetSignalEventCountSumAggregationBySignalIdAndDateRange(string signalId, DateTime start, DateTime end)
        {
            var cycles = 0;
            if (_db.SignalEventCountAggregations.Any(r => r.SignalId == signalId
                                                          && r.BinStartTime >= start && r.BinStartTime <= end))
            {
                cycles = _db.SignalEventCountAggregations.Where(r => r.SignalId == signalId
                                                                     && r.BinStartTime >= start &&
                                                                     r.BinStartTime <= end)
                    .Sum(r => r.EventCount);
            }
            return cycles;
        }

        public List<SignalEventCountAggregation> GetSignalEventCountAggregationBySignalIdAndDateRange(string signalId,
            DateTime startDate, DateTime endDate)
        {
            return _db.SignalEventCountAggregations.Where(r => r.SignalId == signalId
                                                            && r.BinStartTime >= startDate &&
                                                            r.BinStartTime <= endDate).ToList();
        }
    }

}


text:
 Domain Object that is used in the Site Template for OOB Features

**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)
**Assembly:** OfficeDevPnP.Core.dll
## Inheritance Hierarchy
System.Object
 [OfficeDevPnP.Core.Framework.Provisioning.Model.BaseModel](OfficeDevPnP.Core.Framework.Provisioning.Model.BaseModel.md)
## Syntax
```C#
public class Features: BaseModel
```
## Constructors
|**Name**|**Description**|
|:-----|:-----|
| [Features()](OfficeDevPnP.Core.Framework.Provisioning.Model.Features.ctor1.md) | Constructor for Features class
## Properties
|**Name**|**Description**|
|:-----|:-----|
| [SiteFeatures](OfficeDevPnP.Core.Framework.Provisioning.Model.Features.SiteFeatures.md) | A Collection of Features at the Site level
| [WebFeatures](OfficeDevPnP.Core.Framework.Provisioning.Model.Features.WebFeatures.md) | A Collection of Features at the Web level
## See also
- [OfficeDevPnP.Core.Framework.Provisioning.Model](OfficeDevPnP.Core.Framework.Provisioning.Model.md)


text:
package com.dungeonstory.ui.event;

import com.dungeonstory.ui.DungeonStoryUI;

/**
 * Convenience class for accessing the _UI Scoped_ EventBus. If you are using
 * something like the CDI event bus, you don't need a class like this.
 */
public class EventBus {

    public static void register(final Object listener) {
        DungeonStoryUI.getEventBus().register(listener);
    }

    public static void unregister(final Object listener) {
        DungeonStoryUI.getEventBus().unregister(listener);
    }

    public static void post(final Object event) {
        DungeonStoryUI.getEventBus().post(event);
    }
}


text: """Member Node Stress Tester."""


text:
import nltk

nltk.data.path.append("./nltk_data")

import trie

database = trie.Trie()
words = nltk.corpus.webtext.words()
words += nltk.corpus.nps_chat.words()
words += nltk.corpus.brown.words()
#words += nltk.corpus.gutenberg.words()
#words += nltk.corpus.reuters.words()

for word in words:
    database.insert(word)

def auto_complete(word):
    return database.autocomplete(word)


text:
var gulp = require('gulp');

var filesize = require('gulp-filesize');
var rename = require('gulp-rename');

var concat = require('gulp-concat');
var uglify = require('gulp-uglify');

var sass = require('gulp-sass');
var uncss = require('gulp-uncss');
var minifycss = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');

var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');

gulp.task('vendor', function() {
    return gulp.src(['./_lib/jquery/*.js',
                    './_lib/foundation/foundation.js',
                    './_lib/foundation/foundation.accordion.js',
                    './_lib/*.js'])
        .pipe(concat('vendor.js'))
        .pipe(gulp.dest('./js'));
});

gulp.task('sass', function () {
    return gulp.src('./_scss/main.scss')
        .pipe(sass.sync().on('error', sass.logError))
        .pipe(sass({outputStyle: 'expanded'}))
        .pipe(gulp.dest('./css'));
});

gulp.task('uncss', ['sass'], function () {
    return gulp.src('./css/main.css')
        .pipe(uncss({
            html: ['index.html', 'photos/index.html']
        }))
        .pipe(gulp.dest('./css'));
});

gulp.task('minify:css', ['uncss'], function() {
    return gulp.src('./css/main.css')
        .pipe(sourcemaps.init())
        .pipe(minifycss({compatibility: 'ie7'}))
        .pipe(rename('main.min.css'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('./css'));
});

gulp.task('minify:vendor', ['vendor'], function () {
    return gulp.src('./js/vendor.js')
        .pipe(filesize())
        .pipe(uglify())
        .pipe(rename('vendor.min.js'))
        .pipe(gulp.dest('./js'))
        .pipe(filesize());
});

gulp.task('minify:main', function () {
    return gulp.src('./js/main.js')
        .pipe(filesize())
        .pipe(uglify())
        .pipe(rename('main.min.js'))
        .pipe(gulp.dest('./js'))
        .pipe(filesize());
});

gulp.task('imagemin', function () {
    return gulp.src('./_images/*')
        .pipe(imagemin({
            optimizationLevel: 3,
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('./img'));
});

gulp.task('watch', function () {
    gulp.watch('./_scss/**/*.scss', ['sass']);
});

gulp.task('minify', ['minify:vendor', 'minify:main', 'minify:css']);

gulp.task('default', ['sass', 'uncss', 'vendor', 'minify', 'imagemin']);


text:
#include <xip/inventor/core/SbXipDirtyFieldList.h>
#include <xip/inventor/core/SoXipSFData.h>
#include <xip/inventor/core/SoXipMFData.h>

SbPList SbXipDirtyFieldList::mDirty;
SoDelayQueueSensor SbXipDirtyFieldList::mDirtySensor;

void SbXipDirtyFieldList::initClass()
{
	mDirtySensor.setFunction(dirtySensorCB);
}

// Because the data pointers are not serialized, the fields must be marked as dirty after deserialization.
// This static method is called by SoXipSFData and SoXipMFData whenever values are read from a stream.
void SbXipDirtyFieldList::append(SoField *field)
{
	int i;

	if (field)
	{
		for (i = mDirty.getLength() - 1; i >= 0; i--)
		{
			if (mDirty.get(i) == field) return;
		}

		mDirty.append(field);

		if (!mDirtySensor.isScheduled())
		{
			mDirtySensor.schedule();
		}
	}
}

// This static method is called by SoXipSFData and SoXipMFData destructors to make sure we do not have invalid
// pointers in the list.
void SbXipDirtyFieldList::remove(SoField *field)
{
	int i;

	if (field)
	{
		for (i = mDirty.getLength() - 1; i >= 0; i--)
		{
			if (mDirty.get(i) == field)
			{
				mDirty.remove(i);
			}
		}
	}
}

// Delay queue callback that will touch all fields in the "dirty" list.
void SbXipDirtyFieldList::dirtySensorCB(void * data, SoSensor * sensor)
{
	int i;

	if (mDirtySensor.isScheduled())
	{
		mDirtySensor.unschedule();
	}

	for (i = mDirty.getLength() - 1; i >= 0; i--)
	{
		SoField *field = (SoField *) mDirty.get(i);
		if (field)
		{
			field->touch();
		}
	}

	mDirty.truncate(0);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">JustTrustBeri</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

</resources>


text:
var myData= require('../myClasses.json')
var classes= require('../classes.json')

exports.view = function(req, res){

	 email = {'email':req.query.email};

	if(req.query.name!=undefined & req.query.name!=""){
		newClass={'name':req.query.name};
	 	myData["myClasses"].push(newClass);
	 }
	//res.partial('faq');
	res.render('pickClass', {"pickClassData":[myData,classes]} );
};


text:
MiniHack additionally provides support for agents using the [RLlib](https://docs.ray.io/en/latest/rllib.html) library. RLlib is an open-source library for reinforcement learning that offers  high scalability and a unified API for a variety of applications. RLlib natively supports TensorFlow, TensorFlow Eager, and PyTorch. RLlib includes implementations of many popular algorithms, including IMPALA, PPO, Rainbow DQN, A3C, and many more. The full list of algorithms is available [here](https://docs.ray.io/en/latest/rllib-toc.html#algorithms).

For further details, checkout out RLlib [paper](https://arxiv.org/abs/1712.09381) and [blog post](https://docs.ray.io/en/latest/rllib-examples.html#blog-posts).

## Installation

To install and train an RLlib agent use the following commands:
```bash
pip install -e ".[rllib]"
# Test DQN run
python3 -m minihack.agent.rllib.train algo=dqn env=MiniHack-Room-5x5-v0 total_steps=1000000 lr=0.000001
```

## Running Experiments

We use the [hydra](https://github.com/facebookresearch/hydra) framework for configuring our experiments. All environment and training parameters can be specified using command line arguments (or edited directly in `config.yaml`). See `config.yaml` file in  `minihack.agent.rllib` for more information. Be sure to set up appropriate parameters for logging with [wandb](https://wandb.ai/site) (disabled by default).

```bash
# Single A2C run
python3 -m minihack.agent.rllib.train algo=a2c env=MiniHack-Room-15x15-v0 total_steps=1000000 a2c.entropy_coeff=0.001 lr=0.00001

# Single PPO run
python3 -m minihack.agent.rllib.train algo=ppo env=MiniHack-Room-15x15-v0 total_steps=1000000 ppo.entropy_coeff=0.0001 lr=0.00001

# Single DQN run
python3 -m minihack.agent.rllib.train algo=dqn env=MiniHack-Room-15x15-v0 total_steps=1000000 dqn.buffer_size=100000 lr=0.000001

# To perform a sweep on the cluster: add another --multirun command and comma-separate values
python3 -m minihack.agent.rllib.train --multirun algo=a2c env=MiniHack-Room-15x15-v0 lr=0.00001 seed=0,1,2,3,4 total_steps=5000000
```


text:
#include "tensorflow/compiler/tf2xla/lib/util.h"

#include <memory>
#include <vector>

#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/lib/core/errors.h"

namespace tensorflow {

xla::ComputationDataHandle Zeros(xla::ComputationBuilder* builder,
                                 const xla::Shape& shape) {
  return builder->Broadcast(
      builder->ConstantLiteral(xla::Literal::Zero(shape.element_type())),
      xla::AsInt64Slice(shape.dimensions()));
}

xla::ComputationDataHandle FloatLiteral(xla::ComputationBuilder* builder,
                                        xla::PrimitiveType type, double value) {
  switch (type) {
    case xla::F16:
      return builder->ConstantR0<xla::half>(static_cast<xla::half>(value));
      break;
    case xla::BF16:
      return builder->ConstantR0<bfloat16>(static_cast<bfloat16>(value));
      break;
    case xla::F32:
      return builder->ConstantR0<float>(static_cast<float>(value));
      break;
    case xla::F64:
      return builder->ConstantR0<double>(value);
      break;
    case xla::C64:
      return builder->ConstantR0<xla::complex64>(value);
      break;
    default:
      LOG(FATAL) << "unhandled element type " << type;
  }
}

xla::ComputationDataHandle IntegerLiteral(xla::ComputationBuilder* builder,
                                          xla::PrimitiveType type,
                                          int64 value) {
  xla::Literal literal;
  switch (type) {
    case xla::U8:
      literal = std::move(*xla::Literal::CreateR0<uint8>(value));
      break;
    case xla::U32:
      literal = std::move(*xla::Literal::CreateR0<uint32>(value));
      break;
    case xla::U64:
      literal = std::move(*xla::Literal::CreateR0<uint64>(value));
      break;
    case xla::S8:
      literal = std::move(*xla::Literal::CreateR0<int8>(value));
      break;
    case xla::S32:
      literal = std::move(*xla::Literal::CreateR0<int32>(value));
      break;
    case xla::S64:
      literal = std::move(*xla::Literal::CreateR0<int64>(value));
      break;
    case xla::F32:
      literal = std::move(*xla::Literal::CreateR0<float>(value));
      break;
    case xla::F64:
      literal = std::move(*xla::Literal::CreateR0<double>(value));
      break;
    case xla::C64:
      literal = std::move(*xla::Literal::CreateR0<complex64>(value));
      break;
    case xla::PRED:
      LOG(FATAL) << "pred element type is not integral";
    case xla::S16:
    case xla::U16:
      LOG(FATAL) << "u16/s16 literals not yet implemented";
    case xla::BF16:
      literal = std::move(
          *xla::Literal::CreateR0<bfloat16>(static_cast<bfloat16>(value)));
      break;
    case xla::F16:
      literal = std::move(
          *xla::Literal::CreateR0<xla::half>(static_cast<xla::half>(value)));
      break;
    case xla::TUPLE:
      LOG(FATAL) << "tuple element type is not integral";
    case xla::OPAQUE:
      LOG(FATAL) << "opaque element type is not integral";
    default:
      LOG(FATAL) << "unhandled element type " << type;
  }
  return builder->ConstantLiteral(literal);
}

xla::StatusOr<xla::ComputationDataHandle> SliceInMinorDims(
    xla::ComputationBuilder* builder, const xla::ComputationDataHandle& x,
    gtl::ArraySlice<int64> start, gtl::ArraySlice<int64> end) {
  TF_RET_CHECK(start.size() == end.size());
  int64 n_minor_dims = start.size();

  TF_ASSIGN_OR_RETURN(std::unique_ptr<xla::Shape> shape, builder->GetShape(x));

  const int64 n_dims = xla::ShapeUtil::Rank(*shape);
  TF_RET_CHECK(n_minor_dims <= n_dims);
  gtl::ArraySlice<int64> major_dims(xla::AsInt64Slice(shape->dimensions()),
                                    /*pos=*/0,
                                    /*len=*/n_dims - n_minor_dims);

  // Prepends 0s in the major dim
  std::vector<int64> padded_start(n_dims, 0);
  std::copy(start.begin(), start.end(),
            padded_start.begin() + major_dims.size());

  // Prepends the shape of the major dims.
  std::vector<int64> padded_end(n_dims);
  std::copy(major_dims.begin(), major_dims.end(), padded_end.begin());
  std::copy(end.begin(), end.end(), padded_end.begin() + major_dims.size());

  std::vector<int64> strides(n_dims, 1);
  return builder->Slice(x, padded_start, padded_end, strides);
}

xla::StatusOr<xla::ComputationDataHandle> UpdateSlice(
    xla::ComputationBuilder* builder, const xla::ComputationDataHandle& x,
    const xla::ComputationDataHandle& update, gtl::ArraySlice<int64> start) {
  // TODO(phawkins): make int64 work on all backends, remove the int32 cast.
  std::vector<int32> start_as_int32(start.begin(), start.end());
  return builder->DynamicUpdateSlice(
      x, update, builder->ConstantR1<int32>(start_as_int32));
}

xla::StatusOr<xla::ComputationDataHandle> UpdateSliceInMinorDims(
    xla::ComputationBuilder* builder, const xla::ComputationDataHandle& x,
    const xla::ComputationDataHandle& update, gtl::ArraySlice<int64> start) {
  TF_ASSIGN_OR_RETURN(std::unique_ptr<xla::Shape> shape, builder->GetShape(x));
  const int64 n_dims = xla::ShapeUtil::Rank(*shape);
  const int64 n_minor_dims = start.size();
  TF_RET_CHECK(n_minor_dims <= n_dims);
  std::vector<int64> padded_start(n_dims, 0);
  std::copy(start.begin(), start.end(),
            padded_start.begin() + (n_dims - n_minor_dims));
  return UpdateSlice(builder, x, update, padded_start);
}

xla::StatusOr<xla::ComputationDataHandle> TransposeInMinorDims(
    xla::ComputationBuilder* builder, const xla::ComputationDataHandle& x) {
  TF_ASSIGN_OR_RETURN(std::unique_ptr<xla::Shape> shape, builder->GetShape(x));
  const int64 n_dims = xla::ShapeUtil::Rank(*shape);
  TF_RET_CHECK(n_dims >= 2);
  std::vector<int64> permutation(n_dims);
  std::iota(permutation.begin(), permutation.end(), 0);
  std::swap(permutation[n_dims - 1], permutation[n_dims - 2]);
  return builder->Transpose(x, permutation);
}

}  // namespace tensorflow


text:
angular.module("listaTelefonica").directive("uiAccordions",function(){
	return {
		controller: function($scope,$element,$attrs){
			var accordions = [];

			this.registerAccordion = function(accordion){
				accordions.push(accordion);
			}

			this.closeAll = function(){
				accordions.forEach(function(accordion) {
					accordion.isOpened = false;
				});
			}
		}
	};
});

angular.module("listaTelefonica").directive("uiAccordion",function(){
	return {
		templateUrl: "view/accordion.html",
		scope: {
			title: "@"
		},
		transclude: true,
		link: function(scope, element, attrs, ctrl){
			ctrl.registerAccordion(scope);
			scope.open = function(){
				ctrl.closeAll();
				scope.isOpened = true;
			}
		},
		require: "^uiAccordions"
	};
})


text:
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _component = require("../../lib/component/component.js");

var _component2 = _interopRequireDefault(_component);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var useVoice = Symbol();

var Person = function (_Component) {
	_inherits(Person, _Component);

	function Person() {
		_classCallCheck(this, Person);

		return _possibleConstructorReturn(this, Object.getPrototypeOf(Person).apply(this, arguments));
	}

	_createClass(Person, [{
		key: "initialize",
		value: function initialize() {
			this.link("arm", Arm);
		}
	}, {
		key: "yell",
		value: function yell() {
			this[useVoice]();
		}
	}, {
		key: useVoice,
		value: function value() {}
	}]);

	return Person;
}(_component2.default);

var Arm = function (_Component2) {
	_inherits(Arm, _Component2);

	function Arm() {
		_classCallCheck(this, Arm);

		return _possibleConstructorReturn(this, Object.getPrototypeOf(Arm).apply(this, arguments));
	}

	_createClass(Arm, [{
		key: "initialize",
		value: function initialize(side) {
			this.properties("side");
			this.side(side);
		}
	}]);

	return Arm;
}(_component2.default);

describe("component.link (custom function)", function () {
	var person = void 0;

	beforeEach(function () {
		person = new Person();
	});

	it("should copy custom functions from parent links to child links", function () {
		person.arm("left").should.respondTo("yell");
	});

	it("should bind the parent function to the child link", function () {
		(function () {
			person.arm("left").yell("Wubba Lubba Dub Dub!");
		}).should.not.throw();
	});
});


text:
struct ViewerSetup
{
};

//-----------------------------------------------------------------------------
// State Class
//-----------------------------------------------------------------------------
class State
{
public:
	State( unsigned long id = 0 );

	virtual void Load();
	virtual void Close();

	virtual void RequestViewer( ViewerSetup *viewer );
	virtual void Update( float elapsed );
	virtual void Render();

	unsigned long GetID();

private:
	unsigned long m_id; // Application defined ID (must be unique for state switching).
};

#endif


text:
import argparse
import os
import logging
import platform
import re
import subprocess
import urllib2
import json

from core import path_util

from telemetry import benchmark
from telemetry.core import discover
from telemetry.util import command_line
from telemetry.util import matching

CHROMIUM_CONFIG_FILENAME = 'tools/run-perf-test.cfg'
BLINK_CONFIG_FILENAME = 'Tools/run-perf-test.cfg'
SUCCESS, NO_CHANGES, ERROR = range(3)
# Unsupported Perf bisect bots.
EXCLUDED_BOTS = {
    'win_xp_perf_bisect',  # Goma issues: crbug.com/330900
    'win_perf_bisect_builder',
    'win64_nv_tester',
    'winx64_bisect_builder',
    'linux_perf_bisect_builder',
    'mac_perf_bisect_builder',
    'android_perf_bisect_builder',
    'android_arm64_perf_bisect_builder',
    # Bisect FYI bots are not meant for testing actual perf regressions.
    # Hardware configuration on these bots is different from actual bisect bot
    # and these bots runs E2E integration tests for auto-bisect
    # using dummy benchmarks.
    'linux_fyi_perf_bisect',
    'mac_fyi_perf_bisect',
    'win_fyi_perf_bisect',
    # CQ bots on tryserver.chromium.perf
    'android_s5_perf_cq',
    'winx64_10_perf_cq',
    'mac_retina_perf_cq',
    'linux_perf_cq',
}

INCLUDE_BOTS = [
    'all',
    'all-win',
    'all-mac',
    'all-linux',
    'all-android'
]

# Default try bot to use incase builbot is unreachable.
DEFAULT_TRYBOTS =  [
    'linux_perf_bisect',
    'mac_10_11_perf_bisect',
    'winx64_10_perf_bisect',
    'android_s5_perf_bisect',
]

assert not set(DEFAULT_TRYBOTS) & set(EXCLUDED_BOTS),  ( 'A trybot cannot '
    'present in both Default as well as Excluded bots lists.')

class TrybotError(Exception):

  def __str__(self):
    return '%s\nError running tryjob.' % self.args[0]

def _GetTrybotList(builders):
  builders = ['%s' % bot.replace('_perf_bisect', '').replace('_', '-')
              for bot in builders]
  builders.extend(INCLUDE_BOTS)
  return sorted(builders)

def _GetBotPlatformFromTrybotName(trybot_name):
  os_names = ['linux', 'android', 'mac', 'win']
  try:
    return next(b for b in os_names if b in trybot_name)
  except StopIteration:
    raise TrybotError('Trybot "%s" unsupported for tryjobs.' % trybot_name)

def _GetBuilderNames(trybot_name, builders):
  """ Return platform and its available bot name as dictionary."""
  os_names = ['linux', 'android', 'mac', 'win']
  if 'all' not in trybot_name:
    bot = ['%s_perf_bisect' % trybot_name.replace('-', '_')]
    bot_platform = _GetBotPlatformFromTrybotName(trybot_name)
    if 'x64' in trybot_name:
      bot_platform += '-x64'
    return {bot_platform: bot}

  platform_and_bots = {}
  for os_name in os_names:
    platform_and_bots[os_name] = [bot for bot in builders if os_name in bot]

  # Special case for Windows x64, consider it as separate platform
  # config config should contain target_arch=x64 and --browser=release_x64.
  win_x64_bots = [
      win_bot for win_bot in platform_and_bots['win']
      if 'x64' in win_bot]
  # Separate out non x64 bits win bots
  platform_and_bots['win'] = list(
      set(platform_and_bots['win']) - set(win_x64_bots))
  platform_and_bots['win-x64'] = win_x64_bots

  if 'all-win' in trybot_name:
    return {'win': platform_and_bots['win'],
            'win-x64': platform_and_bots['win-x64']}
  if 'all-mac' in trybot_name:
    return {'mac': platform_and_bots['mac']}
  if 'all-android' in trybot_name:
    return {'android': platform_and_bots['android']}
  if 'all-linux' in trybot_name:
    return {'linux': platform_and_bots['linux']}

  return platform_and_bots

def _RunProcess(cmd):
  logging.debug('Running process: "%s"', ' '.join(cmd))
  proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = proc.communicate()
  returncode = proc.poll()
  return (returncode, out, err)

_GIT_CMD = 'git'
if platform.system() == 'Windows':
  # On windows, the git command is installed as 'git.bat'
  _GIT_CMD = 'git.bat'

class Trybot(command_line.ArgParseCommand):
  """ Run telemetry perf benchmark on trybot """

  usage = 'botname benchmark_name [<benchmark run options>]'
  _builders = None

  def __init__(self):
    self._builder_names = None

  @classmethod
  def _GetBuilderList(cls):
    if not cls._builders:
      try:
        f = urllib2.urlopen(
            ('https://build.chromium.org/p/tryserver.chromium.perf/json/'
             'builders'),
            timeout=5)
      # In case of any kind of exception, allow tryjobs to use default trybots.
      # Possible exception are ssl.SSLError, urllib2.URLError,
      # socket.timeout, socket.error.
      except Exception:
        # Incase of any exception return default trybots.
        print ('WARNING: Unable to reach builbot to retrieve trybot '
            'information, tryjob will use default trybots.')
        cls._builders = DEFAULT_TRYBOTS
      else:
        builders = json.loads(f.read()).keys()
        # Exclude unsupported bots like win xp and some dummy bots.
        cls._builders = [bot for bot in builders if bot not in EXCLUDED_BOTS]

    return cls._builders

  def _InitializeBuilderNames(self, trybot):
    self._builder_names = _GetBuilderNames(trybot, self._GetBuilderList())

  @classmethod
  def CreateParser(cls):
    parser = argparse.ArgumentParser(
        ('Run telemetry benchmarks on trybot. You can add all the benchmark '
         'options available except the --browser option'),
        formatter_class=argparse.RawTextHelpFormatter)
    return parser

  @classmethod
  def ProcessCommandLineArgs(cls, parser, options, extra_args, environment):
    del environment  # unused
    for arg in extra_args:
      if arg == '--browser' or arg.startswith('--browser='):
        parser.error('--browser=... is not allowed when running trybot.')
    all_benchmarks = discover.DiscoverClasses(
      start_dir=path_util.GetPerfBenchmarksDir(),
      top_level_dir=path_util.GetPerfDir(),
      base_class=benchmark.Benchmark).values()
    all_benchmark_names = [b.Name() for b in all_benchmarks]
    all_benchmarks_by_names = {b.Name(): b for b in all_benchmarks}
    benchmark_class = all_benchmarks_by_names.get(options.benchmark_name, None)
    if not benchmark_class:
      possible_benchmark_names = matching.GetMostLikelyMatchedObject(
          all_benchmark_names, options.benchmark_name)
      parser.error(
         'No benchmark named "%s". Do you mean any of those benchmarks '
         'below?\n%s' %
         (options.benchmark_name, '\n'.join(possible_benchmark_names)))
    is_benchmark_disabled, reason = cls.IsBenchmarkDisabledOnTrybotPlatform(
        benchmark_class, options.trybot)
    also_run_disabled_option = '--also-run-disabled-tests'
    if is_benchmark_disabled and also_run_disabled_option not in extra_args:
      parser.error('%s To run the benchmark on trybot anyway, add '
                   '%s option.' % (reason, also_run_disabled_option))

  @classmethod
  def IsBenchmarkDisabledOnTrybotPlatform(cls, benchmark_class, trybot_name):
    """ Return whether benchmark will be disabled on trybot platform.

    Note that we cannot tell with certainty whether the benchmark will be
    disabled on the trybot platform since the disable logic in ShouldDisable()
    can be very dynamic and can only be verified on the trybot server platform.

    We are biased on the side of enabling the benchmark, and attempt to
    early discover whether the benchmark will be disabled as our best.

    It should never be the case that the benchmark will be enabled on the test
    platform but this method returns True.

    Returns:
      A tuple (is_benchmark_disabled, reason) whereas |is_benchmark_disabled| is
      a boolean that tells whether we are sure that the benchmark will be
      disabled, and |reason| is a string that shows the reason why we think the
      benchmark is disabled for sure.
    """
    benchmark_name = benchmark_class.Name()
    benchmark_disabled_strings = set()
    if hasattr(benchmark_class, '_disabled_strings'):
      # pylint: disable=protected-access
      benchmark_disabled_strings = benchmark_class._disabled_strings
      # pylint: enable=protected-access
    if 'all' in benchmark_disabled_strings:
      return True, 'Benchmark %s is disabled on all platform.' % benchmark_name
    if trybot_name == 'all':
      return False, ''
    trybot_platform = _GetBotPlatformFromTrybotName(trybot_name)
    if trybot_platform in benchmark_disabled_strings:
      return True, (
          "Benchmark %s is disabled on %s, and trybot's platform is %s." %
          (benchmark_name, ', '.join(benchmark_disabled_strings),
           trybot_platform))
    benchmark_enabled_strings = None
    if hasattr(benchmark_class, '_enabled_strings'):
      # pylint: disable=protected-access
      benchmark_enabled_strings = benchmark_class._enabled_strings
      # pylint: enable=protected-access
    if (benchmark_enabled_strings and
        trybot_platform not in benchmark_enabled_strings and
        'all' not in benchmark_enabled_strings):
      return True, (
          "Benchmark %s is only enabled on %s, and trybot's platform is %s." %
          (benchmark_name, ', '.join(benchmark_enabled_strings),
           trybot_platform))
    if benchmark_class.ShouldDisable != benchmark.Benchmark.ShouldDisable:
      logging.warning(
          'Benchmark %s has ShouldDisable() method defined. If your trybot run '
          'does not produce any results, it is possible that the benchmark '
          'is disabled on the target trybot platform.', benchmark_name)
    return False, ''

  @classmethod
  def AddCommandLineArgs(cls, parser, environment):
    del environment  # unused
    available_bots = _GetTrybotList(cls._GetBuilderList())
    parser.add_argument(
        'trybot', choices=available_bots,
        help=('specify which bots to run telemetry benchmarks on. '
              ' Allowed values are:\n' + '\n'.join(available_bots)),
        metavar='<trybot name>')
    parser.add_argument(
        'benchmark_name', type=str,
        help=('specify which benchmark to run. To see all available benchmarks,'
              ' run `run_benchmark list`'),
        metavar='<benchmark name>')

  def Run(self, options, extra_args=None):
    """Sends a tryjob to a perf trybot.

    This creates a branch, telemetry-tryjob, switches to that branch, edits
    the bisect config, commits it, uploads the CL to rietveld, and runs a
    tryjob on the given bot.
    """
    if extra_args is None:
      extra_args = []
    self._InitializeBuilderNames(options.trybot)

    arguments = [options.benchmark_name] + extra_args

    # First check if there are chromium changes to upload.
    status = self._AttemptTryjob(CHROMIUM_CONFIG_FILENAME, arguments)
    if status not in [SUCCESS, ERROR]:
      # If we got here, there are no chromium changes to upload. Try blink.
      os.chdir('third_party/WebKit/')
      status = self._AttemptTryjob(BLINK_CONFIG_FILENAME, arguments)
      os.chdir('../..')
      if status not in [SUCCESS, ERROR]:
        logging.error('No local changes found in chromium or blink trees. '
                      'browser=%s argument sends local changes to the '
                      'perf trybot(s): %s.', options.trybot,
                      self._builder_names.values())
        return 1
    return 0

  def _UpdateConfigAndRunTryjob(self, bot_platform, cfg_file_path, arguments):
    """Updates perf config file, uploads changes and excutes perf try job.

    Args:
      bot_platform: Name of the platform to be generated.
      cfg_file_path: Perf config file path.

    Returns:
      (result, msg) where result is one of:
          SUCCESS if a tryjob was sent
          NO_CHANGES if there was nothing to try,
          ERROR if a tryjob was attempted but an error encountered
          and msg is an error message if an error was encountered, or rietveld
          url if success, otherwise throws TrybotError exception.
    """
    config = self._GetPerfConfig(bot_platform, arguments)
    config_to_write = 'config = %s' % json.dumps(
        config, sort_keys=True, indent=2, separators=(',', ': '))

    try:
      with open(cfg_file_path, 'r') as config_file:
        if config_to_write == config_file.read():
          return NO_CHANGES, ''
    except IOError:
      msg = 'Cannot find %s. Please run from src dir.' % cfg_file_path
      return (ERROR, msg)

    with open(cfg_file_path, 'w') as config_file:
      config_file.write(config_to_write)
    # Commit the config changes locally.
    returncode, out, err = _RunProcess(
        [_GIT_CMD, 'commit', '-a', '-m', 'bisect config: %s' % bot_platform])
    if returncode:
      raise TrybotError('Could not commit bisect config change for %s,'
                        ' error %s' % (bot_platform, err))
    # Upload the CL to rietveld and run a try job.
    returncode, out, err = _RunProcess([
        _GIT_CMD, 'cl', 'upload', '-f', '--bypass-hooks', '-m',
        'CL for perf tryjob on %s' % bot_platform
    ])
    if returncode:
      raise TrybotError('Could not upload to rietveld for %s, error %s' %
                        (bot_platform, err))

    match = re.search(r'https://codereview.chromium.org/[\d]+', out)
    if not match:
      raise TrybotError('Could not upload CL to rietveld for %s! Output %s' %
                        (bot_platform, out))
    rietveld_url = match.group(0)
    # Generate git try command for available bots.
    git_try_command = [_GIT_CMD, 'cl', 'try', '-m', 'tryserver.chromium.perf']
    for bot in self._builder_names[bot_platform]:
      git_try_command.extend(['-b', bot])
    returncode, out, err = _RunProcess(git_try_command)
    if returncode:
      raise TrybotError('Could not try CL for %s, error %s' %
                        (bot_platform, err))

    return (SUCCESS, rietveld_url)

  def _GetPerfConfig(self, bot_platform, arguments):
    """Generates the perf config for try job.

    Args:
      bot_platform: Name of the platform to be generated.

    Returns:
      A dictionary with perf config parameters.
    """
    # To make sure that we don't mutate the original args
    arguments = arguments[:]

    # Always set verbose logging for later debugging
    if '-v' not in arguments and '--verbose' not in arguments:
        arguments.append('--verbose')

    # Generate the command line for the perf trybots
    target_arch = 'ia32'
    if any(arg == '--chrome-root' or arg.startswith('--chrome-root=') for arg
           in arguments):
      raise ValueError(
          'Trybot does not suport --chrome-root option set directly '
          'through command line since it may contain references to your local '
          'directory')
    if bot_platform in ['win', 'win-x64']:
      arguments.insert(0, 'python tools\\perf\\run_benchmark')
    else:
      arguments.insert(0, './tools/perf/run_benchmark')

    if bot_platform == 'android':
      arguments.insert(1, '--browser=android-chromium')
    elif any('x64' in bot for bot in self._builder_names[bot_platform]):
      arguments.insert(1, '--browser=release_x64')
      target_arch = 'x64'
    else:
      arguments.insert(1, '--browser=release')

    command = ' '.join(arguments)

    return {
        'command': command,
        'repeat_count': '1',
        'max_time_minutes': '120',
        'truncate_percent': '0',
        'target_arch': target_arch,
    }

  def _AttemptTryjob(self, cfg_file_path, arguments):
    """Attempts to run a tryjob from the current directory.

    This is run once for chromium, and if it returns NO_CHANGES, once for blink.

    Args:
      cfg_file_path: Path to the config file for the try job.

    Returns:
      Returns SUCCESS if a tryjob was sent, NO_CHANGES if there was nothing to
      try, ERROR if a tryjob was attempted but an error encountered.
    """
    source_repo = 'chromium'
    if cfg_file_path == BLINK_CONFIG_FILENAME:
      source_repo = 'blink'

    # TODO(prasadv): This method is quite long, we should consider refactor
    # this by extracting to helper methods.
    returncode, original_branchname, err = _RunProcess(
        [_GIT_CMD, 'rev-parse', '--abbrev-ref', 'HEAD'])
    if returncode:
      msg = 'Must be in a git repository to send changes to trybots.'
      if err:
        msg += '\nGit error: %s' % err
      logging.error(msg)
      return ERROR

    original_branchname = original_branchname.strip()

    # Check if the tree is dirty: make sure the index is up to date and then
    # run diff-index
    _RunProcess([_GIT_CMD, 'update-index', '--refresh', '-q'])
    returncode, out, err = _RunProcess([_GIT_CMD, 'diff-index', 'HEAD'])
    if out:
      logging.error(
          'Cannot send a try job with a dirty tree. Commit locally first.')
      return ERROR

    # Make sure the tree does have local commits.
    returncode, out, err = _RunProcess(
        [_GIT_CMD, 'log', 'origin/master..HEAD'])
    if not out:
      return NO_CHANGES

    # Create/check out the telemetry-tryjob branch, and edit the configs
    # for the tryjob there.
    returncode, out, err = _RunProcess(
        [_GIT_CMD, 'checkout', '-b', 'telemetry-tryjob'])
    if returncode:
      logging.error('Error creating branch telemetry-tryjob. '
                    'Please delete it if it exists.\n%s', err)
      return ERROR
    try:
      returncode, out, err = _RunProcess(
          [_GIT_CMD, 'branch', '--set-upstream-to', 'origin/master'])
      if returncode:
        logging.error('Error in git branch --set-upstream-to: %s', err)
        return ERROR
      for bot_platform in self._builder_names:
        if not self._builder_names[bot_platform]:
          logging.warning('No builder is found for %s', bot_platform)
          continue
        try:
          results, output = self._UpdateConfigAndRunTryjob(
              bot_platform, cfg_file_path, arguments)
          if results == ERROR:
            logging.error(output)
            return ERROR
          elif results == NO_CHANGES:
            print ('Skip the try job run on %s because it has been tried in '
                   'previous try job run. ' % bot_platform)
          else:
            print ('Uploaded %s try job to rietveld for %s platform. '
                   'View progress at %s' % (source_repo, bot_platform, output))
        except TrybotError, err:
          print err
          logging.error(err)
    finally:
      # Checkout original branch and delete telemetry-tryjob branch.
      # TODO(prasadv): This finally block could be extracted out to be a
      # separate function called _CleanupBranch.
      returncode, out, err = _RunProcess(
          [_GIT_CMD, 'checkout', original_branchname])
      if returncode:
        logging.error('Could not check out %s. Please check it out and '
                      'manually delete the telemetry-tryjob branch. '
                      ': %s', original_branchname, err)
        return ERROR  # pylint: disable=lost-exception
      logging.info('Checked out original branch: %s', original_branchname)
      returncode, out, err = _RunProcess(
          [_GIT_CMD, 'branch', '-D', 'telemetry-tryjob'])
      if returncode:
        logging.error('Could not delete telemetry-tryjob branch. '
                      'Please delete it manually: %s', err)
        return ERROR  # pylint: disable=lost-exception
      logging.info('Deleted temp branch: telemetry-tryjob')
    return SUCCESS


text:
namespace net {

std::ostream& operator<<(std::ostream& out,
                         GoAwayPayloadDecoder::PayloadState v) {
  switch (v) {
    case GoAwayPayloadDecoder::PayloadState::kStartDecodingFixedFields:
      return out << "kStartDecodingFixedFields";
    case GoAwayPayloadDecoder::PayloadState::kHandleFixedFieldsStatus:
      return out << "kHandleFixedFieldsStatus";
    case GoAwayPayloadDecoder::PayloadState::kReadOpaqueData:
      return out << "kReadOpaqueData";
    case GoAwayPayloadDecoder::PayloadState::kResumeDecodingFixedFields:
      return out << "kResumeDecodingFixedFields";
  }

  NOTREACHED();
  return out;
}

DecodeStatus GoAwayPayloadDecoder::StartDecodingPayload(
    FrameDecoderState* state,
    DecodeBuffer* db) {
  DVLOG(2) << "GoAwayPayloadDecoder::StartDecodingPayload: "
           << state->frame_header();
  DCHECK_EQ(Http2FrameType::GOAWAY, state->frame_header().type);
  DCHECK_LE(db->Remaining(), state->frame_header().payload_length);
  DCHECK_EQ(0, state->frame_header().flags);

  state->InitializeRemainders();
  payload_state_ = PayloadState::kStartDecodingFixedFields;
  return ResumeDecodingPayload(state, db);
}

DecodeStatus GoAwayPayloadDecoder::ResumeDecodingPayload(
    FrameDecoderState* state,
    DecodeBuffer* db) {
  DVLOG(2) << "GoAwayPayloadDecoder::ResumeDecodingPayload: remaining_payload="
           << state->remaining_payload()
           << ", db->Remaining=" << db->Remaining();

  const Http2FrameHeader& frame_header = state->frame_header();
  DCHECK_EQ(Http2FrameType::GOAWAY, frame_header.type);
  DCHECK_LE(db->Remaining(), frame_header.payload_length);
  DCHECK_NE(PayloadState::kHandleFixedFieldsStatus, payload_state_);

  // |status| has to be initialized to some value to avoid compiler error in
  // case PayloadState::kHandleFixedFieldsStatus below, but value does not
  // matter, see DCHECK_NE above.
  DecodeStatus status = DecodeStatus::kDecodeError;
  size_t avail;
  while (true) {
    DVLOG(2) << "GoAwayPayloadDecoder::ResumeDecodingPayload payload_state_="
             << payload_state_;
    switch (payload_state_) {
      case PayloadState::kStartDecodingFixedFields:
        status = state->StartDecodingStructureInPayload(&goaway_fields_, db);
      // FALLTHROUGH_INTENDED

      case PayloadState::kHandleFixedFieldsStatus:
        if (status == DecodeStatus::kDecodeDone) {
          state->listener()->OnGoAwayStart(frame_header, goaway_fields_);
        } else {
          // Not done decoding the structure. Either we've got more payload
          // to decode, or we've run out because the payload is too short,
          // in which case OnFrameSizeError will have already been called.
          DCHECK((status == DecodeStatus::kDecodeInProgress &&
                  state->remaining_payload() > 0) ||
                 (status == DecodeStatus::kDecodeError &&
                  state->remaining_payload() == 0))
              << "\n status=" << status
              << "; remaining_payload=" << state->remaining_payload();
          payload_state_ = PayloadState::kResumeDecodingFixedFields;
          return status;
        }
      // FALLTHROUGH_INTENDED

      case PayloadState::kReadOpaqueData:
        // The opaque data is all the remains to be decoded, so anything left
        // in the decode buffer is opaque data.
        avail = db->Remaining();
        if (avail > 0) {
          state->listener()->OnGoAwayOpaqueData(db->cursor(), avail);
          db->AdvanceCursor(avail);
          state->ConsumePayload(avail);
        }
        if (state->remaining_payload() > 0) {
          payload_state_ = PayloadState::kReadOpaqueData;
          return DecodeStatus::kDecodeInProgress;
        }
        state->listener()->OnGoAwayEnd();
        return DecodeStatus::kDecodeDone;

      case PayloadState::kResumeDecodingFixedFields:
        status = state->ResumeDecodingStructureInPayload(&goaway_fields_, db);
        payload_state_ = PayloadState::kHandleFixedFieldsStatus;
        continue;
    }
    HTTP2_BUG << "PayloadState: " << payload_state_;
  }
}

}  // namespace net