text:
[![Build Status](https://travis-ci.org/httplab/insup.svg?branch=master)](https://travis-ci.org/httplab/insup)
[![Gem Version](https://badge.fury.io/rb/insup.svg)](http://badge.fury.io/rb/insup)
[![Coverage Status](https://coveralls.io/repos/httplab/insup/badge.png)](https://coveralls.io/r/httplab/insup)
[![Code Climate](https://codeclimate.com/github/httplab/insup.png)](https://codeclimate.com/github/httplab/insup)
[![Dependency Status](https://gemnasium.com/httplab/insup.svg)](https://gemnasium.com/httplab/insup)

## Description

Insup Insales theme uploader.

## Installation

```bash
gem install insup
```

## Usage

### Preparing

Enter the directory you want to sync with the remote service. Then type `insup init` to initialize your working directory with **.insup** file that holds all neccessary Insup configuration.

Open **.insup** file with your favourite text editor and modify the configuration according to your needs.

### Configuration
**.insup** file is a YAML file. Here's a list of the configuration options.

* **working_dir** specifies working directory (relative to the directory containing .insup file). Defaults to the current directory.
* **ignore** section specifies an array of patterns that are used to ignore files. Files that match ignore patterns will be neither tracked nor uploaded. The patterns must be specified in Git ignore format relative to the working directory.
* [**tracker**](#trackers) section specifies the tracker to use as well as its configuration. The tracker class is specified by the `class` option.
* [**uploader**](#uploaders) section specifies the uploader to use as well as its configuration. The uploader class is specified by the `class` option.
* **insales** secion holds information for connecting to Insales shop. To use insales features you should specify `subdomain`, `api_key` and `password` parameters.
* **log** section sets logging parameters. Use `file` to specify a log file path, `level` to set log level (`unknown`, `debug`, `error`, `fatal`, `info`, `unknown` and `warn`), and `pattern` to specify log message pattern using `%{timestamp}`, `%{level}`, `%{message}`, and `%{backtrace}` substitutions.
* [**listen**](#listen-mode) section specifies listener options.

#### Trackers

Currently there are two trackers available:

* **Git tracker** finds changes in the working directory using Git index. This tracker will operate only if the working dir is a Git repository. Select this tracker by specifying `Insup::Tracker::GitTracker` or `git` in the `class` section of the tracker configuration.
* **Simple tracker** will always consider all files in the working directory modified (except the ignored ones). Specify `Insup::Tracker::SimpleTracker` or `simple` ins the `class` section.

#### Uploaders

Currently there are two uploaders available:

* **Insales uploader** will upload files to the specified Insales theme. Specify `Insup::Uploader::InsalesUploader` or `insales` in the `class` section of the uploader configuration. Insales uploader also requires `theme_id` to be specified. Working directory should include 3 subfolders *media*, *snippets* and *templates*. The same 3 folders should be specified in the `track` sectio of .insup file.

* **Dummy uploader** will only print its operations to the console without actually uploading anything. It can be used for testing the configuration. Use by specifying `dummy` or `Insup::Uploader::DummyUploader` in the `class` section.

### Operation modes

#### Listen mode

In this mode Insup will continuously listen to the changes in working directory and upload the changes immidiately. It will use the specified uploader, but the tracker is ignored. Listen mode will only watch files that do not match ignore patterns.

Activate listen mode by typing
```bash
insup listen
```
or just
```bash
insup
```
in your working directory.

Listen mode options are specified in **listen** section:
* **force_polling:** force the use of polling when listening to changes (true or false);
* **latency:** delay in seconds between checking for changes;
* **wait_for_delay:** delay in seconds between processing changes when there are any.

#### Track mode
In this mode you can periodically check for changes and upload changed files to the remote storage. Tracker specified in the .insup file is used to detect changes.

Print working directory status accroding to the selected tracker
```bash
insup status
```

Upload changes
```bash
insup commit
```
You can also specify particlular files with the `commit` command:
```bash
insup commit [file1 [file2 [file3 [...]]]]
```
In this case **tracking info is ignored** and each file specified is treated as modified or deleted (if it doesn't actually exist).

### Other commands
List all themes in the Insales shop if `insales` section is given in the .insup file:
```bash
insup insales list-themes
```

Download all Insales theme files into the working directory:
```bash
insup insales download [-f] [-t theme-id]
```
Specify `-f` flag to overwrite any existing file. If no theme ID is specified Insup will download theme specified in the .insup file.

List files in tracked directory:
```bash
insup list-files [--all|--ignored]
```
Use `--all` option to list *all* files, and `--ignored` to list only ignored files. Calling this command without options will result in a list of tracked files only.

#### Getting help
To see a full list of commands available, type:
```bash
insup --help
```
To see help message on the specific command, type:
```bash
insup <command> --help
```

##Troubleshooting

### OS X users
For a reason yet unknown sometimes on a newer versions of OS X Insup will only listen to changes that take place under the last folder listed in `track` settings.

Current workaround is to fall back to filesystem polling by adding the following lines to the configuration:

```yaml
listen:
  force_polling: true
```

Filesystem polling may increase the CPU usage and decrease performance. Use this only if Insup doesn't work otherwise.

### Windows users
There was an issue report from Windows users concerning wrong file encoding upon uploading UTF-8 files to Insales. If you are experiencing encoding problems when running Insup on Windows, please use the following workaround until the problem is investigated and solved.

Before running any `insup` command exectute the following:
```bash
chcp 65001
```

This will change the econding of your Windows console to UTF-8 and allow you to avoid most encoding problems.


text:
from __future__ import unicode_literals

from django.db import models, migrations
import cms.utils.Utils

class Migration(migrations.Migration):

    dependencies = [
        ('cms', '0012_affiliation_styling'),
    ]

    operations = [
        migrations.AddField(
            model_name='affiliation',
            name='icon',
            field=models.FileField(default=b'', upload_to=cms.utils.Utils.getUploadPath, blank=True),
            preserve_default=True,
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Gedmo\Sluggable;

use Doctrine\Common\Util\Debug,
    Doctrine\ORM\Mapping\Driver\YamlDriver,
    Doctrine\ORM\Mapping\Driver\DriverChain,
    Mapping\Fixture\Yaml\Category,
    Gedmo\Mapping\ExtensionMetadataFactory;

/**
 * These are mapping tests for sluggable extension
 *
 * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
 * @package Gedmo.Mapping
 * @link http://www.gediminasm.org
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
class SluggableMappingTest extends \PHPUnit_Framework_TestCase
{
    const TEST_YAML_ENTITY_CLASS = 'Mapping\Fixture\Yaml\Category';
    const SLUGGABLE = 'Mapping\Fixture\Sluggable';
    private $em;

    public function setUp()
    {
        $config = new \Doctrine\ORM\Configuration();
        $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache);
        $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache);
        $config->setProxyDir(TESTS_TEMP_DIR);
        $config->setProxyNamespace('Gedmo\Mapping\Proxy');
        $chainDriverImpl = new DriverChain;
        $chainDriverImpl->addDriver(
            new YamlDriver(array(__DIR__ . '/Driver/Yaml')),
            'Mapping\Fixture\Yaml'
        );
        $reader = new \Doctrine\Common\Annotations\AnnotationReader();
        \Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
            'Gedmo\\Mapping\\Annotation',
            VENDOR_PATH . '/../lib'
        );
        $chainDriverImpl->addDriver(
            new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader),
            'Mapping\Fixture'
        );
        $config->setMetadataDriverImpl($chainDriverImpl);

        $conn = array(
            'driver' => 'pdo_sqlite',
            'memory' => true,
        );

        $evm = new \Doctrine\Common\EventManager();
        $evm->addEventSubscriber(new SluggableListener());
        $this->em = \Doctrine\ORM\EntityManager::create($conn, $config, $evm);
    }

    public function testYamlMapping()
    {
        $meta = $this->em->getClassMetadata(self::TEST_YAML_ENTITY_CLASS);
        $cacheId = ExtensionMetadataFactory::getCacheId(
            self::TEST_YAML_ENTITY_CLASS,
            'Gedmo\Sluggable'
        );
        $config = $this->em->getMetadataFactory()->getCacheDriver()->fetch($cacheId);
        $this->assertArrayHasKey('slugFields', $config);
        $this->assertEquals('slug', $config['slugFields']['slug']['slug']);
        $this->assertArrayHasKey('fields', $config);
        $this->assertEquals(1, count($config['fields']['slug']));
        $this->assertEquals('title', $config['fields']['slug'][0]['field']);
        $this->assertEquals('slug', $config['fields']['slug'][0]['slugField']);
        $this->assertEquals(1, $config['fields']['slug'][0]['position']);
        $this->assertArrayHasKey('style', $config['slugFields']['slug']);
        $this->assertEquals('camel', $config['slugFields']['slug']['style']);
        $this->assertArrayHasKey('separator', $config['slugFields']['slug']);
        $this->assertEquals('_', $config['slugFields']['slug']['separator']);
        $this->assertArrayHasKey('unique', $config['slugFields']['slug']);
        $this->assertTrue($config['slugFields']['slug']['unique']);
        $this->assertArrayHasKey('updatable', $config['slugFields']['slug']);
        $this->assertTrue($config['slugFields']['slug']['updatable']);
    }

    public function testSlugHandlerMapping()
    {
        $meta = $this->em->getClassMetadata(self::SLUGGABLE);
        $cacheId = ExtensionMetadataFactory::getCacheId(
            self::SLUGGABLE,
            'Gedmo\Sluggable'
        );
        $config = $this->em->getMetadataFactory()->getCacheDriver()->fetch($cacheId);

        $this->assertArrayHasKey('handlers', $config);
        $handlers = $config['handlers'];
        $this->assertEquals(2, count($handlers));
        $this->assertArrayHasKey('Gedmo\Sluggable\Handler\TreeSlugHandler', $handlers);
        $this->assertArrayHasKey('Gedmo\Sluggable\Handler\RelativeSlugHandler', $handlers);

        $first = $handlers['Gedmo\Sluggable\Handler\TreeSlugHandler'];
        $this->assertEquals(2, count($first));
        $this->assertArrayHasKey('parentRelationField', $first);
        $this->assertArrayHasKey('separator', $first);
        $this->assertEquals('parent', $first['parentRelationField']);
        $this->assertEquals('/', $first['separator']);

        $second = $handlers['Gedmo\Sluggable\Handler\RelativeSlugHandler'];
        $this->assertEquals(3, count($second));
        $this->assertArrayHasKey('relationField', $second);
        $this->assertArrayHasKey('relationSlugField', $second);
        $this->assertArrayHasKey('separator', $second);
        $this->assertEquals('user', $second['relationField']);
        $this->assertEquals('slug', $second['relationSlugField']);
        $this->assertEquals('/', $second['separator']);
    }
}


text:
@interface AlertControllerFactory() <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, strong) UIViewController *presentingViewController;
@property (nonatomic, assign) CGSize imageSize;
@property (nonatomic, strong) void (^completionHandler)(UIImage *);
@end

@implementation AlertControllerFactory

static AlertControllerFactory *_sharedInstance;

+ (AlertControllerFactory *)defaultFactory
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[AlertControllerFactory alloc] init];
    });

    return _sharedInstance;
}

+ (UIAlertController *)textFieldAlertControllerWithTitle:(NSString *)title andText:(NSString *)text andPlaceHolder:(NSString *)placeHolder actionName:(NSString *)actionName completionHandler:(void (^)(NSString *))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];

    // Keep reference to the textFieldObserver, to remove it on alert dismissal
    id __block textFieldObserver;

    UIAlertAction *createAction = [UIAlertAction actionWithTitle:actionName style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        // Remove observer to void memory leaks
        [[NSNotificationCenter defaultCenter] removeObserver:textFieldObserver];

        // Perform completion handler on typed text
        UITextField *textField = alertController.textFields.firstObject;
        completionHandler(textField.text);
    }];
    // Start action disabled while textfield is empty
    createAction.enabled = (text && text.length > 0);

    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = text?:@"";
        textField.placeholder = placeHolder;

        // Add observer to enable action when textfield has some text.
        // Keep reference to the textFieldObserver, to remove it on alert dismissal
        textFieldObserver = [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:textField queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            createAction.enabled = ![textField.text isEqualToString:@""];
        }];

    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        // Remove observer to void memory leaks
        [[NSNotificationCenter defaultCenter] removeObserver:textFieldObserver];
    }];

    [alertController addAction:createAction];
    [alertController addAction:cancelAction];

    return alertController;
}

+ (UIAlertController *)warningAlertControllerWithTitle:(NSString *)title andMessage:(NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
                                                                             message:message
                                                                      preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    return alertController;
}

+ (UIAlertController *)photoSourceAlertControllerForViewController:(UIViewController *)viewController
                                                     withImageSize:(CGSize)size
                                                 completionHandler:(void (^)(UIImage *))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *libraryAction = [UIAlertAction actionWithTitle:@"Photo Library"
                                                            style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * _Nonnull action) {
            [self getPhotoFromSource:UIImagePickerControllerSourceTypePhotoLibrary
                   forViewController:viewController
                       withImageSize:size
                   completionHandler:completionHandler];
    }];

    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"Take Photo"
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * _Nonnull action) {
            [self getPhotoFromSource:UIImagePickerControllerSourceTypeCamera
                   forViewController:viewController
                       withImageSize:size
                   completionHandler:completionHandler];
    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];

    [alertController addAction:libraryAction];
    [alertController addAction:cameraAction];
    [alertController addAction:cancelAction];

    return alertController;
}

+ (void)getPhotoFromSource:(UIImagePickerControllerSourceType)sourceType
         forViewController:(UIViewController *)viewController
             withImageSize:(CGSize)imageSize
         completionHandler:(void (^)(UIImage *))completionHandler
{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = sourceType;
    imagePickerController.editing = YES;
    imagePickerController.delegate = [self defaultFactory];

    [self defaultFactory].presentingViewController = viewController;
    [self defaultFactory].imageSize = imageSize;
    [self defaultFactory].completionHandler = completionHandler;
    [viewController presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - <UIImagePickerControllerDelegate>

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    // Resize the image to fit given size
    UIImage *scaledImage = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:self.imageSize interpolationQuality:kCGInterpolationHigh];

    // Crop the image to a square
    CGRect croppedRect = CGRectMake((scaledImage.size.width - self.imageSize.width)/2,
                                    (scaledImage.size.height - self.imageSize.height)/2,
                                    self.imageSize.width,
                                    self.imageSize.height);
    UIImage *croppedImage = [scaledImage croppedImage:croppedRect];

    // Return the photo to viewController and dismiss
    self.completionHandler(croppedImage);
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
import { push } from 'react-router-redux'
import { BACK_PATH, NEXT_PATH, ACTION_TYPES } from '../config/select_doctor_config'

function unselectAllItems(i) {

}

// ------------------------------------
// Actions
// ------------------------------------

export function onImageSelectItemClick(items, item) {
  return {
    type: ACTION_TYPES.SELECT_DOCTOR_IMAGE_SELECT_GRID_ON_ITEM_CLICK,
    payload: {
      allItems: items,
      item: item
    }
  }
}

export function back() {
  return (dispatch, getState) => {
    dispatch(push(BACK_PATH))
  }
}

export function next() {
  return (dispatch, getState) => {
    dispatch(push(NEXT_PATH))
  }
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [ACTION_TYPES.SELECT_DOCTOR_IMAGE_SELECT_GRID_ON_ITEM_CLICK]: (state, action) => {
    return Object.assign({}, state, {
      data: {
        doctor: action.payload.item
      }
    })
  }
}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = { data: {} }
export default function selectDoctorReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}


text:
from __future__ import print_function, division
import serial
import time
import atexit
import json
import operator
from functools import partial
import threading

from serial_device import SerialDevice, findSerialDevicePorts, WriteFrequencyError

DEBUG = True
MOTOR_ADDRESS_OFFSET = 128
MOTOR_ADDRESS_MAX = 120
MOTOR_COUNT_LIMIT = 16

lock = threading.Lock()

class AnimaticsMotor(object):

    """sendCmd and sendCmdGetRsp methods must be attached to
    AnimaticsMotor instance before initialize method is called."""

    def __init__(self,*args,**kwargs):
        try:
            self.motor_address = kwargs.pop('motor_address')
        except KeyError:
            self.motor_address = None
        try:
            self.motor_axis = kwargs.pop('motor_axis')
        except KeyError:
            self.motor_axis = None
        try:
            self.motor_name = kwargs.pop('motor_name')
        except KeyError:
            self.motor_name = ''
        try:
            self.scale_factor = kwargs.pop('scale_factor')
        except KeyError:
            self.scale_factor = 1
        try:
            self.set_default_mode = kwargs.pop('set_default_mode')
        except KeyError:
            self.set_default_mode = True

        self.encoder_resolution = None
        self.sample_rate = None
        self.acc_default = 1
        self.vel_default = 1
        self.vel_max = 2
        self.current_limit_default = 100
        self.homing = False
        self.homed = False
        self.vel_default_home = -0.1
        self.current_limit_default_home = 40
        self.origin_shift = 0
        self.pos_list = []
        self.pos_dict = {}
        self.mode = None

    def initialize(self,*args,**kwargs):
        self.encoder_resolution = self.getEncoderResolution()
        self.sample_rate = self.getSampleRate()
        if self.set_default_mode:
            self.setVelModeWithDefaults()

    def getAnimaticsMotorInfo(self):
        animatics_motor_info = {'motor_address': self.motor_address,
                                'motor_axis': self.motor_axis,
                                'motor_name': self.motor_name,
                                'scale_factor': self.scale_factor,
                                'acc_default': self.acc_default,
                                'vel_default': self.vel_default,
                                'vel_max': self.vel_max,
                                'current_limit_default': self.current_limit_default,
                                'vel_default_home': self.current_limit_default,
                                'current_limit_default_home': self.current_limit_default,
                                'homing': self.homing,
                                'homed': self.homed,
                                'mode': self.mode,
                                'origin_shift': self.origin_shift,
                                'pos_list': self.pos_list,
                                'pos_dict': self.pos_dict,
                                'encoder_resolution': self.encoder_resolution,
                                'sample_rate': self.sample_rate,
                                'acc_target': self.getAccTarget(),
                                'vel_target': self.getVelTarget(),
                                'vel': self.getVel(),
                                'pos_target': self.getPosTarget(),
                                'pos': self.getPos(),
                                'pos_error': self.getPosError(),
                                'temperature': self.getTemperature(),
                                'current': self.getCurrent(),
                                'current_limit': self.getCurrentLimit(),
                                'pid_values': self.getPidValues(),
                                'status': self.getStatusTrue(),
                                }
        return animatics_motor_info

    def setParameters(self,parameters):
        if 'motor_axis' in parameters:
            self.setMotorAxis(parameters['motor_axis'])
        if 'motor_name' in parameters:
            self.setMotorName(parameters['motor_name'])
        if 'scale_factor' in parameters:
            self.setScaleFactor(parameters['scale_factor'])
        if 'acc_default' in parameters:
            self.setAccDefault(parameters['acc_default'])
        if 'vel_max' in parameters:
            self.vel_max = parameters['vel_max']
        if 'vel_default' in parameters:
            self.setVelDefault(parameters['vel_default'])
        if 'current_limit_default' in parameters:
            self.setCurrentLimitDefault(parameters['current_limit_default'])
        if 'vel_default_home' in parameters:
            self.vel_default_home = parameters['vel_default_home']
        if 'current_limit_default_home' in parameters:
            self.current_limit_default_home = parameters['current_limit_default_home']
        if 'mode' in parameters:
            mode = parameters['mode']
            try:
                if mode[0].lower() == 'p':
                    self.setPosMode()
                elif mode[0].lower() == 'v':
                    self.setVelMode()
            except IndexError:
                pass
        if 'hardware_limits' in parameters:
            hardware_limits = parameters['hardware_limits']
            if not hardware_limits:
                self.disableHardwareLimits()
        if 'origin_shift' in parameters:
            self.origin_shift = parameters['origin_shift']
        if 'pos_list' in parameters:
            self.pos_list = parameters['pos_list']
        if 'pos_dict' in parameters:
            self.pos_dict = parameters['pos_dict']
        if 'pid_values' in parameters:
            self.setPidValues(parameters['pid_values'])

    def setVelModeWithDefaults(self):

        '''Set acceleration and velocity defaults, set to velocity
        mode, and disable hardware limits.'''

        self.setAcc(self.acc_default)
        self.setVel(self.vel_default)
        self.setVelMode()
        self.disableHardwareLimits()

    def setPosModeWithDefaults(self):

        '''Set acceleration and velocity defaults, set to position
        mode, and disable hardware limits.'''

        self.setAcc(self.acc_default)
        self.setVel(self.vel_default)
        self.setPosMode()
        self.disableHardwareLimits()

    def getMotorAddress(self):
        return self.motor_address

    def setMotorAddress(self,motor_address):
        self.motor_address = int(motor_address)

    def getMotorAxis(self):
        return self.motor_axis

    def setMotorAxis(self,motor_axis):
        self.motor_axis = int(motor_axis)

    def getMotorName(self):
        return self.motor_name

    def setMotorName(self,motor_name):
        self.motor_name = str(motor_name)

    def setAcc(self,acc):

        '''Set acceleration and deceleration target
        (output_unit/s/s)'''

        acc = self._convertAccToMotorUnits(acc)
        bytes_written = self.sendCmd('ADT={acc}'.format(acc=acc))
        return bytes_written

    def setAccDefault(self,acc):

        '''Set acceleration and deceleration target and default
        (output_unit/s/s)'''

        self.acc_default = acc
        bytes_written = self.setAcc(acc)
        return bytes_written

    def setVel(self,vel,suggest=False):

        '''Set velocity target (output_unit/s)'''

        if self.vel_max < vel:
            vel = self.vel_max
        vel = self._convertVelToMotorUnits(vel)
        bytes_written = self.sendCmd('VT={vel}'.format(vel=vel),suggest=suggest)
        return bytes_written

    def setVelDefault(self,vel):

        '''Set velocity target and default (output_unit/s)'''

        if self.vel_max < vel:
            vel = self.vel_max
        self.vel_default = vel
        bytes_written = self.setVel(vel)
        return bytes_written

    def setPos(self,pos,suggest=False):

        '''Set absolute position target (output_unit)'''

        pos = self._convertPosToMotorUnits(pos)
        bytes_written = self.sendCmd('PT={pos}'.format(pos=pos),suggest=suggest)
        return bytes_written

    def setPosRel(self,pos,suggest=False):

        '''Set relative position target (output_unit)'''

        pos = self._convertPosToMotorUnits(pos)
        bytes_written = self.sendCmd('PRT={pos}'.format(pos=pos),suggest=suggest)
        return bytes_written

    def setOrigin(self,pos=0):

        '''Set origin (output_unit) default = 0'''

        pos = self._convertPosToMotorUnits(pos)
        bytes_written = self.sendCmd('O={pos}'.format(pos=pos))
        return bytes_written

    def shiftOrigin(self,pos=0):

        '''Shift the origin by a relative amount (output_unit) default
        = 0 The origin can be shifted during motion without losing
        position counts.'''

        pos = self._convertPosToMotorUnits(pos)
        bytes_written = self.sendCmd('OSH={pos}'.format(pos=pos))
        return bytes_written

    def setVelMode(self):

        '''Set velocity mode. Enables continuous rotation of the motor
        shaft. The go command will cause the shaft to accelerate to
        the velocity target and continue spinning at that
        rate. Positive velocity targets will cause the shaft to rotate
        in one direction, negative in the other.'''

        self.mode = 'vel'
        bytes_written = self.sendCmd('MV')
        return bytes_written

    def setPosMode(self):

        '''Set position mode. The go command will cause the shaft to
        acclerate to the velocity target and spin until decelerating
        and stopping on the position target. Only the absolute value
        of the velocity target is considered, the shaft spins in the
        proper direction to reach the velocity target from the
        starting position.'''

        self.mode = 'pos'
        bytes_written = self.sendCmd('MP')
        return bytes_written

    def setScaleFactor(self,scale_factor):

        '''scale_factor = motor shaft revolutions per 1 output unit
        scale_factor cannot equal 0
        e.g. radian output: scale_factor = 1/(2*math.pi)
        e.g. 100:1 gearhead ratio: scale_factor = 100
        e.g. 100:1 gearhead ratio with reversed direction: scale_factor = -100'''

        if scale_factor == 0:
            raise ValueError('scale_factor cannot be 0!')
        else:
            self.scale_factor = scale_factor

    def getScaleFactor(self):

        '''scale_factor = motor shaft revolutions per 1 output unit
        scale_factor cannot equal 0
        e.g. radian output: scale_factor = 1/(2*math.pi)
        e.g. 100:1 gearhead ratio: scale_factor = 100
        e.g. 100:1 gearhead ratio with reversed direction: scale_factor = -100'''

        return self.scale_factor

    def reset(self):

        '''Total Animatics device reset.'''

        bytes_written = self.sendCmd('Z')
        return bytes_written

    def go(self):

        '''Start motion.'''

        bytes_written = self.sendCmd('G')
        return bytes_written

    def stop(self):

        '''Decelerate the motor to stop.'''

        bytes_written = self.sendCmd('X')
        return bytes_written

    def stopAbrupt(self):

        '''Stop motor abruptly.'''

        bytes_written = self.sendCmd('S')
        return bytes_written

    def goToVel(self,vel=None,suggest=False):

        '''Set velocity mode if necessary and go to directly to
        velocity. Do not pass Go, do not collect $200. Set suggest =
        True if it is OK to ignore this command if sent too quickly
        after previous command. suggest = False (default) causes
        program to wait and block until command is able to send.'''

        if vel is None:
            vel = self.vel_default
        bytes_written = self.setVel(vel,suggest=suggest)
        if 0 < bytes_written:
            if self.mode != 'vel':
                self.setVelMode()
            self.go()
        return bytes_written

    def goToPos(self,pos=0,vel=None,suggest=False):

        '''Set position mode if necessary and go directly to position
        in absolute coordinates. Do not pass Go, do not collect
        $200. Set suggest = True if it is OK to ignore this command if
        sent too quickly after previous command. suggest = False
        (default) causes program to wait and block until command is
        able to send.'''

        if vel is None:
            vel = self.vel_default
        bytes_written = self.setPos(pos,suggest=suggest)
        if 0 < bytes_written:
            if self.mode != 'pos':
                self.setPosMode()
            self.setVel(vel,suggest=False)
            self.go()
        return bytes_written

    def goToPosRel(self,pos=0,vel=None,suggest=False):

        '''Set position mode if necessary and go directly to position
        in relative coordinates. Do not pass Go, do not collect
        $200. Set suggest = True if it is OK to ignore this command if
        sent too quickly after previous command. suggest = False
        (default) causes program to wait and block until command is
        able to send.'''

        if vel is None:
            vel = self.vel_default
        bytes_written = self.setPosRel(pos,suggest=suggest)
        if 0 < bytes_written:
            if self.mode != 'pos':
                self.setPosMode()
            self.setVel(vel,suggest=False)
            self.go()
        return bytes_written

    def goToPosList(self,index,vel=None):

        '''Go to the position stored in instance variable pos_list at
        the given index and vel.'''

        index = int(index)
        pos = self.pos_list[index]
        self.goToPos(pos=pos,vel=vel)

    def goToPosDict(self,key,vel=None):

        '''Go to the position stored in instance variable pos_dict at
        the given key and vel.'''

        key = str(key)
        pos = self.pos_dict[key]
        self.goToPos(pos=pos,vel=vel)

    def atPosDict(self,key):

        '''Check to see if position matches position stored in
        instance variable pos_dict at the given key.'''

        if self.getStatusTrajectoryInProgress():
            return False
        key = str(key)
        pos_target = self.pos_dict[key]
        pos = self.getPos()
        pos_error = abs(pos - pos_target)
        max_pos_error = 0.01
        return pos_error < max_pos_error

    def off(self):

        '''Stop servoing the motor. This will not cause the motor to
        spin freely, use method "free" for that.'''

        bytes_written = self.sendCmd('OFF')
        return bytes_written

    def homeStart(self,vel=None,current_limit=None):
        if vel is None:
            vel = self.vel_default_home
        if current_limit is None:
            current_limit = self.current_limit_default_home
        self.stop()
        self.setCurrentLimit(current_limit)
        self.resetErrors()
        self.goToVel(vel)
        self.homing = True

    def homeInProgress(self):
        return self.homing and not self.homeCompleted()

    def homeCompleted(self):
        return self.homing and \
               not self.getStatusTrajectoryInProgress() and \
               (self.getStatusOverCurrent() or self.getStatusPosError())

    def setHome(self):

        '''Set origin, shift origin by origin_shift value, reset
        errors, and set current limit back to default.'''

        self.homing = False
        self.homed = True
        self.setOrigin()
        self.shiftOrigin(self.origin_shift)
        self.resetErrors()
        self.setCurrentLimit(self.current_limit_default)

    def isHomed(self):
        return self.homed

    def brakeRelease(self):

        '''Release the power safe brakes.'''

        bytes_written = self.sendCmd('BRKRLS')
        return bytes_written

    def brakeEngage(self):

        '''Engage the power safe brakes.'''

        bytes_written = self.sendCmd('BRKENG')
        return bytes_written

    def free(self):

        '''Causes the motor to spin freely.'''

        self.off()
        self.brakeRelease()
        bytes_written = self.resetErrors()
        return bytes_written

    def disablePosHardwareLimit(self):
        if 0 < self.scale_factor:
            bytes_written = self.sendCmd('EIGN(2)')
        else:
            bytes_written = self.sendCmd('EIGN(3)')
        return bytes_written

    def disableNegHardwareLimit(self):
        if 0 < self.scale_factor:
            bytes_written = self.sendCmd('EIGN(3)')
        else:
            bytes_written = self.sendCmd('EIGN(2)')
        return bytes_written

    def resetErrors(self):

        '''Reset system latches to power-up state.'''

        bytes_written = self.sendCmd('ZS')
        return bytes_written

    def disableHardwareLimits(self):
        self.disablePosHardwareLimit()
        self.disableNegHardwareLimit()
        bytes_written = self.resetErrors()
        return bytes_written

    def getEncoderResolution(self):
        return self.sendCmdGetRsp('RRES')

    def getSampleRate(self):
        return self.sendCmdGetRsp('RSAMP')

    def getAccTarget(self):
        acc = self.sendCmdGetRsp('RAT')
        acc = self._convertAccFromMotorUnits(acc)
        return acc

    def getVelTarget(self):
        vel = self.sendCmdGetRsp('RVT')
        vel = self._convertVelFromMotorUnits(vel)
        return vel

    def getVel(self):
        vel = self.sendCmdGetRsp('RVA')
        vel = self._convertVelFromMotorUnits(vel)
        return vel

    def getPosTarget(self):
        pos = self.sendCmdGetRsp('RPT')
        pos = self._convertPosFromMotorUnits(pos)
        return pos

    def getPos(self):
        pos = self.sendCmdGetRsp('RPA')
        pos = self._convertPosFromMotorUnits(pos)
        return pos

    def getPosModulo(self):
        pos = self.sendCmdGetRsp('RPMA')
        pos = self._convertPosFromMotorUnits(pos)
        return pos

    def getPosError(self):
        pos = self.sendCmdGetRsp('REA')
        pos = self._convertPosFromMotorUnits(pos)
        return pos

    def getTemperature(self):
        temp = self.sendCmdGetRsp('RTEMP')
        return temp

    def getCurrent(self):
        current = self.sendCmdGetRsp('RUIA')
        return current

    def setCurrentLimit(self,limit):

        """Set current limit as a percentage of the maximum value. 0 <=
        limit <= 100"""

        amps = (limit/100)*1023
        bytes_written = self.sendCmd('AMPS={amps}'.format(amps=amps))
        return bytes_written

    def setCurrentLimitDefault(self,limit):

        """Set current limit as a percentage of the maximum value. 0 <=
        limit <= 100"""

        self.current_limit_default = limit
        bytes_written = self.setCurrentLimit(limit)
        return bytes_written

    def getCurrentLimit(self):

        """Get current limit as a percentage of the maximum value. 0 <=
        limit <= 100"""

        amps = self.sendCmdGetRsp('RAMPS')
        limit = (amps/1023)*100
        return limit

    def getVoltage(self):
        voltage = self.sendCmdGetRsp('RUJA')
        return voltage

    def getPi(self):

        """Gets the value of PI from the motor. Can be used to check
        if the motor is responding properly."""

        pi = self.sendCmdGetRsp('RPI')
        return pi

    def getSerialAddress(self):
        addr = self.sendCmdGetRsp('RADDR')
        return addr

    def getCanAddress(self):
        addr = self.sendCmdGetRsp('RCADDR')
        return addr

    def getClock(self):
        clock = self.sendCmdGetRsp('RCLK')
        return clock

    def getModeNumber(self):
        mode = self.sendCmdGetRsp('RMODE')
        return mode

    def getMode(self):
        return self.mode

    def getSoftLimitMode(self):
        mode = self.sendCmdGetRsp('RSLM')
        return mode

    def getSoftLimitNeg(self):
        if 0 < self.scale_factor:
            limit = self.sendCmdGetRsp('RSLN')
        else:
            limit = self.sendCmdGetRsp('RSLP')
        return limit

    def getSoftLimitPos(self):
        if 0 < self.scale_factor:
            limit = self.sendCmdGetRsp('RSLP')
        else:
            limit = self.sendCmdGetRsp('RSLN')
        return limit

    def getInputs(self):
        inputs = []
        for input in range(8):
            inputs.append(self.sendCmdGetRsp('RIN({0})'.format(input)))
        return inputs

    def getStatus(self):
        sw0 = self.sendCmdGetRsp('RW(0)')
        sw1 = self.sendCmdGetRsp('RW(1)')
        sw2 = self.sendCmdGetRsp('RW(2)')
        sw3 = self.sendCmdGetRsp('RW(3)')
        if 0 < self.scale_factor:
            p = 'pos'
            n = 'neg'
        else:
            p = 'neg'
            n = 'pos'
        status = {
            'drive_ready': bool(sw0 & 1<<0),
            'motor_is_off': bool(sw0 & 1<<1),
            'trajectory_in_progress': bool(sw0 & 1<<2),
            'bus_voltage_fault': bool(sw0 & 1<<3),
            'over_current_occurred': bool(sw0 & 1<<4),
            'excessive_temperature_fault': bool(sw0 & 1<<5),
            'excessive_position_error': bool(sw0 & 1<<6),
            'velocity_limit': bool(sw0 & 1<<7),
            'real_time_temperature_limit': bool(sw0 & 1<<8),
            'de_dt_error_limit': bool(sw0 & 1<<9),
            p+'_hardware_limit_enabled': bool(sw0 & 1<<10),
            n+'_hardware_limit_enabled': bool(sw0 & 1<<11),
            'historical_'+p+'_hardware_limit': bool(sw0 & 1<<12),
            'historical_'+n+'_hardware_limit': bool(sw0 & 1<<13),
            p+'_hardware_limit_asserted': bool(sw0 & 1<<14),
            n+'_hardware_limit_asserted': bool(sw0 & 1<<15),

            'rise_capture_encoder_0_armed': bool(sw1 & 1<<0),
            'fall_capture_encoder_0_armed': bool(sw1 & 1<<1),
            'rising_edge_captured_encoder_0': bool(sw1 & 1<<2),
            'falling_edge_captured_encoder_0': bool(sw1 & 1<<3),
            'rise_capture_encoder_1_armed': bool(sw1 & 1<<4),
            'fall_capture_encoder_1_armed': bool(sw1 & 1<<5),
            'rising_edge_captured_encoder_1': bool(sw1 & 1<<6),
            'falling_edge_captured_encoder_1': bool(sw1 & 1<<7),
            'capture_0_input_state': bool(sw1 & 1<<8),
            'capture_1_input_state': bool(sw1 & 1<<9),
            'software_limits_enabled': bool(sw1 & 1<<10),
            'software_limit_mode': bool(sw1 & 1<<11),
            'historical_'+p+'_software_limit': bool(sw1 & 1<<12),
            'historical_'+n+'_software_limit': bool(sw1 & 1<<13),
            p+'_software_limit_asserted': bool(sw1 & 1<<14),
            n+'_software_limit_asserted': bool(sw1 & 1<<15),

            'error_channel_0': bool(sw2 & 1<<0),
            'error_channel_1': bool(sw2 & 1<<1),
            'usb_error': bool(sw2 & 1<<2),
            'can_error': bool(sw2 & 1<<4),
            'ethernet_error': bool(sw2 & 1<<6),
            'i2c_running': bool(sw2 & 1<<7),
            'watchdog_event': bool(sw2 & 1<<8),
            'adb_bad_checksum': bool(sw2 & 1<<9),
            'program_running': bool(sw2 & 1<<10),
            'trace_in_progress': bool(sw2 & 1<<11),
            'ee_write_buffer_overflow': bool(sw2 & 1<<12),
            'ee_busy': bool(sw2 & 1<<13),
            'command_error': bool(sw2 & 1<<14),
            'checksum_error': bool(sw2 & 1<<15),

            'position_software_error_limit': bool(sw3 & 1<<0),
            'torque_saturation': bool(sw3 & 1<<1),
            'voltage_saturation': bool(sw3 & 1<<2),
            'wraparound_occurred': bool(sw3 & 1<<3),
            'kg_enabled': bool(sw3 & 1<<4),
            'velocity_direction': bool(sw3 & 1<<5),
            'torque_direction': bool(sw3 & 1<<6),
            'io_fault_latch': bool(sw3 & 1<<7),
            'relative_position_mode': bool(sw3 & 1<<8),
            'x_stop_in_progress': bool(sw3 & 1<<9),
            'peak_current_saturation': bool(sw3 & 1<<10),
            'modulo_rollover': bool(sw3 & 1<<11),
            'brake_asserted': bool(sw3 & 1<<12),
            'brake_ok': bool(sw3 & 1<<13),
            'external_input_go_enabled': bool(sw3 & 1<<14),
            'velocity_target_reached': bool(sw3 & 1<<15),
            }
        return status

    def getStatusTrue(self):
        status = self.getStatus()
        status_true = [key for key in status.keys() if status[key]]
        status_true.sort()
        return status_true

    def getStatusTrueFormatted(self):
        status = self.getStatusTrue()
        # status_formatted = ''
        # for line in status:
        #     status_formatted += line + '\n'
        status_formatted = json.dumps(status,sort_keys=True,separators=(',', ':'))

        return status_formatted

    def getStatusOverCurrent(self):
        response = self.sendCmdGetRsp('RBa')
        return bool(response)

    def getStatusPosError(self):
        response = self.sendCmdGetRsp('RBe')
        return bool(response)

    def getStatusVelError(self):
        response = self.sendCmdGetRsp('RBv')
        return bool(response)

    def getStatusTemperatureError(self):
        response = self.sendCmdGetRsp('RBh')
        return bool(response)

    def getStatusTrajectoryInProgress(self):
        response = self.sendCmdGetRsp('RBt')
        return bool(response)

    def getPidValues(self):
        pid_values = {}
        pid_values['kp'] = self.sendCmdGetRsp('RKP')
        pid_values['ki'] = self.sendCmdGetRsp('RKI')
        pid_values['kd'] = self.sendCmdGetRsp('RKD')
        pid_values['kl'] = self.sendCmdGetRsp('RKL')
        pid_values['ks'] = self.sendCmdGetRsp('RKS')
        pid_values['kv'] = self.sendCmdGetRsp('RKV')
        pid_values['ka'] = self.sendCmdGetRsp('RKA')
        pid_values['kg'] = self.sendCmdGetRsp('RKG')
        return pid_values

    def setPidValues(self,pid_values):
        if 'kp' in pid_values:
            bytes_written = self.sendCmd('KP={0}'.format(pid_values['kp']))
        if 'ki' in pid_values:
            bytes_written = self.sendCmd('KI={0}'.format(pid_values['ki']))
        if 'kd' in pid_values:
            bytes_written = self.sendCmd('KD={0}'.format(pid_values['kd']))
        if 'kl' in pid_values:
            bytes_written = self.sendCmd('KL={0}'.format(pid_values['kl']))
        if 'ks' in pid_values:
            bytes_written = self.sendCmd('KS={0}'.format(pid_values['ks']))
        if 'kv' in pid_values:
            bytes_written = self.sendCmd('KV={0}'.format(pid_values['kv']))
        if 'ka' in pid_values:
            bytes_written = self.sendCmd('KA={0}'.format(pid_values['ka']))
        if 'kg' in pid_values:
            bytes_written = self.sendCmd('KG={0}'.format(pid_values['kg']))
        bytes_written = self.sendCmd('F')
        return bytes_written

    def getModelNumber(self):
        model_number = ''
        model_number += self._getEepromValue(32474,3)
        model_number += self._getEepromValue(32477,1)
        model_number += self._getEepromValue(32481,2)
        return model_number

    def getSerialNumber(self):
        serial_number = ''
        serial_number += self._getEepromValue(32512,1)
        return serial_number

    def _getEepromValue(self,address,length):
        self.sendCmd('xxx=' + str(address))
        self.sendCmd('EPTR=xxx')
        if length == 1:
            self.sendCmd('VLD(dd,{length})'.format(length=length))
            response = self.sendCmdGetRsp('Rdd')
            return str(response)
        elif 1 < length:
            self.sendCmd('VLD(ab[0],{length})'.format(length=length))
            rtn_str = ''
            for index in range(length):
                response = self.sendCmdGetRsp('Rab[{index}]'.format(index=index))
                if response != 0:
                    try:
                        rtn_str += chr(response)
                    except (TypeError,ValueError):
                        rtn_str += str(response)
            return rtn_str
        else:
            return ''

    # From output_unit/s/s
    def _convertAccToMotorUnits(self,acc):
        er = self.encoder_resolution
        sr = self.sample_rate
        sf = self.scale_factor
        print("type(er) = {0}".format(type(er)))
        print("er = {0}".format(er))
        print("type(sr) = {0}".format(type(sr)))
        print("type(sf) = {0}".format(type(sf)))
        acc = acc*(65536*(er/(sr**2))*sf)
        return abs(int(acc))

    # To output_unit/s/s
    def _convertAccFromMotorUnits(self,acc):
        if type(acc) != int:
            raise RuntimeError("acc must be type int, instead {0} is type {1}".format(acc,type(acc)))
        er = self.encoder_resolution
        sr = self.sample_rate
        sf = self.scale_factor
        acc = acc/(65536*(er/(sr**2))*sf)
        return abs(acc)

    # From output_unit/s
    def _convertVelToMotorUnits(self,vel):
        er = self.encoder_resolution
        sr = self.sample_rate
        sf = self.scale_factor
        vel = vel*(65536*(er/sr)*sf)
        return int(vel)

    # To output_unit/s
    def _convertVelFromMotorUnits(self,vel):
        if type(vel) != int:
            raise RuntimeError("vel must be type int, instead {0} is type {1}".format(vel,type(vel)))
        er = self.encoder_resolution
        sr = self.sample_rate
        sf = self.scale_factor
        vel = vel/(65536*(er/sr)*sf)
        return vel

    # From output_unit
    def _convertPosToMotorUnits(self,pos):
        er = self.encoder_resolution
        sr = self.sample_rate
        sf = self.scale_factor
        pos = pos*(er*sf)
        return int(pos)

    # To output_unit
    def _convertPosFromMotorUnits(self,pos):
        if type(pos) != int:
            raise RuntimeError("pos must be type int, instead {0} is type {1}".format(pos,type(pos)))
        er = self.encoder_resolution
        sr = self.sample_rate
        sf = self.scale_factor
        pos = pos/(er*sf)
        return pos

class AnimaticsMotors(list):

    def __init__(self,*args,**kwargs):
        if 'motor_names' in kwargs:
            self.motor_names = kwargs.pop('motor_names')
        else:
            self.motor_names = []
        if 'set_default_mode' in kwargs:
            self.set_default_mode = kwargs.pop('set_default_mode')
        else:
            self.set_default_mode = True

    def getAnimaticsMotorsInfo(self):
        animatics_motors_info = []
        for motor in self:
            if motor.motor_address is not 0:
                animatics_motors_info.append(motor.getAnimaticsMotorInfo())
        return animatics_motors_info

    def areAllHomed(self):
        homed = True
        motor_count = len(self) - 1
        for motor_index in range(1,(motor_count+1)):
            homed = homed and self[motor_index].isHomed()
        return homed

    def address(self,motor_count_limit=MOTOR_COUNT_LIMIT):
        self.sendCmd("WAKE",0)
        time.sleep(0.1)
        self.sendCmd("ECHO",0)
        self.sendCmd("END",0)
        self.sendCmd("SADDR0",0)
        self.sendCmd("ECHO_OFF",0)
        for motor_address in range(motor_count_limit):
            motor_address += 1
            self.sendCmd("SADDR" + str(motor_address),0)
            self.sendCmd("ECHO",motor_address)
            self.sendCmd("SLEEP",motor_address)
        self.sendCmd("WAKE",0)
        time.sleep(0.1)

    def count(self,motor_count_limit=MOTOR_COUNT_LIMIT):
        motor_count = 0
        for motor_address in range(motor_count_limit):
            motor_address += 1
            response = self.sendCmdGetRsp("RPI",motor_address)
            if (0 < len(response)) and (response[0] == '3'):
                print('Found motor {0}!'.format(motor_address))
                motor_count = motor_address
            else:
                break
        if motor_count == 0:
            self.debugPrint("No motors counted!")
        return motor_count

    def initialize(self,motor_count=None):
        if motor_count is None:
            motor_count = self.count()
        for motor_address in range(motor_count+1):
            self.debugPrint('Initializing motor {0}'.format(motor_address))
            motor = AnimaticsMotor(motor_address=motor_address,set_default_mode=self.set_default_mode)
            motor.sendCmd = partial(self.sendCmd,motor_address=motor_address)
            motor.sendCmdGetRsp = partial(self.sendCmdGetRsp,motor_address=motor_address)
            if motor_address is not 0:
                motor.initialize()
            self.append(motor)

    def sortByMotorAddress(self,*args,**kwargs):
        kwargs['key'] = operator.attrgetter('motor_address')
        self.sort(**kwargs)

    def getByMotorAddress(self,motor_address):
        motor_list = []
        for motor_index in range(len(self)):
            motor = self[motor_index]
            if motor.motor_address == motor_address:
                motor_list.append(motor)
        if len(motor_list) == 1:
            return motor_list[0]
        elif 1 < len(motor_list):
            return motor_list

    def sortByMotorAxis(self,*args,**kwargs):
        kwargs['key'] = operator.attrgetter('motor_axis','motor_address')
        self.sort(**kwargs)

    def getByMotorAxis(self,motor_axis):
        motor_list = []
        for motor_index in range(len(self)):
            motor = self[motor_index]
            if motor.motor_axis == motor_axis:
                motor_list.append(motor)
        if len(motor_list) == 1:
            return motor_list[0]
        elif 1 < len(motor_list):
            return motor_list

    def sortByMotorName(self,*args,**kwargs):
        kwargs['key'] = operator.attrgetter('motor_name','motor_address')
        self.sort(**kwargs)

    def getByMotorName(self,motor_name):
        motor_name = str(motor_name)
        motor_list = []
        for motor_index in range(len(self)):
            motor = self[motor_index]
            if motor.motor_name == motor_name:
                motor_list.append(motor)
        if len(motor_list) == 1:
            return motor_list[0]
        elif 1 < len(motor_list):
            return motor_list

    def setParameters(self,parameters_list):
        if len(parameters_list) <= len(self):
            for index in range(len(parameters_list)):
                parameters = parameters_list[index]
                self[index].setParameters(parameters)

    def stop(self):
        self[0].stop()

    def resetErrors(self):
        self[0].resetErrors()

class AnimaticsDevice(SerialDevice):

    BAUDRATE = 9600
    TIMEOUT = 0.05
    WRITE_READ_DELAY = 0.05
    WRITE_WRITE_DELAY = 0.05
    RESET_SLEEP = 1.0

    def __init__(self,*args,**kwargs):
        if 'baudrate' not in kwargs:
            kwargs.update({'baudrate': self.BAUDRATE})
        if 'timeout' not in kwargs:
            kwargs.update({'timeout': self.TIMEOUT})
        if 'write_read_delay' not in kwargs:
            kwargs.update({'write_read_delay': self.WRITE_READ_DELAY})
        if 'write_write_delay' not in kwargs:
            kwargs.update({'write_write_delay': self.WRITE_WRITE_DELAY})
        if 'port' not in kwargs:
            port =  findAnimaticsDevicePort(self.BAUDRATE)
            kwargs.update({'port': port})
        if 'debug' not in kwargs:
            kwargs.update({'debug': DEBUG})
            self.debug = DEBUG
        else:
            self.debug = kwargs['debug']
        if 'set_default_mode' in kwargs:
            self.set_default_mode = kwargs.pop('set_default_mode')
        else:
            self.set_default_mode = True

        t_start = time.time()
        super(AnimaticsDevice,self).__init__(*args,**kwargs)
        atexit.register(self._exitAnimaticsDevice)
        self.motors = AnimaticsMotors(set_default_mode=self.set_default_mode)
        self.motors.sendCmd = self.sendCmd
        self.motors.sendCmdGetRsp = self.sendCmdGetRsp
        self.motors.debugPrint = self.debugPrint
        self.motors.address()
        self.motors.initialize()
        t_end = time.time()
        self.debugPrint('Initialization time =', (t_end - t_start))

    def _exitAnimaticsDevice(self):
        self.stop()

    def getAnimaticsDeviceInfo(self):
        animatics_device_info = self.getSerialDeviceInfo()
        animatics_device_info['motors_info'] = self.motors.getAnimaticsMotorsInfo()
        return animatics_device_info

    def _conditionCmdStr(self,cmd_str,motor_address):
        if motor_address is not None:
            if (0 == len(cmd_str)) or not (MOTOR_ADDRESS_OFFSET <= ord(cmd_str[0]) <= (MOTOR_ADDRESS_OFFSET + MOTOR_ADDRESS_MAX)):
                cmd_str = chr(motor_address + MOTOR_ADDRESS_OFFSET) + cmd_str
        if not (cmd_str.endswith('\r') or cmd_str.endswith(' ')):
            cmd_str += ' '
        return cmd_str

    def sendCmd(self,cmd_str,motor_address=None,suggest=False):

        '''Sends Animatics command to device over serial port and
        returns number of bytes written. Setting suggest=True discards
        the command if it is sent too soon after the previously sent
        command, determined by write_write_delay value.'''

        lock.acquire()
        cmd_str = self._conditionCmdStr(cmd_str,motor_address)
        if (0 < len(cmd_str)) and (MOTOR_ADDRESS_OFFSET <= ord(cmd_str[0]) <= (MOTOR_ADDRESS_OFFSET + MOTOR_ADDRESS_MAX)):
            self.debugPrint(str(ord(cmd_str[0])-MOTOR_ADDRESS_OFFSET) + cmd_str[1:])
        if not suggest:
            bytes_written = self.writeCheckFreq(cmd_str,delay_write=True)
        else:
            try:
                bytes_written = self.writeCheckFreq(cmd_str,delay_write=False)
            except WriteFrequencyError:
                bytes_written = 0
        lock.release()
        return bytes_written

    def sendCmdGetRsp(self,cmd_str,motor_address=None):

        '''Sends Animatics command to device over serial port and
        returns response'''

        lock.acquire()
        cmd_str = self._conditionCmdStr(cmd_str,motor_address)
        if (0 < len(cmd_str)) and (MOTOR_ADDRESS_OFFSET <= ord(cmd_str[0]) <= (MOTOR_ADDRESS_OFFSET + MOTOR_ADDRESS_MAX)):
            self.debugPrint(str(ord(cmd_str[0])-MOTOR_ADDRESS_OFFSET) + cmd_str[1:])
        response = self.writeRead(cmd_str,use_readline=False,check_write_freq=True)
        if (0 < len(response)) and (MOTOR_ADDRESS_OFFSET <= ord(response[0]) <= (MOTOR_ADDRESS_OFFSET + MOTOR_ADDRESS_MAX)):
            self.debugPrint(str(ord(response[0])-MOTOR_ADDRESS_OFFSET) + response[1:])

        # Remove ECHO from response if necessary
        response = response.replace(cmd_str,'')
        try:
            response = int(response)
        except (ValueError,TypeError):
            pass
        lock.release()
        return response

    def stop(self):
        self.motors.stop()

    def resetErrors(self):
        self.motors.resetErrors()

def findAnimaticsDevicePort(baudrate):
    serialPortList = findSerialDevicePorts()
    matchingList = []
    for port in serialPortList:
        try:
            dev = SerialDevice(port=port,
                               baudrate=baudrate,
                               timeout=0.1,
                               write_write_delay=0.1,
                               write_read_delay=0.1,
                               debug=DEBUG)
            dev.flushInput()
            dev.flushOutput()
            dev.writeCheckFreq(chr(MOTOR_ADDRESS_OFFSET)+'WAKE ',delay_write=True)
            time.sleep(0.1)
            dev.writeCheckFreq(chr(MOTOR_ADDRESS_OFFSET)+'WAKE ',delay_write=True)
            time.sleep(0.1)
            dev.flushInput()
            dev.writeCheckFreq(chr(MOTOR_ADDRESS_OFFSET)+'ECHO ',delay_write=True)
            dev.readlines()
            response = dev.writeRead(chr(MOTOR_ADDRESS_OFFSET)+'RPI ',use_readline=False,check_write_freq=True)
            dev.close()
            # Animatics response will either be 'RPI 3.141592741 '
            # or '3.141592741 ' depending on ECHO setting
            # Must enable ECHO so it will work when multiple motors are chained
            response = response.replace(chr(MOTOR_ADDRESS_OFFSET)+'RPI ','')
            if (0 < len(response)) and (response[0] == '3'):
                print("Found an Animatics device!")
                return port
        except serial.SerialException:
            pass

    if len(matchingList) == 0:
        err_str = 'Could not find Animatics device. Check connections and power or specify port.\n'
        err_str += 'Tried ports: ' + str(serialPortList)
        raise RuntimeError(err_str)
    elif 1 < len(matchingList):
        err_str = 'Found more than one Animatics device. Specify port.'
        err_str += 'Matching ports: ' + str(matchingList)
        raise RuntimeError(err_str)
    else:
        return matchingList[0]

# -----------------------------------------------------------------------------------------
if __name__ == '__main__':

    debug = False
    dev = AnimaticsDevice(debug=debug)


text:
\hypertarget{main_8cpp}{\section{test/main.cpp File Reference}
\label{main_8cpp}\index{test/main.\-cpp@{test/main.\-cpp}}
}

main program to run tests

{\ttfamily \#include $<$gtest/gtest.\-h$>$}\\*
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
int \hyperlink{main_8cpp_a3c04138a5bfe5d72780bb7e82a18e627}{main} (int argc, char $\ast$$\ast$argv)
\end{DoxyCompactItemize}

\subsection{Detailed Description}
main program to run tests This program performs all test cases defined in \hyperlink{test_8cpp}{test.\-cpp}

\begin{DoxyAuthor}{Author}
Banuprathap Anandan
\end{DoxyAuthor}
\begin{DoxyDate}{Date}
03/14/2017
\end{DoxyDate}

\subsection{Function Documentation}
\hypertarget{main_8cpp_a3c04138a5bfe5d72780bb7e82a18e627}{\index{main.\-cpp@{main.\-cpp}!main@{main}}
\index{main@{main}!main.cpp@{main.\-cpp}}
\subsubsection[{main}]{\setlength{\rightskip}{0pt plus 5cm}int main (
\begin{DoxyParamCaption}
\item[{int}]{argc, }
\item[{char $\ast$$\ast$}]{argv}
\end{DoxyParamCaption}
)}}\label{main_8cpp_a3c04138a5bfe5d72780bb7e82a18e627}

\begin{DoxyCode}
44                                 \{
45   ::testing::InitGoogleTest(&argc, argv);
46   \textcolor{keywordflow}{return} RUN\_ALL\_TESTS();
47 \}
\end{DoxyCode}


text:
<!--
Description: thorn
Expect:      feed['title'] == u'testing \xfe entity'
-->
<rss>
<channel>
<title>testing þ entity</title>
</channel>
</rss>


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Form\DataTransformer;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Sylius\Component\Core\Model\TaxonInterface;
use Sylius\Component\Taxonomy\Repository\TaxonRepositoryInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Webmozart\Assert\Assert;

final class TaxonsToCodesTransformer implements DataTransformerInterface
{
    /** @var TaxonRepositoryInterface */
    private $taxonRepository;

    public function __construct(TaxonRepositoryInterface $taxonRepository)
    {
        $this->taxonRepository = $taxonRepository;
    }

    /**
     * {@inheritdoc}
     *
     * @throws \InvalidArgumentException
     */
    public function transform($value): Collection
    {
        Assert::nullOrIsArray($value);

        if (empty($value)) {
            return new ArrayCollection();
        }

        return new ArrayCollection($this->taxonRepository->findBy(['code' => $value]));
    }

    /**
     * {@inheritdoc}
     *
     * @throws \InvalidArgumentException
     */
    public function reverseTransform($taxons): array
    {
        Assert::isInstanceOf($taxons, Collection::class);

        if (null === $taxons) {
            return [];
        }

        return array_map(function (TaxonInterface $taxon) {
            return $taxon->getCode();
        }, $taxons->toArray());
    }
}


text:
'use strict'
require('codemo/lib/get-outputs')


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Screen sleep mode on off"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/btnDisable"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnEnable"
        android:layout_below="@+id/btnEnable"
        android:layout_marginTop="48dp"
        android:text="Screen sleep mode disable"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/btnEnable"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:enabled="false"
        android:text="Screen sleep mode enable"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>
<!-- From: file:/home/abado/AndroidStudioProjects/android/utils/src/main/res/layout/screen_mode_dis_ean_act.xml -->


text:
=head1 NAME

merge_stocks.pl - merge stocks using a file with stocks to merge

=head1 DESCRIPTION

merge_stocks.pl -H [database host] -D [database name]  [ -x ] mergefile.txt

Options:

 -H the database host
 -D the database name
 -x flag; if present, delete the empty remaining accession

mergefile.txt: A tab-separated file with two columns. Include the following header as the first line: bad name  good name

All the metadata of bad name will be transferred to good name.
If -x is used, stock with name bad name will be deleted.

=head1 AUTHOR

Lukas Mueller <lam87@cornell.edu>

=cut

use strict;

use Getopt::Std;
use CXGN::DB::InsertDBH;
use CXGN::DB::Schemas;
use CXGN::Stock;

our($opt_H, $opt_D, $opt_x);
getopts('H:D:x');

print "Password for $opt_H / $opt_D: \n";
my $pw = (<STDIN>);
chomp($pw);

my $delete_merged_stock = $opt_x;

print STDERR "Note: -x: Deleting stocks that have been merged into other stocks.\n";

print STDERR "Connecting to database...\n";
my $dsn = 'dbi:Pg:database='.$opt_D.";host=".$opt_H.";port=5432";

my $dbh = DBI->connect($dsn, "postgres", $pw, { AutoCommit => 0, RaiseError=>1 });

print STDERR "Connecting to DBI schema...\n";
my $bcs_schema = Bio::Chado::Schema->connect($dsn, "postgres", $pw);

my $s = CXGN::DB::Schemas->new({ dbh => $dbh });
my $schema = $s->bcs_schema();
my $file = shift;

open(my $F, "<", $file) || die "Can't open file $file.\n";

my $header = <$F>;

my @merged_stocks_to_delete = ();

print STDERR "Skipping header line $header\n";
eval {
    while (<$F>) {
        print STDERR "Read line: $_\n";
	chomp;
	my ($merge_stock_name, $good_stock_name) = split /\t/;
	print STDERR "bad name: $merge_stock_name, good name: $good_stock_name\n";

	# for now, only allow accessions to be merged!
	my $accession_type_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'accession', 'stock_type')->cvterm_id();

	print STDERR "Working with accession type id of $accession_type_id...\n";

	my $stock_row = $schema->resultset("Stock::Stock")->find( { uniquename => $good_stock_name, type_id=>$accession_type_id } );
	if (!$stock_row) {
	    print STDERR "Stock $good_stock_name (of type accession) not found. Skipping...\n";

	    next();
	}

	my $merge_row = $schema->resultset("Stock::Stock")->find( { uniquename => $merge_stock_name, type_id => $accession_type_id  } );
	if (!$merge_row) {
	    print STDERR "Stock $merge_stock_name (of type accession) not available for merging. Skipping\n";
	    next();
	}

	my $good_stock = CXGN::Stock->new( { schema => $schema, stock_id => $stock_row->stock_id });
	my $merge_stock = CXGN::Stock->new( { schema => $schema, stock_id => $merge_row->stock_id });

	print STDERR "Merging stock $merge_stock_name into $good_stock_name... ";
	$good_stock->merge($merge_stock->stock_id());

	if ($delete_merged_stock) {
	    push @merged_stocks_to_delete, $merge_stock->stock_id();
	}

	print STDERR "Done.\n";
    }

    if ($delete_merged_stock) {
	print STDERR "Delete merged stocks ( -x option)...\n";
	foreach my $remove_stock_id (@merged_stocks_to_delete) {
	    my $q = "delete from phenome.stock_owner where stock_id=?";
	    my $h = $dbh->prepare($q);
	    $h->execute($remove_stock_id);

	    $q = "delete from phenome.stock_image where stock_id=?";
	    $h = $dbh->prepare($q);
	    $h->execute($remove_stock_id);

	    my $row = $schema->resultset('Stock::Stock')->find( { stock_id => $remove_stock_id });
	    print STDERR "Deleting stock ".$row->uniquename." (id=$remove_stock_id)\n";
	    $row->delete();
	}
	print STDERR "Done with deletions.\n";
    }

};
if ($@) {
    print STDERR "An ERROR occurred ($@). Rolling back changes...\n";
    $dbh->rollback();
}
else {
    print STDERR "Script is done. Committing... ";
    $dbh->commit();
    print STDERR "Done.\n";
}


text:
title: My Trick of Deciding if a Link Should Open a New Browser Tab
date: '2018-09-20'
slug: target-blank
---

Albert Kim [just discovered one way](https://twitter.com/rudeboybert/status/1042418261596545027) to make links open in new browser tabs for R Markdown users: you can add an attribute `target="_blank"` after a link, e.g., `[example website](https://example.com){target="_blank"}`.

## You should thoroughly learn Pandoc's Markdown

[No matter how many times](/en/2017/11/thanks-tj-mahr/) I have recommended R Markdown users to read the _full_ Pandoc manual at least once, I still want to recommend it again. You won't really appreciate how powerful Pandoc's Markdown is until you read the full manual once. The [`link_attributes` extension](https://pandoc.org/MANUAL.html#extension-link_attributes) is just one of the many, many, many useful features of Pandoc's Markdown.

## What's `target="blank"`?

In Albert's case, however, you still won't know how to make a link open in a new browser tab unless you understand [what `<a target="_blank">` means in HTML](https://www.w3schools.com/tags/att_a_target.asp). The _two_ prerequisites, reading Pandoc's manual _and_ knowing HTML, is probably why many users couldn't figure out how to write a URL in Markdown to be opened in a new tab.

## The real tricky issue

Pure technical issues are often relatively easy to resolve. Things will become complicated whenever humans are involved.

As I expected, there will be people who hate links that always open in new tabs, such as [Bob](https://twitter.com/Bootvis/status/1042448271350943749) in the Twitter thread:

> Please don't decide for the user. If I want to open a link in a new tab, my browser makes it easy to do so, and if I want to go back to your document, I use the back button.

Without `target="_blank"`, readers can actually make the decision by themselves. If they do want the link to be opened in a new tab, they can right-click on the link and use the context menu "Open Link in New Tab", or hold a key while (left-)clicking the link (e.g., on macOS, hold `Command`). This is no big deal^[It might be tricky or impossible on mobile devices where you don't have a physical keyboard, though.]. If you force a link to be opened in a new tab, you may offend readers who would rather hit the Back button instead of closing a new tab when they want to leave the new tab.

The benefit of opening a link in a new tab is that _the state of the current page can be preserved_ while you read the page in the new tab. This is not something that the Back button can absolutely guarantee. Many of you may have been warned when you make payments online that you should not use the Back button (because you may end up paying twice). What happens when you hit the Back button is not necessarily just to bring you back to the previous page.

With that in mind, opening a link in a new tab may sound like a good idea (at least it never hurts technically), but as I mentioned in [a previous post](/en/2018/09/notebook-war/), it is easy to overdo good ideas. Users may hate it when too many new tabs/windows are opened from your web page.

## What on earth do new tabs indicate?

Let's back up a little from the technical stuff and think more about the core problem: what do new tabs mean, and when are you most likely to open a link in a new tab?

There may not be a universal answer that satisfies everyone, but to me, a new tab means _a new context_. Then the question becomes, which links are more likely to take the readers to new contexts? I tend to think that an _external_ URL indicates a new context. By "external URL", I mean a URL that takes you to a different website. Roughly speaking, two websites are different if their domain names are different.

## Open external links in new tabs automatically

Finally we are back to the technical world again. On my personal website, I use a few lines of JavaScript to automatically add `target="_blank"` to external links:

```js
(function() {
  var links = document.getElementsByTagName('a');
  for (var i = 0; i < links.length; i++) {
    if (/^(https?:)?\/\//.test(links[i].getAttribute('href'))) {
      links[i].target = '_blank';
    }
  }
})();
```

To fully understand the code above, you have to understand URLs. You may think URLs are simple, but they may not be. People [make mistakes](/en/2018/01/valid-url/) all the time. People [get confused](https://twitter.com/xieyihui/status/1040441928087683072) over and over again. Relative URLs? Absolute URLs? Absolute relative URLs? Protocol-free URLs? You may read my least favorite part of the **blogdown** book to know more: [Appendix B.1](https://bookdown.org/yihui/blogdown/html.html).

![I'm just going to shoot myself](https://slides.yihui.org/gif/shoot-myself.gif)

Long story short, when I add links to my web pages, I omit the protocol and domain in the URLs^[This makes the URLs more portable: when I change my domain name or protocol, I don't need to update these URLs.] if they are internal links to pages that are still on my website (under `https://yihui.org/`), e.g.,

```md
[the knitr website](/knitr/)
```

and I use full URLs for links to other websites, e.g.,

```md
[the rmarkdown website](https://rmarkdown.rstudio.com)
```

This way, I know that URLs starting with `https://` are supposed to be external links, hence I can detect them using the JS regular expression `/^(https?:)?\/\//`, which can match `https://`, `http://`, and `//`. Once I detect a link of which the `href` attribute points to an external URL, I add the attribute `target="_blank"` to it. So whenever you see a new tab after clicking a link on my website, it means you are being navigated to a different website (be prepared for the new context).

## Summary

I presented a way to make links open in new tabs without requiring the author of the web page to hard-code the `target="_blank"` attribute in links, and at the same time, without annoying readers too much (hopefully). The fundamental assumption of this approach is: a different tab == a different context == a different website. Is this a reasonable assumption for everyone? Of course, I'm not 100% sure.

Good software is never about coding alone. It is about coding plus psychology (thinking one step further to minimize the annoyance). Even trivially small problems are worth thinking.


text:
cask 'unity-android-support-for-editor' do
  version '2017.2.0f3,46dda1414e51'
  sha256 '58ee014bb314b743b9561bf816143f49ef0e53b119ed51c4c641f7cf1cce5255'

  url "http://netstorage.unity3d.com/unity/#{version.after_comma}/MacEditorTargetInstaller/UnitySetup-Android-Support-for-Editor-#{version.before_comma}.pkg"
  name 'Unity Android Build Support'
  homepage 'https://unity3d.com/unity/'

  depends_on cask: 'unity'

  pkg "UnitySetup-Android-Support-for-Editor-#{version.before_comma}.pkg"

  uninstall pkgutil: 'com.unity3d.AndroidSupport'
end


text:
package nl.jqno.equalsverifier.integration.extra_features;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.internal.testhelpers.ExpectedException;
import nl.jqno.equalsverifier.testhelpers.types.Multiple;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class RelaxedEqualsPreconditionTest {

    private static final String PRECONDITION = "Precondition";
    private static final String DIFFERENT_CLASSES = "are of different classes";
    private static final String TWO_IDENTICAL_OBJECTS_APPEAR = "two identical objects appear";
    private static final String NOT_ALL_EQUAL_OBJECT_ARE_EQUAL = "not all equal objects are equal";
    private static final String EQUAL_IS_UNEQUAL =
        "an equal example also appears as unequal example.";
    private static final String OBJECT_APPEARS_TWICE = "the same object appears twice";
    private static final String TWO_OBJECTS_ARE_EQUAL = "two objects are equal to each other";

    private Multiple red;
    private Multiple blue;
    private Multiple green;

    @BeforeEach
    public void setup() {
        red = new Multiple(1, 2);
        blue = new Multiple(2, 1);
        green = new Multiple(2, 2);
    }

    @Test
    public void throw_whenTheFirstExampleIsNull() {
        ExpectedException
            .when(() -> EqualsVerifier.forRelaxedEqualExamples(null, blue))
            .assertThrows(IllegalArgumentException.class)
            .assertMessageContains("First example is null.");
    }

    @Test
    public void throw_whenTheSecondExampleIsNull() {
        ExpectedException
            .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, null))
            .assertThrows(IllegalArgumentException.class)
            .assertMessageContains("Second example is null.");
    }

    @Test
    public void succeed_whenTheVarargArrayIsNull() {
        EqualsVerifier
            .forRelaxedEqualExamples(red, blue, (Multiple[]) null)
            .andUnequalExample(green)
            .verify();
    }

    @Test
    public void fail_whenAVarargParameterIsNull() {
        Multiple another = new Multiple(-1, -2);
        ExpectedException
            .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue, another, null))
            .assertThrows(IllegalArgumentException.class)
            .assertMessageContains("One of the examples is null.");
    }

    @Test
    public void fail_whenTheUnequalExampleIsNull() {
        ExpectedException
            .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExample(null))
            .assertThrows(IllegalArgumentException.class)
            .assertMessageContains("First example is null.");
    }

    @Test
    public void succeed_whenTheUnequalVarargArrayIsNull() {
        EqualsVerifier
            .forRelaxedEqualExamples(red, blue)
            .andUnequalExamples(green, (Multiple[]) null)
            .verify();
    }

    @Test
    public void fail_whenAnUnequalVarargParameterIsNull() {
        Multiple another = new Multiple(3, 3);
        ExpectedException
            .when(() ->
                EqualsVerifier
                    .forRelaxedEqualExamples(red, blue)
                    .andUnequalExamples(green, another, null)
            )
            .assertThrows(IllegalArgumentException.class);
    }

    @Test
    public void fail_whenEqualExamplesAreOfDifferentRuntimeTypes() {
        SubMultiple sm = new SubMultiple(1, 2);
        ExpectedException
            .when(() ->
                EqualsVerifier.forRelaxedEqualExamples(sm, red).andUnequalExample(green).verify()
            )
            .assertFailure()
            .assertMessageContains(
                PRECONDITION,
                DIFFERENT_CLASSES,
                SubMultiple.class.getSimpleName(),
                Multiple.class.getSimpleName()
            );
    }

    @Test
    public void fail_whenTheSameExampleIsGivenTwice() {
        ExpectedException
            .when(() ->
                EqualsVerifier.forRelaxedEqualExamples(red, red).andUnequalExample(green).verify()
            )
            .assertFailure()
            .assertMessageContains(
                PRECONDITION,
                OBJECT_APPEARS_TWICE,
                Multiple.class.getSimpleName()
            );
    }

    @Test
    public void fail_whenTwoExamplesAreIdentical() {
        Multiple aa = new Multiple(1, 2);
        ExpectedException
            .when(() ->
                EqualsVerifier.forRelaxedEqualExamples(red, aa).andUnequalExample(green).verify()
            )
            .assertFailure()
            .assertMessageContains(
                PRECONDITION,
                TWO_IDENTICAL_OBJECTS_APPEAR,
                Multiple.class.getSimpleName()
            );
    }

    @Test
    public void fail_whenTwoExamplesAreNotEqualAtAll() {
        Multiple aa = new Multiple(42, 42);
        ExpectedException
            .when(() ->
                EqualsVerifier.forRelaxedEqualExamples(red, aa).andUnequalExample(green).verify()
            )
            .assertFailure()
            .assertMessageContains(
                PRECONDITION,
                NOT_ALL_EQUAL_OBJECT_ARE_EQUAL,
                Multiple.class.getSimpleName()
            );
    }

    @Test
    public void fail_whenAnEqualExampleIsAlsoGivenAsAnUnequalExample() {
        ExpectedException
            .when(() -> EqualsVerifier.forRelaxedEqualExamples(red, green).andUnequalExample(green))
            .assertThrows(IllegalStateException.class)
            .assertMessageContains(PRECONDITION, EQUAL_IS_UNEQUAL);
    }

    @Test
    public void fail_whenTheSameUnequalExampleIsGivenTwice() {
        ExpectedException
            .when(() ->
                EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, green)
            )
            .assertThrows(IllegalStateException.class)
            .assertMessageContains(PRECONDITION, TWO_OBJECTS_ARE_EQUAL);
    }

    @Test
    public void fail_whenTwoUnequalExamplesAreEqualToEachOther() {
        Multiple xx = new Multiple(2, 2);
        ExpectedException
            .when(() ->
                EqualsVerifier.forRelaxedEqualExamples(red, blue).andUnequalExamples(green, xx)
            )
            .assertThrows(IllegalStateException.class)
            .assertMessageContains(PRECONDITION, TWO_OBJECTS_ARE_EQUAL);
    }

    public static class SubMultiple extends Multiple {

        public SubMultiple(int a, int b) {
            super(a, b);
        }
    }
}


text:
<?php

namespace Symfony\Bundle\DoctrineBundle\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\Tools\EntityRepositoryGenerator;
use Symfony\Bundle\DoctrineBundle\Mapping\DisconnectedMetadataFactory;

/**
 * Generate entity classes from mapping information
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Jonathan H. Wage <jonwage@gmail.com>
 */
class GenerateEntitiesDoctrineCommand extends DoctrineCommand {
	protected function configure() {
		$this->setName('doctrine:generate:entities')->setAliases(array('generate:doctrine:entities'))->setDescription('Generate entity classes and method stubs from your mapping information')->addArgument('name', InputArgument::REQUIRED, 'A bundle name, a namespace, or a class name')
				->addOption('path', null, InputOption::VALUE_REQUIRED, 'The path where to generate entities when it cannot be guessed')->addOption('no-backup', null, InputOption::VALUE_NONE, 'Do not backup existing entities files.')
				->setHelp(
						<<<EOT
The <info>doctrine:generate:entities</info> command generates entity classes
and method stubs from your mapping information:

You have to limit generation of entities:

* To a bundle:

  <info>php app/console doctrine:generate:entities MyCustomBundle</info>

* To a single entity:

  <info>php app/console doctrine:generate:entities MyCustomBundle:User</info>
  <info>php app/console doctrine:generate:entities MyCustomBundle/Entity/User</info>

* To a namespace

  <info>php app/console doctrine:generate:entities MyCustomBundle/Entity</info>

If the entities are not stored in a bundle, and if the classes do not exist,
the command has no way to guess where they should be generated. In this case,
you must provide the <comment>--path</comment> option:

  <info>php app/console doctrine:generate:entities Blog/Entity --path=src/</info>

By default, the unmodified version of each entity is backed up and saved
(e.g. Product.php~). To prevent this task from creating the backup file,
pass the <comment>--no-backup</comment> option:

  <info>php app/console doctrine:generate:entities Blog/Entity --no-backup</info>

<error>Important:</error> Even if you specified Inheritance options in your
XML or YAML Mapping files the generator cannot generate the base and
child classes for you correctly, because it doesn't know which
class is supposed to extend which. You have to adjust the entity
code manually for inheritance to work!

EOT
				);
	}

	protected function execute(InputInterface $input, OutputInterface $output) {
		$manager = new DisconnectedMetadataFactory($this->getContainer()->get('doctrine'));

		try {
			$bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('name'));

			$output->writeln(sprintf('Generating entities for bundle "<info>%s</info>"', $bundle->getName()));
			$metadata = $manager->getBundleMetadata($bundle);
		} catch (\InvalidArgumentException $e) {
			$name = strtr($input->getArgument('name'), '/', '\\');

			if (false !== $pos = strpos($name, ':')) {
				$name = $this->getContainer()->get('doctrine')->getEntityNamespace(substr($name, 0, $pos)) . '\\' . substr($name, $pos + 1);
			}

			if (class_exists($name)) {
				$output->writeln(sprintf('Generating entity "<info>%s</info>"', $name));
				$metadata = $manager->getClassMetadata($name, $input->getOption('path'));
			} else {
				$output->writeln(sprintf('Generating entities for namespace "<info>%s</info>"', $name));
				$metadata = $manager->getNamespaceMetadata($name, $input->getOption('path'));
			}
		}

		$generator = $this->getEntityGenerator();

		$backupExisting = !$input->getOption('no-backup');
		$generator->setBackupExisting($backupExisting);

		$repoGenerator = new EntityRepositoryGenerator();
		foreach ($metadata->getMetadata() as $m) {
			if ($backupExisting) {
				$basename = substr($m->name, strrpos($m->name, '\\') + 1);
				$output->writeln(sprintf('  > backing up <comment>%s.php</comment> to <comment>%s.php~</comment>', $basename, $basename));
			}
			$output->writeln(sprintf('  > generating <comment>%s</comment>', $m->name));
			$generator->generate(array($m), $metadata->getPath());

			if ($m->customRepositoryClassName && false !== strpos($m->customRepositoryClassName, $metadata->getNamespace())) {
				$repoGenerator->writeEntityRepositoryClass($m->customRepositoryClassName, $metadata->getPath());
			}
		}
	}
}


text:
using System;
using System.Text;
using System.Windows.Forms;
using NLog;
using NLog.Windows.Forms;

namespace RichTextBox2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Programmatic configuration that is equivalent to
            // the "toolstrip" target configuration in NLog.config
            ToolStripItemTarget target = new ToolStripItemTarget();
            target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            target.ToolStripName = "statusStrip1";
            target.ItemName = "toolStripStatusLabel1";
            target.FormName = "Form1";

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            Logger logger = LogManager.GetLogger("Example");
            logger.Trace("trace log message, ");
            logger.Debug("debug log message, ");
            logger.Info("info log message, ");
            logger.Warn("warn log message, ");
            logger.Error("error log message, ");
            logger.Fatal("fatal log message");
        }
    }
}


text:
<?php
namespace GbiliAclGuard\Service;

class AclGuardFactory implements \Zend\ServiceManager\FactoryInterface
{
    /**
     *
     * @param ServiceLocatorInterface $sm
     */
    public function createService(\Zend\ServiceManager\ServiceLocatorInterface $sm)
    {
        $guard = new AclGuard();
        $guard->setAcl($sm->get('acl'));
        $guard->setAuthenticationService($sm->get('Zend\Authentication\AuthenticationService'));
        $guard->setMvcEvent($sm->get('Application')->getMvcEvent());
        return $guard;
    }
}


text:
class GraphQL::StaticValidation::Validator
  # Order is important here. Some validators return {GraphQL::Visitor::SKIP}
  # which stops the visit on that node. That way it doesn't try to find fields on types that
  # don't exist, etc.
  VALIDATORS = [
    GraphQL::StaticValidation::DirectivesAreDefined,
    GraphQL::StaticValidation::ArgumentsAreDefined,
    GraphQL::StaticValidation::RequiredArgumentsArePresent,
    GraphQL::StaticValidation::ArgumentLiteralsAreCompatible,
    GraphQL::StaticValidation::FragmentTypesExist,
    GraphQL::StaticValidation::FragmentsAreOnCompositeTypes,
    GraphQL::StaticValidation::FragmentsAreFinite,
    GraphQL::StaticValidation::FragmentsAreUsed,
    GraphQL::StaticValidation::FieldsAreDefinedOnType,
    GraphQL::StaticValidation::FieldsWillMerge,
    GraphQL::StaticValidation::FieldsHaveAppropriateSelections,
  ]

  def initialize(schema:, validators: VALIDATORS)
    @schema = schema
    @validators = validators
  end

  def validate(document)
    context = Context.new(@schema, document)
    @validators.each do |validator|
      validator.new.validate(context)
    end
    context.visitor.visit(document)
    context.errors.map(&:to_h)
  end

  class Context
    attr_reader :schema, :document, :errors, :visitor, :fragments
    def initialize(schema, document)
      @schema = schema
      @document = document
      @fragments = {}
      @errors = []
      @visitor = GraphQL::Visitor.new
      @visitor[GraphQL::Nodes::FragmentDefinition] << -> (node, parent) { @fragments[node.name] = node }
      @type_stack = GraphQL::StaticValidation::TypeStack.new(schema, visitor)
    end

    def object_types
      @type_stack.object_types
    end

    def field_definition
      @type_stack.field_definitions.last
    end
  end
end


text:
class ImportSourceDataTaskPresenter < JobTaskPresenter
  def to_hash
    super.merge({
                    :source_id => model.payload.source_id,
                    :destination_id => model.payload.destination_id,
                    :row_limit => model.payload.row_limit,
                    :truncate => model.payload.truncate,
                    :source_name => model.payload.source.name,
                    :destination_name => model.payload.destination_name || model.payload.destination.name
                })
  end
end


text:
package org.robbins.raspberry.pi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:applicationContext-webapp.xml")
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application;
    }
}


text:
package com.evolveum.midpoint.repo.cache;

import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.schema.cache.CacheType;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.SingleCacheStateInformationType;
import org.cache2k.Cache2kBuilder;
import org.cache2k.expiry.ExpiryPolicy;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 */
@Component
public class GlobalVersionCache extends AbstractGlobalCache {

    private static final Trace LOGGER = TraceManager.getTrace(GlobalVersionCache.class);

    private static final String CACHE_NAME = "versionCache";

    private org.cache2k.Cache<String, GlobalCacheObjectVersionValue> cache;

    public void initialize() {
        if (cache != null) {
            LOGGER.warn("Global version cache was already initialized -- ignoring this request.");
            return;
        }
        long capacity = getCapacity();
        if (capacity == 0) {
            LOGGER.warn("Capacity for " + getCacheType() + " is set to 0; this cache will be disabled (until system restart)");
            cache = null;
        } else {
            cache = new Cache2kBuilder<String, GlobalCacheObjectVersionValue>() {}
                    .name(CACHE_NAME)
                    .entryCapacity(capacity)
                    .expiryPolicy(getExpirePolicy())
                    .storeByReference(true) // this is default in the current version of cache2k; we need this because we update TTL value for cached objects
                    .build();
            LOGGER.info("Created global repository object version cache with a capacity of {} objects", capacity);
        }
    }

    private ExpiryPolicy<String, GlobalCacheObjectVersionValue> getExpirePolicy() {
        return (key, value, loadTime, oldEntry) -> getExpiryTime(value.getObjectType());
    }

    @PreDestroy
    public void destroy() {
        if (cache != null) {
            cache.close();
            cache = null;
        }
    }

    public boolean isAvailable() {
        return cache != null;
    }

    public String get(String oid) {
        if (cache != null) {
            GlobalCacheObjectVersionValue<?> value = cache.peek(oid);
            return value != null ? value.getVersion() : null;
        } else
            return null;
    }

    public void remove(@NotNull String oid) {
        if (cache != null) {
            cache.remove(oid);
        }
    }

    public void remove(@NotNull Class<?> type, String oid) {
        // todo deduplicate
        if (cache != null) {
            if (oid != null) {
                cache.remove(oid);
            } else {
                cache.invokeAll(cache.keys(), e -> {
                    if (e.getValue() != null && type.isAssignableFrom(e.getValue().getObjectType())) {
                        e.remove();
                    }
                    return null;
                });
            }
        }
    }

    @Override
    protected CacheType getCacheType() {
        return CacheType.GLOBAL_REPO_VERSION_CACHE;
    }

    @Override
    public void clear() {
        if (cache != null) {
            cache.clear();
        }
    }

    Collection<SingleCacheStateInformationType> getStateInformation() {
        Map<Class<?>, Integer> counts = new HashMap<>();
        AtomicInteger size = new AtomicInteger(0);
        if (cache != null) {
            cache.invokeAll(cache.keys(), e -> {
                Class<?> objectType = e.getValue().getObjectType();
                counts.compute(objectType, (type, count) -> count != null ? count+1 : 1);
                size.incrementAndGet();
                return null;
            });
            SingleCacheStateInformationType info = new SingleCacheStateInformationType(prismContext)
                    .name(GlobalVersionCache.class.getName())
                    .size(size.get());
            counts.forEach((type, count) ->
                    info.beginComponent()
                        .name(type.getSimpleName())
                        .size(count));
            return Collections.singleton(info);
        } else {
            return Collections.emptySet();
        }
    }

    public <T extends ObjectType> void put(PrismObject<T> object) {
        if (cache != null) {
            cache.put(object.getOid(), new GlobalCacheObjectVersionValue<>(object.asObjectable().getClass(), object.getVersion()));
        }
    }

    public void put(String oid, Class<? extends ObjectType> type, String version) {
        if (cache != null) {
            cache.put(oid, new GlobalCacheObjectVersionValue<>(type, version));
        }
    }
}