text:
package com.aerolush.lucene.store;

import com.spikeify.Spikeify;
import com.spikeify.annotations.Generation;
import com.spikeify.annotations.Ignore;
import com.spikeify.annotations.UserKey;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * File is split in segments of SEGMENT_SIZE (array of bytes)
 */
public class File {

	static int SEGMENT_SIZE = 4096;

	@Generation
	public Integer generation;

	/**
	 * File name
	 */
	@UserKey
	protected String name;

	/**
	 * Total file length in bytes
	 */
	protected long length; // total length

	/**
	 * Last modified time
	 */
	protected long timeModified;

	/**
	 * Unique id of segments associated with file
	 */
	protected String segmentsName;

	/**
	 * file storage ... segment ID -> array of bytes (segment starting at 1)
	 **/
/*	private Map<Long, String> segments = new HashMap<>();

	@Ignore
	private static Map<String, byte[]> cachedSegments = new HashMap<>();*/

	// number of segments stored in different entity
	//	private long segments = 0;

	//private Map<Long, byte[]> data = new HashMap<>();

	// will not be stored into entity ... runtime property only
	@Ignore
	private long segmentPointer = 1;

	// temp buffer
	@Ignore
	private ByteBuffer buffer = ByteBuffer.allocate(SEGMENT_SIZE);

	public File(String fileName) {

		this();
		name = fileName;
	}

	public File() {

		timeModified = System.currentTimeMillis();
		length = 0;
		segmentsName = IdGenerator.generate(10);
	}

	public File(File file, String fileName) {

		this(fileName);
		length = file.getLength();
		segmentsName = file.segmentsName;
	}

	public long getLength() {

		return length;
	}

	/*public long getNumberOfSegments() {
		return data.size();
	}*/

	/**
	 * get specific segment of file
	 *
	 * @param segmentNo
	 * @return
	 * @throws IOException
	 **/
	ByteBuffer getSegment(long segmentNo, Spikeify spikeify) throws IOException {

		String id = FileSegment.generateId(segmentsName, segmentNo);
		FileSegment segment = spikeify.get(FileSegment.class).key(id).now();

		// byte[] segment = data.get(segmentNo);
		if (segment == null) {
			throw new IOException("Cannot read segment: " + segmentNo);
		}

		ByteBuffer buffer = ByteBuffer.allocate(segment.data.length);
		buffer.put(segment.data);
		buffer.flip();
		return buffer;
	}

	/**
	 * Fill up segments in buffer ...
	 *
	 * @param b
	 * @param offset
	 * @param writeLength
	 * @throws IOException
	 */
	void writeBytes(byte[] b, int offset, int writeLength, Spikeify spikeify) throws IOException {

		int remaining = buffer.remaining();

		if (remaining > writeLength) {
			length += writeLength;
			buffer.put(b, offset, writeLength);
		}
		else {
			length += remaining;
			buffer.put(b, offset, remaining);

			syncBuffer(spikeify);

			writeBytes(b, offset + remaining, writeLength - remaining, spikeify);
		}
	}

	private void syncBuffer(Spikeify spikeify) {

		buffer.flip();

		// store into data
		FileSegment segment = new FileSegment(segmentsName, segmentPointer, buffer.array());
		spikeify.update(segment).now();

		// data.put(segmentPointer, buffer.array());

		// TODO: storing into database ... but should we do this here or in directory?

		segmentPointer += 1;

		buffer.clear();
	}

	public String getFileName() {

		return name;
	}

	void close(Spikeify spikeify) {

		// Flush whats left in the buffer
		syncBuffer(spikeify);
	}

	/**
	 * Takes data from file (file name excluded)
	 *
	 * @param file to copy from
	 */
	public void copy(File file) {

		timeModified = System.currentTimeMillis();
		length = file.length;
		segmentsName = file.segmentsName;
	}
}


text:
<?php /** MicroUniqueValidator */

namespace Micro\Validator;

use Micro\Db\Injector;
use Micro\Form\IFormModel;
use Micro\Mvc\Models\Query;

/**
 * UniqueValidator class file.
 *
 * @author Oleg Lunegov <testuser@mail.linpax.org>
 * @link https://github.com/linpax/microphp-framework
 * @copyright Copyright (c) 2013 Oleg Lunegov
 * @license https://github.com/linpax/microphp-framework/blob/master/LICENSE
 * @package Micro
 * @subpackage Validator
 * @version 1.0
 * @since 1.0
 */
class UniqueValidator extends BaseValidator
{
    /**
     * @inheritdoc
     */
    public function validate(IFormModel $model)
    {
        foreach ($this->elements AS $element) {
            if (!$model->checkAttributeExists($element)) {
                $this->errors[] = 'Parameter '.$element.' not defined in class '.get_class($model);

                return false;
            }
            $elementValue = $model->$element;

            $query = new Query((new Injector)->getDriver());
            $query->select = $this->params['attribute'];
            $query->table = $this->params['table'];
            $query->addWhere($this->params['attribute'].'="'.$elementValue.'"');
            $query->limit = 1;
            $query->single = true;

            if ($query->run()) {
                return false;
            }
        }

        return true;
    }

    /**
     * @inheritdoc
     */
    public function client(IFormModel $model)
    {
        return '';
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/*
This is the custom post type post template.
If you edit the post type name, you've got
to change the name of this template to
reflect that name change.

i.e. if your custom post type is called
register_post_type( 'bookmarks',
then your single template should be
single-bookmarks.php

*/
?>

<?php get_header(); ?>

							<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

							<article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article">

<?php the_title(); ?>

<?php
										printf(__('Posted <time class="updated" datetime="%1$s" pubdate>%2$s</time> by %3$s & filed under %4$s.', 'bonestheme'), get_the_time('Y-m-j'), get_the_time(__('F jS, Y', 'bonestheme')), bones_get_the_author_posts_link(), get_the_term_list( $post->ID, 'custom_cat', ' ', ', ', '' ));
									?>

									<?php the_content(); ?>

<?php echo get_the_term_list( get_the_ID(), 'custom_tag', '' . __('Custom Tags:', 'bonestheme') . ' ', ', ' ) ?>

								<?php comments_template(); ?>

							<?php endwhile; ?>

							<?php else : ?>

<?php _e("Oops, Post Not Found!", "bonestheme"); ?>

<?php _e("Uh Oh. Something is missing. Try double checking things.", "bonestheme"); ?>

<?php _e("This is the error message in the single-custom_type.php template.", "bonestheme"); ?>

							<?php endif; ?>

						<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
Custom build hooks and scripts for Elastic Beanstalk:

- Optimizing NPM dependency installation, inspired by [this](http://stackoverflow.com/a/21260702/880859) StackOverflow anwer
- Customizing nginx proxy settings
- Installing and starting redis-server

## Usage

In order to use these build hooks in your application, all you need to do is add the following `env.config` file in a `.ebextensions/` directory in the root of your project:

```yaml
packages:
  yum:
    git: []
    gcc: []
    gcc-c++: []
    libxml2: []
    libxml2-devel: []
    make: []
    openssl-devel: []

option_settings:
  - option_name: NODE_ENV
    value: production
  - namespace: aws:elasticbeanstalk:container:nodejs
    option_name: NodeVersion
    value: 4.3.0

files:
  "/tmp/deployment/config/etc#nginx#nginx.conf" :
    mode: "000775"
    owner: root
    group: users
    source: https://raw.githubusercontent.com/jakemmarsh/ebs-setup/master/nginx.conf
  "/opt/elasticbeanstalk/env.vars" :
    mode: "000775"
    owner: root
    group: users
    source: https://raw.githubusercontent.com/jakemmarsh/ebs-setup/master/env.vars
  "/opt/elasticbeanstalk/hooks/configdeploy/pre/40install_node.sh" :
    mode: "000775"
    owner: root
    group: users
    source: https://raw.githubusercontent.com/jakemmarsh/ebs-setup/master/predeploy/40install_node.sh
  "/opt/elasticbeanstalk/hooks/appdeploy/pre/50npm.sh" :
    mode: "000775"
    owner: root
    group: users
    source: https://raw.githubusercontent.com/jakemmarsh/ebs-setup/master/predeploy/50npm.sh
  "/opt/elasticbeanstalk/hooks/configdeploy/pre/50npm.sh" :
    mode: "000666"
    owner: root
    group: users
    content: |
       #no need to run npm install during configdeploy
  "/opt/elasticbeanstalk/hooks/appdeploy/pre/40install_node.sh" :
    mode: "000775"
    owner: root
    group: users
    source: https://raw.githubusercontent.com/jakemmarsh/ebs-setup/master/predeploy/40install_node.sh
  "/opt/elasticbeanstalk/hooks/appdeploy/pre/70install_redis.sh" :
    mode: "000775"
    owner: root
    group: users
    source: https://raw.githubusercontent.com/jakemmarsh/ebs-setup/master/predeploy/70install_redis.sh
  "/opt/elasticbeanstalk/hooks/appdeploy/post/00redis_server.sh" :
    mode: "000775"
    owner: root
    group: users
    source: https://raw.githubusercontent.com/jakemmarsh/ebs-setup/master/postdeploy/00redis_server.sh
```


text:
import {TranslationUnit} from './translation-unit';
/**
 * Created by martin on 29.06.2017.
 */

export class AutoTranslateResult {

  public static Success(tu: TranslationUnit): AutoTranslateResult {
    return new AutoTranslateResult(tu, true, false, null);
  }

  public static Failed(tu: TranslationUnit, details: string): AutoTranslateResult {
    return new AutoTranslateResult(tu, false, false, details);
  }

  public static Ignored(tu: TranslationUnit, details: string): AutoTranslateResult {
    return new AutoTranslateResult(tu, true, true, details);
  }

  private constructor(private _transUnit: TranslationUnit, private _success: boolean, private _ignored: boolean, private _details: string) {

  }

  public success(): boolean {
    return this._success;
  }

  public failed(): boolean {
    return !this._success;
  }

  public ignored(): boolean {
    return this._ignored;
  }

  public details(): string {
    return this._details;
  }

  public translationUnit(): TranslationUnit {
    return this._transUnit;
  }

}


text:
pushd C:\Development\anagogic-backup-swift
net stop anagogicbackup
"\Program Files\Anagogic\Backup\unins000.exe" /silent
rmdir /s /q build
rmdir /s /q dist
python setup.py py2exe
pushd C:\Development\anagogic-backup-swift\Installer
"\Program Files\Inno Setup 5\iscc.exe" Preprocessed-anagogic-swift-backup-setup.iss
Output\anagogic-swift-backup-setup.exe /silent
popd
python scripts\set_htdocs_reg.py
python scripts\set_swift_reg.py
REM python scripts\set_sentry_reg.py
net start anagogicbackup
popd


text:
"""
	Found here is a great example of how modifications are implemented inside of ScalyMUCK. All modifications that
	are intended to be loaded into ScalyMUCK must be provided in the form of a module you can merely drag and drop
	into application/game/ and from there the server host can modify their server_config.cfg file to add the modification
	to the loaded modification listing.

	This software is licensed under the MIT license.
	Please refer to LICENSE.txt for more information.
"""

import string

from blinker import signal

import game.models
import game.exception

class Modification:
	""" Main class object to load and initialize the scommands modification. """
	world = None
	interface = None
	session = None
	modloader = None

	pre_user_look = signal('pre_user_look')
	post_user_look = signal('post_user_look')
	pre_user_say = signal('pre_user_say')
	post_user_say = signal('post_user_say')
	pre_user_pose = signal('pre_user_pose')
	post_user_pose = signal('post_user_pose')
	pre_item_pickup = signal('pre_item_pickup')
	post_item_pickup = signal('post_item_pickup')
	pre_item_drop = signal('pre_item_drop')
	post_item_drop = signal('post_item_drop')
	post_user_create = signal('post_user_create')
	pre_exit_room = signal('pre_exit_room')
	post_exit_room = signal('post_exit_room')
	pre_show_description = signal('pre_show_description')

	def initialize(self, **kwargs):
		"""

		This initializes an instance of the scommands modification and it will remain loaded in memory

		until the server owner either unloads it or reloads it which therefore will reset
		any associated data unless the data had been defined on the class definition itself
		rather than being initialized in this function.

		Keyword arguments:
			* config -- This is the instance of Settings that contains all loaded configuration settings available for this modification, if the file exists. If the file does not exist, then this will simply be None.
			* interface -- This is the instance of the user interface used internally by ScalyMUCK. Generally, you won't need access to this for any reason and is currently deprecated for later removal.

		Actions such as binding your Blinker signals should be performed here so that events will be
		received properly when they occur.

		Along with initializing the modification, __init__ acts as a gateway for other important

		data passed in by the modloader under the **kwargs argument.

		"""

		self.config = kwargs['config']
		self.interface = kwargs['interface']
		self.session = kwargs['session']
		self.world = kwargs['world']
		self.permissions = kwargs['permissions']
		self.modloader = kwargs['modloader']

		signal('post_client_authenticated').connect(self.callback_client_authenticated)
		signal('pre_message_sent').connect(self.callback_message_sent)

	def __del__(self):
		signal('post_client_authenticated').disconnect(self.callback_client_authenticated)
		signal('pre_message_sent').disconnect(self.callback_message_sent)

	# Commands
	def command_say(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']

		if (input == ''):
			sender.send('Usage: say <message>')
			return

		results = self.pre_user_say.send(None, sender=sender, input=input)
		for result in results:
			if (result[1] is True):
				return

		sender.location.broadcast('%s says, "%s"' % (sender.display_name, input), sender)
		sender.send('You say, "%s"' % (input))
		self.post_user_say.send(None, sender=sender, input=input)

	def command_pose(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']
		results = self.pre_user_pose.send(None, sender=sender, input=input)
		for result in results:
			if (result[1] is True):
				return

		sender.location.broadcast('%s %s' % (sender.display_name, kwargs['input']))
		self.post_user_pose.send(None, sender=sender, input=input)

	def command_look(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']
		target = sender.location
		name = sender.location.name

		self.pre_user_look.send(sender=sender, input=input)

		if (input != ''):
			target = sender.location.find_player(name=input)
			if (target is None):
				target = sender.location.find_bot(name=input)

			if (target is not None):
				name = target.display_name
				if (type(target) is game.models.Player):
					target.send('++++++++ %s is looking at you!' % (sender.display_name))
			else:
				target = sender.location.find_item(name=input)
				if (target is None):
					target = sender.inventory.find_item(name=input)

				if (target is not None):
					name = target.name
				else:
					sender.send('I do not see that.')
					return
		sender.send('<' + name + '>')

		if (type(target) is game.models.Room):
			sender.send('Obvious Exits: ')
			if (len(target.exits) != 0):
				for exit in target.exits:
					sender.send('	%s' % (exit.name))
			else:
				sender.send('	None')

			sender.send('People: ')
			for player in target.players:
				sender.send('	%s' % (player.display_name))

			sender.send('Bots: ')
			if (len(target.bots) != 0):
				for bot in target.bots:
					sender.send('	%s' % (bot.display_name))
			else:
				sender.send('	None')

			sender.send('Items: ')
			if (len(target.items) != 0):
				for item in target.items:
					sender.send('	%s' % (item.name))
			else:
				sender.send('	None')

		self.pre_show_description.send(None, sender=sender, target=target)
		sender.send('Description:')
		sender.send(target.description)

		self.post_user_look.send(sender=sender, input=input, target=target)

	def command_move(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']

		if (input == ''):
			sender.send('Usage: move <name of exit>')
			return

		exit = sender.location.find_exit(name=input)
		if (exit is not None):
			sender.send(exit.user_enter_message)
			sender.location.broadcast('%s %s' % (sender.display_name, exit.room_enter_message), sender)
			results = self.pre_exit_room.send(None, sender=sender, target=exit.target_id)
			for result in results:
				if (result[1] is True):
					return
			sender.set_location(exit.target_id)
			sender.location.broadcast('%s %s' % (sender.display_name, exit.room_exit_message), sender)
			sender.send(exit.user_exit_message)
			self.command_look(sender=sender, input='')
			self.post_exit_room.send(None, sender=sender, target=sender.location)
		else:
			sender.send('I do not see that.')

	def command_inventory(self, **kwargs):
		sender = kwargs['sender']

		sender.send('Items:')
		if (len(sender.inventory.items) != 0):
			for item in sender.inventory.items:
				sender.send('	%s' % (item.name))
		else:
			sender.send('	None')

		# Pocket dimension anybody?
		if (len(sender.inventory.players) != 0):
			sender.send('People: ')
			for player in sender.inventory.players:
				sender.send('	%s' % (player.display_name))

	def command_take(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']

		if (input == ''):
			sender.send('Usage: take <object name>')
			return

		item = sender.location.find_item(name=input)
		if (item is not None):
			results = self.pre_item_pickup.send(None, sender=sender, item=item)
			for result in results:
				if (result[1] is True):
					return

			sender.send('Taken.')

			item.set_location(sender.inventory)
			self.post_item_pickup.send(None, sender=sender, item=item)
		else:
			sender.send('I do not see that.')

	def command_passwd(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']

		if (input == ''):
			sender.send('Usage: passwd <password>')
			return

		sender.set_password(input)
		sender.send('Your password has been changed. Remember it well.')

	def command_drop(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']

		if (input == ''):
			sender.send('Usage: drop <item name>')
			return

		item = sender.inventory.find_item(name=input)
		if (item is not None):
			results = self.pre_item_drop.send(sender=sender, item=item)
			for result in results:
				if (result[1] is True):
					return

			item.set_location(sender.location)
			sender.send('You dropped a/an %s.' % (item.name ))
			sender.location.broadcast('%s drops a/an %s.' % (sender.display_name, item.name), sender)
			self.post_item_drop.send(sender=sender, item=item)
		else:
			sender.send('I see no such item.')

	def command_help(self, **kwargs):
		sender = kwargs['sender']
		input = kwargs['input']

		sender.send('For more information, type: help <command/category>')

		if (input == ''):
			sender.send('Available command categories:')
			categories = []
			for command in self.modloader.commands:
				privilege = self.modloader.commands[command]['privilege']
				if ((privilege == 1 and sender.is_admin is False) or (privilege == 2 and sender.is_sadmin is False) or (privilege == 3 and sender.is_owner is False)):
					continue

				if ('category' in self.modloader.commands[command]):
					category = self.modloader.commands[command]['category']
					if (category not in categories):
						categories.append(category)
						sender.send('\t+ ' + category)
				elif ('Unclassed' not in categories):
					categories.append('Unclassed')
					sender.send('\t+ Unclassed')

		else:
			l_input = input.lower()
			if (input not in self.modloader.commands):
				category_contents = [ ]

				for command in self.modloader.commands:
					privilege = self.modloader.commands[command]['privilege']
					if ((privilege == 1 and sender.is_admin is False) or (privilege == 2 and sender.is_sadmin is False) or (privilege == 3 and sender.is_owner is False)):
						continue

					if ('category' in self.modloader.commands[command]):
						category = self.modloader.commands[command]['category']
						if (category.lower() == l_input):
							category_contents.append(command)
					elif (l_input == 'unclassed'):
						category_contents.append(command)

				if (len(category_contents) == 0):
					sender.send('No such command or category: %s' % input)
				else:
					sender.send('Available commands in category %s:' % input)
					for command_name in category_contents:
						sender.send('\t+ %s - %s' % (command_name, self.modloader.commands[command_name]['description']))
			else:
				privilege = self.modloader.commands[l_input]['privilege']
				if ((privilege == 1 and sender.is_admin is False) or (privilege == 2 and sender.is_sadmin is False) or (privilege == 3 and sender.is_owner is False)):
					sender.send('No such command or category: %s' % input)
					return

				sender.send('From: %s' % (self.modloader.commands[input]['modification']))
				sender.send('Usage: %s' % (self.modloader.commands[input]['usage']))
				sender.send(self.modloader.commands[input]['description'])

	def command_quit(self, **kwargs):
		sender = kwargs['sender']
		sender.disconnect()

	def command_froguser(self, **kwargs):
		sender = kwargs['sender']
		args = kwargs['arguments']
		if (len(args) < 1):
			sender.send('Usage: frog <name>')
			return

		name = args[0]
		target = self.world.find_player(name=string.lower(name))
		if (target is not None):
			if (target is sender):
				sender.send('That is yourself!')
				return
			elif (target.is_sadmin ==1 or target.is_owner == 1):
				sender.send('You cannot do that, they are too powerful.')
				return
			else:
				sender.send('User "%s" frogged. Check your inventory.' % (target.display_name))
				sender.location.broadcast('%s has turned %s into a small plastic figurine, never to move again.' % (sender.display_name, target.display_name), sender, target)
				item = self.world.create_item(target.display_name, target.description, sender, sender.inventory)
				target.send('%s has turned you into a small plastic figurine, never to move again and discreetly places you in their inventory.' % (sender.display_name))
				target.delete()
		else:
			sender.send('User "%s" does not exist anywhere.' % (name))

	def command_adduser(self, **kwargs):
		sender = kwargs['sender']
		args = kwargs['arguments']
		if (len(args) < 2):
			sender.send('Usage: adduser <name> <password>')
			return

		name = args[0]
		password = args[1]

		if (self.world.find_player(name=string.lower(name)) is not None):
			sender.send('User already exists.')
			return

		# TODO: Make this take server prefs into consideration, and also let this have a default location ...
		player = self.world.create_player(name, password, game.models.server.work_factor, sender.location)
		sender.send('User "%s" created.' % (name))
		self.post_user_create.send(None, creator=sender, created=player)

	def command_admin(self, **kwargs):
		sender = kwargs['sender']
		args = kwargs['arguments']
		if (len(args) < 1):
			sender.send('Usage: admin <name>')
			return

		name = args[0]

		target = self.world.find_player(name=string.lower(name))
		if (target is not None):
			if (target is sender):
				sender.send('That is yourself!')
				return
			elif (sender.check_admin_trump(target) is False):
				sender.send('You cannot do that. They are too strong.')
				target.send('%s tried to take your administrator privileges away.' % (sender.display_name))
				return

			target.set_is_admin(target.is_admin is False)
			if (target.is_admin == 0):
				sender.send('%s is no longer an administrator.' % (target.display_name))
				target.send('%s took your adminship.' % (sender.display_name))
				return
			else:
				sender.send('%s is now an administrator.' % (target.display_name))
				target.send('%s gave you adminship rights.' % (sender.display_name))
				return
			sender.send('Unknown user.')

	def command_sadmin(self, **kwargs):
		sender = kwargs['sender']
		args = kwargs['arguments']
		if (len(args) < 1):
			sender.send('Usage: sadmin <name>')
			return

		name = args[0]

		target = self.world.find_player(name=string.lower(name))
		if (target is not None):
			if (target is sender):
				sender.send('That is yourself!')
				return
			elif (sender.check_admin_trump(target) is False):
				sender.send('You cannot do that. They are too strong.')
				target.send('%s tried to take your super administrator privileges away.' % (sender.display_name))
				return

			target.set_is_super_admin(target.is_sadmin is False)
			if (target.is_sadmin is False):
				sender.send('%s is no longer a super administrator.' % (target.display_name))
				target.send('%s took your super adminship.' % (sender.display_name))
				return
			else:
				sender.send('%s is now a super administrator.' % (target.display_name))
				target.send('%s gave you super adminship rights.' % (sender.display_name))
				return
			sender.send('Unknown user.')

	def command_chown(self, **kwargs):
		sender = kwargs['sender']
		args = kwargs['arguments']

		if (len(args) < 2):
			sender.send('Usage: chown <item name> <new owner>')
			return

		item_name = args[0]
		owner_name = args[1]

		item = sender.inventory.find_item(name=item_name)
		if (item.owner_id != sender.id):
			sender.send('This is not your item.')
			return

		player = self.world.find_player(name=owner_name)
		if (player is None):
			sender.send('There is no such player.')
		else:
			item.set_owner(player)
			sender.send('%s now owns that item.' % (player.display_name))
			player.send('%s has given you a %s.' % (sender.display_name, item.name))

	def command_ping(self, **kwargs):
		kwargs['sender'].send('Pong.')

	def command_wwi(self, **kwargs):
		sender = kwargs['sender']

		listing = self.interface.get_online_players()
		longest_length = 0
		for player in listing:
			length = len(player.display_name)
			if (length > longest_length):
				longest_length = length

		spacing = ''
		for i in range(longest_length+7):
			spacing += ' '

		sender.send('Name%sLocation' % spacing)
		for player in listing:
			spacing = ''
			for i in range((longest_length+11)-len(player.display_name)):
				spacing += ' '
			sender.send('%s%s%s' % (player.display_name, spacing, player.location.name))
		sender.send('Who/Where/Idle')

	# Callbacks
	def callback_client_authenticated(self, trigger, sender):
		""" Callback that is bound to the "post_client_authenticated" event.

		Callbacks like this one are helpful in cases that if you want to initialize
		certain data upon the authentication of a certain client -- perhaps you're loading
		mod data that is related to this client.

		Refer to the :command:`__init__` function.

		"""
		self.command_look(sender=sender, input='')

	def callback_message_sent(self, trigger, sender, input):
		""" Callback that is bound to the "pre_message_sent" event.

		Callbacks like this one are helpful in cases that if you want to intercept
		input for any reason, such as an interactive menu that will handle it's own
		text parsing for handling menu functions as that if the callback at any point
		returns true, the server will not pass the input text into the core parser.

		Refer to the :command:`__init__` function.

		"""
		if (len(input) != 0):
			if (input[0] == ':'):
				self.command_pose(sender=sender, input=input[1:].lstrip())
				return True
			elif (input[0] == '"'):
				self.command_say(sender=sender, input=input[1:].lstrip())
				return True

		return False

	def get_commands(self):
		""" Returns a dictionary mapping the available commands in this modification.

		This is a function call merely for the purpose of being able to provide variable
		output, so that if the modification has an accompanying configuration file it can
		omit or include certain commands based on the configuration settings loaded in the
		modification's :command:`__init__` function.

		"""
		command_dict = {
			'say':
			{
				'command': self.command_say,
				'description': 'Makes you say something. Only visible to the current room you\'re in.',
				'usage': 'say <arbitrary text> | "<arbitrary text>',
				'aliases': [ 'speak' ],
				'privilege': 0,
				'category': 'General'
			},

			'pose':
			{
				'command': self.command_pose,
				'description': 'Used to show arbitrary action. Only visible to the current room you\'re in.',
				'usage': 'pose <arbitrary pose> | :<arbitrary pose>',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'look':
			{
				'command': self.command_look,
				'description': 'Get your bearings. Look around in the local area to see what you can see.',
				'usage': 'look [room name | item name | player name]',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'move':
			{
				'command': self.command_move,
				'description': 'Moves to a new location.',
				'usage': 'move <exit name>',
				'aliases': [ 'go' ],
				'privilege': 0,
				'category': 'General'
			},

			'inventory':
			{
				'command': self.command_inventory,
				'description': 'View your inventory.',
				'usage': 'inventory',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'take':
			{
				'command': self.command_take,
				'description': 'Take an item from the current room.',
				'usage': 'take <item>',
				'aliases': [ 'get' ],
				'privilege': 0,
				'category': 'General'
			},

			'passwd':
			{
				'command': self.command_passwd,
				'description': 'Changes your password.',
				'usage': 'passwd <new password>',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'drop':
			{
				'command': self.command_drop,
				'description': 'Drops an item from your inventory.',
				'usage': 'drop <item name>',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'help':
			{
				'command': self.command_help,
				'description': 'Displays the help text.',
				'usage': 'help [command name]',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'quit':
			{
				'command': self.command_quit,
				'description': 'Drops your connection from the server.',
				'usage': 'quit',
				'aliases': [ 'leave' ],
				'privilege': 0,
				'category': 'General'
			},

			'frog':
			{
				'command': self.command_froguser,
				'description': 'Deletes a user from the world -- making them an item in your inventory to with as you please.',
				'usage': 'frog <player name>',
				'aliases': [ ],
				'privilege': 2,
				'category': 'Administration'
			},

			'adduser':
			{
				'command': self.command_adduser,
				'description': 'Creates a new player in the world.',
				'usage': 'adduser <name> <password>',
				'aliases': [ ],
				'privilege': 2,
				'category': 'Administration'
			},

			'admin':
			{
				'command': self.command_admin,
				'description': 'Toggles the admin status of a specified player.',
				'usage': 'admin <name>',
				'aliases': [ ],
				'privilege': 1,
				'category': 'Administration'
			},

			'sadmin':
			{
				'command': self.command_sadmin,
				'description': 'Toggles the super admin status of a specified player.',
				'usage': 'sadmin <name>',
				'aliases': [ ],
				'privilege': 2,
				'category': 'Administration'
			},

			'chown':
			{
				'command': self.command_chown,
				'description': 'Transfers ownership of an item in your inventory or in the room to a specified player providied you are the original owner.',
				'usage': 'chown <item name> <new owner name>',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'ping':
			{
				'command': self.command_ping,
				'description': 'Ping-Pong.',
				'usage': 'ping',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			},

			'wwi':
			{
				'command': self.command_wwi,
				'description': 'See a list of connected people.',
				'usage': 'wwi',
				'aliases': [ ],
				'privilege': 0,
				'category': 'General'
			}
		}
		return command_dict


text:
package ch20annotations;

import com.sun.mirror.apt.*;
import com.sun.mirror.declaration.*;
import java.util.*;

/**
 * APT-based annotation processing.
 */
public class D10_InterfaceExtractorProcessorFactory implements AnnotationProcessorFactory {
	public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds,
			AnnotationProcessorEnvironment env) {
		return new D09_InterfaceExtractorProcessor(env);
	}

	public Collection<String> supportedAnnotationTypes() {
		return Collections.singleton("ch20annotations.D07_ExtractInterface");
	}

	public Collection<String> supportedOptions() {
		return Collections.emptySet();
	}
}


text:
import os
from typing import List, Union

from django.conf import settings
from django.conf.urls import include
from django.conf.urls.i18n import i18n_patterns
from django.contrib.auth.views import (
    LoginView,
    PasswordResetCompleteView,
    PasswordResetConfirmView,
    PasswordResetDoneView,
)
from django.urls import path, re_path
from django.urls.resolvers import URLPattern, URLResolver
from django.utils.module_loading import import_string
from django.views.generic import RedirectView, TemplateView

from zerver.forms import LoggingSetPasswordForm
from zerver.lib.integrations import WEBHOOK_INTEGRATIONS
from zerver.lib.rest import rest_path
from zerver.tornado.views import cleanup_event_queue, get_events, get_events_internal, notify
from zerver.views.alert_words import add_alert_words, list_alert_words, remove_alert_words
from zerver.views.attachments import list_by_user, remove
from zerver.views.auth import (
    api_fetch_api_key,
    api_get_server_settings,
    json_fetch_api_key,
    log_into_subdomain,
    login_page,
    logout_then_login,
    password_reset,
    remote_user_jwt,
    remote_user_sso,
    saml_sp_metadata,
    show_deactivation_notice,
    start_remote_user_sso,
    start_social_login,
    start_social_signup,
)
from zerver.views.compatibility import check_global_compatibility
from zerver.views.custom_profile_fields import (
    create_realm_custom_profile_field,
    delete_realm_custom_profile_field,
    list_realm_custom_profile_fields,
    remove_user_custom_profile_data,
    reorder_realm_custom_profile_fields,
    update_realm_custom_profile_field,
    update_user_custom_profile_data,
)
from zerver.views.digest import digest_page
from zerver.views.documentation import IntegrationView, MarkdownDirectoryView, integration_doc
from zerver.views.drafts import create_drafts, delete_draft, edit_draft, fetch_drafts
from zerver.views.email_mirror import email_mirror_message
from zerver.views.events_register import events_register_backend
from zerver.views.home import accounts_accept_terms, desktop_home, home
from zerver.views.hotspots import mark_hotspot_as_read
from zerver.views.invite import (
    generate_multiuse_invite_backend,
    get_user_invites,
    invite_users_backend,
    resend_user_invite_email,
    revoke_multiuse_invite,
    revoke_user_invite,
)
from zerver.views.message_edit import (
    delete_message_backend,
    get_message_edit_history,
    json_fetch_raw_message,
    update_message_backend,
)
from zerver.views.message_fetch import get_messages_backend, messages_in_narrow_backend
from zerver.views.message_flags import (
    mark_all_as_read,
    mark_stream_as_read,
    mark_topic_as_read,
    update_message_flags,
)
from zerver.views.message_send import render_message_backend, send_message_backend, zcommand_backend
from zerver.views.muting import mute_user, unmute_user, update_muted_topic
from zerver.views.portico import (
    app_download_link_redirect,
    apps_view,
    hello_view,
    landing_view,
    plans_view,
    team_view,
)
from zerver.views.presence import (
    get_presence_backend,
    get_statuses_for_realm,
    update_active_status_backend,
    update_user_status_backend,
)
from zerver.views.push_notifications import (
    add_android_reg_id,
    add_apns_device_token,
    remove_android_reg_id,
    remove_apns_device_token,
)
from zerver.views.reactions import add_reaction, remove_reaction
from zerver.views.realm import (
    check_subdomain_available,
    deactivate_realm,
    realm_reactivation,
    update_realm,
    update_realm_user_settings_defaults,
)
from zerver.views.realm_domains import (
    create_realm_domain,
    delete_realm_domain,
    list_realm_domains,
    patch_realm_domain,
)
from zerver.views.realm_emoji import delete_emoji, list_emoji, upload_emoji
from zerver.views.realm_export import delete_realm_export, export_realm, get_realm_exports
from zerver.views.realm_icon import delete_icon_backend, get_icon_backend, upload_icon
from zerver.views.realm_linkifiers import (
    create_linkifier,
    delete_linkifier,
    list_linkifiers,
    update_linkifier,
)
from zerver.views.realm_logo import delete_logo_backend, get_logo_backend, upload_logo
from zerver.views.realm_playgrounds import add_realm_playground, delete_realm_playground
from zerver.views.registration import (
    accounts_home,
    accounts_home_from_multiuse_invite,
    accounts_register,
    create_realm,
    find_account,
    get_prereg_key_and_redirect,
    realm_redirect,
)
from zerver.views.report import (
    report_csp_violations,
    report_error,
    report_narrow_times,
    report_send_times,
    report_unnarrow_times,
)
from zerver.views.storage import get_storage, remove_storage, update_storage
from zerver.views.streams import (
    add_default_stream,
    add_subscriptions_backend,
    create_default_stream_group,
    deactivate_stream_backend,
    delete_in_topic,
    get_streams_backend,
    get_subscribers_backend,
    get_topics_backend,
    json_get_stream_id,
    list_subscriptions_backend,
    remove_default_stream,
    remove_default_stream_group,
    remove_subscriptions_backend,
    update_default_stream_group_info,
    update_default_stream_group_streams,
    update_stream_backend,
    update_subscription_properties_backend,
    update_subscriptions_backend,
    update_subscriptions_property,
)
from zerver.views.submessage import process_submessage
from zerver.views.thumbnail import backend_serve_thumbnail
from zerver.views.tutorial import set_tutorial_status
from zerver.views.typing import send_notification_backend
from zerver.views.unsubscribe import email_unsubscribe
from zerver.views.upload import (
    serve_file_backend,
    serve_file_url_backend,
    serve_local_file_unauthed,
    upload_file_backend,
)
from zerver.views.user_groups import (
    add_user_group,
    delete_user_group,
    edit_user_group,
    get_user_group,
    update_user_group_backend,
)
from zerver.views.user_settings import (
    confirm_email_change,
    delete_avatar_backend,
    json_change_settings,
    regenerate_api_key,
    set_avatar_backend,
)
from zerver.views.users import (
    add_bot_backend,
    avatar,
    create_user_backend,
    deactivate_bot_backend,
    deactivate_user_backend,
    deactivate_user_own_backend,
    get_bots_backend,
    get_members_backend,
    get_profile_backend,
    get_subscription_backend,
    get_user_by_email,
    patch_bot_backend,
    reactivate_user_backend,
    regenerate_bot_api_key,
    update_user_backend,
)
from zerver.views.video_calls import (
    complete_zoom_user,
    deauthorize_zoom_user,
    get_bigbluebutton_url,
    join_bigbluebutton,
    make_zoom_video_call,
    register_zoom_user,
)
from zerver.views.zephyr import webathena_kerberos_login
from zproject import dev_urls
from zproject.legacy_urls import legacy_urls

if settings.TWO_FACTOR_AUTHENTICATION_ENABLED:
    from two_factor.gateways.twilio.urls import urlpatterns as tf_twilio_urls
    from two_factor.urls import urlpatterns as tf_urls

# NB: There are several other pieces of code which route requests by URL:
#
#   - legacy_urls.py contains API endpoint written before the redesign
#     and should not be added to.
#
#   - runtornado.py has its own URL list for Tornado views.  See the
#     invocation of web.Application in that file.
#
#   - The Nginx config knows which URLs to route to Django or Tornado.
#
#   - Likewise for the local dev server in tools/run-dev.py.

# These endpoints constitute the currently designed API (V1), which uses:
# * REST verbs
# * Basic auth (username:password is email:apiKey)
# * Take and return json-formatted data
#
# If you're adding a new endpoint to the code that requires authentication,
# please add it here.
# See rest_dispatch in zerver.lib.rest for an explanation of auth methods used
#
# All of these paths are accessed by either a /json or /api/v1 prefix;
# e.g. `PATCH /json/realm` or `PATCH /api/v1/realm`.
v1_api_and_json_patterns = [
    # realm-level calls
    rest_path("realm", PATCH=update_realm),
    rest_path("realm/user_settings_defaults", PATCH=update_realm_user_settings_defaults),
    path("realm/subdomain/<subdomain>", check_subdomain_available),
    # realm/domains -> zerver.views.realm_domains
    rest_path("realm/domains", GET=list_realm_domains, POST=create_realm_domain),
    rest_path("realm/domains/<domain>", PATCH=patch_realm_domain, DELETE=delete_realm_domain),
    # realm/emoji -> zerver.views.realm_emoji
    rest_path("realm/emoji", GET=list_emoji),
    rest_path(
        "realm/emoji/<emoji_name>",
        POST=upload_emoji,
        DELETE=(delete_emoji, {"intentionally_undocumented"}),
    ),
    # this endpoint throws a status code 400 JsonableError when it should be a 404.
    # realm/icon -> zerver.views.realm_icon
    rest_path("realm/icon", POST=upload_icon, DELETE=delete_icon_backend, GET=get_icon_backend),
    # realm/logo -> zerver.views.realm_logo
    rest_path("realm/logo", POST=upload_logo, DELETE=delete_logo_backend, GET=get_logo_backend),
    # realm/filters and realm/linkifiers -> zerver.views.realm_linkifiers
    rest_path("realm/linkifiers", GET=list_linkifiers),
    rest_path("realm/filters", POST=create_linkifier),
    rest_path("realm/filters/<int:filter_id>", DELETE=delete_linkifier, PATCH=update_linkifier),
    # realm/playgrounds -> zerver.views.realm_playgrounds
    rest_path("realm/playgrounds", POST=add_realm_playground),
    rest_path("realm/playgrounds/<int:playground_id>", DELETE=delete_realm_playground),
    # realm/profile_fields -> zerver.views.custom_profile_fields
    rest_path(
        "realm/profile_fields",
        GET=list_realm_custom_profile_fields,
        PATCH=reorder_realm_custom_profile_fields,
        POST=create_realm_custom_profile_field,
    ),
    rest_path(
        "realm/profile_fields/<int:field_id>",
        PATCH=update_realm_custom_profile_field,
        DELETE=delete_realm_custom_profile_field,
    ),
    # realm/deactivate -> zerver.views.deactivate_realm
    rest_path("realm/deactivate", POST=deactivate_realm),
    # users -> zerver.views.users
    rest_path("users", GET=get_members_backend, POST=create_user_backend),
    rest_path("users/me", GET=get_profile_backend, DELETE=deactivate_user_own_backend),
    rest_path("users/<int:user_id>/reactivate", POST=reactivate_user_backend),
    rest_path(
        "users/<int:user_id>",
        GET=get_members_backend,
        PATCH=update_user_backend,
        DELETE=deactivate_user_backend,
    ),
    rest_path("users/<int:user_id>/subscriptions/<int:stream_id>", GET=get_subscription_backend),
    rest_path("users/<email>", GET=get_user_by_email),
    rest_path("bots", GET=get_bots_backend, POST=add_bot_backend),
    rest_path("bots/<int:bot_id>/api_key/regenerate", POST=regenerate_bot_api_key),
    rest_path("bots/<int:bot_id>", PATCH=patch_bot_backend, DELETE=deactivate_bot_backend),
    # invites -> zerver.views.invite
    rest_path("invites", GET=get_user_invites, POST=invite_users_backend),
    rest_path("invites/<int:prereg_id>", DELETE=revoke_user_invite),
    rest_path("invites/<int:prereg_id>/resend", POST=resend_user_invite_email),
    # invites/multiuse -> zerver.views.invite
    rest_path("invites/multiuse", POST=generate_multiuse_invite_backend),
    # invites/multiuse -> zerver.views.invite
    rest_path("invites/multiuse/<int:invite_id>", DELETE=revoke_multiuse_invite),
    # mark messages as read (in bulk)
    rest_path("mark_all_as_read", POST=mark_all_as_read),
    rest_path("mark_stream_as_read", POST=mark_stream_as_read),
    rest_path("mark_topic_as_read", POST=mark_topic_as_read),
    rest_path("zcommand", POST=zcommand_backend),
    # Endpoints for syncing drafts.
    rest_path("drafts", GET=fetch_drafts, POST=create_drafts),
    rest_path("drafts/<int:draft_id>", PATCH=edit_draft, DELETE=delete_draft),
    # messages -> zerver.views.message*
    # GET returns messages, possibly filtered, POST sends a message
    rest_path(
        "messages",
        GET=(get_messages_backend, {"allow_anonymous_user_web"}),
        POST=(send_message_backend, {"allow_incoming_webhooks"}),
    ),
    rest_path(
        "messages/<int:message_id>",
        GET=(json_fetch_raw_message, {"allow_anonymous_user_web"}),
        PATCH=update_message_backend,
        DELETE=delete_message_backend,
    ),
    rest_path("messages/render", POST=render_message_backend),
    rest_path("messages/flags", POST=update_message_flags),
    rest_path("messages/<int:message_id>/history", GET=get_message_edit_history),
    rest_path("messages/matches_narrow", GET=messages_in_narrow_backend),
    rest_path("users/me/subscriptions/properties", POST=update_subscription_properties_backend),
    rest_path("users/me/subscriptions/<int:stream_id>", PATCH=update_subscriptions_property),
    rest_path("submessage", POST=process_submessage),
    # New endpoint for handling reactions.
    # reactions -> zerver.view.reactions
    # POST adds a reaction to a message
    # DELETE removes a reaction from a message
    rest_path("messages/<int:message_id>/reactions", POST=add_reaction, DELETE=remove_reaction),
    # attachments -> zerver.views.attachments
    rest_path("attachments", GET=list_by_user),
    rest_path("attachments/<int:attachment_id>", DELETE=remove),
    # typing -> zerver.views.typing
    # POST sends a typing notification event to recipients
    rest_path("typing", POST=send_notification_backend),
    # user_uploads -> zerver.views.upload
    rest_path("user_uploads", POST=upload_file_backend),
    rest_path(
        "user_uploads/<realm_id_str>/<path:filename>",
        GET=(serve_file_url_backend, {"override_api_url_scheme"}),
    ),
    # bot_storage -> zerver.views.storage
    rest_path("bot_storage", PUT=update_storage, GET=get_storage, DELETE=remove_storage),
    # Endpoint used by mobile devices to register their push
    # notification credentials
    rest_path(
        "users/me/apns_device_token", POST=add_apns_device_token, DELETE=remove_apns_device_token
    ),
    rest_path("users/me/android_gcm_reg_id", POST=add_android_reg_id, DELETE=remove_android_reg_id),
    # users/*/presnece => zerver.views.presence.
    rest_path("users/me/presence", POST=update_active_status_backend),
    # It's important that this sit after users/me/presence so that
    # Django's URL resolution order doesn't break the
    # /users/me/presence endpoint.
    rest_path("users/<user_id_or_email>/presence", GET=get_presence_backend),
    rest_path("realm/presence", GET=get_statuses_for_realm),
    rest_path("users/me/status", POST=update_user_status_backend),
    # user_groups -> zerver.views.user_groups
    rest_path("user_groups", GET=get_user_group),
    rest_path("user_groups/create", POST=add_user_group),
    rest_path("user_groups/<int:user_group_id>", PATCH=edit_user_group, DELETE=delete_user_group),
    rest_path("user_groups/<int:user_group_id>/members", POST=update_user_group_backend),
    # users/me -> zerver.views.user_settings
    rest_path("users/me/api_key/regenerate", POST=regenerate_api_key),
    rest_path("users/me/avatar", POST=set_avatar_backend, DELETE=delete_avatar_backend),
    # users/me/hotspots -> zerver.views.hotspots
    rest_path(
        "users/me/hotspots",
        POST=(
            mark_hotspot_as_read,
            # This endpoint is low priority for documentation as
            # it is part of the web app-specific tutorial.
            {"intentionally_undocumented"},
        ),
    ),
    # users/me/tutorial_status -> zerver.views.tutorial
    rest_path(
        "users/me/tutorial_status",
        POST=(
            set_tutorial_status,
            # This is a relic of an old Zulip tutorial model and
            # should be deleted.
            {"intentionally_undocumented"},
        ),
    ),
    # settings -> zerver.views.user_settings
    rest_path("settings", PATCH=json_change_settings),
    # These next two are legacy aliases for /settings, from before
    # we merged the endpoints. They are documented in the `/json/settings`
    # documentation, rather than having dedicated pages.
    rest_path("settings/display", PATCH=(json_change_settings, {"intentionally_undocumented"})),
    rest_path(
        "settings/notifications", PATCH=(json_change_settings, {"intentionally_undocumented"})
    ),
    # users/me/alert_words -> zerver.views.alert_words
    rest_path(
        "users/me/alert_words",
        GET=list_alert_words,
        POST=add_alert_words,
        DELETE=remove_alert_words,
    ),
    # users/me/custom_profile_data -> zerver.views.custom_profile_data
    rest_path(
        "users/me/profile_data",
        PATCH=update_user_custom_profile_data,
        DELETE=remove_user_custom_profile_data,
    ),
    rest_path(
        "users/me/<int:stream_id>/topics", GET=(get_topics_backend, {"allow_anonymous_user_web"})
    ),
    # streams -> zerver.views.streams
    # (this API is only used externally)
    rest_path("streams", GET=get_streams_backend),
    # GET returns `stream_id`, stream name should be encoded in the URL query (in `stream` param)
    rest_path("get_stream_id", GET=json_get_stream_id),
    # GET returns "stream info" (undefined currently?), HEAD returns whether stream exists (200 or 404)
    rest_path("streams/<int:stream_id>/members", GET=get_subscribers_backend),
    rest_path(
        "streams/<int:stream_id>", PATCH=update_stream_backend, DELETE=deactivate_stream_backend
    ),
    # Delete topic in stream
    rest_path("streams/<int:stream_id>/delete_topic", POST=delete_in_topic),
    rest_path("default_streams", POST=add_default_stream, DELETE=remove_default_stream),
    rest_path("default_stream_groups/create", POST=create_default_stream_group),
    rest_path(
        "default_stream_groups/<int:group_id>",
        PATCH=update_default_stream_group_info,
        DELETE=remove_default_stream_group,
    ),
    rest_path(
        "default_stream_groups/<int:group_id>/streams", PATCH=update_default_stream_group_streams
    ),
    # GET lists your streams, POST bulk adds, PATCH bulk modifies/removes
    rest_path(
        "users/me/subscriptions",
        GET=list_subscriptions_backend,
        POST=add_subscriptions_backend,
        PATCH=update_subscriptions_backend,
        DELETE=remove_subscriptions_backend,
    ),
    # muting -> zerver.views.muting
    rest_path("users/me/subscriptions/muted_topics", PATCH=update_muted_topic),
    rest_path("users/me/muted_users/<int:muted_user_id>", POST=mute_user, DELETE=unmute_user),
    # used to register for an event queue in tornado
    rest_path("register", POST=events_register_backend),
    # events -> zerver.tornado.views
    rest_path("events", GET=get_events, DELETE=cleanup_event_queue),
    # report -> zerver.views.report
    #
    # These endpoints are for internal error/performance reporting
    # from the browser to the web app, and we don't expect to ever
    # include in our API documentation.
    rest_path(
        "report/error",
        # Logged-out browsers can hit this endpoint, for portico page JS exceptions.
        POST=(report_error, {"allow_anonymous_user_web", "intentionally_undocumented"}),
    ),
    rest_path("report/send_times", POST=(report_send_times, {"intentionally_undocumented"})),
    rest_path(
        "report/narrow_times",
        POST=(report_narrow_times, {"allow_anonymous_user_web", "intentionally_undocumented"}),
    ),
    rest_path(
        "report/unnarrow_times",
        POST=(report_unnarrow_times, {"allow_anonymous_user_web", "intentionally_undocumented"}),
    ),
    # Used to generate a Zoom video call URL
    rest_path("calls/zoom/create", POST=make_zoom_video_call),
    # Used to generate a BigBlueButton video call URL
    rest_path("calls/bigbluebutton/create", GET=get_bigbluebutton_url),
    # export/realm -> zerver.views.realm_export
    rest_path("export/realm", POST=export_realm, GET=get_realm_exports),
    rest_path("export/realm/<int:export_id>", DELETE=delete_realm_export),
]

integrations_view = IntegrationView.as_view()

# These views serve pages (HTML). As such, their internationalization
# must depend on the URL.
#
# If you're adding a new page to the website (as opposed to a new
# endpoint for use by code), you should add it here.
i18n_urls = [
    path("", home, name="home"),
    # We have a desktop-specific landing page in case we change our /
    # to not log in in the future. We don't want to require a new
    # desktop app build for everyone in that case
    path("desktop_home/", desktop_home),
    # Backwards-compatibility (legacy) Google auth URL for the mobile
    # apps; see https://github.com/zulip/zulip/issues/13081 for
    # background.  We can remove this once older versions of the
    # mobile app are no longer present in the wild.
    path("accounts/login/google/", start_social_login, {"backend": "google"}),
    path("accounts/login/start/sso/", start_remote_user_sso, name="start-login-sso"),
    path("accounts/login/sso/", remote_user_sso, name="login-sso"),
    path("accounts/login/jwt/", remote_user_jwt),
    path("accounts/login/social/<backend>", start_social_login, name="login-social"),
    path("accounts/login/social/<backend>/<extra_arg>", start_social_login, name="login-social"),
    path("accounts/register/social/<backend>", start_social_signup, name="signup-social"),
    path(
        "accounts/register/social/<backend>/<extra_arg>", start_social_signup, name="signup-social"
    ),
    path("accounts/login/subdomain/<token>", log_into_subdomain),
    # We have two entries for accounts/login; only the first one is
    # used for URL resolution.  The second here is to allow
    # reverse("login") in templates to
    # return `/accounts/login/`.
    path("accounts/login/", login_page, {"template_name": "zerver/login.html"}, name="login_page"),
    path("accounts/login/", LoginView.as_view(template_name="zerver/login.html"), name="login"),
    path("accounts/logout/", logout_then_login),
    path("accounts/webathena_kerberos_login/", webathena_kerberos_login),
    path("accounts/password/reset/", password_reset, name="password_reset"),
    path(
        "accounts/password/reset/done/",
        PasswordResetDoneView.as_view(template_name="zerver/reset_emailed.html"),
    ),
    path(
        "accounts/password/reset/<uidb64>/<token>/",
        PasswordResetConfirmView.as_view(
            success_url="/accounts/password/done/",
            template_name="zerver/reset_confirm.html",
            form_class=LoggingSetPasswordForm,
        ),
        name="password_reset_confirm",
    ),
    path(
        "accounts/password/done/",
        PasswordResetCompleteView.as_view(template_name="zerver/reset_done.html"),
    ),
    path("accounts/deactivated/", show_deactivation_notice),
    # Displays digest email content in browser.
    path("digest/", digest_page),
    # Registration views, require a confirmation ID.
    path("accounts/home/", accounts_home),
    path(
        "accounts/send_confirm/<email>",
        TemplateView.as_view(template_name="zerver/accounts_send_confirm.html"),
        name="signup_send_confirm",
    ),
    path(
        "accounts/new/send_confirm/<email>",
        TemplateView.as_view(template_name="zerver/accounts_send_confirm.html"),
        {"realm_creation": True},
        name="new_realm_send_confirm",
    ),
    path("accounts/register/", accounts_register, name="accounts_register"),
    path(
        "accounts/do_confirm/<confirmation_key>",
        get_prereg_key_and_redirect,
        name="get_prereg_key_and_redirect",
    ),
    path(
        "accounts/confirm_new_email/<confirmation_key>",
        confirm_email_change,
        name="confirm_email_change",
    ),
    # Email unsubscription endpoint. Allows for unsubscribing from various types of emails,
    # including the welcome emails (day 1 & 2), missed PMs, etc.
    path(
        "accounts/unsubscribe/<email_type>/<confirmation_key>",
        email_unsubscribe,
        name="unsubscribe",
    ),
    # Portico-styled page used to provide email confirmation of terms acceptance.
    path("accounts/accept_terms/", accounts_accept_terms, name="accept_terms"),
    # Find your account
    path("accounts/find/", find_account, name="find_account"),
    # Go to organization subdomain
    path("accounts/go/", realm_redirect, name="realm_redirect"),
    # Realm creation
    path("new/", create_realm),
    path("new/<creation_key>", create_realm, name="create_realm"),
    # Realm reactivation
    path("reactivate/<confirmation_key>", realm_reactivation, name="realm_reactivation"),
    # Login/registration
    path("register/", accounts_home, name="register"),
    path("login/", login_page, {"template_name": "zerver/login.html"}, name="login_page"),
    path("join/<confirmation_key>/", accounts_home_from_multiuse_invite, name="join"),
    # Used to generate a Zoom video call URL
    path("calls/zoom/register", register_zoom_user),
    path("calls/zoom/complete", complete_zoom_user),
    path("calls/zoom/deauthorize", deauthorize_zoom_user),
    # Used to join a BigBlueButton video call
    path("calls/bigbluebutton/join", join_bigbluebutton),
    # API and integrations documentation
    path("integrations/doc-html/<integration_name>", integration_doc),
    path("integrations/", integrations_view),
    path("integrations/<path:path>", integrations_view),
    # Landing page, features pages, signup form, etc.
    path("hello/", hello_view),
    path("new-user/", RedirectView.as_view(url="/hello", permanent=True)),
    path("features/", landing_view, {"template_name": "zerver/features.html"}),
    path("plans/", plans_view, name="plans"),
    path("apps/", apps_view),
    path("apps/download/<platform>", app_download_link_redirect),
    path("apps/<platform>", apps_view),
    path(
        "developer-community/", RedirectView.as_view(url="/development-community/", permanent=True)
    ),
    path(
        "development-community/",
        landing_view,
        {"template_name": "zerver/development-community.html"},
    ),
    # Renamed to have a cleared URL.
    path(
        "developer-community/", RedirectView.as_view(url="/development-community/", permanent=True)
    ),
    path("attribution/", landing_view, {"template_name": "zerver/attribution.html"}),
    path("team/", team_view),
    path("history/", landing_view, {"template_name": "zerver/history.html"}),
    path("why-zulip/", landing_view, {"template_name": "zerver/why-zulip.html"}),
    path("for/education/", landing_view, {"template_name": "zerver/for-education.html"}),
    path("for/events/", landing_view, {"template_name": "zerver/for-events.html"}),
    path("for/open-source/", landing_view, {"template_name": "zerver/for-open-source.html"}),
    path("for/research/", landing_view, {"template_name": "zerver/for-research.html"}),
    path("for/business/", landing_view, {"template_name": "zerver/for-business.html"}),
    path("for/companies/", RedirectView.as_view(url="/for/business/", permanent=True)),
    path("case-studies/tum/", landing_view, {"template_name": "zerver/tum-case-study.html"}),
    path("case-studies/ucsd/", landing_view, {"template_name": "zerver/ucsd-case-study.html"}),
    path("case-studies/rust/", landing_view, {"template_name": "zerver/rust-case-study.html"}),
    path("case-studies/lean/", landing_view, {"template_name": "zerver/lean-case-study.html"}),
    path(
        "for/communities/",
        landing_view,
        {"template_name": "zerver/for-communities.html"},
    ),
    # We merged this into /for/communities.
    path(
        "for/working-groups-and-communities/",
        RedirectView.as_view(url="/for/communities/", permanent=True),
    ),
    path("security/", landing_view, {"template_name": "zerver/security.html"}),
]

# Make a copy of i18n_urls so that they appear without prefix for english
urls: List[Union[URLPattern, URLResolver]] = list(i18n_urls)

# Include the dual-use patterns twice
urls += [
    path("api/v1/", include(v1_api_and_json_patterns)),
    path("json/", include(v1_api_and_json_patterns)),
]

# user_uploads -> zerver.views.upload.serve_file_backend
#
# This URL is an exception to the URL naming schemes for endpoints. It
# supports both API and session cookie authentication, using a single
# URL for both (not 'api/v1/' or 'json/' prefix). This is required to
# easily support the mobile apps fetching uploaded files without
# having to rewrite URLs, and is implemented using the
# 'override_api_url_scheme' flag passed to rest_dispatch
urls += [
    path(
        "user_uploads/temporary/<token>/<filename>",
        serve_local_file_unauthed,
        name="local_file_unauthed",
    ),
    rest_path(
        "user_uploads/<realm_id_str>/<path:filename>",
        GET=(serve_file_backend, {"override_api_url_scheme"}),
    ),
    # This endpoint redirects to camo; it requires an exception for the
    # same reason.
    rest_path("thumbnail", GET=(backend_serve_thumbnail, {"override_api_url_scheme"})),
    # Avatars have the same constraint because their URLs are included
    # in API data structures used by both the mobile and web clients.
    rest_path(
        "avatar/<email_or_id>",
        GET=(avatar, {"override_api_url_scheme", "allow_anonymous_user_web"}),
    ),
    rest_path(
        "avatar/<email_or_id>/medium",
        {"medium": True},
        GET=(avatar, {"override_api_url_scheme", "allow_anonymous_user_web"}),
    ),
]

# This URL serves as a way to receive CSP violation reports from the users.
# We use this endpoint to just log these reports.
urls += [
    path("report/csp_violations", report_csp_violations),
]

# Incoming webhook URLs
# We don't create URLs for particular Git integrations here
# because of generic one below
for incoming_webhook in WEBHOOK_INTEGRATIONS:
    if incoming_webhook.url_object:
        urls.append(incoming_webhook.url_object)

# Desktop-specific authentication URLs
urls += [
    rest_path("json/fetch_api_key", POST=json_fetch_api_key),
]

# Mobile-specific authentication URLs
urls += [
    # Used as a global check by all mobile clients, which currently send
    # requests to https://zulip.com/compatibility almost immediately after
    # starting up.
    path("compatibility", check_global_compatibility),
]

v1_api_mobile_patterns = [
    # This json format view used by the mobile apps lists which
    # authentication backends the server allows as well as details
    # like the requested subdomains'd realm icon (if known) and
    # server-specific compatibility.
    path("server_settings", api_get_server_settings),
    # This json format view used by the mobile apps accepts a username
    # password/pair and returns an API key.
    path("fetch_api_key", api_fetch_api_key),
]

# View for uploading messages from email mirror
urls += [
    path("email_mirror_message", email_mirror_message),
]

# Include URL configuration files for site-specified extra installed
# Django apps
for app_name in settings.EXTRA_INSTALLED_APPS:
    app_dir = os.path.join(settings.DEPLOY_ROOT, app_name)
    if os.path.exists(os.path.join(app_dir, "urls.py")):
        urls += [path("", include(f"{app_name}.urls"))]
        i18n_urls += import_string(f"{app_name}.urls.i18n_urlpatterns")

# Tornado views
urls += [
    # Used internally for communication between Django and Tornado processes
    #
    # Since these views don't use rest_dispatch, they cannot have
    # asynchronous Tornado behavior.
    path("notify_tornado", notify),
    path("api/v1/events/internal", get_events_internal),
]

# Python Social Auth

urls += [path("", include("social_django.urls", namespace="social"))]
urls += [path("saml/metadata.xml", saml_sp_metadata)]

# SCIM2

from zerver.lib.scim import (
    ZulipSCIMSearchView,
    ZulipSCIMUserSearchView,
    ZulipSCIMUsersView,
    ZulipSCIMView,
)

urls += [
    # We have to register all the SCIM URL patterns first, because we override
    # all the SCIM View classes and we need Django to use them instead of
    # the django-scim2 Views that the app will register.
    re_path(r"^scim/v2/$", ZulipSCIMView.as_view(implemented=False)),
    re_path(r"^scim/v2/.search$", ZulipSCIMSearchView.as_view(implemented=False)),
    re_path(r"^scim/v2/Users/.search$", ZulipSCIMUserSearchView.as_view()),
    re_path(r"^scim/v2/Users(?:/(?P<uuid>[^/]+))?$", ZulipSCIMUsersView.as_view()),
    # Everything below here are features that we don't yet support and we want
    # to explicitly mark them to return "Not Implemented" rather than running
    # the django-scim2 code for them.
    re_path(
        r"^scim/v2/Groups/.search$",
        ZulipSCIMView.as_view(implemented=False),
    ),
    re_path(
        r"^scim/v2/Groups(?:/(?P<uuid>[^/]+))?$",
        ZulipSCIMView.as_view(implemented=False),
    ),
    re_path(r"^scim/v2/Me$", ZulipSCIMView.as_view(implemented=False)),
    re_path(
        r"^scim/v2/ServiceProviderConfig$",
        ZulipSCIMView.as_view(implemented=False),
    ),
    re_path(
        r"^scim/v2/ResourceTypes(?:/(?P<uuid>[^/]+))?$",
        ZulipSCIMView.as_view(implemented=False),
    ),
    re_path(r"^scim/v2/Schemas(?:/(?P<uuid>[^/]+))?$", ZulipSCIMView.as_view(implemented=False)),
    re_path(r"^scim/v2/Bulk$", ZulipSCIMView.as_view(implemented=False)),
    # At the end we still register the django-scim2 url patterns (even though we override them all above)
    # so that reverse("scim:viewname") still works like the internal library code expects.
    path("scim/v2/", include("django_scim.urls", namespace="scim")),
]

# User documentation site
help_documentation_view = MarkdownDirectoryView.as_view(
    template_name="zerver/documentation_main.html", path_template="/zerver/help/%s.md"
)
api_documentation_view = MarkdownDirectoryView.as_view(
    template_name="zerver/documentation_main.html", path_template="/zerver/api/%s.md"
)
policy_documentation_view = MarkdownDirectoryView.as_view(
    template_name="zerver/documentation_main.html",
    policies_view=True,
)
urls += [
    # Redirects due to us having moved the docs:
    path(
        "help/delete-a-stream", RedirectView.as_view(url="/help/archive-a-stream", permanent=True)
    ),
    path("api/delete-stream", RedirectView.as_view(url="/api/archive-stream", permanent=True)),
    path(
        "help/change-the-topic-of-a-message",
        RedirectView.as_view(url="/help/rename-a-topic", permanent=True),
    ),
    path(
        "help/configure-missed-message-emails",
        RedirectView.as_view(url="/help/email-notifications", permanent=True),
    ),
    path(
        "help/add-an-alert-word",
        RedirectView.as_view(
            url="/help/pm-mention-alert-notifications#alert-words", permanent=True
        ),
    ),
    path(
        "help/test-mobile-notifications",
        RedirectView.as_view(url="/help/mobile-notifications", permanent=True),
    ),
    path(
        "help/troubleshooting-desktop-notifications",
        RedirectView.as_view(
            url="/help/desktop-notifications#troubleshooting-desktop-notifications", permanent=True
        ),
    ),
    path(
        "help/change-notification-sound",
        RedirectView.as_view(
            url="/help/desktop-notifications#change-notification-sound", permanent=True
        ),
    ),
    path(
        "help/configure-message-notification-emails",
        RedirectView.as_view(url="/help/email-notifications", permanent=True),
    ),
    path(
        "help/disable-new-login-emails",
        RedirectView.as_view(url="/help/email-notifications#new-login-emails", permanent=True),
    ),
    # This redirect is particularly important, because the old URL
    # appears in links from Welcome Bot messages.
    path(
        "help/about-streams-and-topics",
        RedirectView.as_view(url="/help/streams-and-topics", permanent=True),
    ),
    path(
        "help/community-topic-edits",
        RedirectView.as_view(url="/help/configure-who-can-edit-topics", permanent=True),
    ),
    path(
        "help/only-allow-admins-to-add-emoji",
        RedirectView.as_view(
            url="/help/custom-emoji#change-who-can-add-custom-emoji", permanent=True
        ),
    ),
    path(
        "help/configure-who-can-add-custom-emoji",
        RedirectView.as_view(
            url="/help/custom-emoji#change-who-can-add-custom-emoji", permanent=True
        ),
    ),
    path(
        "help/add-custom-emoji",
        RedirectView.as_view(url="/help/custom-emoji", permanent=True),
    ),
    path(
        "help/night-mode",
        RedirectView.as_view(url="/help/dark-theme", permanent=True),
    ),
    path("help/", help_documentation_view),
    path("help/<path:article>", help_documentation_view),
    path("api/", api_documentation_view),
    path("api/<slug:article>", api_documentation_view),
    path("policies/", policy_documentation_view),
    path("policies/<slug:article>", policy_documentation_view),
    path(
        "privacy/",
        RedirectView.as_view(url="/policies/privacy"),
    ),
    path(
        "terms/",
        RedirectView.as_view(url="/policies/terms"),
    ),
]

# Two-factor URLs
if settings.TWO_FACTOR_AUTHENTICATION_ENABLED:
    urls += [path("", include(tf_urls)), path("", include(tf_twilio_urls))]

if settings.DEVELOPMENT:
    urls += dev_urls.urls
    i18n_urls += dev_urls.i18n_urls
    v1_api_mobile_patterns += dev_urls.v1_api_mobile_patterns

urls += [
    path("api/v1/", include(v1_api_mobile_patterns)),
]

# The sequence is important; if i18n URLs don't come first then
# reverse URL mapping points to i18n URLs which causes the frontend
# tests to fail
urlpatterns = i18n_patterns(*i18n_urls) + urls + legacy_urls


text:
package transport

import (
	"sync"
	"time"

	"golang.org/x/net/context"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	"github.com/coreos/etcd/raft"
	"github.com/coreos/etcd/raft/raftpb"
	"github.com/docker/swarmkit/log"
	"github.com/pkg/errors"
)

// ErrIsNotFound indicates that peer was never added to transport.
var ErrIsNotFound = errors.New("peer not found")

// Raft is interface which represents Raft API for transport package.
type Raft interface {
	ReportUnreachable(id uint64)
	ReportSnapshot(id uint64, status raft.SnapshotStatus)
	IsIDRemoved(id uint64) bool
	UpdateNode(id uint64, addr string)

	NodeRemoved()
}

// Config for Transport
type Config struct {
	HeartbeatInterval time.Duration
	SendTimeout       time.Duration
	Credentials       credentials.TransportCredentials
	RaftID            string

	Raft
}

// Transport is structure which manages remote raft peers and sends messages
// to them.
type Transport struct {
	config *Config

	unknownc chan raftpb.Message

	mu      sync.Mutex
	peers   map[uint64]*peer
	stopped bool

	ctx    context.Context
	cancel context.CancelFunc
	done   chan struct{}

	deferredConns map[*grpc.ClientConn]*time.Timer
}

// New returns new Transport with specified Config.
func New(cfg *Config) *Transport {
	ctx, cancel := context.WithCancel(context.Background())
	if cfg.RaftID != "" {
		ctx = log.WithField(ctx, "raft_id", cfg.RaftID)
	}
	t := &Transport{
		peers:    make(map[uint64]*peer),
		config:   cfg,
		unknownc: make(chan raftpb.Message),
		done:     make(chan struct{}),
		ctx:      ctx,
		cancel:   cancel,

		deferredConns: make(map[*grpc.ClientConn]*time.Timer),
	}
	go t.run(ctx)
	return t
}

func (t *Transport) run(ctx context.Context) {
	defer func() {
		log.G(ctx).Debug("stop transport")
		t.mu.Lock()
		defer t.mu.Unlock()
		t.stopped = true
		for _, p := range t.peers {
			p.stop()
			p.cc.Close()
		}
		for cc, timer := range t.deferredConns {
			timer.Stop()
			cc.Close()
		}
		t.deferredConns = nil
		close(t.done)
	}()
	for {
		select {
		case <-ctx.Done():
			return
		default:
		}

		select {
		case m := <-t.unknownc:
			if err := t.sendUnknownMessage(ctx, m); err != nil {
				log.G(ctx).WithError(err).Warnf("ignored message %s to unknown peer %x", m.Type, m.To)
			}
		case <-ctx.Done():
			return
		}
	}
}

// Stop stops transport and waits until it finished
func (t *Transport) Stop() {
	t.cancel()
	<-t.done
}

// Send sends raft message to remote peers.
func (t *Transport) Send(m raftpb.Message) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.stopped {
		return errors.New("transport stopped")
	}
	if t.config.IsIDRemoved(m.To) {
		return errors.Errorf("refusing to send message %s to removed member %x", m.Type, m.To)
	}
	p, ok := t.peers[m.To]
	if !ok {
		log.G(t.ctx).Warningf("sending message %s to an unrecognized member ID %x", m.Type, m.To)
		select {
		// we need to process messages to unknown peers in separate goroutine
		// to not block sender
		case t.unknownc <- m:
		case <-t.ctx.Done():
			return t.ctx.Err()
		default:
			return errors.New("unknown messages queue is full")
		}
		return nil
	}
	if err := p.send(m); err != nil {
		return errors.Wrapf(err, "failed to send message %x to %x", m.Type, m.To)
	}
	return nil
}

// AddPeer adds new peer with id and address addr to Transport.
// If there is already peer with such id in Transport it will return error if
// address is different (UpdatePeer should be used) or nil otherwise.
func (t *Transport) AddPeer(id uint64, addr string) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.stopped {
		return errors.New("transport stopped")
	}
	if ep, ok := t.peers[id]; ok {
		if ep.address() == addr {
			return nil
		}
		return errors.Errorf("peer %x already added with addr %s", id, ep.addr)
	}
	log.G(t.ctx).Debugf("transport: add peer %x with address %s", id, addr)
	p, err := newPeer(id, addr, t)
	if err != nil {
		return errors.Wrapf(err, "failed to create peer %x with addr %s", id, addr)
	}
	t.peers[id] = p
	return nil
}

// RemovePeer removes peer from Transport and wait for it to stop.
func (t *Transport) RemovePeer(id uint64) error {
	t.mu.Lock()
	defer t.mu.Unlock()

	if t.stopped {
		return errors.New("transport stopped")
	}
	p, ok := t.peers[id]
	if !ok {
		return ErrIsNotFound
	}
	delete(t.peers, id)
	cc := p.conn()
	p.stop()
	timer := time.AfterFunc(8*time.Second, func() {
		t.mu.Lock()
		if !t.stopped {
			delete(t.deferredConns, cc)
			cc.Close()
		}
		t.mu.Unlock()
	})
	// store connection and timer for cleaning up on stop
	t.deferredConns[cc] = timer

	return nil
}

// UpdatePeer updates peer with new address. It replaces connection immediately.
func (t *Transport) UpdatePeer(id uint64, addr string) error {
	t.mu.Lock()
	defer t.mu.Unlock()

	if t.stopped {
		return errors.New("transport stopped")
	}
	p, ok := t.peers[id]
	if !ok {
		return ErrIsNotFound
	}
	if err := p.update(addr); err != nil {
		return err
	}
	log.G(t.ctx).Debugf("peer %x updated to address %s", id, addr)
	return nil
}

// UpdatePeerAddr updates peer with new address, but delays connection creation.
// New address won't be used until first failure on old address.
func (t *Transport) UpdatePeerAddr(id uint64, addr string) error {
	t.mu.Lock()
	defer t.mu.Unlock()

	if t.stopped {
		return errors.New("transport stopped")
	}
	p, ok := t.peers[id]
	if !ok {
		return ErrIsNotFound
	}
	if err := p.updateAddr(addr); err != nil {
		return err
	}
	return nil
}

// PeerConn returns raw grpc connection to peer.
func (t *Transport) PeerConn(id uint64) (*grpc.ClientConn, error) {
	t.mu.Lock()
	defer t.mu.Unlock()
	p, ok := t.peers[id]
	if !ok {
		return nil, ErrIsNotFound
	}
	p.mu.Lock()
	active := p.active
	p.mu.Unlock()
	if !active {
		return nil, errors.New("peer is inactive")
	}
	return p.conn(), nil
}

// PeerAddr returns address of peer with id.
func (t *Transport) PeerAddr(id uint64) (string, error) {
	t.mu.Lock()
	defer t.mu.Unlock()
	p, ok := t.peers[id]
	if !ok {
		return "", ErrIsNotFound
	}
	return p.address(), nil
}

// HealthCheck checks health of particular peer.
func (t *Transport) HealthCheck(ctx context.Context, id uint64) error {
	t.mu.Lock()
	p, ok := t.peers[id]
	t.mu.Unlock()
	if !ok {
		return ErrIsNotFound
	}
	ctx, cancel := t.withContext(ctx)
	defer cancel()
	return p.healthCheck(ctx)
}

// Active returns true if node was recently active and false otherwise.
func (t *Transport) Active(id uint64) bool {
	t.mu.Lock()
	defer t.mu.Unlock()
	p, ok := t.peers[id]
	if !ok {
		return false
	}
	p.mu.Lock()
	active := p.active
	p.mu.Unlock()
	return active
}

func (t *Transport) longestActive() (*peer, error) {
	var longest *peer
	var longestTime time.Time
	t.mu.Lock()
	defer t.mu.Unlock()
	for _, p := range t.peers {
		becameActive := p.activeTime()
		if becameActive.IsZero() {
			continue
		}
		if longest == nil {
			longest = p
			continue
		}
		if becameActive.Before(longestTime) {
			longest = p
			longestTime = becameActive
		}
	}
	if longest == nil {
		return nil, errors.New("failed to find longest active peer")
	}
	return longest, nil
}

func (t *Transport) dial(addr string) (*grpc.ClientConn, error) {
	grpcOptions := []grpc.DialOption{
		grpc.WithBackoffMaxDelay(8 * time.Second),
	}
	if t.config.Credentials != nil {
		grpcOptions = append(grpcOptions, grpc.WithTransportCredentials(t.config.Credentials))
	} else {
		grpcOptions = append(grpcOptions, grpc.WithInsecure())
	}

	if t.config.SendTimeout > 0 {
		grpcOptions = append(grpcOptions, grpc.WithTimeout(t.config.SendTimeout))
	}

	cc, err := grpc.Dial(addr, grpcOptions...)
	if err != nil {
		return nil, err
	}

	return cc, nil
}

func (t *Transport) withContext(ctx context.Context) (context.Context, context.CancelFunc) {
	ctx, cancel := context.WithCancel(ctx)

	go func() {
		select {
		case <-ctx.Done():
		case <-t.ctx.Done():
			cancel()
		}
	}()
	return ctx, cancel
}

func (t *Transport) resolvePeer(ctx context.Context, id uint64) (*peer, error) {
	longestActive, err := t.longestActive()
	if err != nil {
		return nil, err
	}
	ctx, cancel := context.WithTimeout(ctx, t.config.SendTimeout)
	defer cancel()
	addr, err := longestActive.resolveAddr(ctx, id)
	if err != nil {
		return nil, err
	}
	return newPeer(id, addr, t)
}

func (t *Transport) sendUnknownMessage(ctx context.Context, m raftpb.Message) error {
	p, err := t.resolvePeer(ctx, m.To)
	if err != nil {
		return errors.Wrapf(err, "failed to resolve peer")
	}
	defer p.cancel()
	if err := p.sendProcessMessage(ctx, m); err != nil {
		return errors.Wrapf(err, "failed to send message")
	}
	return nil
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Brodo & Hawksworth, Op. bot. 42: 156 (1977)

#### Original name
Alectoria sulcata f. vulpinoides Zahlbr.

### Remarks
null


text:
import debug from 'debug'

export default function(statusCode, message) {
  // next MUST need for a error handler of the connect
  return (err, req, res, next) => { //eslint-disable-line no-unused-vars
    debug('error')(`${message} ,${err}`)
    res.statusCode = statusCode
    res.end(`${message} : ${err.status}`)
  }
}


text:
package com.opengamma.strata.product;

import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Offset.offset;

import org.junit.jupiter.api.Test;

import com.opengamma.strata.basics.ImmutableReferenceData;

/**
 * Test {@link SecurityTrade}.
 */
public class SecurityTradeTest {

  private static final TradeInfo TRADE_INFO = TradeInfo.of(date(2016, 6, 30));
  private static final SecurityId SECURITY_ID = SecurityId.of("OG-Test", "Id");
  private static final SecurityId SECURITY_ID2 = SecurityId.of("OG-Test", "Id2");
  private static final double QUANTITY = 100;
  private static final double QUANTITY2 = 200;
  private static final double PRICE = 123.50;
  private static final double PRICE2 = 120.50;

  //-------------------------------------------------------------------------
  @Test
  public void test_of() {
    SecurityTrade test = SecurityTrade.of(TRADE_INFO, SECURITY_ID, QUANTITY, PRICE);
    assertThat(test.getInfo()).isEqualTo(TRADE_INFO);
    assertThat(test.getSecurityId()).isEqualTo(SECURITY_ID);
    assertThat(test.getQuantity()).isEqualTo(QUANTITY);
    assertThat(test.getPrice()).isEqualTo(PRICE);
    assertThat(test.withInfo(TRADE_INFO).getInfo()).isEqualTo(TRADE_INFO);
    assertThat(test.withQuantity(129).getQuantity()).isCloseTo(129d, offset(0d));
    assertThat(test.withPrice(129).getPrice()).isCloseTo(129d, offset(0d));
  }

  @Test
  public void test_builder() {
    SecurityTrade test = sut();
    assertThat(test.getInfo()).isEqualTo(TRADE_INFO);
    assertThat(test.getSecurityId()).isEqualTo(SECURITY_ID);
    assertThat(test.getQuantity()).isEqualTo(QUANTITY);
    assertThat(test.getPrice()).isEqualTo(PRICE);
  }

  //-------------------------------------------------------------------------
  @Test
  public void test_summarize() {
    SecurityTrade trade = sut();
    PortfolioItemSummary expected = PortfolioItemSummary.builder()
        .portfolioItemType(PortfolioItemType.TRADE)
        .productType(ProductType.SECURITY)
        .description("Id x 100")
        .build();
    assertThat(trade.summarize()).isEqualTo(expected);
  }

  //-------------------------------------------------------------------------
  @Test
  public void test_resolveTarget() {
    GenericSecurity security = GenericSecurityTest.sut();
    Trade test = sut().resolveTarget(ImmutableReferenceData.of(SECURITY_ID, security));
    GenericSecurityTrade expected = GenericSecurityTrade.of(TRADE_INFO, security, QUANTITY, PRICE);
    assertThat(test).isEqualTo(expected);
  }

  //-------------------------------------------------------------------------
  @Test
  public void coverage() {
    coverImmutableBean(sut());
    coverBeanEquals(sut(), sut2());
  }

  @Test
  public void test_serialization() {
    assertSerialization(sut());
  }

  //-------------------------------------------------------------------------
  static SecurityTrade sut() {
    return SecurityTrade.builder()
        .info(TRADE_INFO)
        .securityId(SECURITY_ID)
        .quantity(QUANTITY)
        .price(PRICE)
        .build();
  }

  static SecurityTrade sut2() {
    return SecurityTrade.builder()
        .info(TradeInfo.empty())
        .securityId(SECURITY_ID2)
        .quantity(QUANTITY2)
        .price(PRICE2)
        .build();
  }

}


text:
The `Recime Command Line Tool` allows you to scaffold your bot from terminal. It creates your account based on the email you have provided and lets you deploy it to **[Recime](https://recime.ai)** cloud.

[![Build Status](https://travis-ci.org/Recime/recime-cli.svg?branch=master)](https://travis-ci.org/Recime/recime-cli)
[![Go Report Card](https://goreportcard.com/badge/github.com/recime/recime-cli)](https://goreportcard.com/report/github.com/recime/recime-cli)

## macOS

Install [Homebrew](http://brew.sh/)  by pasting the below command at a Terminal prompt:

    /usr/bin/ru by -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

To install all the Go and Recime CLI, just run the following command, Homebrew takes care of the rest for you:

  brew tap recime/tools && brew install recime-cli

This will install all the dependencies, configure path and install the CLI accessible globally. Once installation is complete

## Source

`Recime Command Line Tool` is built using [Go](https://golang.org/dl/). Therefore, if you have go tools installs then type the following command to install:

```
go get -v -u github.com/recime/recime-cli

```

Plese make sure that `go` is installed and **GOROOT** and **GO_PATH** is configured correctly and you will need go 1.6+ to install `recime-cli`.

The following commands are currently available in the `Recime Command Line Tool`:

```bash
  config      Initializes bot config vars
  create      Scaffolds the bot from an interactive prompt
  deploy      Deploys the bot to Recime cloud
  login       Logs into your Recime account
  platform    Configures the Platform
  run         Runs the bot locally
```

## License

Copyright © 2017 Recime Inc. All rights reserved.


text:
var types = require('./types')

var name = {}

name.decode = function (buf, offset) {
  var list = []
  var oldOffset = offset
  var len = buf[offset++]

  if (len >= 0xc0) {
    var res = name.decode(buf, buf.readUInt16BE(offset - 1) - 0xc000)
    name.decode.bytes = 2
    return res
  }

  while (len) {
    if (len >= 0xc0) {
      list.push(name.decode(buf, buf.readUInt16BE(offset - 1) - 0xc000))
      offset++
      break
    }

    list.push(buf.toString('utf-8', offset, offset + len))
    offset += len
    len = buf[offset++]
  }

  name.decode.bytes = offset - oldOffset
  return list.join('.')
}

name.encode = function (n, buf, offset) {
  var list = n.split('.')
  var oldOffset = offset

  for (var i = 0; i < list.length; i++) {
    var len = buf.write(list[i], offset + 1)
    buf[offset] = len
    offset += len + 1
  }

  buf[offset++] = 0

  name.encode.bytes = offset - oldOffset
  return buf
}

name.encodingLength = function (n) {
  return Buffer.byteLength(n) + 2
}

var str = {}

str.encode = function (s, buf, offset) {
  var len = buf.write(s, offset + 1)
  buf[offset] = len
  str.encode.bytes = len + 1
  return buf
}

str.decode = function (buf, offset) {
  var len = buf[offset]
  var s = buf.toString('utf-8', offset + 1, offset + 1 + len)
  str.decode.bytes = len + 1
  return s
}

str.encodingLength = function (s) {
  return Buffer.byteLength(s) + 1
}

var QUERY_FLAG = 0x0000
var RESPONSE_FLAG = 0x8400

var header = {}

header.decode = function (buf, offset) {
  var flags = buf.readUInt16BE(offset + 2)
  if (flags !== RESPONSE_FLAG && flags !== QUERY_FLAG) throw new Error('bad type: ' + flags)

  header.decode.bytes = 12
  return {
    type: flags === RESPONSE_FLAG ? 'response' : 'query',
    qdcount: buf.readUInt16BE(offset + 4),
    ancount: buf.readUInt16BE(offset + 6),
    nscount: buf.readUInt16BE(offset + 8),
    arcount: buf.readUInt16BE(offset + 10)
   }
}

header.encode = function (h, buf, offset) {
  buf.writeUInt16BE(0, offset)
  buf.writeUInt16BE(h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG, offset + 2)
  buf.writeUInt16BE(h.qdcount, offset + 4)
  buf.writeUInt16BE(h.ancount, offset + 6)
  buf.writeUInt16BE(h.nscount, offset + 8)
  buf.writeUInt16BE(h.arcount, offset + 10)

  header.encode.bytes = 12
  return buf
}

header.encodingLength = function (h) {
  return 12
}

var runknown = {}

runknown.encode = function (data, buf, offset) {
  buf.writeUInt16BE(data.length, offset)
  data.copy(buf, offset + 2)

  runknown.encode.bytes = data.length + 2
  return buf
}

runknown.decode = function (buf, offset) {
  var len = buf.readUInt16BE(offset)
  var data = buf.slice(offset + 2, offset + 2 + len)
  runknown.decode.bytes = len + 2
  return data
}

runknown.encodingLength = function (data) {
  return data.length + 2
}

var rtxt = {}

rtxt.encode = function (s, buf, offset) {
  str.encode(s, buf, offset + 2)
  buf.writeUInt16BE(str.encode.bytes, offset)
  rtxt.encode.bytes = str.encode.bytes + 2
  return buf
}

rtxt.decode = function (buf, offset) {
  var s = str.decode(buf, offset + 2)
  rtxt.decode.bytes = str.decode.bytes + 2
  return s
}

rtxt.encodingLength = function (s) {
  return str.encodingLength(s) + 2
}

var rhinfo = {}

rhinfo.encode = function (data, buf, offset) {
  var oldOffset = offset
  offset += 2
  str.encode(data.cpu, buf, offset)
  offset += str.encode.bytes
  str.encode(data.os, buf, offset)
  offset += str.encode.bytes
  buf.writeUInt32BE(offset - oldOffset - 2, oldOffset)
  rhinfo.encode.bytes = offset - oldOffset
  return buf
}

rhinfo.decode = function (buf, offset) {
  var oldOffset = offset

  var data = {}
  offset += 2
  data.cpu = str.decode(buf, offset)
  offset += str.decode.bytes
  data.os = str.decode(buf, offset)
  offset += str.decode.bytes
  rhinfo.decode.bytes = offset - oldOffset
  return data
}

rhinfo.encodingLength = function (data) {
  return str.encodingLength(data.cpu) + str.encodingLength(data.os) + 2
}

var rptr = {}

rptr.encode = function (data, buf, offset) {
  name.encode(data, buf, offset + 2)
  buf.writeUInt16BE(name.encode.bytes, offset)
  rptr.encode.bytes = name.encode.bytes + 2
  return buf
}

rptr.decode = function (buf, offset) {
  var data = name.decode(buf, offset + 2)
  rptr.decode.bytes = name.decode.bytes + 2
  return data
}

rptr.encodingLength = function (data) {
  return name.encodingLength(data) + 2
}

var rsrv = {}

rsrv.encode = function (data, buf, offset) {
  buf.writeUInt16BE(data.priority || 0, offset + 2)
  buf.writeUInt16BE(data.weight || 0, offset + 4)
  buf.writeUInt16BE(data.port || 0, offset + 6)
  name.encode(data.target, buf, offset + 8)

  var len = name.encode.bytes + 6
  buf.writeUInt16BE(len, offset)

  rsrv.encode.bytes = len + 2
  return buf
}

rsrv.decode = function (buf, offset) {
  var len = buf.readUInt16BE(offset)

  var data = {}
  data.priority = buf.readUInt16BE(offset + 2)
  data.weight = buf.readUInt16BE(offset + 4)
  data.port = buf.readUInt16BE(offset + 6)
  data.target = name.decode(buf, offset + 8)

  rsrv.decode.bytes = len + 2
  return data
}

rsrv.encodingLength = function (data) {
  return 8 + name.encodingLength(data.target)
}

var ra = {}

ra.encode = function (host, buf, offset) {
  buf.writeUInt16BE(4, offset)
  offset += 2

  var nums = host.split('.')
  for (var i = 0; i < 4; i++) buf[offset++] = Number(nums[i])

  ra.encode.bytes = 6
  return buf
}

ra.decode = function (buf, offset) {
  offset += 2

  var host = []
  for (var i = 0; i < 4; i++) host.push(buf[offset++])

  ra.decode.bytes = 6
  return host.join('.')
}

ra.encodingLength = function (host) {
  return 6
}

var raaaa = {}

raaaa.encode = function (host, buf, offset) {
  buf.writeUInt16BE(16, offset)
  offset += 2

  var nums = host.split(':')
  var idx = nums.indexOf('')
  var missing = 8 - nums.length
  for (var i = 0; i < missing; i++) nums.splice(idx, 0, '0')
  for (var j = 0; j < nums.length; j++) buf.writeUInt16BE(parseInt(nums[j] || 0, 16), offset + 2 * j)

  raaaa.encode.bytes = 18
  return buf
}

raaaa.decode = function (buf, offset) {
  offset += 2

  var host = []
  for (var i = 0; i < 16; i += 2) host.push(buf.toString('hex', offset + i, offset + i + 2))

  raaaa.decode.bytes = 18
  return host.join(':').replace(/(:|^)0000(:0000)*(:|$)/, '$1$3').replace(/(^|:)0*(\d)/g, '$1$2')
}

raaaa.encodingLength = function (host) {
  return 18
}

var answer = {}

var renc = function (type) {
  switch (type.toUpperCase()) {
    case 'A': return ra
    case 'PTR': return rptr
    case 'TXT': return rtxt
    case 'AAAA': return raaaa
    case 'SRV': return rsrv
    case 'HINFO': return rhinfo
  }
  return runknown
}

answer.decode = function (buf, offset) {
  var a = {}
  var oldOffset = offset

  a.name = name.decode(buf, offset)
  offset += name.decode.bytes
  a.type = types.toString(buf.readUInt16BE(offset))
  a.class = buf.readUInt16BE(offset + 2)
  a.ttl = buf.readUInt32BE(offset + 4)

  var enc = renc(a.type)
  a.data = enc.decode(buf, offset + 8)
  offset += 8 + enc.decode.bytes

  answer.decode.bytes = offset - oldOffset
  return a
}

answer.encode = function (a, buf, offset) {
  var oldOffset = offset

  name.encode(a.name, buf, offset)
  offset += name.encode.bytes

  buf.writeUInt16BE(types.toType(a.type), offset)
  buf.writeUInt16BE(a.class === undefined ? 1 : a.class, offset + 2)
  buf.writeUInt32BE(a.ttl || 0, offset + 4)

  var enc = renc(a.type)
  enc.encode(a.data, buf, offset + 8)
  offset += 8 + enc.encode.bytes

  answer.encode.bytes = offset - oldOffset
  return buf
}

answer.encodingLength = function (a) {
  return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(a.data)
}

var question = {}

question.decode = function (buf, offset) {
  var oldOffset = offset
  var q = {}

  q.name = name.decode(buf, offset)
  offset += name.decode.bytes

  q.type = types.toString(buf.readUInt16BE(offset))
  offset += 2

  q.class = buf.readUInt16BE(offset)
  offset += 2

  question.decode.bytes = offset - oldOffset
  return q
}

question.encode = function (q, buf, offset) {
  var oldOffset = offset

  name.encode(q.name, buf, offset)
  offset += name.encode.bytes

  buf.writeUInt16BE(types.toType(q.type), offset)
  offset += 2

  buf.writeUInt16BE(q.class === undefined ? 1 : q.class, offset)
  offset += 2

  question.encode.bytes = offset - oldOffset
  return q
}

question.encodingLength = function (q) {
  return name.encodingLength(q.name) + 4
}

var encodeList = function (list, enc, buf, offset) {
  for (var i = 0; i < list.length; i++) {
    enc.encode(list[i], buf, offset)
    offset += enc.encode.bytes
  }
  return offset
}

var encodingLengthList = function (list, enc) {
  var len = 0
  for (var i = 0; i < list.length; i++) len += enc.encodingLength(list[i])
  return len
}

exports.encode = function (result) {
  result.qdcount = result.questions ? result.questions.length : 0
  result.ancount = result.answers ? result.answers.length : 0
  result.nscount = result.authorities ? result.authorities.length : 0
  result.arcount = result.additionals ? result.additionals.length : 0

  var len = header.encodingLength(result)
  len += encodingLengthList(result.questions || [], question)
  len += encodingLengthList(result.answers || [], answer)
  len += encodingLengthList(result.authorities || [], answer)
  len += encodingLengthList(result.additionals || [], answer)

  var buf = new Buffer(len)
  header.encode(result, buf, 0)

  var offset = header.encode.bytes
  offset = encodeList(result.questions || [], question, buf, offset)
  offset = encodeList(result.answers || [], answer, buf, offset)
  offset = encodeList(result.authorities || [], answer, buf, offset)
  offset = encodeList(result.additionals || [], answer, buf, offset)

  return buf
}

var decodeList = function (list, enc, buf, offset) {
  for (var i = 0; i < list.length; i++) {
    list[i] = enc.decode(buf, offset)
    offset += enc.decode.bytes
  }
  return offset
}

exports.decode = function (buf) {
  var result = header.decode(buf, 0)
  var offset = header.decode.bytes

  offset = decodeList(result.questions = new Array(result.qdcount), question, buf, offset)
  offset = decodeList(result.answers = new Array(result.ancount), answer, buf, offset)
  offset = decodeList(result.authorities = new Array(result.nscount), answer, buf, offset)
  offset = decodeList(result.additionals = new Array(result.arcount), answer, buf, offset)

  return result
}


text:
package com.microrisc.simply.iqrf.dpa.v21x.typeconvertors;

import com.microrisc.simply.iqrf.dpa.v21x.types.BondedNodes;
import com.microrisc.simply.protocol.mapping.ConvertorFactoryMethod;
import com.microrisc.simply.typeconvertors.PrimitiveConvertor;
import com.microrisc.simply.typeconvertors.ValueConversionException;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Provides functionality for conversion from IQRF DPA bit array of bonded nodes
 * to {@code Integer[]} values
 *
 * @author Michal Konopa
 */
public final class BondedNodesConvertor extends PrimitiveConvertor {
    /** Logger. */
    private static final Logger logger = LoggerFactory.getLogger(BondedNodesConvertor.class);

    private BondedNodesConvertor() {
    }

    /** Singleton. */
    private static final BondedNodesConvertor instance = new BondedNodesConvertor();

    /**
     * @return {@code BondedNodesConvertor} instance
     */
    @ConvertorFactoryMethod
    static public BondedNodesConvertor getInstance() {
        return instance;
    }

    /** Size of returned response. */
    static public final int TYPE_SIZE = 32;

    @Override
    public int getGenericTypeSize() {
        return TYPE_SIZE;
    }

    /**
     * Currently not supported. Throws {@code UnsupportedOperationException }.
     * @throws UnsupportedOperationException
     */
    @Override
    public short[] toProtoValue(Object value) throws ValueConversionException {
        throw new UnsupportedOperationException("Currently not supported");
    }

    @Override
    public Object toObject(short[] protoValue) throws ValueConversionException {
        logger.debug("toObject - start: protoValue={}", protoValue);

        // maximal bonded node number
        final int MAX_BONDED_NODE_NUMBER = 0xEF;
        final int MAX_BYTES_USED = (int)Math.ceil(MAX_BONDED_NODE_NUMBER / 8.0);

        List<Integer> bondedNodesList = new LinkedList<>();

        for (int byteId = 0; byteId < 32; byteId++) {
            if (byteId >= MAX_BYTES_USED) {
                break;
            }

            if (protoValue[byteId] == 0) {
                continue;
            }

            int bitComp = 1;
            for (int bitId = 0; bitId < 8; bitId++) {
                if ((protoValue[byteId] & bitComp) == bitComp) {
                    bondedNodesList.add(byteId * 8 + bitId);
                }
                bitComp *= 2;
            }
        }
        BondedNodes bondedNodes = new BondedNodes(bondedNodesList);

        logger.debug("toObject - end: {}", bondedNodes);
        return bondedNodes;
    }

}


text:
package com.oberasoftware.home.zwave.core.utils;

import com.oberasoftware.home.zwave.exceptions.HomeAutomationException;

/**
 * @author renarj
 */
@FunctionalInterface
public interface EventSupplier<T> {
    T get() throws HomeAutomationException;
}


text:
<?php

namespace backend\models;

use Yii;
use common\models\User;
/**
 * This is the model class for table "rol".
 *
 * @property integer $id
 * @property string $rol_nombre
 * @property integer $rol_valor
 */
class Rol extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'rol';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['rol_valor'], 'integer'],
            [['rol_nombre'], 'string', 'max' => 45],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'rol_nombre' => 'Rol Nombre',
            'rol_valor' => 'Rol Valor',
        ];
    }
    public function getUsers()
    {
        return $this->hasMany(User::className(),['rol_id'=>'id']);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$/locales/de.js" charset="UTF-8" />
  </component>
</project>