INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Handles pagination of object listings.
def _paginate(self, current_page, query_set, per_page=10): """ Handles pagination of object listings. Args: current_page int: Current page number query_set (:class:`QuerySet<pyoko:pyoko.db.queryset.QuerySet>`): Object listing queryset. per_page int: ...
Creates a message for the given channel.
def create_message(current): """ Creates a message for the given channel. .. code-block:: python # request: { 'view':'_zops_create_message', 'message': { 'channel': key, # of channel 'body': string, # message text., ...
Initial display of channel content. Returns channel description members no of members last 20 messages etc.
def show_channel(current, waited=False): """ Initial display of channel content. Returns channel description, members, no of members, last 20 messages etc. .. code-block:: python # request: { 'view':'_zops_show_channel', 'key': key, } ...
Get old messages for a channel. 20 messages per request
def channel_history(current): """ Get old messages for a channel. 20 messages per request .. code-block:: python # request: { 'view':'_zops_channel_history, 'channel_key': key, 'timestamp': datetime, # timestamp data of o...
Push timestamp of latest message of an ACTIVE channel.
def report_last_seen_message(current): """ Push timestamp of latest message of an ACTIVE channel. This view should be called with timestamp of latest message; - When user opens (clicks on) a channel. - Periodically (eg: setInterval for 15secs) while user staying in a channel. .. code-block:: ...
List channel memberships of current user
def list_channels(current): """ List channel memberships of current user .. code-block:: python # request: { 'view':'_zops_list_channels', } # response: { 'channels': [ {...
Number of unread messages for current user
def unread_count(current): """ Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status': 'OK', 'co...
Returns last N notifications for current user
def get_notifications(current): """ Returns last N notifications for current user .. code-block:: python # request: { 'view':'_zops_unread_messages', 'amount': int, # Optional, defaults to 8 } # response: ...
Create a public channel. Can be a broadcast channel or normal chat room.
def create_channel(current): """ Create a public channel. Can be a broadcast channel or normal chat room. Chat room and broadcast distinction will be made at user subscription phase. .. code-block:: python # request: { 'view':'_zops_create_chan...
Subscribe member ( s ) to a channel
def add_members(current): """ Subscribe member(s) to a channel .. code-block:: python # request: { 'view':'_zops_add_members', 'channel_key': key, 'read_only': boolean, # true if this is a Broadcast channel, ...
Subscribe users of a given unit to given channel
def add_unit_to_channel(current): """ Subscribe users of a given unit to given channel JSON API: .. code-block:: python # request: { 'view':'_zops_add_unit_to_channel', 'unit_key': key, 'ch...
Search users for adding to a public room or creating one to one direct messaging
def search_user(current): """ Search users for adding to a public room or creating one to one direct messaging .. code-block:: python # request: { 'view':'_zops_search_user', 'query': string, } # res...
Search on units for subscribing it s users to a channel
def search_unit(current): """ Search on units for subscribing it's users to a channel .. code-block:: python # request: { 'view':'_zops_search_unit', 'query': string, } # response: { ...
Create a One - To - One channel between current and selected user.
def create_direct_channel(current): """ Create a One-To-One channel between current and selected user. .. code-block:: python # request: { 'view':'_zops_create_direct_channel', 'user_key': key, } # response: { 'des...
Search in messages. If channel_key given search will be limited to that channel otherwise search will be performed on all of user s subscribed channels.
def find_message(current): """ Search in messages. If "channel_key" given, search will be limited to that channel, otherwise search will be performed on all of user's subscribed channels. .. code-block:: python # request: { 'view':'_zops_search_...
Delete a channel
def delete_channel(current): """ Delete a channel .. code-block:: python # request: { 'view':'_zops_delete_channel, 'channel_key': key, } # response: { 'status': 'OK', ...
Update channel name or description
def edit_channel(current): """ Update channel name or description .. code-block:: python # request: { 'view':'_zops_edit_channel, 'channel_key': key, 'name': string, 'description': string, ...
Pin a channel to top of channel list
def pin_channel(current): """ Pin a channel to top of channel list .. code-block:: python # request: { 'view':'_zops_pin_channel, 'channel_key': key, } # response: { 'status':...
Delete a message
def delete_message(current): """ Delete a message .. code-block:: python # request: { 'view':'_zops_delete_message, 'message_key': key, } # response: { 'key': key, ...
Edit a message a user own.
def edit_message(current): """ Edit a message a user own. .. code-block:: python # request: { 'view':'_zops_edit_message', 'message': { 'body': string, # message text 'key': key } } # response: ...
Flag inappropriate messages
def flag_message(current): """ Flag inappropriate messages .. code-block:: python # request: { 'view':'_zops_flag_message', 'message_key': key, } # response: { ' 'status': 'Created', 'code': 201, ...
remove flag of a message
def unflag_message(current): """ remove flag of a message .. code-block:: python # request: { 'view':'_zops_flag_message', 'key': key, } # response: { ' 'status': 'OK', 'code': 200, } "...
Returns applicable actions for current user for given message key
def get_message_actions(current): """ Returns applicable actions for current user for given message key .. code-block:: python # request: { 'view':'_zops_get_message_actions', 'key': key, } # response: { 'actions':[('name_stri...
Favorite a message
def add_to_favorites(current): """ Favorite a message .. code-block:: python # request: { 'view':'_zops_add_to_favorites, 'key': key, } # response: { 'status': 'Created', 'code': 201 'favorit...
Remove a message from favorites
def remove_from_favorites(current): """ Remove a message from favorites .. code-block:: python # request: { 'view':'_zops_remove_from_favorites, 'key': key, } # response: { 'status': 'OK', 'code': 200 ...
List user s favorites. If channel_key given will return favorites belong to that channel.
def list_favorites(current): """ List user's favorites. If "channel_key" given, will return favorites belong to that channel. .. code-block:: python # request: { 'view':'_zops_list_favorites, 'channel_key': key, } # response: {...
Creates a direct messaging channel between two user
def get_or_create_direct_channel(cls, initiator_key, receiver_key): """ Creates a direct messaging channel between two user Args: initiator: User, who want's to make first contact receiver: User, other party Returns: (Channel, receiver_name) ...
Creates MQ exchange for this channel Needs to be defined only once.
def create_exchange(self): """ Creates MQ exchange for this channel Needs to be defined only once. """ mq_channel = self._connect_mq() mq_channel.exchange_declare(exchange=self.code_name, exchange_type='fanout', ...
Deletes MQ exchange for this channel Needs to be defined only once.
def delete_exchange(self): """ Deletes MQ exchange for this channel Needs to be defined only once. """ mq_channel = self._connect_mq() mq_channel.exchange_delete(exchange=self.code_name)
serialized form for channel listing
def get_channel_listing(self): """ serialized form for channel listing """ return {'name': self.name, 'key': self.channel.key, 'type': self.channel.typ, 'read_only': self.read_only, 'is_online': self.is_online(), ...
Creates user s private exchange
def create_exchange(self): """ Creates user's private exchange Actually user's private channel needed to be defined only once, and this should be happened when user first created. But since this has a little performance cost, to be safe we always call it before binding t...
Binds ( subscribes ) users private exchange to channel exchange Automatically called at creation of subscription record.
def bind_to_channel(self): """ Binds (subscribes) users private exchange to channel exchange Automatically called at creation of subscription record. """ if self.channel.code_name != self.user.prv_exchange: channel = self._connect_mq() channel.exchange_bin...
Serializes message for given user.
def serialize(self, user=None): """ Serializes message for given user. Note: Should be called before first save(). Otherwise "is_update" will get wrong value. Args: user: User object Returns: Dict. JSON serialization ready dictionary object ...
Re - publishes updated message
def _republish(self): """ Re-publishes updated message """ mq_channel = self.channel._connect_mq() mq_channel.basic_publish(exchange=self.channel.key, routing_key='', body=json.dumps(self.serialize()))
Provide a reasonable default crawl name using the user name and date
def defaultCrawlId(): """ Provide a reasonable default crawl name using the user name and date """ timestamp = datetime.now().isoformat().replace(':', '_') user = getuser() return '_'.join(('crawl', user, timestamp))
Run Nutch command using REST API.
def main(argv=None): """Run Nutch command using REST API.""" global Verbose, Mock if argv is None: argv = sys.argv if len(argv) < 5: die('Bad args') try: opts, argv = getopt.getopt(argv[1:], 'hs:p:mv', ['help', 'server=', 'port=', 'mock', 'verbose']) except getopt.Geto...
Call the Nutch Server do some error checking and return the response.
def call(self, verb, servicePath, data=None, headers=None, forceText=False, sendJson=True): """Call the Nutch Server, do some error checking, and return the response. :param verb: One of nutch.RequestVerbs :param servicePath: path component of URL to append to endpoint, e.g. '/config' :...
Create a new named ( cid ) configuration from a parameter dictionary ( config_data ).
def create(self, cid, configData): """ Create a new named (cid) configuration from a parameter dictionary (config_data). """ configArgs = {'configId': cid, 'params': configData, 'force': True} cid = self.server.call('post', "/config/create", configArgs, forceText=True, headers=Te...
Return list of jobs at this endpoint.
def list(self, allJobs=False): """ Return list of jobs at this endpoint. Call get(allJobs=True) to see all jobs, not just the ones managed by this Client """ jobs = self.server.call('get', '/job') return [Job(job['id'], self.server) for job in jobs if allJobs or self._...
Create a job given a command: param command: Nutch command one of nutch. LegalJobs: param args: Additional arguments to pass to the job: return: The created Job
def create(self, command, **args): """ Create a job given a command :param command: Nutch command, one of nutch.LegalJobs :param args: Additional arguments to pass to the job :return: The created Job """ command = command.upper() if command not in LegalJo...
: param seed: A Seed object ( this or urlDir must be specified ): param urlDir: The directory on the server containing the seed list ( this or urlDir must be specified ): param args: Extra arguments for the job: return: a created Job object
def inject(self, seed=None, urlDir=None, **args): """ :param seed: A Seed object (this or urlDir must be specified) :param urlDir: The directory on the server containing the seed list (this or urlDir must be specified) :param args: Extra arguments for the job :return: a created J...
Create a new named ( sid ) Seed from a list of seed URLs
def create(self, sid, seedList): """ Create a new named (sid) Seed from a list of seed URLs :param sid: the name to assign to the new seed list :param seedList: the list of seeds to use :return: the created Seed object """ seedUrl = lambda uid, url: {"id": uid, ...
Create a new named ( sid ) Seed from a file containing URLs It s assumed URLs are whitespace seperated.
def createFromFile(self, sid, filename): """ Create a new named (sid) Seed from a file containing URLs It's assumed URLs are whitespace seperated. :param sid: the name to assign to the new seed list :param filename: the name of the file that contains URLs :return: the cr...
Given a completed job start the next job in the round or return None
def _nextJob(self, job, nextRound=True): """ Given a completed job, start the next job in the round, or return None :param nextRound: whether to start jobs from the next round if the current round is completed. :return: the newly started Job, or None if no job was started """ ...
Check the status of the current job activate the next job if it s finished and return the active job
def progress(self, nextRound=True): """ Check the status of the current job, activate the next job if it's finished, and return the active job If the current job has failed, a NutchCrawlException will be raised with no jobs attached. :param nextRound: whether to start jobs from the nex...
Execute all jobs in the current round and return when they have finished.
def nextRound(self): """ Execute all jobs in the current round and return when they have finished. If a job fails, a NutchCrawlException will be raised, with all completed jobs from this round attached to the exception. :return: a list of all completed Jobs """ ...
Execute all queued rounds and return when they have finished.
def waitAll(self): """ Execute all queued rounds and return when they have finished. If a job fails, a NutchCrawlException will be raised, with all completed jobs attached to the exception :return: a list of jobs completed for each round, organized by round (list-of-lists) ...
Create a JobClient for listing and creating jobs. The JobClient inherits the confId from the Nutch client.
def Jobs(self, crawlId=None): """ Create a JobClient for listing and creating jobs. The JobClient inherits the confId from the Nutch client. :param crawlId: crawlIds to use for this client. If not provided, will be generated by nutch.defaultCrawlId() :return: a JobClie...
Launch a crawl using the given seed: param seed: Type ( Seed or SeedList ) - used for crawl: param seedClient: if a SeedList is given the SeedClient to upload if None a default will be created: param jobClient: the JobClient to be used if None a default will be created: param rounds: the number of rounds in the crawl: ...
def Crawl(self, seed, seedClient=None, jobClient=None, rounds=1, index=True): """ Launch a crawl using the given seed :param seed: Type (Seed or SeedList) - used for crawl :param seedClient: if a SeedList is given, the SeedClient to upload, if None a default will be created :para...
>>> import pprint >>> input_line1 = Apr 24 00: 00: 02 node haproxy [ 12298 ]: 1. 1. 1. 1: 48660 [ 24/ Apr/ 2019: 00: 00: 02. 358 ] pre - staging~ pre - staging_doc/ pre - staging_active 261/ 0/ 2/ 8/ 271 200 2406 - - ---- 4/ 4/ 0/ 1/ 0 0/ 0 { AAAAAA: AAAAA_AAAAA: AAAAA_AAAAA_AAAAA: 300A||| user
def haproxy(line): #TODO Handle all message formats ''' >>> import pprint >>> input_line1 = 'Apr 24 00:00:02 node haproxy[12298]: 1.1.1.1:48660 [24/Apr/2019:00:00:02.358] pre-staging~ pre-staging_doc/pre-staging_active 261/0/2/8/271 200 2406 - - ---- 4/4/0/1/0 0/0 {AAAAAA:AAAAA_AAAAA:AAAAA_AAAAA_AAAAA:3...
>>> import pprint >>> input_line1 = { \ remote_addr: 127. 0. 0. 1 remote_user: - timestamp: 1515144699. 201 \ request: GET/ HTTP/ 1. 1 status: 200 request_time: 0. 000 \ body_bytes_sent: 396 http_referer: - http_user_agent: python - requests/ 2. 18. 4 \ http_x_forwarded_for: - upstream_response_time: - \ } >>> output_l...
def nginx_access(line): ''' >>> import pprint >>> input_line1 = '{ \ "remote_addr": "127.0.0.1","remote_user": "-","timestamp": "1515144699.201", \ "request": "GET / HTTP/1.1","status": "200","request_time": "0.000", \ "body_bytes_sent": "396","htt...
>>> import pprint >>> input_line1 = 2017 - 08 - 17T07: 56: 33. 489 + 0200 I REPL [ signalProcessingThread ] shutting down replication subsystems >>> output_line1 = mongodb ( input_line1 ) >>> pprint. pprint ( output_line1 ) { data: { component: REPL context: [ signalProcessingThread ] message: shutting down replication...
def mongodb(line): ''' >>> import pprint >>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems' >>> output_line1 = mongodb(input_line1) >>> pprint.pprint(output_line1) {'data': {'component': 'REPL', 'context': '[sig...
>>> import pprint >>> input_line1 = [ 23/ Aug/ 2017 11: 35: 25 ] INFO [ app. middleware_log_req: 50 ] View func called: { exception: null processing_time: 0. 00011801719665527344 url: <url > host: localhost user: testing post_contents: method: POST } >>> output_line1 = django ( input_line1 ) >>> pprint. pprint ( output...
def django(line): ''' >>> import pprint >>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }' >>> output_line1...
>>> import pprint >>> input_line = { level: warning timestamp: 2018 - 02 - 07T06: 37: 00. 297610Z event: exited via keyboard interrupt type: log id: 20180207T063700_4d03fe800bd111e89ecb96000007bc65 _: { ln: 58 file:/ usr/ local/ lib/ python2. 7/ dist - packages/ basescript/ basescript. py name: basescript. basescript f...
def basescript(line): ''' >>> import pprint >>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/ba...
>>> import pprint >>> input_line = [ 2017 - 08 - 30T06: 27: 19 158 ] [ WARN ] [ o. e. m. j. JvmGcMonitorService ] [ Glsuj_2 ] [ gc ] [ 296816 ] overhead spent [ 1. 2s ] collecting in the last [ 1. 3s ] >>> output_line = elasticsearch ( input_line ) >>> pprint. pprint ( output_line ) { data: { garbage_collector: gc gc_c...
def elasticsearch(line): ''' >>> import pprint >>> input_line = '[2017-08-30T06:27:19,158] [WARN ][o.e.m.j.JvmGcMonitorService] [Glsuj_2] [gc][296816] overhead, spent [1.2s] collecting in the last [1.3s]' >>> output_line = elasticsearch(input_line) >>> pprint.pprint(output_line) {'data': {'garba...
>>> line1 = [ 2018 - 04 - 03T00: 22: 38 048 ] [ DEBUG ] [ o. e. c. u. c. QueueResizingEsThreadPoolExecutor ] [ search17/ search ]: there were [ 2000 ] tasks in [ 809ms ] avg task time [ 28. 4micros ] EWMA task execution [ 790nanos ] [ 35165. 36 tasks/ s ] optimal queue is [ 35165 ] current capacity [ 1000 ] >>> line2 =...
def elasticsearch_ispartial_log(line): ''' >>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], current capacit...
Get an attribute defined by this session
def get(self, attr, default=None): """Get an attribute defined by this session""" attrs = self.body.get('attributes') or {} return attrs.get(attr, default)
if data can t found in cache then it will be fetched from db parsed and stored to cache for each lang_code.
def get_all(self, cat): """ if data can't found in cache then it will be fetched from db, parsed and stored to cache for each lang_code. :param cat: cat of catalog data :return: """ return self._get_from_local_cache(cat) or self._get_from_cache(cat) or self._get...
get from redis cache locally then return
def _fill_get_item_cache(self, catalog, key): """ get from redis, cache locally then return :param catalog: catalog name :param key: :return: """ lang = self._get_lang() keylist = self.get_all(catalog) self.ITEM_CACHE[lang][catalog] = dict([(i['va...
Utility method to quickly get a server up and running.
def run(self, host, port, debug=True, validate_requests=True): """Utility method to quickly get a server up and running. :param debug: turns on Werkzeug debugger, code reloading, and full logging. :param validate_requests: whether or not to ensure that requests are sent ...
Given a parsed JSON request object call the correct Intent Launch or SessionEnded function.
def dispatch_request(self, body): """Given a parsed JSON request object, call the correct Intent, Launch, or SessionEnded function. This function is called after request parsing and validaion and will raise a `ValueError` if an unknown request type comes in. :param body: JSON o...
Decorator to register a handler for the given intent.
def intent(self, intent_name): """Decorator to register a handler for the given intent. The decorated function can either take 0 or 2 arguments. If two are specified, it will be provided a dictionary of `{slot_name: value}` and a :py:class:`alexandra.session.Session` instance. ...
Kullanıcı şifresini encrypt ederek set eder.
def set_password(self, raw_password): """ Kullanıcı şifresini encrypt ederek set eder. Args: raw_password (str) """ self.password = pbkdf2_sha512.encrypt(raw_password, rounds=10000, salt_size=10)
encrypt password if not already encrypted
def encrypt_password(self): """ encrypt password if not already encrypted """ if self.password and not self.password.startswith('$pbkdf2'): self.set_password(self.password)
sends message to users private mq exchange Args: title: message: sender: url: typ:
def send_notification(self, title, message, typ=1, url=None, sender=None): """ sends message to users private mq exchange Args: title: message: sender: url: typ: """ self.created_channels.channel.add_message( ...
Send arbitrary cmd and data to client
def send_client_cmd(self, data, cmd=None, via_queue=None): """ Send arbitrary cmd and data to client if queue name passed by "via_queue" parameter, that queue will be used instead of users private exchange. Args: data: dict cmd: string via_que...
shifts on a given number of record in the original file: param offset: number of record
def seek(self, offset): """ shifts on a given number of record in the original file :param offset: number of record """ if self._shifts: if 0 <= offset < len(self._shifts): current_pos = self._file.tell() new_pos = self._shifts[offset] ...
: return: number of records processed from the original file
def tell(self): """ :return: number of records processed from the original file """ if self._shifts: t = self._file.tell() if t == self._shifts[0]: return 0 elif t == self._shifts[-1]: return len(self._shifts) - 1 ...
Assigning the workflow to itself. The selected job is checked to see if there is an assigned role. If it does not have a role assigned to it it takes the job to itself and displays a message that the process is successful. If there is a role assigned to it it does not do any operation and the message is displayed on th...
def assign_yourself(self): """ Assigning the workflow to itself. The selected job is checked to see if there is an assigned role. If it does not have a role assigned to it, it takes the job to itself and displays a message that the process is successful. ...
The workflow method to be assigned to the person with the same role and unit as the user... code - block:: python
def select_role(self): """ The workflow method to be assigned to the person with the same role and unit as the user. .. code-block:: python # request: { 'task_inv_key': string, } """ roles = [(m.key,...
With the workflow instance and the task invitation is assigned a role.
def send_workflow(self): """ With the workflow instance and the task invitation is assigned a role. """ task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance select_role = self.input['form']['select_role'] if wfi.cur...
The time intervals at which the workflow is to be extended are determined... code - block:: python
def select_postponed_date(self): """ The time intervals at which the workflow is to be extended are determined. .. code-block:: python # request: { 'task_inv_key': string, } """ _form = forms.Jso...
Invitations with the same workflow status are deleted. Workflow instance and invitation roles change.
def save_date(self): """ Invitations with the same workflow status are deleted. Workflow instance and invitation roles change. """ task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance if wfi.current_actor.e...
If there is a role assigned to the workflow and it is the same as the user it can drop the workflow. If it does not exist it can not do anything.
def suspend(self): """ If there is a role assigned to the workflow and it is the same as the user, it can drop the workflow. If it does not exist, it can not do anything. .. code-block:: python # request: { 'task_inv_ke...
Finds out if the piece is on the home row.
def on_home_row(self, location=None): """ Finds out if the piece is on the home row. :return: bool for whether piece is on home row or not """ location = location or self.location return (self.color == color.white and location.rank == 1) or \ (self.color =...
Finds if move from current get_location would result in promotion
def would_move_be_promotion(self, location=None): """ Finds if move from current get_location would result in promotion :type: location: Location :rtype: bool """ location = location or self.location return (location.rank == 1 and self.color == color.black) or \ ...
Finds square directly in front of Pawn
def square_in_front(self, location=None): """ Finds square directly in front of Pawn :type: location: Location :rtype: Location """ location = location or self.location return location.shift_up() if self.color == color.white else location.shift_down()
Finds possible moves one step and two steps in front of Pawn.
def forward_moves(self, position): """ Finds possible moves one step and two steps in front of Pawn. :type: position: Board :rtype: list """ if position.is_square_empty(self.square_in_front(self.location)): """ If square in front is empty ...
Adds specified diagonal as a capture move if it is one
def _one_diagonal_capture_square(self, capture_square, position): """ Adds specified diagonal as a capture move if it is one """ if self.contains_opposite_color_piece(capture_square, position): if self.would_move_be_promotion(): for move in self.create_promot...
Finds out all possible capture moves
def capture_moves(self, position): """ Finds out all possible capture moves :rtype: list """ try: right_diagonal = self.square_in_front(self.location.shift_right()) for move in self._one_diagonal_capture_square(right_diagonal, position): y...
Finds out if pawn is on enemy center rank.
def on_en_passant_valid_location(self): """ Finds out if pawn is on enemy center rank. :rtype: bool """ return (self.color == color.white and self.location.rank == 4) or \ (self.color == color.black and self.location.rank == 3)
Finds if their opponent s pawn is next to this pawn
def _is_en_passant_valid(self, opponent_pawn_location, position): """ Finds if their opponent's pawn is next to this pawn :rtype: bool """ try: pawn = position.piece_at_square(opponent_pawn_location) return pawn is not None and \ isinstanc...
Yields en_passant moves in given direction if it is legal.
def add_one_en_passant_move(self, direction, position): """ Yields en_passant moves in given direction if it is legal. :type: direction: function :type: position: Board :rtype: gen """ try: if self._is_en_passant_valid(direction(self.location), positi...
Finds possible en passant moves.
def en_passant_moves(self, position): """ Finds possible en passant moves. :rtype: list """ # if pawn is not on a valid en passant get_location then return None if self.on_en_passant_valid_location(): for move in itertools.chain(self.add_one_en_passant_move(...
Finds out the locations of possible moves given board. Board position.: pre get_location is on board and piece at specified get_location on position
def possible_moves(self, position): """ Finds out the locations of possible moves given board.Board position. :pre get_location is on board and piece at specified get_location on position :type: position: Board :rtype: list """ for move in itertools.chain(self.fo...
Main method
def main(): """ Main method """ print("Creating a new game...") new_game = Game(Human(color.white), Human(color.black)) result = new_game.play() print("Result is ", result)
Build a dict containing a valid response to an Alexa request.
def respond(text=None, ssml=None, attributes=None, reprompt_text=None, reprompt_ssml=None, end_session=True): """ Build a dict containing a valid response to an Alexa request. If speech output is desired, either of `text` or `ssml` should be specified. :param text: Plain text speech output...
Convenience method to save a little bit of typing for the common case of reprompting the user. Simply calls: py: func: alexandra. util. respond with the given arguments and holds the session open.
def reprompt(text=None, ssml=None, attributes=None): """Convenience method to save a little bit of typing for the common case of reprompting the user. Simply calls :py:func:`alexandra.util.respond` with the given arguments and holds the session open. One of either the `text` or `ssml` should be provide...
Ensure the request s timestamp doesn t fall outside of the app s specified tolerance.
def validate_request_timestamp(req_body, max_diff=150): """Ensure the request's timestamp doesn't fall outside of the app's specified tolerance. Returns True if this request is valid, False otherwise. :param req_body: JSON object parsed out of the raw POST data of a request. :param max_diff: Maxim...
Ensure that the certificate and signature specified in the request headers are truely from Amazon and correctly verify.
def validate_request_certificate(headers, data): """Ensure that the certificate and signature specified in the request headers are truely from Amazon and correctly verify. Returns True if certificate verification succeeds, False otherwise. :param headers: Dictionary (or sufficiently dictionary-like) m...
Download and validate a specified Amazon PEM file.
def _get_certificate(cert_url): """Download and validate a specified Amazon PEM file.""" global _cache if cert_url in _cache: cert = _cache[cert_url] if cert.has_expired(): _cache = {} else: return cert url = urlparse(cert_url) host = url.netloc.lowe...
Check if version is already applied in the database.
def is_processed(self, db_versions): """Check if version is already applied in the database. :param db_versions: """ return self.number in (v.number for v in db_versions if v.date_done)
Check if version is a no operation version.
def is_noop(self): """Check if version is a no operation version. """ has_operations = [mode.pre_operations or mode.post_operations for mode in self._version_modes.values()] has_upgrade_addons = [mode.upgrade_addons or mode.remove_addons ...
Return a VersionMode for a mode name.
def _get_version_mode(self, mode=None): """Return a VersionMode for a mode name. When the mode is None, we are working with the 'base' mode. """ version_mode = self._version_modes.get(mode) if not version_mode: version_mode = self._version_modes[mode] = VersionMode(n...
Add an operation to the version
def add_operation(self, operation_type, operation, mode=None): """Add an operation to the version :param mode: Name of the mode in which the operation is executed :type mode: str :param operation_type: one of 'pre', 'post' :type operation_type: str :param operation: the ...
Add a backup operation to the version.
def add_backup_operation(self, backup, mode=None): """Add a backup operation to the version. :param backup: To either add or skip the backup :type backup: Boolean :param mode: Name of the mode in which the operation is executed For now, backups are mode-independent ...
Return pre - operations only for the mode asked
def pre_operations(self, mode=None): """ Return pre-operations only for the mode asked """ version_mode = self._get_version_mode(mode=mode) return version_mode.pre_operations
Return post - operations only for the mode asked
def post_operations(self, mode=None): """ Return post-operations only for the mode asked """ version_mode = self._get_version_mode(mode=mode) return version_mode.post_operations
Return merged set of main addons and mode s addons
def upgrade_addons_operation(self, addons_state, mode=None): """ Return merged set of main addons and mode's addons """ installed = set(a.name for a in addons_state if a.state in ('installed', 'to upgrade')) base_mode = self._get_version_mode() addons_list = base...
get copy of object
def copy(self): """ get copy of object :return: ReactionContainer """ return type(self)(reagents=[x.copy() for x in self.__reagents], meta=self.__meta.copy(), products=[x.copy() for x in self.__products], reactants=[x.copy() fo...