text:
<?php

namespace BingAds\Reporting;

/**
 * Defines the attributes and performance statistics columns that you can include in the ProductTargetPerformanceReportRequest.
 *
 * @link http://msdn.microsoft.com/en-us/library/dn195844(v=msads.90).aspx ProductTargetPerformanceReportColumn Value Set
 *
 * @used-by ProductTargetPerformanceReportRequest
 */
final class ProductTargetPerformanceReportColumn
{
    /** The account name. */
    const AccountName = 'AccountName';
    /** The Bing Ads assigned number of an account. */
    const AccountNumber = 'AccountNumber';
    /** The Bing Ads assigned identifier of an account. */
    const AccountId = 'AccountId';
    /** The time period of each report row. */
    const TimePeriod = 'TimePeriod';
    /** The campaign name. */
    const CampaignName = 'CampaignName';
    /** The Bing Ads assigned identifier of a campaign. */
    const CampaignId = 'CampaignId';
    /** The ad group name. */
    const AdGroupName = 'AdGroupName';
    /** The Bing Ads assigned identifier of an ad group. */
    const AdGroupId = 'AdGroupId';
    /** The name of the product target. */
    const ProductTarget = 'ProductTarget';
    /** The Bing Ads assigned identifier of an ad group criterion. */
    const AdGroupCriterionId = 'AdGroupCriterionId';
    /** The Bing Ads assigned identifier of an ad. */
    const AdId = 'AdId';
    /** The maximum cost per click. */
    const CurrentMaxCpc = 'CurrentMaxCpc';
    /** The account currency type. */
    const CurrencyCode = 'CurrencyCode';
    /** The number of times an ad has been displayed on search results pages. */
    const Impressions = 'Impressions';
    /** The number of times that the ads in the account were clicked. */
    const Clicks = 'Clicks';
    /** The click-through rate (CTR) is the number of times an ad was clicked, divided by the number of times the ad was shown (impressions). */
    const Ctr = 'Ctr';
    /** The average cost per click (CPC). */
    const AverageCpc = 'AverageCpc';
    /** The cost per click (CPC) summed for each click. */
    const Spend = 'Spend';
    /** The number of conversions. */
    const Conversions = 'Conversions';
    /** The conversion rate as a percentage. */
    const ConversionRate = 'ConversionRate';
    /** The cost per conversion. */
    const CostPerConversion = 'CostPerConversion';
    /** The device name attribute of a device OS target bid. */
    const DeviceType = 'DeviceType';
    /** The ad group language. */
    const Language = 'Language';
    /** The campaign status. */
    const CampaignStatus = 'CampaignStatus';
    /** The account lifecycle status. */
    const AccountStatus = 'AccountStatus';
    /** The ad group status. */
    const AdGroupStatus = 'AdGroupStatus';
    /** The keyword status. */
    const KeywordStatus = 'KeywordStatus';
    /** The destination URL attribute of the ad, keyword, or ad group criterion. */
    const DestinationUrl = 'DestinationUrl';
    /** The keyword bid match type. */
    const BidMatchType = 'BidMatchType';
    /** The match type used to deliver an ad. */
    const DeliveredMatchType = 'DeliveredMatchType';
    /** The current network setting of an ad group. */
    const Network = 'Network';
    /** The report will include a column that indicates whether the ad impression appeared in a top position or elsewhere. */
    const TopVsOther = 'TopVsOther';
    /** The operating system of the device reported in the DeviceType column. */
    const DeviceOS = 'DeviceOS';
    /** The number of conversions from other ads within the same account that were preceded by one or more clicks from this ad. */
    const Assists = 'Assists';
    /** Cost information that is optionally provided by advertisers, including non-advertising costs, taxes, and shipping. */
    const ExtendedCost = 'ExtendedCost';
    /** The revenue optionally reported by the advertiser as a result of conversions. */
    const Revenue = 'Revenue';
    /** The return on ad spend (ROAS). */
    const ReturnOnAdSpend = 'ReturnOnAdSpend';
    /** The cost per assist. */
    const CostPerAssist = 'CostPerAssist';
    /** The revenue per conversion. */
    const RevenuePerConversion = 'RevenuePerConversion';
    /** The revenue per assist. */
    const RevenuePerAssist = 'RevenuePerAssist';
}


text:
<?php
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @category    Phrozn
 * @package     Phrozn\Provider
 * @author      Victor Farazdagi
 * @license     http://www.apache.org/licenses/LICENSE-2.0
 */

namespace Phrozn\Provider;
use Phrozn\Has;

/**
 * Provider producing factory
 *
 * @category    Phrozn
 * @package     Phrozn\Provider
 * @author      Victor Farazdagi
 */
class Factory
{
    /**
     * Create provider instance
     *
     * @param string $type Provider typ to initialize
     * @param mixed $data Provider data
     *
     * return \Phrozn\Provider
     */
    public function create($type, $data)
    {
        // try to see if we have user defined plugin
        $class = 'PhroznPlugin\\Provider\\' . ucfirst($type);
        if (!class_exists($class)) {
            $class = 'Phrozn\\Provider\\' . ucfirst($type);
            if (!class_exists($class)) {
                throw new \RuntimeException("Provider of type '{$type}' not found..");
            }
        }
        $object = new $class;
        $object->setConfig($data);
        return $object;
    }

}

redpajama_set_name: RedPajamaGithub


text:
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. Because it only uses comparisons to operate on elements, it is a comparison sort.

## The Code:

Here is an implementation of counting sort

```go
func Sort(inputArray []int) []int {
	swapped := true
	for swapped {
		swapped = false
		for i := 1; i <= len(inputArray)-1; i++ {
			if inputArray[i-1] > inputArray[i] {
				inputArray[i], inputArray[i-1] = inputArray[i-1], inputArray[i]
				swapped = true
			}
		}
	}

	return inputArray
}
```

## Performance

* Worst case performance: **O(n2)**
* Best case performance: **O(n)**
* Average case performance: **O(n2)**
* Worst case space complexity: **O(n) total, O(1) auxiliary**

## See also

[Bubble Sort on Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)

*Written by [brotherpowers](https://www.brotherpowers.com/)*


text:
from eca_catalogue.categorization.abstract_models import *

class ProductCategory(AbstractProductCategory):
    pass

class NestedProductCategory(AbstractNestedProductCategory):
    pass


text:
<?php
/**
 * Created by PhpStorm.
 * User: vladislav
 * Date: 21.02.16
 * Time: 14:34
 */

namespace AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class AppBundle extends Bundle
{
}


text:
import sys
import contextlib
import io
import logging
try:
    import queue
except ImportError:
    import Queue as queue
import re
import threading
import time
import uuid

import pytest
import zmq

import networkzero as nw0
_logger = nw0.core.get_logger("networkzero.tests")
nw0.core._enable_debug_logging()


text:
require 'facets/array/permutation'
require 'test/unit'
require 'set'

class TestEnumerablePermutation < Test::Unit::TestCase

  def test_permutation
    o = Set.new
    %w[a b c].permutation{ |x| o << x.join('') }
    r = Set.new(['abc','acb','bac','bca','cab','cba'])
    assert_equal( r, o )
  end

end


text:
<template name="about">

        Introduction

This application provides a code base to act as a custom user interface for a SIEM.
               It is meant as a configuration utility for the components that don't already
               have a front-end - i.e. for custom code or advanced features that are not configurable via an existing UI.

        Architecture

The high-level architecture is shown below.

The key components are the following:

Meteor is the framework used as a base for this app. It comes prepackaged with a whole bunch of javascript packages, MongoDB and Node.js

Mongo is used as a data store with components on the server (MongoDB) and on the client (Mini Mongo).

Node.js is used as an web app server that allows server-side javascript code to be executed (from server/ or common/).

Meteor also allows the use of Node packages managed via NPM.

The deploy.js server-side javascript handles the configuration updates to the SIEM.

The getList.js server-side javascript handles the download of blacklists from online sources and the data parsing to extract the exact data needed by the SIEM.

The validate.js javascript handles the validation of the data before storing it into MongoDB. It is also used before the deployment.

        User Roles

Your user name is {{username}} and you are part of the {{role}} role.

Roles are defined as follows.

Role	Purpose

DevOps	Superuser for this app. Full admin and data access.

Security Analyst	Manage whitelists & blacklists used for security enrichment and reduction of false positives.

Solution Architect	Update the list of hosts used by a managed service. This is meant to adjust the input filters of the SIEM.

</template>


text:
'''OpenGL extension NV.pixel_data_range

Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_NV_pixel_data_range'
_DEPRECATED = False
GL_WRITE_PIXEL_DATA_RANGE_NV = constant.Constant( 'GL_WRITE_PIXEL_DATA_RANGE_NV', 0x8878 )
GL_READ_PIXEL_DATA_RANGE_NV = constant.Constant( 'GL_READ_PIXEL_DATA_RANGE_NV', 0x8879 )
GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV = constant.Constant( 'GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV', 0x887A )
glget.addGLGetConstant( GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV, (1,) )
GL_READ_PIXEL_DATA_RANGE_LENGTH_NV = constant.Constant( 'GL_READ_PIXEL_DATA_RANGE_LENGTH_NV', 0x887B )
glget.addGLGetConstant( GL_READ_PIXEL_DATA_RANGE_LENGTH_NV, (1,) )
GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV = constant.Constant( 'GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV', 0x887C )
GL_READ_PIXEL_DATA_RANGE_POINTER_NV = constant.Constant( 'GL_READ_PIXEL_DATA_RANGE_POINTER_NV', 0x887D )
glPixelDataRangeNV = platform.createExtensionFunction(
'glPixelDataRangeNV',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLenum,constants.GLsizei,ctypes.c_void_p,),
doc='glPixelDataRangeNV(GLenum(target), GLsizei(length), c_void_p(pointer)) -> None',
argNames=('target','length','pointer',),
deprecated=_DEPRECATED,
)

glFlushPixelDataRangeNV = platform.createExtensionFunction(
'glFlushPixelDataRangeNV',dll=platform.GL,
extension=EXTENSION_NAME,
resultType=None,
argTypes=(constants.GLenum,),
doc='glFlushPixelDataRangeNV(GLenum(target)) -> None',
argNames=('target',),
deprecated=_DEPRECATED,
)

def glInitPixelDataRangeNV():
    '''Return boolean indicating whether this extension is available'''
    return extensions.hasGLExtension( EXTENSION_NAME )


text:
package org.vaadin.addons.tuningdatefield.widgetset.client.ui.events;

import com.google.gwt.event.shared.EventHandler;

public interface CalendarOpenHandler extends EventHandler{

    public void onCalendarOpen(CalendarOpenEvent event);
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150615_163416_create_user_table extends Migration
{
    public function up()
    {
    	$this->createTable('user',[
    		'id'=>Schema::TYPE_PK,
    		'username'=>Schema::TYPE_STRING.' NOT NULL',
    		'email'=>Schema::TYPE_STRING.' NOT NULL',
    		'password_hash'=>Schema::TYPE_STRING.' NOT NULL',
    		'status'=>Schema::TYPE_SMALLINT.' NOT NULL',
    		'auth_key'=>Schema::TYPE_STRING.'(32) NOT NULL',
    		'created_at'=>Schema::TYPE_INTEGER.' NOT NULL',
    		'updated_at'=>Schema::TYPE_INTEGER.' NOT NULL'

    	]);

    }

    public function down()
    {
        $this->dropTable('user');
    }
}


text: Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.


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

namespace YetiCommon
{
    // Tracks local port numbers used by developer tools.
    public class WorkstationPorts
    {
        // ------------------ WORKSTATION --------------------------------------------------------
        // These are local port only used on the workstation.

        public static readonly List<int> LLDB_SERVERS =
            Enumerable.Range(LLDB_SERVER_FIRST, LLDB_SERVER_LAST - LLDB_SERVER_FIRST).ToList();

        // Reserve ports 44420 - 44429 for use by LLDB servers.
        public const int LLDB_SERVER_FIRST = 44420;
        public const int LLDB_SERVER_LAST = 44429;

        // Reserve port 44430 for use by MountRemote.
        public const int MOUNT_REMOTE = 44430;

        // Reserve port 44431 for use by the ggp CLI for the webserver used during login.
        public const int GGP_CLI = 44431;

        // Reserve ports 44432-44442 for use by the local assets stream manager.
        public const int LOCAL_ASSETS_STREAM_MANAGER_FIRST = 44432;
        public const int LOCAL_ASSETS_STREAM_MANAGER_LAST = 44442;

        // Reserve ports 44443 and 44446 for use by the launch controller.
        public const int LAUNCH_CONTROLLER_WEB = 44443;
        public const int LAUNCH_CONTROLLER = 44446;

        // Reserve port 44444 for use by the Process Manager local gRPC server.
        public const int PROCESS_MANAGER = 44444;

        // Reserve port 44445 for use by the System Tray App local gRPC server.
        public const int SYSTEM_TRAY_APP = 44445;

        // Reserve ports 44448 and 44449 for use by the SDK Proxy.
        public const int SDK_PROXY = 44448;
        public const int SDK_PROXY_WEB = 44449;

        // Reserve ports 44450-44459 for ggp_sync.
        public const int GGP_RSYNC_FIRST = 44450;
        public const int GGP_RSYNC_LAST = 44459;

        // Reserve port 44460 for use by Log Manager.
        public const int LOG_MANAGER = 44460;

        // Reserve ports 19999, 27300, 38920 for rgp and renderdoc.
        public const int DIVE_LOCAL = 19999;
        public const int RGP_LOCAL = 27300;
        public const int RENDERDOC_LOCAL = 38920;

        // ------------------ GAMELET LOCAL -------------------------------------------------------
        // These are ports used locally on the gamelet.

        // Ports for the debugger and for compressed remote deploy.
        public static readonly List<int> REMOTE_DEPLOY_AND_LLDB_GDB_SERVERS =
            Enumerable.Range(REMOTE_DEPLOY_AND_LLDB_GDB_SERVER_FIRST,
                REMOTE_DEPLOY_AND_LLDB_GDB_SERVER_LAST -
                     REMOTE_DEPLOY_AND_LLDB_GDB_SERVER_FIRST).ToList();
        public const int REMOTE_LLDB_SERVER = 44500;
        public const int REMOTE_DEPLOY_AND_LLDB_GDB_SERVER_FIRST = 44510;
        public const int REMOTE_DEPLOY_AND_LLDB_GDB_SERVER_LAST = 44519;

        // ------------------ GAMELET EXTERNAL ----------------------------------------------------
        // These are ports used on the gamelet and are not blocked by the firewall.

        // Reserve ports 19999, 27300, 38920 for rgp and renderdoc.
        public const int DIVE_REMOTE = 19999;
        public const int RGP_REMOTE = 27300;
        public const int RENDERDOC_REMOTE = 38920;

        // TODO: Move this port to the workstation range
        // Reserve port 44730 for use by the Metrics Uploader service.
        public const int METRICS_UPLOADER = 44730;
    }
}


text:
#ifndef INVADERS_H
#define INVADERS_H

/*
* Game functions
*/

#include <GL/glut.h>
#include "./SOIL/SOIL.h"
#include <SDL/SDL.h>
#include <time.h>
#include "shapes.h"
#include "scene.h"
#include "transforms.h"
#include "settings.h"

/* ------------------------------- GLOBALS ---------------------------------- */
// Textures
extern GLuint laserblur;

// Game mechanics
extern int shots_player_count;
extern int shots_enemy_count;
extern int enemies_left;
extern int level;
extern int paused;
extern int gameover;
extern int victory;

// Movement
extern GLfloat playerPosition; // player position (x)
extern GLfloat playerSpeed; // player speed
extern GLfloat laserSpeed; // laser speed
extern GLfloat enemyPositionX; // enemy position (x)
extern GLfloat enemyPositionY; // enemy position (y)
extern GLfloat enemySpeed; // enemy horizontal speed

extern const int TOTAL_ENEMIES;
/* ------------------------------- GLOBALS ---------------------------------- */

/* ------------------------------- PLAYER ----------------------------------- */
typedef struct player {

        // Coordinates
        GLfloat x[4];
        GLfloat y[4];

        // Movement
        GLfloat boundaryL;
        GLfloat boundaryR;

        // Health
        int health;

        // Score
        int score;

        // Powerup
        int powerup;

        // Laser cooldown
        int cooldown;

} PLAYER;

extern PLAYER* player;

// Create/Destroy
PLAYER* createPlayer();
void drawPlayer(PLAYER* player);
void killPlayer(PLAYER* player);
void destroyPlayer(PLAYER* player);

// Movement
char checkBorders(GLfloat x);
/* ------------------------------- PLAYER ----------------------------------- */

/* ------------------------------- ENEMY ------------------------------------ */
typedef struct enemy {

        // Coordinates
        GLfloat x[4];
        GLfloat y[4];

        // Health
        int health;

        // Type
        int shape;

        // Movement
        GLfloat pos_x;
        GLfloat pos_y;

        // Animation
        int frame;
        GLfloat current_time;

        // Boundaries
        GLfloat boundaryL; // left
        GLfloat boundaryR; // right
        GLfloat boundaryD; // down
        GLfloat boundaryU; // up

        // Laser cooldown
        int cooldown;

} ENEMY;

extern ENEMY** enemies; // 25 enemies (5x5)

ENEMY **createEnemyMatrix();
void destroyEnemyMatrix(ENEMY** enemat);
ENEMY *createEnemy(int xindex, int yindex);
void moveEnemies(ENEMY** enemies);
void drawEnemy(ENEMY* enemy);
void destroyEnemy(ENEMY* enemy);

/* ------------------------------- ENEMY ------------------------------------ */

/* ------------------------------- LASER ------------------------------------ */
typedef struct laser {

        // Coordinates
        GLfloat x[4];
        GLfloat y[4];

        // Movement
        int position;

        // Boundary
        GLfloat boundaryU; // up
        GLfloat boundaryD; // down

        // Has it exploded yet?
        int explosion;

        // Color
        char color;

} LASER;

extern LASER** shots_player;
extern LASER** shots_enemy;

// Create/Destroy
LASER* createLaser(int x, int y, int color);
void destroyLaser(LASER *laser);

// Action
void enemyShoot(LASER*** shots_enemy, ENEMY** enemies);
void shootLaser_Player(LASER** shots, int *amount, int x);
void shootLaser_Enemy(LASER** shots, int *amount, int x, int y);
void drawLaser(LASER* laser);
/* ------------------------------- LASER ------------------------------------ */

/* ----------------------------- EXPLOSION ---------------------------------- */
void drawExplosion(float x, float y, int color);
/* ----------------------------- EXPLOSION ---------------------------------- */

/* ----------------------------- ANIMATIONS --------------------------------- */
int switchTexture();
/* ----------------------------- ANIMATIONS --------------------------------- */

/* -------------------------------- GAME ------------------------------------ */
void levelUp();
void saveGame();
void resetGame();
/* -------------------------------- GAME ------------------------------------ */

#endif


text:
PHP Parser
==========

[![Build Status](https://travis-ci.org/nikic/PHP-Parser.svg?branch=master)](https://travis-ci.org/nikic/PHP-Parser) [![Coverage Status](https://coveralls.io/repos/github/nikic/PHP-Parser/badge.svg?branch=master)](https://coveralls.io/github/nikic/PHP-Parser?branch=master)

This is a PHP 5.2 to PHP 7.2 parser written in PHP. Its purpose is to simplify static code analysis and
manipulation.

[**Documentation for version 4.x**][doc_master] (stable; for running on PHP >= 7.0; for parsing PHP 5.2 to PHP 7.2).

[Documentation for version 3.x][doc_3_x] (stable; for running on PHP >= 5.5; for parsing PHP 5.2 to PHP 7.2).

Features
--------

The main features provided by this library are:

 * Parsing PHP 5 and PHP 7 code into an abstract syntax tree (AST).
   * Invalid code can be parsed into a partial AST.
   * The AST contains accurate location information.
 * Dumping the AST in human-readable form.
 * Converting an AST back to PHP code.
   * Experimental: Formatting can be preserved for partially changed ASTs.
 * Infrastructure to traverse and modify ASTs.
 * Resolution of namespaced names.
 * Evaluation of constant expressions.
 * Builders to simplify AST construction for code generation.
 * Converting an AST into JSON and back.

Quick Start
-----------

Install the library using [composer](https://getcomposer.org):

    php composer.phar require nikic/php-parser

Parse some PHP code into an AST and dump the result in human-readable form:

```php
<?php
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;

$code = <<<'CODE'
<?php

function test($foo)
{
    var_dump($foo);
}
CODE;

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
try {
    $ast = $parser->parse($code);
} catch (Error $error) {
    echo "Parse error: {$error->getMessage()}\n";
    return;
}

$dumper = new NodeDumper;
echo $dumper->dump($ast) . "\n";
```

This dumps an AST looking something like this:

```
array(
    0: Stmt_Function(
        byRef: false
        name: Identifier(
            name: test
        )
        params: array(
            0: Param(
                type: null
                byRef: false
                variadic: false
                var: Expr_Variable(
                    name: foo
                )
                default: null
            )
        )
        returnType: null
        stmts: array(
            0: Stmt_Expression(
                expr: Expr_FuncCall(
                    name: Name(
                        parts: array(
                            0: var_dump
                        )
                    )
                    args: array(
                        0: Arg(
                            value: Expr_Variable(
                                name: foo
                            )
                            byRef: false
                            unpack: false
                        )
                    )
                )
            )
        )
    )
)
```

Let's traverse the AST and perform some kind of modification. For example, drop all function bodies:

```php
use PhpParser\Node;
use PhpParser\Node\Stmt\Function_;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;

$traverser = new NodeTraverser();
$traverser->addVisitor(new class extends NodeVisitorAbstract {
    public function enterNode(Node $node) {
        if ($node instanceof Function_) {
            // Clean out the function body
            $node->stmts = [];
        }
    }
});

$ast = $traverser->traverse($ast);
echo $dumper->dump($ast) . "\n";
```

This gives us an AST where the `Function_::$stmts` are empty:

```
array(
    0: Stmt_Function(
        byRef: false
        name: Identifier(
            name: test
        )
        params: array(
            0: Param(
                type: null
                byRef: false
                variadic: false
                var: Expr_Variable(
                    name: foo
                )
                default: null
            )
        )
        returnType: null
        stmts: array(
        )
    )
)
```

Finally, we can convert the new AST back to PHP code:

```php
use PhpParser\PrettyPrinter;

$prettyPrinter = new PrettyPrinter\Standard;
echo $prettyPrinter->prettyPrintFile($ast);
```

This gives us our original code, minus the `var_dump()` call inside the function:

```php
<?php

function test($foo)
{
}
```

For a more comprehensive introduction, see the documentation.

Documentation
-------------

 1. [Introduction](doc/0_Introduction.markdown)
 2. [Usage of basic components](doc/2_Usage_of_basic_components.markdown)

Component documentation:

 * [Walking the AST](doc/component/Walking_the_AST.markdown)
   * Node visitors
   * Modifying the AST from a visitor
   * Short-circuiting traversals
   * Interleaved visitors
   * Simple node finding API
   * Parent and sibling references
 * [Name resolution](doc/component/Name_resolution.markdown)
   * Name resolver options
   * Name resolution context
 * [Pretty printing](doc/component/Pretty_printing.markdown)
   * Converting AST back to PHP code
   * Customizing formatting
   * Formatting-preserving code transformations
 * [AST builders](doc/component/AST_builders.markdown)
   * Fluent builders for AST nodes
 * [Lexer](doc/component/Lexer.markdown)
   * Lexer options
   * Token and file positions for nodes
   * Custom attributes
 * [Error handling](doc/component/Error_handling.markdown)
   * Column information for errors
   * Error recovery (parsing of syntactically incorrect code)
 * [Constant expression evaluation](doc/component/Constant_expression_evaluation.markdown)
   * Evaluating constant/property/etc initializers
   * Handling errors and unsupported expressions
 * [JSON representation](doc/component/JSON_representation.markdown)
   * JSON encoding and decoding of ASTs
 * [Performance](doc/component/Performance.markdown)
   * Disabling XDebug
   * Reusing objects
   * Garbage collection impact
 * [Frequently asked questions](doc/component/FAQ.markdown)
   * Parent and sibling references

 [doc_3_x]: https://github.com/nikic/PHP-Parser/tree/3.x/doc
 [doc_master]: https://github.com/nikic/PHP-Parser/tree/master/doc


text:
<!--
Tests that AR hit test results are available in rAF as soon as hit test source is available.
-->
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="../resources/webxr_e2e.css">
  </head>
  <body>
    <canvas id="webgl-canvas"></canvas>
    <script src="../../../../../../third_party/blink/web_tests/resources/testharness.js"></script>
    <script src="../resources/webxr_e2e.js"></script>
    <script>var shouldAutoCreateNonImmersiveSession = false;</script>
    <script src="../resources/webxr_boilerplate.js"></script>
    <script>
      setup({single_test: true});

      const TestState = Object.freeze({
        "Initial":  0,
        "RequestHitTestSource": 1,
        "HitTestSourceRequested": 2,
        "HitTestSourceAvailable": 3,  // hitTestSource variable is guaranteed to be non-null in this state
        "Done": 4,
      });

      let testState = null;

      let hitTestSource = null;

      function stepStartHitTesting() {
        const sessionInfo = sessionInfos[sessionTypes.AR];
        const referenceSpace = sessionInfo.currentRefSpace;

        testState = TestState.Initial;

        // There is no way we can guarantee that the recording starts with a plane detected - the
        // recording only contains sensors stream and camera images, not the ARCore session state
        // itself. ARCore should work in exactly the same way as if it is a brand new session, so
        // it will go through "camera not tracking" state at the beginning, on to detecting some
        // feature points, and then to actually finding the plane. Given that, we should allow
        // for retry logic in the test - the initial hit tests may return empty results until
        // ARCore detects a plane.
        // Since we try every frame and we currently run at 30FPS, it should mean we'll retry for
        // 5 seconds.
        let retries_left = 30 * 5;

        onARFrameCallback = (session, frame) => {
          switch(testState) {

            case TestState.Initial: {
              const pose = frame.getViewerPose(referenceSpace);
              if(!pose || pose.emulatedPosition) {
                // Wait for session to stabilize.
                return;
              }

              testState = TestState.RequestHitTestSource;
              return;
            }
            case TestState.RequestHitTestSource: {
              // Try to create a hit test source from within a frame.
              sessionInfo.currentSession.requestHitTestSource({
                space: referenceSpace,
                offsetRay: new XRRay()
              }).then((hts) => {
                hitTestSource = hts;
                testState = TestState.HitTestSourceAvailable;
              }).catch((err) => {
                assert_unreached("XRSession.requestHitTestSource() promise rejected.");
                testState = TestState.Done;
              });

              testState = TestState.HitTestSourceRequested;

              return;
            }
            case TestState.HitTestSourceAvailable: {
              const results = frame.getHitTestResults(hitTestSource);
              if(results.length) {
                testState = TestState.Done;
                done();
              } else {
                --retries_left;
                if(retries_left > 0) {
                  // Retry.
                  testState = TestState.RequestHitTestSource;
                } else {
                  assert_unreached("Hit test results were not available right after the hit test source was created.");
                  testState = TestState.Done;
                }
              }

              // Irrespective of the results, we won't need this hit test source anymore.
              hitTestSource.cancel();
              hitTestSource = null;

              return;
            }
            default:
              return;
          }
        };
      }
    </script>
  </body>
</html>


text:
<?php
/**
 * Created by b17
 * 4/14/12 12:11 PM
 */

namespace Arch\AdminBundle\Twig\Extension;

use Symfony\Component\HttpFoundation\Request;

class PageExtension extends \Twig_Extension
{
    protected $_request;

    public function __construct(Request $request)
    {
        $this->_request = $request;
    }

    public function getFunctions()
    {
        return array(
            'controllerName'    =>  new \Twig_Function_Method($this, 'getControllerName'),
            'actionName'        =>  new \Twig_Function_Method($this, 'getActionName'),
        );
    }

    public function getControllerName()
    {
        $controllerTemplate = $this->_request->get('_controller');
        $pattern = "#Controller\\\([a-zA-Z]*)Controller#";
        preg_match($pattern, $controllerTemplate, $matches);
        return $matches[1];
    }

    public function getActionName()
    {
        $pattern = "#::([a-zA-Z]*)Action#";
        preg_match($pattern, $this->_request->get('_controller'), $matches);
        return $matches[1];
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'admin_page';
    }
}


text:
package rocket.agile.com.mainlibrary.model.actionItems;

import com.google.gson.annotations.SerializedName;
import io.realm.RealmObject;
import rocket.agile.com.mainlibrary.Interface.ActionModel;

/**
 * Created by KeithK on 5/29/17.
 *
 * Purpose:  Class stores values for email service
 * Function: A) Responsible for providing values to be stored in Realm for email
 *
 *
 */

public class ActionEmail extends RealmObject implements ActionModel {

    @SerializedName("actionType")
    private int actionType;
    @SerializedName("faIcon")
    private String faIcon;
    @SerializedName("name")
    private String name;
    @SerializedName("email")
    private String email;
    @SerializedName("subject")
    private String subject;

    public int getActionType() { return this.actionType; }
    public void setActionType(int actionType) { this.actionType = actionType; }

    public String getFAIcon() { return this.faIcon; }
    public void setFaIcon(String faIcon) { this.faIcon = faIcon; }

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

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    public String getSubject() { return subject; }
    public void setSubject(String subject) { this.subject = subject; }

    // Required default constructor
    public ActionEmail() {}

    // Custom constructor
    public ActionEmail(int actionType, String faIcon, String name, String email, String subject) {
        this.setActionType(actionType);
        this.setFaIcon(faIcon);
        this.setName(name);
        this.setEmail(email);
        this.setSubject(subject);
    }
}


text:
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")

class Time
  class <<self
    attr_writer :testing_offset
    alias_method :real_now, :now
    def now
      time = real_now
      if @testing_offset
        time = time - @testing_offset
      end
      time
    end

  end
end

class Test::Unit::TestCase

  # to get local/current time with specified time zone, e.g. with_time_zone("UTC")) {Time.now} returns the current time of time zone 'UTC'
  def with_time_zone(tz_name)
    prev_tz = ENV['TZ']
    ENV['TZ'] = tz_name
    yield
  ensure
    ENV['TZ'] = prev_tz
  end

  def pretend_now_is(time)
    begin
      Time.testing_offset = Time.now - time
      yield
    ensure
      Time.testing_offset = nil
    end
  end

end


text:
if [ ! -e all_output.actual ]; then
    echo "This script must be run after running test.sh in a folder such as tests/plugin_test"
    exit 1
fi
# Regenerates the files in a folder with all_output.actual
for file in expected/*.php.expected; do
    basename=$(basename "$file")
    srcname=${basename/\.expected/}
    echo "Regenerating $srcname"
    grep -E "^src/$srcname" all_output.actual > $file;
done


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/welcome_bg"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/btnReg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="2015 新题型四六级助手"
        android:textColor="#dddddd"
        android:textSize="10.0sp" />

</RelativeLayout>


text:
require 'spec_helper'

describe DeskApi::Resource do
  subject do
    @client ||= DeskApi::Client.new DeskApi::CONFIG
  end

  context '#initialize' do
    it 'stores the client' do
      subject.articles.instance_variable_get(:@_client).should eq(subject)
    end

    it 'is not loaded initially' do
      subject.articles.instance_variable_get(:@_loaded).should be_false
    end

    it 'sets up the link to self' do
      subject.articles.href.should_not be_nil
    end
  end

  context '#exec!', :vcr do
    it 'loads the current resource' do
      subject.articles.send(:exec!).instance_variable_get(:@_loaded).should be_true
    end

    it 'can be forced to reload' do
      subject.articles.instance_variable_set(:@_loaded, true)
      subject.should_receive(:get).and_call_original
      subject.articles.send(:exec!, true)
    end
  end

  context '#method_missing', :vcr do
    it 'loads the resource to find a suitable method' do
      articles = subject.articles
      articles.instance_variable_set(:@_loaded, false)
      articles.should_receive(:exec!).and_call_original
      articles.entries
    end

    it 'raises an error if method does not exist' do
      lambda { subject.articles.some_other_method }.should raise_error(NoMethodError)
    end
  end

  context '#by_url', :vcr do
    it 'finds resources by url' do
      subject.articles.by_url('/api/v2/articles/1295677').should be_an_instance_of(DeskApi::Resource)
    end
  end

  context '#get_self' do
    it 'returns the hash for self' do
      subject.articles.get_self.should eq({
        "href" => "/api/v2/articles"
      })
    end
  end

  context '#href' do
    it 'returns the href for self' do
      subject.articles.href.should eq('/api/v2/articles')
    end

    it 'sets the href' do
      res = DeskApi::Resource.new(subject, {
        '_links'=>{'self'=>{'href'=>'/api/v2/cases'}}
      }, true)

      res.href.should eq('/api/v2/cases')
      res.href = '/api/v2/articles'
      res.href.should eq('/api/v2/articles')
    end
  end

  context '#type' do
    it 'returns the resources type' do
      res = DeskApi::Resource.new(subject, {
        '_links'=>{'self'=>{'href'=>'/api/v2/cases','class'=>'page'}}
      }, true)
      res.type.should eq('page')
    end
  end

  context '#search' do
    it 'allows searching on search enabled resources', :vcr do
      subject.articles.search(text: 'Lorem Ipsum').total_entries.should eq(0)
    end
  end

  context '#create' do
    it 'creates a new topic', :vcr do
      topic = subject.topics.create({
        name: 'My new topic'
      }).name.should eq('My new topic')
    end

    it 'throws an error creating a user', :vcr do
      lambda { subject.users.create(name: 'Some User') }.should raise_error(DeskApi::Error::MethodNotAllowed)
    end
  end

  context '#update' do
    it 'updates a topic', :vcr do
      topic = subject.topics.entries.first

      topic.description = 'Some new description'
      topic.update({
        name: 'Updated topic name'
      })

      topic.name.should eq('Updated topic name')
      topic.description.should eq('Some new description')
    end

    it 'throws an error updating a user', :vcr do
      user = subject.users.entries.first
      lambda { user.update(name: 'Some User') }.should raise_error(DeskApi::Error::MethodNotAllowed)
    end

    it 'can update without a hash', :vcr do
      topic = subject.topics.entries.first
      topic.description = 'Another description update.'
      topic.update
      subject.topics.entries.first.description.should eq('Another description update.')
    end
  end

  context '#delete' do
    it 'deletes a resource', :vcr do
      subject.articles.create({
        subject: 'My subject',
        body: 'Some text for this new article',
        _links: {
          topic: subject.topics.entries.first.get_self
        }
      }).delete.should be_true
    end

    it 'throws an error deleting a non deletalbe resource', :vcr do
      user = subject.users.entries.first
      lambda { user.delete }.should raise_error(DeskApi::Error::MethodNotAllowed)
    end
  end

  describe 'embeddable' do
    it 'allows to declare embedds' do
      lambda { subject.cases.embed(:assigned_user) }.should_not raise_error
    end

    it 'changes the url' do
      subject.cases.embed(:assigned_user).href.should eq('/api/v2/cases?embed=assigned_user')
    end

    context 'if you use embed' do
      before do
        VCR.turn_off! ignore_cassettes: true

        @stubs  ||= Faraday::Adapter::Test::Stubs.new
        @client ||= DeskApi::Client.new(DeskApi::CONFIG).tap do |client|
          client.middleware = Proc.new do |builder|
            builder.response :mashify
            builder.response :dates
            builder.response :json, content_type: /application\/json/
            builder.adapter :test, @stubs
          end
        end
      end

      after do
        VCR.turn_on!
      end

      it 'does not load the resource again' do
        times_called = 0
        @stubs.get('/api/v2/cases?embed=assigned_user') do
          times_called += 1
          [
            200,
            { 'content-type' => 'application/json' },
            File.open(File.join(RSpec.configuration.root_path, 'stubs', 'cases_embed_assigned_user.json')).read
          ]
        end

        first_case = @client.cases.embed(:assigned_user).entries.first
        first_case.assigned_user.name.should eq('Thomas Stachl')
        first_case.assigned_user.instance_variable_get(:@_loaded).should be_true
        times_called.should eq(1)
      end

      it 'can be used in finder' do
        @stubs.get('/api/v2/cases/3011?embed=customer') do
          [
            200,
            { 'content-type' => 'application/json' },
            File.open(File.join(RSpec.configuration.root_path, 'stubs', 'case_embed_customer.json')).read
          ]
        end

        customer = @client.cases.find(3011, embed: :customer).customer
        customer.first_name.should eq('Thomas')
        customer = @client.cases.find(3011, embed: [:customer]).customer
        customer.first_name.should eq('Thomas')
      end
    end
  end

  context '#query_params' do
    before do
      @page = DeskApi::Resource.new(subject, {
        '_links'=>{'self'=>{'href'=>'/api/v2/cases?page=2&per_page=50'}}
      }, true)
    end

    it 'allows to get query params from the current resource' do
      @page.send(:query_params_include?, 'page').should eq('2')
      @page.send(:query_params_include?, 'per_page').should eq('50')
    end

    it 'returns nil if param not found' do
      @page.send(:query_params_include?, 'blup').should be_nil
    end
  end

  context '#query_params=' do
    before do
      @page = DeskApi::Resource.new(subject, {
        '_links'=>{'self'=>{'href'=>'/api/v2/cases'}}
      }, true)
    end

    it 'sets query params on the current url' do
      @page.send(:query_params=, { page: 5, per_page: 50 })
      @page.instance_variable_get(:@_definition)['_links']['self']['href'].should eq('/api/v2/cases?page=5&per_page=50')
    end
  end

  context '#get_linked_resource' do
    it 'returns linked resources', :vcr do
      subject.cases.entries.first.customer.should be_an_instance_of(DeskApi::Resource)
    end

    it 'returns nil if link is nil', :vcr do
      subject.articles.next.should be_nil
    end

    it 'saves the linked resource instead of the url', :vcr do
      first_case = subject.cases.entries.first
      first_case.customer.should be_an_instance_of(DeskApi::Resource)
      first_case.instance_variable_get(:@_definition)['_links']['customer'].should be_an_instance_of(DeskApi::Resource)
    end
  end

  context '#page' do
    it 'returns the current page and loads if page not defined', :vcr do
      subject.articles.page.should eq(1)
    end

    it 'sets the page' do
      subject.cases.page(5).page.should eq(5)
    end

    it 'sets the resource to not loaded', :vcr do
      cases = subject.cases.send(:exec!)
      cases.page(5).instance_variable_get(:@_loaded).should be_false
    end

    it 'keeps the resource as loaded', :vcr do
      cases = subject.cases.send(:exec!)
      cases.page(1).instance_variable_get(:@_loaded).should be_true
    end
  end

  context '#find' do
    it 'loads the requested resource', :vcr do
      subject.cases.find(3065).subject.should eq('Testing the Tank again')
    end

    it 'has an alias by_id', :vcr do
      subject.cases.find(3065).subject.should eq('Testing the Tank again')
    end
  end
end


text:
require File.dirname(__FILE__) + '/helper'

class RequestTest < Test::Unit::TestCase
  it 'responds to #user_agent' do
    request = Sinatra::Request.new({'HTTP_USER_AGENT' => 'Test'})
    assert request.respond_to?(:user_agent)
    assert_equal 'Test', request.user_agent
  end

  it 'parses POST params when Content-Type is form-dataish' do
    request = Sinatra::Request.new(
      'REQUEST_METHOD' => 'PUT',
      'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
      'rack.input' => StringIO.new('foo=bar')
    )
    assert_equal 'bar', request.params['foo']
  end

  it 'is secure when the url scheme is https' do
    request = Sinatra::Request.new('rack.url_scheme' => 'https')
    assert request.secure?
  end

  it 'is not secure when the url scheme is http' do
    request = Sinatra::Request.new('rack.url_scheme' => 'http')
    assert !request.secure?
  end

  it 'respects X-Forwarded-Proto header for proxied SSL' do
    request = Sinatra::Request.new('HTTP_X_FORWARDED_PROTO' => 'https')
    assert request.secure?
  end
end


text:
import * as React from 'react';
import * as Utils from '../lib/Utils';
import RunList, { RunListProps } from './RunList';
import TestUtils from '../TestUtils';
import produce from 'immer';
import { ApiFilter, PredicateOp } from '../apis/filter';
import {
  ApiRun,
  ApiRunDetail,
  ApiResourceType,
  ApiRunMetric,
  RunMetricFormat,
  RunStorageState,
} from '../apis/run';
import { Apis, RunSortKeys, ListRequest } from '../lib/Apis';
import { MetricMetadata } from '../lib/RunUtils';
import { NodePhase } from '../lib/StatusUtils';
import { ReactWrapper, ShallowWrapper, shallow } from 'enzyme';
import { range } from 'lodash';

class RunListTest extends RunList {
  public _loadRuns(request: ListRequest): Promise<string> {
    return super._loadRuns(request);
  }
}

describe('RunList', () => {
  let tree: ShallowWrapper | ReactWrapper;

  const onErrorSpy = jest.fn();
  const listRunsSpy = jest.spyOn(Apis.runServiceApi, 'listRuns');
  const getRunSpy = jest.spyOn(Apis.runServiceApi, 'getRun');
  const getPipelineSpy = jest.spyOn(Apis.pipelineServiceApi, 'getPipeline');
  const getExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'getExperiment');
  // We mock this because it uses toLocaleDateString, which causes mismatches between local and CI
  // test enviroments
  const formatDateStringSpy = jest.spyOn(Utils, 'formatDateString');

  function generateProps(): RunListProps {
    return {
      history: {} as any,
      location: { search: '' } as any,
      match: '' as any,
      onError: onErrorSpy,
    };
  }

  function mockNRuns(n: number, runTemplate: Partial<ApiRunDetail>): void {
    getRunSpy.mockImplementation(id =>
      Promise.resolve(
        produce(runTemplate, draft => {
          draft.run = draft.run || {};
          draft.run.id = id;
          draft.run.name = 'run with id: ' + id;
        }),
      ),
    );

    listRunsSpy.mockImplementation(() =>
      Promise.resolve({
        runs: range(1, n + 1).map(i => {
          if (runTemplate.run) {
            return produce(runTemplate.run as Partial<ApiRun>, draft => {
              draft.id = 'testrun' + i;
              draft.name = 'run with id: testrun' + i;
            });
          }
          return {
            id: 'testrun' + i,
            name: 'run with id: testrun' + i,
          } as ApiRun;
        }),
      }),
    );

    getPipelineSpy.mockImplementation(() => ({ name: 'some pipeline' }));
    getExperimentSpy.mockImplementation(() => ({ name: 'some experiment' }));
  }

  function getMountedInstance(): RunList {
    tree = TestUtils.mountWithRouter(<RunList {...generateProps()} />);
    return tree.instance() as RunList;
  }

  function getShallowInstance(): RunList {
    tree = shallow(<RunList {...generateProps()} />);
    return tree.instance() as RunList;
  }

  beforeEach(() => {
    formatDateStringSpy.mockImplementation((date?: Date) => {
      return date ? '1/2/2019, 12:34:56 PM' : '-';
    });
    onErrorSpy.mockClear();
    listRunsSpy.mockClear();
    getRunSpy.mockClear();
    getPipelineSpy.mockClear();
    getExperimentSpy.mockClear();
  });

  afterEach(async () => {
    // unmount() should be called before resetAllMocks() in case any part of the unmount life cycle
    // depends on mocks/spies
    if (tree) {
      await tree.unmount();
    }
    jest.resetAllMocks();
  });

  it('renders the empty experience', () => {
    expect(shallow(<RunList {...generateProps()} />)).toMatchSnapshot();
  });

  describe('in archived state', () => {
    it('renders the empty experience', () => {
      const props = generateProps();
      props.storageState = RunStorageState.ARCHIVED;
      expect(shallow(<RunList {...props} />)).toMatchSnapshot();
    });

    it('loads runs whose storage state is not ARCHIVED when storage state equals AVAILABLE', async () => {
      mockNRuns(1, {});
      const props = generateProps();
      props.storageState = RunStorageState.AVAILABLE;
      tree = shallow(<RunList {...props} />);
      await (tree.instance() as RunListTest)._loadRuns({});
      expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        encodeURIComponent(
          JSON.stringify({
            predicates: [
              {
                key: 'storage_state',
                op: PredicateOp.NOTEQUALS,
                string_value: RunStorageState.ARCHIVED.toString(),
              },
            ],
          } as ApiFilter),
        ),
      );
    });

    it('loads runs whose storage state is ARCHIVED when storage state equals ARCHIVED', async () => {
      mockNRuns(1, {});
      const props = generateProps();
      props.storageState = RunStorageState.ARCHIVED;
      tree = shallow(<RunList {...props} />);
      await (tree.instance() as RunListTest)._loadRuns({});
      expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        encodeURIComponent(
          JSON.stringify({
            predicates: [
              {
                key: 'storage_state',
                op: PredicateOp.EQUALS,
                string_value: RunStorageState.ARCHIVED.toString(),
              },
            ],
          } as ApiFilter),
        ),
      );
    });

    it('augments request filter with storage state predicates', async () => {
      mockNRuns(1, {});
      const props = generateProps();
      props.storageState = RunStorageState.ARCHIVED;
      tree = shallow(<RunList {...props} />);
      await (tree.instance() as RunListTest)._loadRuns({
        filter: encodeURIComponent(
          JSON.stringify({
            predicates: [{ key: 'k', op: 'op', string_value: 'val' }],
          }),
        ),
      });
      expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        encodeURIComponent(
          JSON.stringify({
            predicates: [
              {
                key: 'k',
                op: 'op',
                string_value: 'val',
              },
              {
                key: 'storage_state',
                op: PredicateOp.EQUALS,
                string_value: RunStorageState.ARCHIVED.toString(),
              },
            ],
          } as ApiFilter),
        ),
      );
    });
  });

  it('loads one run', async () => {
    mockNRuns(1, {});
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
    );
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('reloads the run when refresh is called', async () => {
    mockNRuns(0, {});
    const props = generateProps();
    tree = TestUtils.mountWithRouter(<RunList {...props} />);
    await (tree.instance() as RunList).refresh();
    tree.update();
    expect(Apis.runServiceApi.listRuns).toHaveBeenCalledTimes(2);
    expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
      '',
      10,
      RunSortKeys.CREATED_AT + ' desc',
      undefined,
      undefined,
      '',
    );
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('loads multiple runs', async () => {
    mockNRuns(5, {});
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('calls error callback when loading runs fails', async () => {
    TestUtils.makeErrorResponseOnce(
      jest.spyOn(Apis.runServiceApi, 'listRuns'),
      'bad stuff happened',
    );
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).toHaveBeenLastCalledWith(
      'Error: failed to fetch runs.',
      new Error('bad stuff happened'),
    );
  });

  it('displays error in run row if pipeline could not be fetched', async () => {
    mockNRuns(1, { run: { pipeline_spec: { pipeline_id: 'test-pipeline-id' } } });
    TestUtils.makeErrorResponseOnce(getPipelineSpy, 'bad stuff happened');
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(tree).toMatchSnapshot();
  });

  it('displays error in run row if experiment could not be fetched', async () => {
    mockNRuns(1, {
      run: {
        resource_references: [
          {
            key: { id: 'test-experiment-id', type: ApiResourceType.EXPERIMENT },
          },
        ],
      },
    });
    TestUtils.makeErrorResponseOnce(getExperimentSpy, 'bad stuff happened');
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(tree).toMatchSnapshot();
  });

  it('displays error in run row if it failed to parse (run list mask)', async () => {
    TestUtils.makeErrorResponseOnce(jest.spyOn(Apis.runServiceApi, 'getRun'), 'bad stuff happened');
    const props = generateProps();
    props.runIdListMask = ['testrun1', 'testrun2'];
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(tree).toMatchSnapshot();
  });

  it('shows run time for each run', async () => {
    mockNRuns(1, {
      run: {
        created_at: new Date(2018, 10, 10, 10, 10, 10),
        finished_at: new Date(2018, 10, 10, 11, 11, 11),
        status: 'Succeeded',
      },
    });
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('loads runs for a given experiment id', async () => {
    mockNRuns(1, {});
    const props = generateProps();
    props.experimentIdMask = 'experiment1';
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
      undefined,
      undefined,
      undefined,
      'EXPERIMENT',
      'experiment1',
      undefined,
    );
  });

  it('loads runs for a given namespace', async () => {
    mockNRuns(1, {});
    const props = generateProps();
    props.namespaceMask = 'namespace1';
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(Apis.runServiceApi.listRuns).toHaveBeenLastCalledWith(
      undefined,
      undefined,
      undefined,
      'NAMESPACE',
      'namespace1',
      undefined,
    );
  });

  it('loads given list of runs only', async () => {
    mockNRuns(5, {});
    const props = generateProps();
    props.runIdListMask = ['run1', 'run2'];
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(Apis.runServiceApi.listRuns).not.toHaveBeenCalled();
    expect(Apis.runServiceApi.getRun).toHaveBeenCalledTimes(2);
    expect(Apis.runServiceApi.getRun).toHaveBeenCalledWith('run1');
    expect(Apis.runServiceApi.getRun).toHaveBeenCalledWith('run2');
  });

  it('adds metrics columns', async () => {
    mockNRuns(2, {
      run: {
        metrics: [
          { name: 'metric1', number_value: 5 },
          { name: 'metric2', number_value: 10 },
        ],
        status: 'Succeeded',
      },
    });
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('shows pipeline name', async () => {
    mockNRuns(1, {
      run: { pipeline_spec: { pipeline_id: 'test-pipeline-id', pipeline_name: 'pipeline name' } },
    });
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('retrieves pipeline from backend to display name if not in spec', async () => {
    mockNRuns(1, {
      run: { pipeline_spec: { pipeline_id: 'test-pipeline-id' /* no pipeline_name */ } },
    });
    getPipelineSpy.mockImplementationOnce(() => ({ name: 'test pipeline' }));
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('shows link to recurring run config', async () => {
    mockNRuns(1, {
      run: {
        resource_references: [
          {
            key: { id: 'test-recurring-run-id', type: ApiResourceType.JOB },
          },
        ],
      },
    });
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('shows experiment name', async () => {
    mockNRuns(1, {
      run: {
        resource_references: [
          {
            key: { id: 'test-experiment-id', type: ApiResourceType.EXPERIMENT },
          },
        ],
      },
    });
    getExperimentSpy.mockImplementationOnce(() => ({ name: 'test experiment' }));
    const props = generateProps();
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('hides experiment name if instructed', async () => {
    mockNRuns(1, {
      run: {
        resource_references: [
          {
            key: { id: 'test-experiment-id', type: ApiResourceType.EXPERIMENT },
          },
        ],
      },
    });
    getExperimentSpy.mockImplementationOnce(() => ({ name: 'test experiment' }));
    const props = generateProps();
    props.hideExperimentColumn = true;
    tree = shallow(<RunList {...props} />);
    await (tree.instance() as RunListTest)._loadRuns({});
    expect(props.onError).not.toHaveBeenCalled();
    expect(tree).toMatchSnapshot();
  });

  it('renders run name as link to its details page', () => {
    expect(
      getMountedInstance()._nameCustomRenderer({ value: 'test run', id: 'run-id' }),
    ).toMatchSnapshot();
  });

  it('renders pipeline name as link to its details page', () => {
    expect(
      getMountedInstance()._pipelineVersionCustomRenderer({
        id: 'run-id',
        value: { displayName: 'test pipeline', pipelineId: 'pipeline-id', usePlaceholder: false },
      }),
    ).toMatchSnapshot();
  });

  it('handles no pipeline id given', () => {
    expect(
      getMountedInstance()._pipelineVersionCustomRenderer({
        id: 'run-id',
        value: { displayName: 'test pipeline', usePlaceholder: false },
      }),
    ).toMatchSnapshot();
  });

  it('shows "View pipeline" button if pipeline is embedded in run', () => {
    expect(
      getMountedInstance()._pipelineVersionCustomRenderer({
        id: 'run-id',
        value: { displayName: 'test pipeline', pipelineId: 'pipeline-id', usePlaceholder: true },
      }),
    ).toMatchSnapshot();
  });

  it('handles no pipeline name', () => {
    expect(
      getMountedInstance()._pipelineVersionCustomRenderer({
        id: 'run-id',
        value: { /* no displayName */ usePlaceholder: true },
      }),
    ).toMatchSnapshot();
  });

  it('renders pipeline name as link to its details page', () => {
    expect(
      getMountedInstance()._recurringRunCustomRenderer({
        id: 'run-id',
        value: { id: 'recurring-run-id' },
      }),
    ).toMatchSnapshot();
  });

  it('renders experiment name as link to its details page', () => {
    expect(
      getMountedInstance()._experimentCustomRenderer({
        id: 'run-id',
        value: { displayName: 'test experiment', id: 'experiment-id' },
      }),
    ).toMatchSnapshot();
  });

  it('renders no experiment name', () => {
    expect(
      getMountedInstance()._experimentCustomRenderer({
        id: 'run-id',
        value: { /* no displayName */ id: 'experiment-id' },
      }),
    ).toMatchSnapshot();
  });

  it('renders status as icon', () => {
    expect(
      getShallowInstance()._statusCustomRenderer({ value: NodePhase.SUCCEEDED, id: 'run-id' }),
    ).toMatchSnapshot();
  });

  it('renders metric buffer', () => {
    expect(
      getShallowInstance()._metricBufferCustomRenderer({ value: {}, id: 'run-id' }),
    ).toMatchSnapshot();
  });

  it('renders an empty metric when there is no metric', () => {
    expect(
      getShallowInstance()._metricCustomRenderer({ value: undefined, id: 'run-id' }),
    ).toMatchSnapshot();
  });

  it('renders an empty metric when metric is empty', () => {
    expect(
      getShallowInstance()._metricCustomRenderer({ value: {}, id: 'run-id' }),
    ).toMatchSnapshot();
  });

  it('renders an empty metric when metric value is empty', () => {
    expect(
      getShallowInstance()._metricCustomRenderer({ value: { metric: {} }, id: 'run-id' }),
    ).toMatchSnapshot();
  });

  it('renders percentage metric', () => {
    expect(
      getShallowInstance()._metricCustomRenderer({
        id: 'run-id',
        value: { metric: { number_value: 0.3, format: RunMetricFormat.PERCENTAGE } },
      }),
    ).toMatchSnapshot();
  });

  it('renders raw metric', () => {
    expect(
      getShallowInstance()._metricCustomRenderer({
        id: 'run-id',
        value: {
          metadata: { count: 1, maxValue: 100, minValue: 10 } as MetricMetadata,
          metric: { number_value: 55 } as ApiRunMetric,
        },
      }),
    ).toMatchSnapshot();
  });

  it('renders pipeline version name as link to its details page', () => {
    expect(
      getMountedInstance()._pipelineVersionCustomRenderer({
        id: 'run-id',
        value: {
          displayName: 'test pipeline version',
          pipelineId: 'pipeline-id',
          usePlaceholder: false,
          versionId: 'version-id',
        },
      }),
    ).toMatchSnapshot();
  });
});


text:
name: "Matthias Trachsel"
biography: "[Not used for alumni]"
role: "Alumni"
photo: "MatthiasTrachsel.jpg"
last: "Trachsel"
seniority: "4"
---


text:
import os
import os.path
import concurrent.futures
import threading

class AppDaemon:
    def __init__(self, logging, loop, **kwargs):

        #
        # Import various AppDaemon bits and pieces now to avoid circular import
        #

        import appdaemon.utils as utils
        import appdaemon.thread_async as appq
        import appdaemon.utility_loop as utility
        import appdaemon.plugin_management as plugins
        import appdaemon.threading
        import appdaemon.app_management as apps
        import appdaemon.callbacks as callbacks
        import appdaemon.futures as futures
        import appdaemon.state as state
        import appdaemon.events as events
        import appdaemon.services as services
        import appdaemon.sequences as sequences
        import appdaemon.scheduler as scheduler

        self.logging = logging
        self.logging.register_ad(self)
        self.logger = logging.get_logger()
        self.threading = None
        self.callbacks = None
        self.futures = None
        self.state = None

        self.config = kwargs
        self.booted = "booting"
        self.config["ad_version"] = utils.__version__
        self.check_app_updates_profile = ""

        self.was_dst = False

        self.last_state = None

        self.executor = None
        self.loop = None
        self.srv = None
        self.appd = None
        self.stopping = False
        self.http = None
        self.admin_loop = None

        self.global_vars = {}
        self.global_lock = threading.RLock()

        self.config_file_modified = 0

        self.sched = None
        self.thread_async = None
        self.utility = None
        self.module_debug = kwargs["module_debug"]

        # User Supplied/Defaults

        self.load_distribution = "roundrobbin"
        utils.process_arg(self, "load_distribution", kwargs)

        self.app_dir = None
        utils.process_arg(self, "app_dir", kwargs)

        self.starttime = None
        utils.process_arg(self, "starttime", kwargs)

        self.latitude = None
        utils.process_arg(self, "latitude", kwargs, float=True)

        self.longitude = None
        utils.process_arg(self, "longitude", kwargs, float=True)

        self.elevation = None
        utils.process_arg(self, "elevation", kwargs, int=True)

        self.time_zone = None
        utils.process_arg(self, "time_zone", kwargs)

        self.tz = None
        self.loop = loop

        self.logfile = None
        self.errfile = None

        self.config_file = None
        utils.process_arg(self, "config_file", kwargs)

        self.config_dir = None
        utils.process_arg(self, "config_dir", kwargs)

        self.timewarp = 1
        utils.process_arg(self, "timewarp", kwargs, float=True)

        self.max_clock_skew = 1
        utils.process_arg(self, "max_clock_skew", kwargs, int=True)

        self.thread_duration_warning_threshold = 10
        utils.process_arg(self, "thread_duration_warning_threshold", kwargs, float=True)

        self.threadpool_workers = 10
        utils.process_arg(self, "threadpool_workers", kwargs, int=True)

        self.endtime = None
        utils.process_arg(self, "endtime", kwargs)

        self.loglevel = "INFO"
        utils.process_arg(self, "loglevel", kwargs)

        self.api_port = None
        utils.process_arg(self, "api_port", kwargs)

        self.utility_delay = 1
        utils.process_arg(self, "utility_delay", kwargs, int=True)

        self.admin_delay = 1
        utils.process_arg(self, "admin_delay", kwargs, int=True)

        self.max_utility_skew = self.utility_delay * 2
        utils.process_arg(self, "max_utility_skew", kwargs, float=True)

        self.check_app_updates_profile = False
        utils.process_arg(self, "check_app_updates_profile", kwargs)

        self.production_mode = False
        utils.process_arg(self, "production_mode", kwargs)

        self.invalid_yaml_warnings = True
        utils.process_arg(self, "invalid_yaml_warnings", kwargs)

        self.missing_app_warnings = True
        utils.process_arg(self, "missing_app_warnings", kwargs)

        self.log_thread_actions = False
        utils.process_arg(self, "log_thread_actions", kwargs)

        self.qsize_warning_threshold = 50
        utils.process_arg(self, "qsize_warning_threshold", kwargs, int=True)

        self.qsize_warning_step = 60
        utils.process_arg(self, "qsize_warning_step", kwargs, int=True)

        self.qsize_warning_iterations = 10
        utils.process_arg(self, "qsize_warning_iterations", kwargs, int=True)

        self.internal_function_timeout = 10
        utils.process_arg(self, "internal_function_timeout", kwargs, int=True)

        self.namespaces = {}
        utils.process_arg(self, "namespaces", kwargs)

        self.exclude_dirs = ["__pycache__"]
        if "exclude_dirs" in kwargs:
            self.exclude_dirs += kwargs["exclude_dirs"]

        self.stop_function = None
        utils.process_arg(self, "stop_function", kwargs)

        if not kwargs.get("cert_verify", True):
            self.certpath = False

        if kwargs.get("disable_apps") is True:
            self.apps = False
            self.logging.log("INFO", "Apps are disabled")
        else:
            self.apps = True

        #
        # Set up services
        #
        self.services = services.Services(self)

        #
        # Set up sequences
        #
        self.sequences = sequences.Sequences(self)

        #
        # Set up scheduler
        #
        self.sched = scheduler.Scheduler(self)

        #
        # Set up state
        #
        self.state = state.State(self)

        #
        # Set up events
        #
        self.events = events.Events(self)

        #
        # Set up callbacks
        #
        self.callbacks = callbacks.Callbacks(self)

        #
        # Set up futures
        #
        self.futures = futures.Futures(self)

        if self.apps is True:
            if self.app_dir is None:
                if self.config_dir is None:
                    self.app_dir = utils.find_path("apps")
                    self.config_dir = os.path.dirname(self.app_dir)
                else:
                    self.app_dir = os.path.join(self.config_dir, "apps")

            utils.check_path("config_dir", self.logger, self.config_dir, permissions="rwx")
            utils.check_path("appdir", self.logger, self.app_dir)

            # Initialize Apps

            self.app_management = apps.AppManagement(self, kwargs.get("app_config_file", None))

            # threading setup

            self.threading = appdaemon.threading.Threading(self, kwargs)

        self.stopping = False

        #
        # Set up Executor ThreadPool
        #
        if "threadpool_workers" in kwargs:
            self.threadpool_workers = int(kwargs["threadpool_workers"])

        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=self.threadpool_workers)

        # Initialize Plugins

        if "plugins" in kwargs:
            args = kwargs["plugins"]
        else:
            args = None

        self.plugins = plugins.Plugins(self, args)

        # Create thread_async Loop

        self.logger.debug("Starting thread_async loop")

        if self.apps is True:
            self.thread_async = appq.ThreadAsync(self)
            loop.create_task(self.thread_async.loop())

        # Create utility loop

        self.logger.debug("Starting utility loop")

        self.utility = utility.Utility(self)
        loop.create_task(self.utility.loop())

    def stop(self):
        self.stopping = True
        if self.admin_loop is not None:
            self.admin_loop.stop()
        if self.thread_async is not None:
            self.thread_async.stop()
        if self.sched is not None:
            self.sched.stop()
        if self.utility is not None:
            self.utility.stop()
        if self.plugins is not None:
            self.plugins.stop()

    def terminate(self):
        if self.state is not None:
            self.state.terminate()

    #
    # Utilities
    #

    def register_http(self, http):

        import appdaemon.admin_loop as admin_loop

        self.http = http
        # Create admin loop

        if http.admin is not None:
            self.logger.debug("Starting admin loop")

            self.admin_loop = admin_loop.AdminLoop(self)
            self.loop.create_task(self.admin_loop.loop())


text:
import type { YearListProps } from './types';
export declare const YearList: ({ baseMonth, setBaseMonth, onMonthChange, currentDate, ...props }: YearListProps) => JSX.Element;


text:
class Ability
  include CanCan::Ability
  include Hydra::Ability
  include Hydra::PolicyAwareAbility

  def user_groups
    return @user_groups if @user_groups

    @user_groups = default_user_groups
    @user_groups |= current_user.groups if current_user and current_user.respond_to? :groups
    @user_groups |= ['registered'] unless current_user.new_record?
    @user_groups |= @session[:virtual_groups] unless @session.blank?
    @user_groups
  end

  def create_permissions(user=nil, session=nil)
    if full_login?
      if @user_groups.include? "administrator"
        can :manage, MediaObject
        can :manage, MasterFile
        can :inspect, MediaObject
        can :manage, Admin::Group
        can :manage, Admin::Collection
      end

      if @user_groups.include? "group_manager"
        can :manage, Admin::Group do |group|
          group.nil? or !['administrator','group_manager'].include?(group.name)
        end
      end

      if is_member_of_any_collection?
        can :create, MediaObject
      end

      if @user_groups.include? "manager"
        can :create, Admin::Collection
      end
    end
  end

  def custom_permissions(user=nil, session=nil)
    unless full_login? and @user_groups.include? "administrator"
      cannot :read, MediaObject do |mediaobject|
        !mediaobject.published? && !test_edit(mediaobject.pid)
      end

      can :read, MasterFile do |master_file|
        can? :read, masterfile.mediaobject
      end

      can :read, Derivative do |derivative|
        can? :read, derivative.masterfile.mediaobject
      end

      cannot :read, Admin::Collection unless full_login?

      if full_login?
        can :read, Admin::Collection do |collection|
          is_member_of?(collection)
        end

        unless (is_member_of_any_collection? or @user_groups.include? 'manager')
          cannot :read, Admin::Collection
        end

        can :update_access_control, MediaObject do |mediaobject|
          @user.in?(mediaobject.collection.managers) ||
            (is_editor_of?(mediaobject.collection) && !mediaobject.published?)
        end

        can :unpublish, MediaObject do |mediaobject|
          @user.in?(mediaobject.collection.managers)
        end

        can :update, Admin::Collection do |collection|
          is_editor_of?(collection)
        end

        can :update_unit, Admin::Collection do |collection|
          @user.in?(collection.managers)
        end

        can :update_access_control, Admin::Collection do |collection|
          @user.in?(collection.managers)
        end

        can :update_managers, Admin::Collection do |collection|
          @user.in?(collection.managers)
        end

        can :update_editors, Admin::Collection do |collection|
          @user.in?(collection.managers)
        end

        can :update_depositors, Admin::Collection do |collection|
          is_editor_of?(collection)
        end

        can :inspect, MediaObject do |mediaobject|
         is_member_of?(mediaobject.collection)
        end

        # Users logged in through LTI cannot share
        can :share, MediaObject

        cannot :update, MediaObject do |mediaobject|
          (!is_member_of?(mediaobject.collection)) ||
            ( mediaobject.published? && !@user.in?(mediaobject.collection.managers) )
        end

        cannot :destroy, MediaObject do |mediaobject|
          # non-managers can only destroy mediaobject if it's unpublished
          (!is_member_of?(mediaobject.collection)) ||
            ( mediaobject.published? && !@user.in?(mediaobject.collection.managers) )
        end

        cannot :destroy, Admin::Collection do |collection, other_user_collections=[]|
          !@user.in?(collection.managers)
        end
      end
    end
  end

  def is_member_of?(collection)
     @user_groups.include?("administrator") ||
       @user.in?(collection.managers, collection.editors, collection.depositors)
  end

  def is_editor_of?(collection)
     @user_groups.include?("administrator") ||
       @user.in?(collection.managers, collection.editors)
  end

  def is_member_of_any_collection?
    @user.id.present? and Admin::Collection.where("#{ActiveFedora::SolrService.solr_name("inheritable_edit_access_person", Hydra::Datastream::RightsMetadata.indexer)}" => @user.user_key).first.present?
  end

  def full_login?
    return @full_login unless @full_login.nil?

    @full_login = @session.present? ? @session[:full_login] : true
    @full_login
  end
end