text:
<?php

namespace App\Service;

use App\Entity\Framework\ImportLog;
use App\Entity\Framework\LsAssociation;
use App\Entity\Framework\LsDoc;
use App\Entity\Framework\LsItem;
use Doctrine\ORM\EntityManagerInterface;
use Ramsey\Uuid\Uuid;

class GithubImport
{
    public function __construct(private EntityManagerInterface $entityManager)
    {
    }

    protected function getEntityManager(): EntityManagerInterface
    {
        return $this->entityManager;
    }

    /**
     * Parse an Github document into a LsDoc/LsItem hierarchy.
     *
     * @param array $missingFieldsLog
     */
    public function parseCSVGithubDocument(array $lsItemKeys, string $fileContent, string $lsDocId, string $frameworkToAssociate, $missingFieldsLog): void
    {
        $csvContent = str_getcsv($fileContent, "\n");
        $headers = [];
        $content = [];

        foreach ($csvContent as $i => $row) {
            $tempContent = [];
            $row = str_getcsv($row, ',');

            if (0 === $i) {
                $headers = $row;
                continue;
            }

            foreach ($headers as $h => $col) {
                if ($h < count($row)) {
                    $tempContent[$col] = $row[$h];
                }
            }

            $content[] = $tempContent;
        }

        $this->saveCSVGithubDocument($lsItemKeys, $content, $lsDocId, $frameworkToAssociate, $missingFieldsLog);
    }

    /**
     * Save an Github document into a LsDoc/LsItem hierarchy.
     *
     * @param array $lsItemKeys
     * @param array $content
     * @param array $missingFieldsLog
     */
    public function saveCSVGithubDocument($lsItemKeys, $content, $lsDocId, $frameworkToAssociate, $missingFieldsLog): void
    {
        $em = $this->getEntityManager();
        $lsDoc = $em->getRepository(LsDoc::class)->find($lsDocId);

        if (null !== $missingFieldsLog && count($missingFieldsLog) > 0) {
            foreach ($missingFieldsLog as $messageError) {
                $errorLog = new ImportLog();
                $errorLog->setLsDoc($lsDoc);
                $errorLog->setMessage($messageError);
                $errorLog->setMessageType('warning');

                $em->persist($errorLog);
            }
        } else {
            $successLog = new ImportLog();
            $successLog->setLsDoc($lsDoc);
            $successLog->setMessage('Items successfully imported.');
            $successLog->setMessageType('info');

            $em->persist($successLog);
        }

        // Build the lsItems array
        $lsItems = [];
        $sequenceNumbers = [];
        $humanCodingValues = [];
        for ($i = 0, $iMax = count($content); $i < $iMax; ++$i) {
            $lineContent = $content[$i];
            if (!$this->isValidItemContent($lineContent, $lsItemKeys)) {
                $lsItems[$i] = null;
                continue;
            }

            $lsItem = $this->parseCSVGithubStandard($lsDoc, $lsItemKeys, $lineContent);

            if (null !== $lsItem) {
                if (!empty($lsItem->getHumanCodingScheme())) {
                    $humanCodingValues[$lsItem->getHumanCodingScheme()] = $i;
                }

                $seq = $lineContent[trim($lsItemKeys['sequenceNumber'] ?? null)] ?? null;
                if (!is_numeric($seq)) {
                    $seq = null;
                }
                $sequenceNumbers[$i] = $seq;
            }

            $lsItems[$i] = $lsItem;
        }

        // Build associations
        for ($i = 0, $iMax = count($content); $i < $iMax; ++$i) {
            if (null === ($lsItems[$i] ?? null)) {
                continue;
            }

            $lsItem = $lsItems[$i];

            // Check if the lsItems UUID exists in the ls_association table and
            // if it is do not create a new association. This allows content
            // updates but doesn't double up the associations.
            $thisItemsUUID = $lsItem->getIdentifier();
            $associationExists = $em->getRepository(LsAssociation::class)->findOneBy(['originNodeIdentifier' => $thisItemsUUID]);
            $logDetails = date('Y/m/d h:i:s A ')."The lsItem with the Human coding scheme of {$content[$i]['Human Coding Scheme']} and UUID of {$thisItemsUUID} has been added.";

            if (!$associationExists) {
                // Log new items added.
                $errorLog = new ImportLog();
                $errorLog->setLsDoc($lsDoc);
                $errorLog->setMessage($logDetails);
                $errorLog->setMessageType('warning');
                $em->persist($errorLog);

                // check if the item returns a humancodingscheme
                $parent = $content[$i][$lsItemKeys['isChildOf'] ?? null] ?? null;
                if (empty($parent)) {
                    $humanCoding = $lsItem->getHumanCodingScheme();
                    $parent = substr($humanCoding, 0, strrpos($humanCoding, '.'));
                }

                if (array_key_exists($parent, $humanCodingValues)) {
                    $lsItems[$humanCodingValues[$parent]]->addChild($lsItem, null, $sequenceNumbers[$i]);
                } else {
                    $lsDoc->addTopLsItem($lsItem, null, $sequenceNumbers[$i]);
                }

                $this->saveAssociations($i, $content, $lsItemKeys, $lsItem, $lsDoc, $frameworkToAssociate);
            }
        }
    }

    /**
     * @param int       $position
     * @param array     $content
     * @param array     $lsItemKeys
     * @param string    $frameworkToAssociate
     */
    public function saveAssociations($position, $content, $lsItemKeys, LsItem $lsItem, LsDoc $lsDoc, $frameworkToAssociate): void
    {
        $fieldsAndTypes = LsAssociation::allTypesForImportFromCSV();
        // We don't use is_child_of because that it already used to create parents relations before. :)
        // checking each association field
        foreach ($fieldsAndTypes as $fieldName => $assocType) {
            if (array_key_exists($fieldName, $lsItemKeys) && $cfAssociations = $content[$position][trim($lsItemKeys[$fieldName])]) {
                foreach (explode(',', $cfAssociations) as $cfAssociation) {
                    $this->addItemRelated($lsDoc, $lsItem, $cfAssociation, $frameworkToAssociate, $assocType);
                }
            }
        }
    }

    /**
     * @param string  $cfAssociation
     * @param string  $frameworkToAssociate
     * @param string  $assocType
     */
    public function addItemRelated(LsDoc $lsDoc, LsItem $lsItem, $cfAssociation, $frameworkToAssociate, $assocType): void
    {
        $em = $this->getEntityManager();

        if ('' !== trim($cfAssociation)) {
            if ('all' === $frameworkToAssociate) {
                $itemsAssociated = $em->getRepository(LsItem::class)
                    ->findAllByIdentifierOrHumanCodingSchemeByValue($cfAssociation);
            } else {
                $itemsAssociated = $em->getRepository(LsItem::class)
                    ->findByAllIdentifierOrHumanCodingSchemeByLsDoc($frameworkToAssociate, $cfAssociation);
            }

            if (count($itemsAssociated) > 0) {
                foreach ($itemsAssociated as $itemAssociated) {
                    $this->saveAssociation($lsDoc, $lsItem, $itemAssociated, $assocType);
                }
            } else {
                $this->saveAssociation($lsDoc, $lsItem, $cfAssociation, $assocType);
            }
        }
    }

    /**
     * @param string|LsItem $elementAssociated
     * @param string $assocType
     */
    public function saveAssociation(LsDoc $lsDoc, LsItem $lsItem, $elementAssociated, $assocType): void
    {
        $association = new LsAssociation();
        $association->setType($assocType);
        $association->setLsDoc($lsDoc);
        $association->setOrigin($lsItem);

        if (is_string($elementAssociated)) {
            if (Uuid::isValid($elementAssociated)) {
                $association->setDestinationNodeIdentifier($elementAssociated);
            } elseif (false === !filter_var($elementAssociated, FILTER_VALIDATE_URL)) {
                $association->setDestinationNodeUri($elementAssociated);
                $association->setDestinationNodeIdentifier(Uuid::uuid5(Uuid::NAMESPACE_URL, $elementAssociated));
            } else {
                $encodedHumanCodingScheme = $this->encodeHumanCodingScheme($elementAssociated);
                $association->setDestinationNodeUri($encodedHumanCodingScheme);
                $association->setDestinationNodeIdentifier(Uuid::uuid5(Uuid::NAMESPACE_URL, $encodedHumanCodingScheme));
            }
        } else {
            $association->setDestination($elementAssociated);
        }

        $this->getEntityManager()->persist($association);
    }

    /**
     * @param string $humanCodingScheme
     */
    protected function encodeHumanCodingScheme($humanCodingScheme): string
    {
        $prefix = 'data:text/x-ref-unresolved;base64,';

        return $prefix.base64_encode($humanCodingScheme);
    }

    /**
     * @param array $lsItemKeys
     * @param array $data
     */
    public function parseCSVGithubStandard(LsDoc $lsDoc, $lsItemKeys, $data): LsItem
    {
        $em = $this->getEntityManager();

        // Query the db for matching UUIDs.
        $resultOfSearch = $em->getRepository(LsItem::class)->findOneBy(['identifier' => $data[$lsItemKeys['identifier']]]);

        $itemAttributes = ['humanCodingScheme', 'abbreviatedStatement', 'conceptKeywords', 'language', 'license', 'notes'];

        // If not in the DB create a new lsItem.
        if (null === $resultOfSearch) {
            $lsItem = $this->assignValuesToItem(new LsItem(), $lsDoc, $lsItemKeys, $data, $itemAttributes);
            $em->persist($lsItem);

            return $lsItem;
        }

        // Update if in db and changed.
        $fullStatement = $resultOfSearch->getFullStatement();
        if ($data[$lsItemKeys['fullStatement']] !== $fullStatement) {
            $lsItem = $this->assignValuesToItem($resultOfSearch, $lsDoc, $lsItemKeys, $data, $itemAttributes);
            $em->persist($lsItem);

            // Log if we make an update.
            $logDetails = date('Y/m/d h:i:s A ')."The lsItem with the Human coding scheme of {$data[$lsItemKeys['humanCodingScheme']]} has been updated.";
            $errorLog = new ImportLog();
            $errorLog->setLsDoc($lsDoc);
            $errorLog->setMessage($logDetails);
            $errorLog->setMessageType('warning');

            $em->persist($errorLog);

            return $lsItem;
        }

        return $resultOfSearch;
    }

    /**
     * It returns true|false is a line from content has the requried columns.
     */
    private function isValidItemContent(array $lineContent, array $lsItemKeys): bool
    {
        return ($lineContent[$lsItemKeys['fullStatement']] ?? '') !== '';
    }

    /**
     * assign values relatd with the key to a Item.
     */
    private function assignValuesToItem(LsItem $lsItem, LsDoc $lsDoc, array $lsItemKeys, array $lineContent, array $keys): LsItem
    {
        $lsItem->setLsDoc($lsDoc);
        $lsItem->setFullStatement($lineContent[$lsItemKeys['fullStatement']]);

        if (array_key_exists($lsItemKeys['identifier'], $lineContent) && Uuid::isValid($lineContent[$lsItemKeys['identifier']])) {
            $lsItem->setIdentifier($lineContent[$lsItemKeys['identifier']]);
            $lsItem->setUri('local:'.$lineContent[$lsItemKeys['identifier']]);
        }

        foreach ($keys as $key) {
            if ('license' === $key) {
                // Skip loading licence from the CSV for now
                continue;
            }

            if (array_key_exists($key, $lsItemKeys) && array_key_exists($lsItemKeys[$key], $lineContent)) {
                $lsItem->{'set'.ucfirst($key)}($lineContent[$lsItemKeys[$key]]);
            }
        }

        return $lsItem;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>My Project: Ilwis::Point3D< CrdType > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

My Project

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Enumerations

Ilwis

Point3D

Public Member Functions |
List of all members

Ilwis::Point3D< CrdType > Class Template Reference

#include <point.h>

Inheritance diagram for Ilwis::Point3D< CrdType >:

  <map id="Ilwis::Point3D< CrdType >_map" name="Ilwis::Point3D< CrdType >_map">
<area href="class_ilwis_1_1_point.html" alt="Ilwis::Point< CrdType >" shape="rect" coords="0,0,159,24"/>
</map>

Public Member Functions

 	Point3D (CrdType v1, CrdType v2, CrdType v3=0)

 	Point3D (const Point2D< CrdType > &p)

 	Point3D (Point3D< CrdType > &&crd)

 	Point3D (const Point3D< CrdType > &crd)

 	Point3D (const std::vector< CrdType > &v)

template<typename U >

 	Point3D (const Point3D< U > &p)

template<typename U >

 	Point3D (const Point2D< U > &p)

 	operator std::vector< CrdType > ()

CrdType 	z () const

void 	z (CrdType v)

Ilwis::Point3D< CrdType > & 	operator= (const Ilwis::Point2D< CrdType > &p2)

Ilwis::Point3D< CrdType > & 	operator= (const Ilwis::Point3D< CrdType > &p2)

Ilwis::Point3D< CrdType > & 	operator= (const Ilwis::Point3D< CrdType > &&p2)

bool 	is0 () const

Point3D< CrdType > & 	operator+= (const std::vector< CrdType > &vec)

Point3D< CrdType > & 	operator-= (const std::vector< CrdType > &vec)

Point3D< CrdType > & 	operator+= (CrdType v)

Point3D< CrdType > & 	operator*= (const std::vector< CrdType > &vec)

Point3D< CrdType > & 	operator*= (CrdType v)

Point3D< CrdType > & 	operator/= (CrdType v)

double 	distance (const Point3D< CrdType > &crd)

 Public Member Functions inherited from Ilwis::Point< CrdType >

CrdType 	x () const

CrdType 	y () const

void 	x (CrdType v)

void 	y (CrdType v)

bool 	isValid () const

bool 	is0 () const

Additional Inherited Members

 Protected Member Functions inherited from Ilwis::Point< CrdType >

 	Point (CrdType d1, CrdType d2)

void 	init ()

 Protected Attributes inherited from Ilwis::Point< CrdType >

CrdType 	undefined

CrdType 	_x

CrdType 	_y

Detailed Description

template<typename CrdType = qint32>

class Ilwis::Point3D< CrdType >

A point in 3D space. It is a derivative of the Point class. As the base class already offer the x,y components no further implementation of these is needed. The class mostely implements special operations on 3D points and a z coordinate

Constructor & Destructor Documentation

template<typename CrdType = qint32>

          Ilwis::Point3D< CrdType >::Point3D
          (
          CrdType
          v1,

          CrdType
          v2,

          CrdType
          v3 = 0

          )

inline

Basic constructor from three values. The last value maybe left undefined in which case it defaults to zero. This is done to make mixing two dimensional and three dimensional points easier

Parameters

v1	x dimension

v2	y dimension

v3	z dimension

template<typename CrdType = qint32>

          Ilwis::Point3D< CrdType >::Point3D
          (
          const Point2D< CrdType > &
          p	)

inline

Copy constructor for 2D points. It ensure that 2D and 3D points can be interchanged

Parameters

2D	point

Member Function Documentation

template<typename CrdType = qint32>

          Point3D<CrdType>& Ilwis::Point3D< CrdType >::operator*=
          (
          const std::vector< CrdType > &
          vec	)

inline

Multiplies the value of a 3 element vector with the values of coordinate elements. Note that if one the vector values is undefined the behavior of the point becomes undefined. If the vector has not three elements nothing will happen.

Parameters

a	vector with exactly three values.

Returns

the changed point.

template<typename CrdType = qint32>

          Point3D<CrdType>& Ilwis::Point3D< CrdType >::operator*=
          (
          CrdType
          v	)

inline

Multiplies the value with the values of coordinate elements. Note that if one the value is undefined the behavior of the point becomes undefined.

Parameters

a	value for which the multiplication has been defined

Returns

the changed point.

template<typename CrdType = qint32>

          Point3D<CrdType>& Ilwis::Point3D< CrdType >::operator+=
          (
          const std::vector< CrdType > &
          vec	)

inline

Adds the value of a 3 element vector to the values of coordinate elements. Note that if one the vector values is undefined the behavior of the point becomes undefined. If the vector has not three elements nothing will happen.

Parameters

a	vector with exactly three values.

Returns

the changed point.

template<typename CrdType = qint32>

          Point3D<CrdType>& Ilwis::Point3D< CrdType >::operator/=
          (
          CrdType
          v	)

inline

Divides the value with the values of coordinate elements. Note that if one the value is undefined the behavior of the point becomes undefined. if the division factor is 0 nothing will happen

Parameters

a	value for which the division has been defined

Returns

the changed point.

template<typename CrdType = qint32>

          Ilwis::Point3D<CrdType>& Ilwis::Point3D< CrdType >::operator=
          (
          const Ilwis::Point2D< CrdType > &
          p2	)

inline

Assigns a the values of a 2D point to a 3D point. The z is set to 0

Parameters

p2

Returns

template<typename CrdType = qint32>

          CrdType Ilwis::Point3D< CrdType >::z
          (
          	)
           const

inline

returns the z value of a point

Returns

z value

template<typename CrdType = qint32>

          void Ilwis::Point3D< CrdType >::z
          (
          CrdType
          v	)

inline

sets the z value of a point

Parameters

z	value

The documentation for this class was generated from the following file:

Ilwis4/Ilwis4/projects/IlwisCore/core/util/point.h

<address class="footer">
Generated on Wed Jan 22 2014 12:04:10 for My Project by

 1.8.5
</address>

redpajama_set_name: RedPajamaGithub


text:
extern zend_class_entry *zephirperformance_zephirperformance_ce;

ZEPHIR_INIT_CLASS(ZephirPerformance_ZephirPerformance);

PHP_METHOD(ZephirPerformance_ZephirPerformance, guid);
PHP_METHOD(ZephirPerformance_ZephirPerformance, batch);

ZEND_BEGIN_ARG_INFO_EX(arginfo_zephirperformance_zephirperformance_batch, 0, 0, 0)
	ZEND_ARG_INFO(0, count)
ZEND_END_ARG_INFO()

ZEPHIR_INIT_FUNCS(zephirperformance_zephirperformance_method_entry) {
	PHP_ME(ZephirPerformance_ZephirPerformance, guid, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	PHP_ME(ZephirPerformance_ZephirPerformance, batch, arginfo_zephirperformance_zephirperformance_batch, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
  PHP_FE_END
};


text:
@implementation VCRURLSessionTestsHelper

+ (NSString *)pathToCassetteWithName:(NSString *)name
{
    NSURL *baseURL = [NSURL URLWithString:@(CASSETTES_ROOT)];
    return [[baseURL URLByAppendingPathComponent:name] path];
}

@end


text:
#ifndef ORILIB_ETHINTERFACEINIT_T_H
#define ORILIB_ETHINTERFACEINIT_T_H

#include "ORILIB_t.h"

typedef struct {
    Uint8 nodeId;
} ORILIB_t_EthInterfaceConf;

#endif /* ORILIB_ETHINTERFACEINIT_T_H */


text:
package com.amazonaws.services.greengrass.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.greengrass.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ResourceAccessPolicyMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ResourceAccessPolicyMarshaller {

    private static final MarshallingInfo<String> PERMISSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Permission").build();
    private static final MarshallingInfo<String> RESOURCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ResourceId").build();

    private static final ResourceAccessPolicyMarshaller instance = new ResourceAccessPolicyMarshaller();

    public static ResourceAccessPolicyMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ResourceAccessPolicy resourceAccessPolicy, ProtocolMarshaller protocolMarshaller) {

        if (resourceAccessPolicy == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(resourceAccessPolicy.getPermission(), PERMISSION_BINDING);
            protocolMarshaller.marshall(resourceAccessPolicy.getResourceId(), RESOURCEID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
#pragma once

#include <lib/conversion/rotation.h>
#include <lib/matrix/matrix/math.hpp>
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/log.h>
#include <uORB/Subscription.hpp>
#include <uORB/topics/sensor_correction.h>

namespace calibration
{
class Accelerometer
{
public:
	static constexpr int MAX_SENSOR_COUNT = 4;

	static constexpr uint8_t DEFAULT_PRIORITY = 50;
	static constexpr uint8_t DEFAULT_EXTERNAL_PRIORITY = 25;

	static constexpr const char *SensorString() { return "ACC"; }

	Accelerometer();
	explicit Accelerometer(uint32_t device_id, bool external = false);

	~Accelerometer() = default;

	void PrintStatus();

	void set_calibration_index(uint8_t calibration_index) { _calibration_index = calibration_index; }
	void set_device_id(uint32_t device_id, bool external = false);
	void set_external(bool external = true);
	void set_offset(const matrix::Vector3f &offset) { _offset = offset; }
	void set_scale(const matrix::Vector3f &scale) { _scale = scale; }
	void set_rotation(Rotation rotation);

	uint8_t calibration_count() const { return _calibration_count; }
	uint32_t device_id() const { return _device_id; }
	bool enabled() const { return (_priority > 0); }
	bool external() const { return _external; }
	const int32_t &priority() const { return _priority; }
	const matrix::Dcmf &rotation() const { return _rotation; }
	const Rotation &rotation_enum() const { return _rotation_enum; }

	// apply offsets and scale
	// rotate corrected measurements from sensor to body frame
	inline matrix::Vector3f Correct(const matrix::Vector3f &data) const
	{
		return _rotation * matrix::Vector3f{(data - _thermal_offset - _offset).emult(_scale)};
	}

	bool ParametersSave();
	void ParametersUpdate();

	void Reset();

	void SensorCorrectionsUpdate(bool force = false);

private:
	uORB::Subscription _sensor_correction_sub{ORB_ID(sensor_correction)};

	Rotation _rotation_enum{ROTATION_NONE};

	matrix::Dcmf _rotation;
	matrix::Vector3f _offset;
	matrix::Vector3f _scale;
	matrix::Vector3f _thermal_offset;

	int8_t _calibration_index{-1};
	uint32_t _device_id{0};
	int32_t _priority{-1};

	bool _external{false};

	uint8_t _calibration_count{0};
};
} // namespace calibration


text:
package nl.knaw.huygens.timbuctoo.rml;

import com.google.common.collect.Maps;
import nl.knaw.huygens.timbuctoo.rml.datasource.JoinHandler;
import nl.knaw.huygens.timbuctoo.rml.datasource.joinhandlers.HashMapBasedJoinHandler;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static nl.knaw.huygens.timbuctoo.util.StreamIterator.stream;

class TestDataSource implements DataSource {
  private final Iterable<Map<String, String>> data;
  private final ErrorHandler errorHandler;
  private final JoinHandler joinHandler = new HashMapBasedJoinHandler();

  TestDataSource(Iterable<Map<String, String>> data) {
    this(data, null);
  }

  TestDataSource(Iterable<Map<String, String>> data, ErrorHandler errorHandler) {
    this.data = data;
    this.errorHandler = errorHandler;
  }

  @Override
  public Stream<Row> getRows(ErrorHandler defaultErrorHandler) {
    return stream(data.iterator())
      .map(values -> {
        Map<String, String> mutableValues = Maps.newHashMap(values);
        Map<String, List<String>> joinValues = joinHandler.resolveReferences(mutableValues);

        Set<String> unMappedKeys = mutableValues.keySet().stream()
          .filter(key -> mutableValues.get(key) == null || mutableValues.get(key).isEmpty())
          .collect(Collectors.toSet());

        for (String key : unMappedKeys) {
          mutableValues.remove(key);
        }
        return (Row) new TestRow(mutableValues, joinValues, errorHandler == null ? defaultErrorHandler : errorHandler);
      });
  }

  @Override
  public void willBeJoinedOn(String fieldName, String referenceJoinValue, String uri, String outputFieldName) {
    joinHandler.willBeJoinedOn(fieldName, referenceJoinValue, uri, outputFieldName);
  }

}


text:
docker run -it -p 8080:8080 --rm rahmanusta/tryjshell

#run local on arm64
docker run -it -p 8080:8080 --rm rahmanusta/tryjshell.arm

sudo docker run --name nginx-proxy -dit --restart unless-stopped \
    --publish 80:80 \
    --publish 443:443 \
    --volume /etc/nginx/certs \
    --volume /etc/nginx/vhost.d \
    --volume /usr/share/nginx/html \
    --volume /var/run/docker.sock:/tmp/docker.sock:ro \
    nginxproxy/nginx-proxy

sudo docker run --name nginx-proxy-letsencrypt -dit --restart unless-stopped \
    --volumes-from nginx-proxy \
    --volume /var/run/docker.sock:/var/run/docker.sock:ro \
    --env "DEFAULT_EMAIL=rahman.usta.88@gmail.com" \
    jrcs/letsencrypt-nginx-proxy-companion

sudo docker run --name tryjshell -dit --restart unless-stopped --expose 8080 \
    --env "VIRTUAL_HOST=www.tryjshell.org,tryjshell.org" \
    --env "VIRTUAL_PORT=8080" \
    --env "LETSENCRYPT_HOST=www.tryjshell.org,tryjshell.org" \
    --env "LETSENCRYPT_EMAIL=rahman.usta.88@gmail.com" \
    rahmanusta/tryjshell.arm


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddNewCriteriaJPanel.java
 *
 * Created on Jun 24, 2011, 6:14:10 AM
 */

package presentation.guiForPredictionAlgorithmEvaluation;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;

import business.predictionAlgorithmEvaluation.PredictionCriteria;

/**
 *
 * @author Dinh
 */
public class AddNewPreEvaCriteriaJPanel extends javax.swing.JPanel {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private JDialog parent;
	private boolean ok;
	private PredictionCriteria predictionCriteria;

	public boolean isOk() {
		return ok;
	}

	public PredictionCriteria getPredictionCriteria() {
		return predictionCriteria;
	}

	/** Creates new form AddNewCriteriaJPanel */
	public AddNewPreEvaCriteriaJPanel(JDialog jDialog) {
		this.parent = jDialog;
		initComponents();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		preEvaCriJLabel = new javax.swing.JLabel();
		preEvaCriJComboBox = new javax.swing.JComboBox();
		cancelJButton = new javax.swing.JButton();
		okJButton = new javax.swing.JButton();

		preEvaCriJLabel.setFont(new java.awt.Font("Tahoma", 1, 11));
		preEvaCriJLabel.setText("Prediction Evaluation Criteria:");

		preEvaCriJComboBox
				.setModel(new DefaultComboBoxModel(
						business.predictionAlgorithmEvaluation.PredictionAlgorithmEvaluationAPI.PREDICTION_CRITERIA_LIST));

		cancelJButton.setText("Cancel");
		cancelJButton.addActionListener(new java.awt.event.ActionListener() {
			@Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				cancelJButtonActionPerformed(evt);
			}
		});

		okJButton.setText("OK");
		okJButton.addActionListener(new java.awt.event.ActionListener() {
			@Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				okJButtonActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
		this.setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(preEvaCriJLabel)
								.addGap(18, 18, 18)
								.addComponent(preEvaCriJComboBox,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addContainerGap(38, Short.MAX_VALUE))
				.addGroup(
						javax.swing.GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap(111, Short.MAX_VALUE)
								.addComponent(okJButton)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addComponent(cancelJButton).addContainerGap()));

		layout.linkSize(javax.swing.SwingConstants.HORIZONTAL,
				new java.awt.Component[] { cancelJButton, okJButton });

		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(preEvaCriJLabel)
												.addComponent(
														preEvaCriJComboBox,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addGap(18, 18, 18)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(cancelJButton)
												.addComponent(okJButton))
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		layout.linkSize(javax.swing.SwingConstants.VERTICAL,
				new java.awt.Component[] { cancelJButton, okJButton });

	}// </editor-fold>//GEN-END:initComponents

	private void okJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_okJButtonActionPerformed
		ok = true;

		predictionCriteria = business.predictionAlgorithmEvaluation.PredictionAlgorithmEvaluationAPI
				.getPredictionAlgorithm((String) preEvaCriJComboBox
						.getSelectedItem());

		this.parent.dispose();
	}// GEN-LAST:event_okJButtonActionPerformed

	private void cancelJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cancelJButtonActionPerformed
		ok = false;

		this.parent.dispose();
	}// GEN-LAST:event_cancelJButtonActionPerformed

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton cancelJButton;
	private javax.swing.JButton okJButton;
	private javax.swing.JComboBox preEvaCriJComboBox;
	private javax.swing.JLabel preEvaCriJLabel;

	// End of variables declaration//GEN-END:variables

	public JDialog getParentDialog() {
		return parent;
	}

}


text:
package br.com.transmetais.dao;

import br.com.transmetais.bean.Unidade;
import br.com.transmetais.dao.commons.CrudDAO;

public interface UnidadeDAO extends CrudDAO<Unidade>{

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ aem-sling-contrib
  ~ https://github.com/dherges/aem-sling-contrib
  ~
  ~ Copyright (c) 2016 David Herges
  ~ Licensed under the MIT license.
  -->

<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:Dialog"
    title="Button"
    xtype="tabpanel">
    <items jcr:primaryType="cq:WidgetCollection">
        <settings
            jcr:primaryType="cq:Widget"
            title="Settings"
            xtype="panel">
            <items jcr:primaryType="cq:WidgetCollection">
                <text
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Text"
                    name="./text"
                    xtype="textfield"/>
                <href
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Link Target"
                    fieldDescription="Link is only shown when HTML tag name is <a>"
                    name="./href"
                    xtype="pathfield"/>
            </items>
        </settings>
        <display
            jcr:primaryType="cq:Widget"
            title="Display"
            xtype="panel">
            <items jcr:primaryType="cq:WidgetCollection">
                <htmlTagName
                    jcr:primaryType="cq:Widget"
                    defaultValue="a"
                    fieldLabel="HTML Tag Name"
                    name="./htmlTagName"
                    type="select"
                    xtype="selection">
                    <options jcr:primaryType="cq:WidgetCollection">
                        <a
                            jcr:primaryType="nt:unstructured"
                            text="a"
                            value="a"/>
                        <button
                            jcr:primaryType="nt:unstructured"
                            text="button"
                            value="button"/>
                    </options>
                </htmlTagName>
                <cssButtonType
                    jcr:primaryType="cq:Widget"
                    defaultValue="btn-default"
                    fieldLabel="Button Type"
                    name="./cssButtonType"
                    type="select"
                    xtype="selection">
                    <options jcr:primaryType="cq:WidgetCollection">
                        <default
                            jcr:primaryType="nt:unstructured"
                            text="btn-default"
                            value="btn-default"/>
                        <primary
                            jcr:primaryType="nt:unstructured"
                            text="btn-primary"
                            value="btn-primary"/>
                        <success
                            jcr:primaryType="nt:unstructured"
                            text="btn-success"
                            value="btn-success"/>
                        <info
                            jcr:primaryType="nt:unstructured"
                            text="btn-info"
                            value="btn-info"/>
                        <warning
                            jcr:primaryType="nt:unstructured"
                            text="btn-warning"
                            value="btn-warning"/>
                        <danger
                            jcr:primaryType="nt:unstructured"
                            text="btn-danger"
                            value="btn-danger"/>
                        <link
                            jcr:primaryType="nt:unstructured"
                            text="btn-link"
                            value="btn-link"/>
                  </options>
                </cssButtonType>
                <cssSize
                    jcr:primaryType="cq:Widget"
                    defaultValue=""
                    fieldLabel="Button Size"
                    name="./cssButtonSize"
                    type="select"
                    xtype="selection">
                    <options jcr:primaryType="cq:WidgetCollection">
                        <default
                            jcr:primaryType="nt:unstructured"
                            text="Default"
                            value=""/>
                        <large
                            jcr:primaryType="nt:unstructured"
                            text="btn-lg"
                            value="btn-lg"/>
                        <small
                            jcr:primaryType="nt:unstructured"
                            text="btn-sm"
                            value="btn-sm"/>
                        <extrasmall
                            jcr:primaryType="nt:unstructured"
                            text="btn-xs"
                            value="btn-xs"/>
                  </options>
                </cssSize>
                <blockLevel
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Block Level?"
                    name="./isBlockLevel"
                    type="checkbox"
                    xtype="selection"/>
                <disabled
                    jcr:primaryType="cq:Widget"
                    fieldLabel="Disabled?"
                    name="./isDisabled"
                    type="checkbox"
                    xtype="selection"/>
          </items>
      </display>
    </items>
</jcr:root>


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class DatastoreDestroyedEvent extends DatastoreEvent {
}


text:
FROM golang:1.13

RUN mkdir -p /go/src/github.com/eventials/go-tus

WORKDIR /go/src/github.com/eventials/go-tus

RUN go get github.com/stretchr/testify
RUN go get github.com/tus/tusd
RUN go get github.com/syndtr/goleveldb/leveldb


text:
package org.apache.eagle.jpm.analyzer.mr.suggestion;

import com.typesafe.config.Config;
import org.apache.eagle.jpm.analyzer.Evaluator;
import org.apache.eagle.jpm.analyzer.Processor;
import org.apache.eagle.jpm.mr.historyentity.JobSuggestionAPIEntity;
import org.apache.eagle.jpm.analyzer.meta.model.MapReduceAnalyzerEntity;
import org.apache.eagle.jpm.analyzer.publisher.Result;
import org.apache.eagle.jpm.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.eagle.jpm.util.MRJobTagName.*;

public class JobSuggestionEvaluator implements Evaluator<MapReduceAnalyzerEntity>, Serializable {
    private static final Logger LOG = LoggerFactory.getLogger(JobSuggestionEvaluator.class);

    private Config config;

    public JobSuggestionEvaluator(Config config) {
        this.config = config;
    }

    private List<Processor> loadProcessors(MapReduceJobSuggestionContext context) {
        List<Processor> processors = new ArrayList<>();
        processors.add(new MapReduceCompressionSettingProcessor(context));
        processors.add(new MapReduceSplitSettingProcessor(context));
        processors.add(new MapReduceDataSkewProcessor(context));
        processors.add(new MapReduceGCTimeProcessor(context));
        processors.add(new MapReduceSpillProcessor(context));
        processors.add(new MapReduceTaskNumProcessor(context));
        //processors.add(new MapReduceQueueResourceProcessor(context));

        return processors;
    }

    @Override
    public Result.EvaluatorResult evaluate(MapReduceAnalyzerEntity analyzerEntity) {
        if (analyzerEntity.getCurrentState().equalsIgnoreCase(Constants.JobState.RUNNING.toString())) {
            return null;
        }

        if (analyzerEntity.getTotalCounters() == null) {
            LOG.warn("Total counters of Job {} is null", analyzerEntity.getJobId());
            return null;
        }
        if (analyzerEntity.getMapCounters() == null && analyzerEntity.getReduceCounters() == null) {
            LOG.warn("Map/Reduce task counters of Job {} are null", analyzerEntity.getJobId());
            return null;
        }

        try {
            Result.EvaluatorResult result = new Result.EvaluatorResult();

            MapReduceJobSuggestionContext jobContext = new MapReduceJobSuggestionContext(analyzerEntity);
            if (jobContext.getNumMaps() == 0) {
                return null;
            }

            for (Processor processor : loadProcessors(jobContext)) {
                Result.ProcessorResult processorResult = processor.process(analyzerEntity);
                if (processorResult != null) {
                    result.addProcessorResult(processor.getClass(), processorResult);
                    result.addProcessorEntity(processor.getClass(), createJobSuggestionEntity(processorResult, analyzerEntity));
                }
            }
            return result;
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
            return null;
        }

    }

    private static JobSuggestionAPIEntity createJobSuggestionEntity(Result.ProcessorResult processorResult, MapReduceAnalyzerEntity entity) {
        Map<String, String> tags = new HashMap<>();
        tags.put(JOB_ID.toString(), entity.getJobId());
        tags.put(JOD_DEF_ID.toString(), entity.getJobDefId());
        tags.put(SITE.toString(), entity.getSiteId());
        tags.put(USER.toString(), entity.getUserId());
        tags.put(RULE_TYPE.toString(), processorResult.getRuleType().toString());
        tags.put(JOB_QUEUE.toString(), entity.getJobQueueName());
        tags.put(JOB_TYPE.toString(), entity.getJobType());
        JobSuggestionAPIEntity jobSuggestionAPIEntity = new JobSuggestionAPIEntity();
        jobSuggestionAPIEntity.setTags(tags);
        jobSuggestionAPIEntity.setTimestamp(entity.getStartTime());  // startTime as the job timestamp
        jobSuggestionAPIEntity.setOptimizerSuggestion(processorResult.getMessage());
        jobSuggestionAPIEntity.setOptimizerSettings(processorResult.getSettings());

        return jobSuggestionAPIEntity;
    }

}


text:
'use strict';

const elements = require('../utils/editor-elements.js');
const expectation = require('../utils/expectation.js');
const errors = require('../utils/error-list.js');

const consoleDdl = elements.getDdlConsole();
const cheatElementList = elements.getCheatElementList();
const moreCheatButton = elements.getMoreCheatsButton();
const xmlCheatCount = elements.getXmlCheatCount();

const sampleCode = `abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
012345679:0123 456 789:0,1&~#!`;
const sampleCodeExpected = {
  GameShark: 'ABCDEFAB,CDEF0123,45679012,34567890',
  'Game Genie': 'ABCD:EF,ABCD:EF,0123:45,6790:12,3456:78',
  Raw: 'ABCD:EF,ABCD:EF,0123:45,6790:12,3456:78'
};

module.exports = {
  addCheats,
  addOneCheat,
  removeCheats,
  removeOneCheat,
  consoleChanges
};

///////////////////////////////////////////////////////////////////////////

function addOneCheat(){
  browser.get('#/editor');
  const cheat = elements.getCheatElementWrapper(0);

  expect(cheatElementList.count()).toBe(0);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', 'No cheat code');
  expect(elements.getXmlCheatLines().count()).toBe(0);

  moreCheatButton.click();

  expect(cheatElementList.count()).toBe(1);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', 'Cheat #1 has no name');
  expect(elements.getXmlCheatLines().count()).toBe(1);
  expect(elements.getCheatElementLegend(0).getText()).toBe('Cheat #1 remove');
  expectation.expectCheat(cheat).toHave('', '', 'GameShark', '');
  expect(cheat.placeHolder()).not.toBe('');

  testFormat();
  testName();
  testHacker();
  testCode();
  testAll();

  //////////////////////////////////

  function testFormat(){
    resetCheat(cheat);
    doTest('GameShark');
    doTest('Game Genie');

    function doTest(format){
      cheat.format(format);

      expect(cheat.format()).toBe(format);
      expect(cheatElementList.count()).toBe(1);
      expect(xmlCheatCount.getText()).toBe('"0"');
      expect(elements.getXmlCheatLines().count()).toBe(1);

      if(!format){
        errors.expect.toContain('Cheat #1 has no format');
      }else{
        errors.expect.not.toContain('Cheat #1 has no format');
      }
    }
  }

  function testName(){
    resetCheat(cheat);
    doTest('');
    doTest('short name');
    doTest('very very very loooooong name, too much long, longer name ever written');

    function doTest(name){
      cheat
        .format('GameShark')
        .name(name);

      expect(cheat.name()).toBe(name.substr(0, 50));
      expect(cheatElementList.count()).toBe(1);
      expect(xmlCheatCount.getText()).toBe('"0"');
      expect(elements.getXmlCheatLines().count()).toBe(1);
      errors.expect.toBeKo();

      if(!name){
        errors.expect.toContain('Cheat #1 has no name');
      }else{
        errors.expect.not.toContain('Cheat #1 has no name');
      }
    }
  }

  function testHacker(){
    resetCheat(cheat);
    doTest('');
    doTest('short hacker name');
    doTest('very very very loooooong hacker name, too much long, longer hacker name ever written');

    function doTest(hacker){
      cheat
        .format('GameShark')
        .name('name')
        .hacker(hacker);

      expect(cheat.hacker()).toBe(hacker.substr(0, 50));
      expect(cheatElementList.count()).toBe(1);
      expect(xmlCheatCount.getText()).toBe('"0"');
      expect(elements.getXmlCheatLines().count()).toBe(1);
    }
  }

  function testCode(){
    resetCheat(cheat);
    doTest('');
    doTest(sampleCode);

    function doTest(code){
      let expectedCount = 0;
      cheat
        .format('GameShark')
        .name('some name')
        .code(code);

      expect(cheat.code()).toBe(code);
      expect(cheatElementList.count()).toBe(1);

      if(!code){
        errors.expect.toBeKoWith('Cheats Errors', 'Cheat #1 has invalid code');
      }else{
        expectedCount = 1;
        errors.expect.toBeKoWithout('Cheats Errors');
      }

      expect(xmlCheatCount.getText()).toBe(`"${expectedCount}"`);
      expect(elements.getXmlCheatLines().count()).toBe(1);
    }
  }

  function testAll(){
    resetCheat(cheat);
    cheat
      .name('some cheat')
      .format('GameShark')
      .code(sampleCode);

    expectation.expectCheat(cheat).toHave('some cheat', '', 'GameShark', sampleCode);
    expect(cheatElementList.count()).toBe(1);
    expect(xmlCheatCount.getText()).toBe('"1"');
    errors.expect.toBeKoWithout('Cheats Errors');
    expect(elements.getXmlCheatLines().count()).toBe(1);

    const xmlCheat = elements.getXmlCheatWrapper(0);
    expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"Unknown"', '"GameShark"', sampleCodeExpected.GameShark);

    cheat.hacker('someone');
    expectation.expectCheat(cheat).toHave('some cheat', 'someone', 'GameShark', sampleCode);
    expect(cheatElementList.count()).toBe(1);
    expect(xmlCheatCount.getText()).toBe('"1"');
    errors.expect.toBeKoWithout('Cheats Errors');

    expect(elements.getXmlCheatLines().count()).toBe(1);
    expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"someone"', '"GameShark"', sampleCodeExpected.GameShark);

    cheat.format('Game Genie');
    expectation.expectCheat(cheat).toHave('some cheat', 'someone', 'Game Genie', sampleCode);
    expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"someone"', '"Game Genie"', sampleCodeExpected['Game Genie']);
  }
}

///////////////////////////////////////////////////////////////////////////

function removeOneCheat(){
  browser.get('#/editor');

  const cheat = elements.getCheatElementWrapper(0);

  expect(cheatElementList.count()).toBe(0);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', 'No cheat code');

  moreCheatButton.click();
  expect(cheatElementList.count()).toBe(1);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', 'Cheat #1 has no name');
  expect(elements.getXmlCheatLines().count()).toBe(1);

  expect(elements.getCheatElementLegend(0).getText()).toBe('Cheat #1 remove');

  cheat
    .name('some cheat')
    .hacker('someone')
    .format('GameShark')
    .code(sampleCode);

  expect(cheatElementList.count()).toBe(1);
  expect(xmlCheatCount.getText()).toBe('"1"');
  errors.expect.toBeKoWithout('Cheats Errors');
  expect(elements.getXmlCheatLines().count()).toBe(1);

  const xmlCheat = elements.getXmlCheatWrapper(0);
  expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"someone"', '"GameShark"', sampleCodeExpected.GameShark);

  elements.getCheatRemoveButton(0).click();
  expect(cheatElementList.count()).toBe(0);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', 'No cheat code');
  expect(elements.getXmlCheatLines().count()).toBe(0);
}

///////////////////////////////////////////////////////////////////////////

function addCheats(){
  browser.get('#/editor');

  const cheats = [
    elements.getCheatElementWrapper(0),
    elements.getCheatElementWrapper(1)
  ];
  const xmlCheats = [
    elements.getXmlCheatWrapper(0),
    elements.getXmlCheatWrapper(1)
  ];
  const expectedErrors = [];

  expect(cheatElementList.count()).toBe(0);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', 'No cheat code');
  expect(elements.getXmlCheatLines().count()).toBe(0);

  for(let j=0; j<cheats.length; j++){
    moreCheatButton.click();
    expectedErrors.push(`Cheat #${j+1} has no name`);
  }

  expect(cheatElementList.count()).toBe(cheats.length);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', expectedErrors);
  expect(elements.getXmlCheatLines().count()).toBe(cheats.length);

  cheats.forEach((cheat, i) => {
    expect(elements.getCheatElementLegend(i).getText()).toBe(`Cheat #${i+1} remove`);
    expectation.expectCheat(cheat).toHave('', '', 'GameShark', '');
  });

  cheats[0]
    .name('some cheat')
    .hacker('someone')
    .format('GameShark')
    .code('1234567812345678');

  expect(elements.getXmlCheatLines().count()).toBe(cheats.length);

  cheats[1]
    .name('another cheat')
    .hacker('another guy')
    .format('Game Genie')
    .code('ABCDEF');

  expect(elements.getXmlCheatLines().count()).toBe(cheats.length);
  expect(cheatElementList.count()).toBe(cheats.length);
  expect(xmlCheatCount.getText()).toBe(`"${cheats.length}"`);
  errors.expect.toBeKoWithout('Cheats Errors');

  expectation.expectCheat(cheats[0]).toHave('some cheat', 'someone', 'GameShark', '1234567812345678');
  expectation.expectCheat(cheats[1]).toHave('another cheat', 'another guy', 'Game Genie', 'ABCDEF');

  expectation.expectCheat(xmlCheats[0]).toHave('"some cheat"', '"someone"', '"GameShark"', '12345678,12345678');
  expectation.expectCheat(xmlCheats[1]).toHave('"another cheat"', '"another guy"', '"Game Genie"', 'ABCD:EF');
}

///////////////////////////////////////////////////////////////////////////

function removeCheats(){
  browser.get('#/editor');

  const cheat = elements.getCheatElementWrapper;
  const xmlCheat = elements.getXmlCheatWrapper;
  let cheatCount = 3;
  const expectedErrors = [];

  expect(cheatElementList.count()).toBe(0);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', 'No cheat code');
  expect(elements.getXmlCheatLines().count()).toBe(0);

  for(let j=0; j<cheatCount; j++){
    moreCheatButton.click();
    expectedErrors.push(`Cheat #${j+1} has no name`);
  }

  expect(cheatElementList.count()).toBe(cheatCount);
  expect(xmlCheatCount.getText()).toBe('"0"');
  errors.expect.toBeKoWith('Cheats Errors', expectedErrors);
  expect(elements.getXmlCheatLines().count()).toBe(cheatCount);

  cheat(0)
    .name('some cheat')
    .hacker('someone')
    .format('GameShark')
    .code('1234567812345678');

  cheat(1)
    .name('another cheat')
    .hacker('another guy')
    .format('Game Genie')
    .code('ABCDEF');

  cheat(2)
    .name('third cheat')
    .hacker('third guy')
    .format('GameShark')
    .code('01CDEF01');

  expect(elements.getXmlCheatLines().count()).toBe(cheatCount);
  expect(cheatElementList.count()).toBe(cheatCount);
  expect(xmlCheatCount.getText()).toBe(`"${cheatCount}"`);
  errors.expect.toBeKoWithout('Cheats Errors');

  deleteCheat(1);
  checkCheat(
    0,
    ['some cheat', 'someone', 'GameShark', '1234567812345678'],
    ['"some cheat"', '"someone"', '"GameShark"', '12345678,12345678']
  );
  checkCheat(
    1,
    ['third cheat', 'third guy', 'GameShark', '01CDEF01'],
    ['"third cheat"', '"third guy"', '"GameShark"', '01CDEF01']
  );

  deleteCheat(0);
  checkCheat(
    0,
    ['third cheat', 'third guy', 'GameShark', '01CDEF01'],
    ['"third cheat"', '"third guy"', '"GameShark"', '01CDEF01']
  );

  deleteCheat(0);

  //////////////////////////////////

  function deleteCheat(id){
    elements.getCheatRemoveButton(id).click();
    cheatCount--;
    expect(elements.getXmlCheatLines().count()).toBe(cheatCount);
    expect(cheatElementList.count()).toBe(cheatCount);
    expect(xmlCheatCount.getText()).toBe(`"${cheatCount}"`);

    if(cheatCount > 0){
      errors.expect.toBeKoWithout('Cheats Errors');
    }else{
      errors.expect.toBeKoWith('Cheats Errors', 'No cheat code');
    }
  }

  function checkCheat(id, cheatProperties, xmlCheatValues){
    expectation.expectCheat(cheat(id)).toHave.apply(null, cheatProperties);
    expect(elements.getCheatElementLegend(id).getText()).toBe(`Cheat #${id+1} remove`);
    expectation.expectCheat(xmlCheat(id)).toHave.apply(null, xmlCheatValues);
  }
}

///////////////////////////////////////////////////////////////////////////

function consoleChanges(){
  browser.get('#/editor');

  const cheat = elements.getCheatElementWrapper(0);

  expect(elements.getXmlCheatLines().count()).toBe(0);
  moreCheatButton.click();
  expect(elements.getXmlCheatLines().count()).toBe(1);
  expect(elements.getCheatElementLegend(0).getText()).toBe('Cheat #1 remove');
  expectation.expectCheat(cheat).toHave('', '', 'GameShark', '');

  const oldPlaceHolder = cheat.placeHolder();
  expect(oldPlaceHolder).not.toBe('');

  cheat
    .name('some cheat')
    .hacker('someone')
    .format('GameShark')
    .code(sampleCode);

  expectation.expectCheat(cheat).toHave('some cheat', 'someone', 'GameShark', sampleCode);
  expect(cheatElementList.count()).toBe(1);
  expect(xmlCheatCount.getText()).toBe('"1"');
  errors.expect.toBeKoWithout('Cheats Errors');

  expect(elements.getXmlCheatLines().count()).toBe(1);

  const xmlCheat = elements.getXmlCheatWrapper(0);
  expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"someone"', '"GameShark"', sampleCodeExpected.GameShark);

  consoleDdl('NES');

  expectation.expectCheat(cheat).toHave('some cheat', 'someone', 'Raw', sampleCode);
  expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"someone"', '"Raw"', sampleCodeExpected.Raw);

  cheat.code('');

  expect(cheat.placeHolder()).not.toBe('');
  expect(cheat.placeHolder()).not.toBe(oldPlaceHolder);

  elements.getCheatRemoveButton(0).click();
  expect(elements.getXmlCheatLines().count()).toBe(0);
  expect(cheatElementList.count()).toBe(0);
  moreCheatButton.click();
  expect(elements.getXmlCheatLines().count()).toBe(1);
  expect(cheatElementList.count()).toBe(1);

  cheat
    .name('some cheat')
    .hacker('someone')
    .code(sampleCode);

  expectation.expectCheat(cheat).toHave('some cheat', 'someone', 'Raw', sampleCode);
  expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"someone"', '"Raw"', sampleCodeExpected.Raw);

  consoleDdl('Game Boy');
  expectation.expectCheat(cheat).toHave('some cheat', 'someone', 'GameShark', sampleCode);
  expectation.expectCheat(xmlCheat).toHave('"some cheat"', '"someone"', '"GameShark"', sampleCodeExpected.GameShark);
}

///////////////////////////////////////////////////////////////////////////

function resetCheat(cheat){
  cheat
    .name('')
    .hacker('')
    .format('GameShark')
    .code('');
}


text:
import json
from ctypes import *
import logging
from typing import Optional

from vcx.common import do_call, create_cb, do_call_sync

async def vcx_agent_provision(config: str) -> None:
    """
    Provision an agent in the agency, populate configuration and wallet for this agent.
    Example:
    import json
    enterprise_config = {
        'agency_url': 'http://localhost:8080',
        'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
        'agency_verkey': "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR",
        'wallet_name': 'LIBVCX_SDK_WALLET',
        'agent_seed': '00000000000000000000000001234561',
        'enterprise_seed': '000000000000000000000000Trustee1',
        'wallet_key': '1234'
    }
    vcx_config = await vcx_agent_provision(json.dumps(enterprise_config))
    :param config: JSON configuration
    :return: Configuration for vcx_init call.
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_agent_provision, "cb"):
        logger.debug("vcx_agent_provision: Creating callback")
        vcx_agent_provision.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_char_p))

    c_config = c_char_p(config.encode('utf-8'))

    result = await do_call('vcx_agent_provision_async',
                           c_config,
                           vcx_agent_provision.cb)

    logger.debug("vcx_agent_provision completed")
    return result.decode()

async def vcx_agent_update_info(config: str) -> None:
    """
    Update information on the agent (ie, comm method and type)
    :param config:
    :return:
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_agent_update_info, "cb"):
        logger.debug("vcx_agent_update_info: Creating callback")
        vcx_agent_update_info.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32))

    c_config = c_char_p(config.encode('utf-8'))

    result = await do_call('vcx_agent_update_info',
                           c_config,
                           vcx_agent_update_info.cb)

    logger.debug("vcx_agent_update_info completed")
    return result

async def vcx_ledger_get_fees() -> str:
    """
    Get ledger fees from the sovrin network
    Example:
    fees = await vcx_ledger_get_fees()
    :return: JSON representing fees
        { "txnType1": amount1, "txnType2": amount2, ..., "txnTypeN": amountN }
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_ledger_get_fees, "cb"):
        logger.debug("vcx_ledger_get_fees: Creating callback")
        vcx_ledger_get_fees.cb = create_cb(CFUNCTYPE(None, c_uint32))

    result = await do_call('vcx_ledger_get_fees',
                           vcx_ledger_get_fees.cb)

    logger.debug("vcx_ledger_get_fees completed")
    return result

async def vcx_messages_download(status: str = None, uids: str = None, pw_dids: str = None) -> str:
    """
    Retrieve messages from the agent
    :param status: optional, comma separated - query for messages with the specified status.
                                     Possible statuses:
                                     MS-101 - Created
                                     MS-102 - Sent
                                     MS-103 - Received
                                     MS-104 - Accepted
                                     MS-105 - Rejected
                                     MS-106 - Reviewed
    :param uids: optional, comma separated - query for messages with the specified uids
    :param pw_dids: optional, comma separated - DID's pointing to specific connection
    :return: message
        [{"pairwiseDID":"did","msgs":[{"statusCode":"MS-106","payload":null,"senderDID":"","uid":"6BDkgc3z0E","type":"aries","refMsgId":null,"deliveryDetails":[],"decryptedPayload":"{"@msg":".....","@type":{"fmt":"json","name":"aries","ver":"1.0"}}"}]}]
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_messages_download, "cb"):
        logger.debug("vcx_messages_download: Creating callback")
        vcx_messages_download.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_char_p))

    if status:
        c_status = c_char_p(status.encode('utf-8'))
    else:
        c_status = None

    if uids:
        c_uids = c_char_p(uids.encode('utf-8'))
    else:
        c_uids = None

    if pw_dids:
        c_pw_dids = c_char_p(pw_dids.encode('utf-8'))
    else:
        c_pw_dids = None

    result = await do_call('vcx_messages_download',
                           c_status,
                           c_uids,
                           c_pw_dids,
                           vcx_messages_download.cb)

    logger.debug("vcx_messages_download completed")
    return result

async def vcx_messages_update_status(msg_json: str):
    """
    Update the status of messages from the specified connection
    :param msg_json: messages to update:
        [
            {
                "pairwiseDID":"string",
                "uids":["string"]
            },
            ...
        ]
    :return:
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_messages_update_status, "cb"):
        logger.debug("vcx_messages_update_status: Creating callback")
        vcx_messages_update_status.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32))

    c_msg_json = c_char_p(msg_json.encode('utf-8'))
    c_status = c_char_p("MS-106".encode('utf-8'))

    result = await do_call('vcx_messages_update_status',
                           c_status,
                           c_msg_json,
                           vcx_messages_update_status.cb)

    logger.debug("vcx_messages_update_status completed")
    return result

def vcx_pool_set_handle(handle: int) -> None:
    """
    Sets the pool handle for libvcx to use, called before vcx_init_minimal
    :param handle: pool handle
    """
    c_handle = c_uint32(handle)

    do_call_sync('vcx_pool_set_handle', c_handle)

async def vcx_get_ledger_author_agreement():
    """
    Retrieve author agreement and acceptance mechanisms set on the Ledger
    :return: {"text":"Default agreement", "version":"1.0.0", "aml": {"label1": "description"}}
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_get_ledger_author_agreement, "cb"):
        logger.debug("vcx_get_ledger_author_agreement: Creating callback")
        vcx_get_ledger_author_agreement.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_char_p))
    result = await do_call('vcx_get_ledger_author_agreement',
                           vcx_get_ledger_author_agreement.cb)

    logger.debug("vcx_get_ledger_author_agreement completed")
    return result.decode()

def vcx_set_active_txn_author_agreement_meta(text: Optional[str],
                                             version: Optional[str],
                                             hash: Optional[str],
                                             acc_mech_type: str,
                                             time_of_acceptance: int) -> None:
    """
    Set some accepted agreement as active.
    As result of successful call of this function appropriate metadata will be appended to each write request.

    :param text and version - (optional) raw data about TAA from ledger.
               These parameters should be passed together.
               These parameters are required if hash parameter is ommited.
    :param hash - (optional) hash on text and version. This parameter is required if text and version parameters are ommited.
    :param acc_mech_type - mechanism how user has accepted the TAA
    :param time_of_acceptance - UTC timestamp when user has accepted the TAA

    :return: no value
    """
    logger = logging.getLogger(__name__)

    name = 'vcx_set_active_txn_author_agreement_meta'

    c_text = c_char_p(text.encode('utf-8')) if text else None
    c_version = c_char_p(version.encode('utf-8')) if version else None
    c_hash = c_char_p(hash.encode('utf-8')) if hash else None
    c_acc_mech_type = c_char_p(acc_mech_type.encode('utf-8'))
    c_time_of_acceptance = c_uint64(time_of_acceptance)

    do_call_sync(name, c_text, c_version, c_hash, c_acc_mech_type, c_time_of_acceptance)
    logger.debug("set_active_txn_author_agreement_meta completed")

async def vcx_get_request_price(action_json: str,
                                requester_info_json: Optional[str]):
    """
    Update the status of messages from the specified connection
    :param action_json: {
         "auth_type": ledger transaction alias or associated value,
         "auth_action": type of an action.,
         "field": transaction field,
         "old_value": (Optional) old value of a field, which can be changed to a new_value (mandatory for EDIT action),
         "new_value": (Optional) new value that can be used to fill the field,
     }
    :param requester_info_json: (Optional) {
         "role": string - role of a user which can sign transaction.
         "count": string - count of users.
         "is_owner": bool - if user is an owner of transaction.
     } otherwise context info will be used

    :return: price - tokens amount required for action performing
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_get_request_price, "cb"):
        logger.debug("vcx_get_request_price: Creating callback")
        vcx_get_request_price.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_uint64))

    c_action_json = c_char_p(action_json.encode('utf-8'))
    c_requester_info_json = c_char_p(requester_info_json.encode('utf-8')) if requester_info_json is not None else None

    result = await do_call('vcx_get_request_price',
                           c_action_json,
                           c_requester_info_json,
                           vcx_get_request_price.cb)

    logger.debug("vcx_get_request_price completed")
    return result

async def vcx_endorse_transaction(transaction: str) -> None:
    """
    Endorse transaction to the ledger preserving an original author
    :param transaction: transaction to endorse
    :return:
    """
    logger = logging.getLogger(__name__)

    if not hasattr(vcx_endorse_transaction, "cb"):
        logger.debug("vcx_endorse_transaction: Creating callback")
        vcx_endorse_transaction.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32))

    c_transaction = c_char_p(transaction.encode('utf-8'))

    result = await do_call('vcx_endorse_transaction',
                           c_transaction,
                           vcx_endorse_transaction.cb)

    logger.debug("vcx_endorse_transaction completed")
    return result


text:
package org.apache.isis.core.metamodel.facets.object.choices.enums;

import org.apache.isis.core.metamodel.facetapi.Facet;

public interface EnumFacet extends Facet {

}


text:
"""Parse Python source and extract unresolved symbols."""

import ast
import sys
from contextlib import contextmanager
from itertools import chain

from importmagic.six import string_types
from importmagic.util import parse_ast

try:
    import builtins as __builtin__
except:
    import __builtin__

class _InvalidSymbol(Exception):
    pass

class Scope(object):
    GLOBALS = ['__name__', '__file__', '__loader__', '__package__', '__path__']
    PYTHON3_BUILTINS = ['PermissionError']
    ALL_BUILTINS = set(dir(__builtin__)) | set(GLOBALS) | set(PYTHON3_BUILTINS)

    def __init__(self, parent=None, define_builtins=True, is_class=False):
        self._parent = parent
        self._definitions = set()
        self._references = set()
        self._children = []
        self._cursors = [self]
        self._cursor = self
        self._define_builtins = define_builtins
        self._is_class = is_class
        if define_builtins:
            self._define_builtin_symbols()
        self._add_symbol = []
        self._symbol = []

    @contextmanager
    def start_symbol(self):
        self._add_symbol.append(self._add_symbol[-1] if self._add_symbol else self.reference)
        try:
            yield self
        finally:
            self.flush_symbol()

    @contextmanager
    def start_definition(self):
        self._add_symbol.append(self.define)
        try:
            yield self
        finally:
            self.flush_symbol()

    @contextmanager
    def start_reference(self):
        self._add_symbol.append(self.reference)
        try:
            yield self
        finally:
            self.flush_symbol()

    def extend_symbol(self, segment, extend_only=False):
        if extend_only and not self._symbol:
            return
        self._symbol.append(segment)

    def end_symbol(self):
        if self._symbol:
            add = self._add_symbol[-1] if self._add_symbol else self.reference
            add('.'.join(self._symbol))
            self._symbol = []

    def flush_symbol(self):
        self.end_symbol()
        if self._add_symbol:
            self._add_symbol.pop()

    @classmethod
    def from_source(cls, src, trace=False, define_builtins=True):
        scope = Scope(define_builtins=define_builtins)
        visitor = UnknownSymbolVisitor(scope, trace=trace)
        if isinstance(src, string_types):
            src = parse_ast(src)
        visitor.visit(src)
        scope.flush_symbol()
        return scope

    def _define_builtin_symbols(self):
        self._cursor._definitions.update(Scope.ALL_BUILTINS)

    def define(self, name):
        if '.' in name:
            self.reference(name)
        else:
            self._cursor._definitions.add(name)

    def reference(self, name):
        self._cursor._references.add(name)

    @contextmanager
    def enter(self, is_class=False):
        child = Scope(self._cursor, is_class=is_class, define_builtins=self._define_builtins)
        self._cursor._children.append(child)
        self._cursors.append(child)
        self._cursor = child
        try:
            yield child
        finally:
            child.end_symbol()
            self._cursors.pop()
            self._cursor = self._cursors[-1]

    def find_unresolved_and_unreferenced_symbols(self):
        """Find any unresolved symbols, and unreferenced symbols from this scope.

        :returns: ({unresolved}, {unreferenced})
        """
        unresolved = set()
        unreferenced = self._definitions.copy()
        self._collect_unresolved_and_unreferenced(set(), set(), unresolved, unreferenced,
                                                  frozenset(self._definitions), start=True)
        return unresolved, unreferenced - Scope.ALL_BUILTINS

    def _collect_unresolved_and_unreferenced(self, definitions, definitions_excluding_top,
                                             unresolved, unreferenced, top, start=False):
        scope_definitions = definitions | self._definitions
        scope_definitions_excluding_top = definitions_excluding_top | (set() if start else self._definitions)

        # When we're in a class, don't export definitions to descendant scopes
        if not self._is_class:
            definitions = scope_definitions
            definitions_excluding_top = scope_definitions_excluding_top

        for reference in self._references:
            symbols = set(_symbol_series(reference))
            # Symbol has no definition anywhere in ancestor scopes.
            if symbols.isdisjoint(scope_definitions):
                unresolved.add(reference)
            # Symbol is referenced only in the top level scope.
            elif not symbols.isdisjoint(top) and symbols.isdisjoint(scope_definitions_excluding_top):
                unreferenced -= symbols

        # Recurse
        for child in self._children:
            child._collect_unresolved_and_unreferenced(
                definitions, definitions_excluding_top, unresolved, unreferenced, top,
            )

    def __repr__(self):
        return 'Scope(definitions=%r, references=%r, children=%r)' \
            % (self._definitions - Scope.ALL_BUILTINS, self._references, self._children)

def _symbol_series(s):
    tokens = s.split('.')
    return ['.'.join(tokens[:n + 1]) for n in range(len(tokens))]

class UnknownSymbolVisitor(ast.NodeVisitor):
    def __init__(self, scope=None, trace=False):
        super(UnknownSymbolVisitor, self).__init__()
        self._scope = scope or Scope()
        self._trace = trace

    def visit(self, node):
        if node is None:
            return
        elif isinstance(node, list):
            for subnode in node:
                self.visit(subnode)
            return
        if self._trace:
            print(node, vars(node))
        method = getattr(self, 'visit_%s' % node.__class__.__name__, None)
        if method is not None:
            try:
                method(node)
            except Exception:
                # print >> sys.stderr, node, vars(node)
                raise
        else:
            self.generic_visit(node)
            self._scope.end_symbol()

    def visit_Raise(self, node):
        if hasattr(node, 'type'):  # Python 2: raise A[, B[, C]]
            with self._scope.start_reference():
                self.visit(node.type)
            with self._scope.start_reference():
                self.visit(node.inst)
            with self._scope.start_reference():
                self.visit(node.tback)
        else:                      # Python 3: raise A[ from B]
            with self._scope.start_reference():
                self.visit(node.exc)
            with self._scope.start_reference():
                self.visit(node.cause)

    def visit_TryExcept(self, node):
        for sub in node.body:
            with self._scope.start_reference():
                self.visit(sub)
        self.visit(node.handlers)
        for n in node.orelse:
            with self._scope.start_reference():
                self.visit(n)

    def visit_ExceptHandler(self, node):
        with self._scope.start_reference():
            self.visit(node.type)
        with self._scope.start_definition():
            if isinstance(node.name, str):
                # Python 3
                self._scope.extend_symbol(node.name)
            else:
                self.visit(node.name)
        for n in node.body:
            with self._scope.start_reference():
                self.visit(n)

    def visit_Return(self, node):
        with self._scope.start_reference():
            self.visit(node.value)

    def visit_If(self, node):
        with self._scope.start_reference():
            self.visit(node.test)
        for child in node.body:
            with self._scope.start_reference():
                self.visit(child)
        for child in node.orelse:
            with self._scope.start_reference():
                self.visit(child)

    def visit_While(self, node):
        return self.visit_If(node)

    def visit_FunctionDef(self, node):
        self._scope.define(node.name)
        self.visit_Lambda(node)

    def visit_Lambda(self, node):
        for decorator in getattr(node, 'decorator_list', []):
            with self._scope.start_reference() as scope:
                self.visit(decorator)
        with self._scope.enter() as scope:
            with scope.start_definition():
                args = node.args
                for arg in [args.kwarg, args.vararg]:
                    if arg:
                        # arg is either an "arg" object (Python 3.4+) or a str
                        scope.define(arg.arg if hasattr(arg, 'arg') else arg)
                # kwonlyargs was added in Python 3
                for arg in args.args + getattr(args, 'kwonlyargs', []):
                    scope.define(arg.id if hasattr(arg, 'id') else arg.arg)

                    # Python 3 arguments annotation
                    if hasattr(arg, 'annotation') and arg.annotation:
                        self.visit(arg.annotation)

                for default in args.defaults:
                    self.visit(default)

                # Python 3 return annotation
                if hasattr(node, 'returns'):
                    self.visit(node.returns)
            body = [node.body] if isinstance(node, ast.Lambda) else node.body
            with scope.start_reference():
                for statement in body:
                    self.visit(statement)

    def visit_ListComp(self, node):
        return self.visit_GeneratorExp(node)

    def visit_Print(self, node):
        for value in node.values:
            with self._scope.start_reference():
                self.visit(value)
        if node.dest:
            with self._scope.start_reference():
                self.visit(node.dest)

    def visit_GeneratorExp(self, node):
        with self._scope.start_reference():
            self.visit(node.elt)
        for elt in node.generators:
            self.visit(elt)

    def visit_comprehension(self, node):
        with self._scope.start_definition():
            self.visit(node.target)
        with self._scope.start_reference():
            self.visit(node.iter)
        for elt in node.ifs:
            with self._scope.start_reference():
                self.visit(elt)

    def visit_Assign(self, node):
        for target in node.targets:
            with self._scope.start_definition():
                self.visit(target)
        with self._scope.start_reference():
            self.visit(node.value)

    def visit_ClassDef(self, node):
        for decorator in getattr(node, 'decorator_list', []):
            with self._scope.start_reference():
                self.visit(decorator)
        self._scope.define(node.name)
        for base in node.bases:
            with self._scope.start_reference():
                self.visit(base)
        with self._scope.enter(is_class=True):
            for body in node.body:
                with self._scope.start_reference():
                    self.visit(body)

    def visit_ImportFrom(self, node):
        for name in node.names:
            if name.name == '*':
                # TODO: Do something?
                continue
            symbol = name.asname or name.name.split('.')[0]
            self._scope.define(symbol)
            # Explicitly add a reference for __future__ imports so they don't
            # get pruned.
            if node.module == '__future__':
                self._scope.reference(symbol)
        self.generic_visit(node)

    def visit_Import(self, node):
        for name in node.names:
            self._scope.define(name.asname or name.name)
        self.generic_visit(node)

    def visit_With(self, node):
        if hasattr(node, 'items'):
            for item in node.items:
                self._visit_withitem(item)
        else:
            self._visit_withitem(node)
        with self._scope.start_reference():
            self.visit(node.body)

    def _visit_withitem(self, node):
        if node.optional_vars:
            with self._scope.start_definition():
                self.visit(node.optional_vars)
        with self._scope.start_reference():
            self.visit(node.context_expr)

    def visit_For(self, node):
        with self._scope.start_definition():
            self.visit(node.target)
        with self._scope.start_reference():
            self.visit(node.iter)
        with self._scope.start_reference():
            self.visit(node.body)
        with self._scope.start_reference():
            self.visit(node.orelse)

    def visit_Attribute(self, node, chain=False):
        if isinstance(node.value, ast.Name):
            self._scope.extend_symbol(node.value.id)
            self._scope.extend_symbol(node.attr)
            if not chain:
                self._scope.end_symbol()
        elif isinstance(node.value, ast.Attribute):
            self.visit_Attribute(node.value, chain=True)
            self._scope.extend_symbol(node.attr, extend_only=True)
        else:
            self._scope.end_symbol()
            self.visit(node.value)
            self._scope.end_symbol()

    def visit_Subscript(self, node):
        self._scope.end_symbol()
        with self._scope.start_reference():
            self.visit(node.value)
        self.visit(node.slice)

    def visit_Call(self, node):
        with self._scope.start_reference():
            self.visit(node.func)
        # Python 3.5 AST removed starargs and kwargs
        additional = []
        if getattr(node, 'starargs', None):
            additional.append(node.starargs)
        if getattr(node, 'kwargs', None):
            additional.append(node.kwargs)
        for arg in chain(node.args, node.keywords, additional):
            with self._scope.start_reference():
                self.visit(arg)

    def visit_Name(self, node):
        self._scope.extend_symbol(node.id)
        self._scope.end_symbol()

if __name__ == '__main__':
    with open(sys.argv[1]) as fd:
        scope = Scope.from_source(fd.read())
    unresolved, unreferenced = scope.find_unresolved_and_unreferenced_symbols()
    from pprint import pprint
    pprint(unresolved)
    pprint(unreferenced)


text:
DJHeroInput
===========

Make games for the DJ Hero controller with Unity


text:
package org.kodomottbj.sunchen.edu.kodomottbj.util;

import android.os.Environment;

public interface CommonSetting {
	String SDCardDiretory = "/sdcard/kodomoTTBJ/";
	String ExamPrefix = "examdata/data/";
	String Exams_List = SDCardDiretory + "examdata/data/";
	String XMLPostfix = ".xml";
	int SendDownload = 1083;
	int RecvDownload = 1084;
	String Sys_userName = "androidexam_Username";
	String DownloadSuccess = "SUCCESS";
	String DownloadFailed = "FAILED";
	String DownloadSuccessTag = "RS";
	String FileNameTag = "fileNameTag";
	String SubjectLocationTag = "location";
	String QueryURL = "http://server.chenyoca.com/androidexam/downloadlist.html";
	String CheckVersionURL = "http://sakai-tsukuba.org/kodomoTTBJ/index.php/Admin/Index/checkVersion";
	String UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
	String DownloadExamFileURL = "http://sakai-tsukuba.org/kodomoTTBJ/Uploads/examdata.zip";
	String AuthURL = "http://sakai-tsukuba.org/kodomoTTBJ/index.php/Home/RestAPI/checkUser";
	String SendAnswer = "http://sakai-tsukuba.org/kodomoTTBJ/index.php/Home/RestAPI/updateExamData";
	String SendAnswerlocal = "http://192.168.150.101/kodomoTTBJ/index.php/Home/RestAPI/updateExamData";
	String CheckLevel = "http://sakai-tsukuba.org/kodomoTTBJ/index.php/Home/RestAPI/checkLevel";
	String CheckLevelocal = "http://192.168.150.101/kodomoTTBJ/index.php/Home/RestAPI/checkLevel";
	String TestURL = "http://192.168.31.210/kodomoTTBJ/index.php/Home/RestAPI/insertAnswer";
	String CorAswDB = "androidexam_correct_answer_database";
}


text:
package com.casetrack.spring.bean;

public class InspCharBean {
	private String InspLotNum;
	private String InspOperNum;
	private String InspSampleNum;
	private String InspCharNum;
	private String InspCharDesc;
	private String Status;
	private Integer Attribute;
	private String DataOrigin;
	private String AdditionalInfo;
	private Integer InspectedCount;
	private Integer NomConfCount;
	private String UpperLimit;
	private String LowerLimit;
	private String MeanValue;
	private Integer AboveCount;
	private Integer BelowCount;
	private String Valuation;
	public String getInspLotNum() {
		return InspLotNum;
	}
	public void setInspLotNum(String inspLotNum) {
		InspLotNum = inspLotNum;
	}
	public String getInspOperNum() {
		return InspOperNum;
	}
	public void setInspOperNum(String inspOperNum) {
		InspOperNum = inspOperNum;
	}
	public String getInspSampleNum() {
		return InspSampleNum;
	}
	public void setInspSampleNum(String inspSampleNum) {
		InspSampleNum = inspSampleNum;
	}
	public String getInspCharNum() {
		return InspCharNum;
	}
	public void setInspCharNum(String inspCharNum) {
		InspCharNum = inspCharNum;
	}
	public String getInspCharDesc() {
		return InspCharDesc;
	}
	public void setInspCharDesc(String inspCharDesc) {
		InspCharDesc = inspCharDesc;
	}
	public String getStatus() {
		return Status;
	}
	public void setStatus(String status) {
		Status = status;
	}
	public Integer getAttribute() {
		return Attribute;
	}
	public void setAttribute(Integer attribute) {
		Attribute = attribute;
	}
	public String getDataOrigin() {
		return DataOrigin;
	}
	public void setDataOrigin(String dataOrigin) {
		DataOrigin = dataOrigin;
	}
	public String getAdditionalInfo() {
		return AdditionalInfo;
	}
	public void setAdditionalInfo(String additionalInfo) {
		AdditionalInfo = additionalInfo;
	}
	public Integer getInspectedCount() {
		return InspectedCount;
	}
	public void setInspectedCount(Integer inspectedCount) {
		InspectedCount = inspectedCount;
	}
	public Integer getNomConfCount() {
		return NomConfCount;
	}
	public void setNomConfCount(Integer nomConfCount) {
		NomConfCount = nomConfCount;
	}
	public String getUpperLimit() {
		return UpperLimit;
	}
	public void setUpperLimit(String upperLimit) {
		UpperLimit = upperLimit;
	}
	public String getLowerLimit() {
		return LowerLimit;
	}
	public void setLowerLimit(String lowerLimit) {
		LowerLimit = lowerLimit;
	}
	public String getMeanValue() {
		return MeanValue;
	}
	public void setMeanValue(String meanValue) {
		MeanValue = meanValue;
	}
	public Integer getAboveCount() {
		return AboveCount;
	}
	public void setAboveCount(Integer aboveCount) {
		AboveCount = aboveCount;
	}
	public Integer getBelowCount() {
		return BelowCount;
	}
	public void setBelowCount(Integer belowCount) {
		BelowCount = belowCount;
	}
	public String getValuation() {
		return Valuation;
	}
	public void setValuation(String valuation) {
		Valuation = valuation;
	}
}


text:
namespace notifications {
namespace {

class IconConverterTest : public testing::Test {
 public:
  IconConverterTest() : encoded_result_(), decoded_result_() {}
  ~IconConverterTest() override = default;

  void SetUp() override {
    auto icon_converter = std::make_unique<PngIconConverterImpl>();
    icon_converter_ = std::move(icon_converter);
  }

  void OnIconsEncoded(base::OnceClosure quit_closure,
                      std::unique_ptr<EncodeResult> encoded_result) {
    encoded_result_ = std::move(encoded_result);
    std::move(quit_closure).Run();
  }

  void OnIconsDecoded(base::OnceClosure quit_closure,
                      std::unique_ptr<DecodeResult> decoded_result) {
    decoded_result_ = std::move(decoded_result);
    std::move(quit_closure).Run();
  }

  void VerifyEncodeRoundTrip(std::vector<SkBitmap> input) {
    EXPECT_EQ(decoded_icons()->size(), input.size());
    for (size_t i = 0; i < input.size(); i++) {
      EXPECT_EQ(input[i].height(), decoded_icons()->at(i).height());
      EXPECT_EQ(input[i].width(), decoded_icons()->at(i).width());
    }
  }

 protected:
  IconConverter* icon_converter() { return icon_converter_.get(); }
  std::vector<SkBitmap>* decoded_icons() {
    return &decoded_result_->decoded_icons;
  }
  std::vector<std::string>* encoded_data() {
    return &encoded_result_->encoded_data;
  }

 private:
  base::test::TaskEnvironment task_environment_;
  std::unique_ptr<IconConverter> icon_converter_;
  std::unique_ptr<EncodeResult> encoded_result_;
  std::unique_ptr<DecodeResult> decoded_result_;

  DISALLOW_COPY_AND_ASSIGN(IconConverterTest);
};

TEST_F(IconConverterTest, EncodeRoundTrip) {
  SkBitmap icon1, icon2;
  icon1.allocN32Pixels(3, 4);
  icon2.allocN32Pixels(12, 13);
  std::vector<SkBitmap> input = {std::move(icon1), std::move(icon2)};
  {
    base::RunLoop run_loop;
    icon_converter()->ConvertIconToString(
        input, base::BindOnce(&IconConverterTest::OnIconsEncoded,
                              base::Unretained(this), run_loop.QuitClosure()));
    run_loop.Run();
  }
  EXPECT_EQ(encoded_data()->size(), input.size());
  {
    base::RunLoop run_loop;
    icon_converter()->ConvertStringToIcon(
        *encoded_data(),
        base::BindOnce(&IconConverterTest::OnIconsDecoded,
                       base::Unretained(this), run_loop.QuitClosure()));
    run_loop.Run();
    VerifyEncodeRoundTrip(input);
  }
}

}  // namespace
}  // namespace notifications


text:
package com.jetbrains.python.quickFixes;

import com.intellij.testFramework.TestDataPath;
import com.jetbrains.python.PyPsiBundle;
import com.jetbrains.python.PyQuickFixTestCase;
import com.jetbrains.python.inspections.PyArgumentListInspection;
import com.jetbrains.python.psi.LanguageLevel;

@TestDataPath("$CONTENT_ROOT/../testData/quickFixes/PyRemoveArgumentQuickFixTest/")
public class PyRemoveArgumentQuickFixTest extends PyQuickFixTestCase {

  public void testDuplicate() {
    doQuickFixTest(PyArgumentListInspection.class, PyPsiBundle.message("QFIX.NAME.remove.argument"));
  }

  public void testDuplicateArg() {
    doQuickFixTest(PyArgumentListInspection.class,
                   PyPsiBundle.message("QFIX.NAME.remove.argument"),
                   LanguageLevel.PYTHON27);
  }

  public void testDuplicateKWArg() {
    doQuickFixTest(PyArgumentListInspection.class,
                   PyPsiBundle.message("QFIX.NAME.remove.argument"),
                   LanguageLevel.PYTHON27);
  }

  public void testPostKwArg() {
    doQuickFixTest(PyArgumentListInspection.class,
                   PyPsiBundle.message("QFIX.NAME.remove.argument"),
                   LanguageLevel.PYTHON27);
  }

  public void testUnexpected() {
    doQuickFixTest(PyArgumentListInspection.class, PyPsiBundle.message("QFIX.NAME.remove.argument"));
  }

}


text:
package org.kuali.rice.krad.bo.test;

public interface TestEBOInterfaceSub extends TestEBOInterface {
}


text:
This is the publisher part of Untied. Untied is an observer pattern implementation to distributed systems.

For usage information, please visit the [Untied](http://github.com/redu/untied) page.

[![Build Status](https://travis-ci.org/redu/untied-publisher.png)](https://travis-ci.org/redu/untied-publisher)

## Installation

Add this line to your application's Gemfile:

    gem 'untied-publisher'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install untied-publisher

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var BaseIndexGenerator = require('../sub-base.js');

var ModelServiceGenerator = module.exports = function JsonServiceGenerator(args, options, config) {
    BaseIndexGenerator.apply(this, arguments);
    console.log('Creating a model service named: "' + this.name + 'Model".');
};

util.inherits(ModelServiceGenerator, BaseIndexGenerator);

ModelServiceGenerator.prototype.files = function files() {
    var app = 'app/',
        path = 'scripts/services/',
        file = this.name + 'Model.js';

    this.copy('s.js', app + path + file);
    this.addScriptToIndex(
        {
            block: '<!-- build:js scripts/main.js -->'
        },
        [
            path + file
        ]
    );
};