code
stringlengths
1
18.2k
user_id=initiator_key, name=receiver_name) Subscriber.objects.get_or_create(channel=channel, user_id=receiver_key, name=UserModel.objects.get(initiator_key).full_name) return channel, receiver_name
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', durable=True)
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)
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(), 'actions': self.get_actions(), 'unread': self.unread_count()}
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 to the channel we currently subscribe """ channel ...
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_bind(source=self.channel.code_name, destination=self.user.prv_excha...
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 """ return { 'content': self.body, 'type': self.typ, 'updated_at': self.updated...
'cmd': 'message', 'avatar_url': self.sender.avatar, 'key': self.key, }
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()))
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))
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.GetoptError as err: # print help information and exit: ...
opt, val in opts: if opt in ('-h', '--help'): echo2(USAGE); sys.exit() elif opt in ('-s', '--server'): serverEndpoint = val elif opt in ('-p', '--port'): serverEndpoint = 'http://localhost:%s' % val elif opt in ('-m', '--mock'): Mock = 1 elif opt in ('-v', '--verbose'): Verbose = 1 else: die(USAGE) cmd = argv[0] crawlI...
> 4: args = eval(argv[4]) nt = Nutch(crawlId, confId, serverEndpoint, urlDir) nt.Jobs().create(cmd, **args)
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' :param data: Data to attach to thi...
just get the text :param sendJson: Whether to treat attached data as JSON or not """ default_data = {} if sendJson else "" data = data if data else default_data headers = headers if headers else JsonAcceptHeader.copy() if not sendJson: headers.update(TextSendHeader) if verb not in RequestVerbs: die('Server call verb mu...
Request data:" % verb.upper(), data) echo2("%s Request headers:" % verb.upper(), headers) verbFn = RequestVerbs[verb] if sendJson: resp = verbFn(self.serverEndpoint + servicePath, json=data, headers=headers) else: resp = verbFn(self.serverEndpoint + servicePath, data=data, headers=headers) if Verbose: echo2("Response h...
if forceText or 'content-type' not in resp.headers or resp.headers['content-type'] == 'text/plain': if Verbose: echo2("Response text:", resp.text) return resp.text content_type = resp.headers['content-type'] if content_type == 'application/json' and not forceText: if Verbose: echo2("Response JSON:", resp.json()) return...
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=TextAcceptHeader) new_config = Config(cid,...
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._job_owned(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 LegalJobs: warn('Nutch command must be one of: %s' % ', '.join(LegalJobs...
= command parameters['crawlId'] = self.crawlId parameters['confId'] = self.confId parameters['args'].update(args) job_info = self.server.call('post', "/job/create", parameters, JsonAcceptHeader) job = Job(job_info['id'], self.server) return job
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 Job object """ if seed: if urlDir and url...
seed.seedPath elif urlDir: pass else: raise NutchException("Must specify seed or urlDir") args['url_dir'] = urlDir return self.create('INJECT', **args)
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, "url": url} if not isinstance(seedList,tuple): seedList = ...
"seedUrls": [seedUrl(uid, url) for uid, url in enumerate(seedList)] } # As per resolution of https://issues.apache.org/jira/browse/NUTCH-2123 seedPath = self.server.call('post', "/seed/create", seedListData, TextAcceptHeader) new_seed = Seed(sid, seedPath, self.server) return new_seed
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 created Seed object """ urls = [] with open(filenam...
urls.append(url) return self.create(sid, tuple(urls))
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 """ jobInfo = job.info() assert jobInfo['state'...
'GENERATE' elif jobInfo['type'] == 'GENERATE': nextCommand = 'FETCH' elif jobInfo['type'] == 'FETCH': nextCommand = 'PARSE' elif jobInfo['type'] == 'PARSE': nextCommand = 'UPDATEDB' elif jobInfo['type'] == 'UPDATEDB': nextCommand = 'INVERTLINKS' elif jobInfo['type'] == 'INVERTLINKS': nextCommand = 'DEDUP' elif jobInfo[...
if nextRound and self.currentRound < self.totalRounds: nextCommand = 'GENERATE' self.currentRound += 1 else: return None return self.jobClient.create(nextCommand)
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 next round if the current job/round i...
are running. """ currentJob = self.currentJob if currentJob is None: return currentJob jobInfo = currentJob.info() if jobInfo['state'] == 'RUNNING': return currentJob elif jobInfo['state'] == 'FINISHED': nextJob = self._nextJob(currentJob, nextRound) self.currentJob = nextJob return nextJob else: error = NutchCrawlExce...
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 """ finishedJobs = [] if self.currentJob is None: self.current...
self.progress(nextRound=False) # updates self.currentJob if oldJob and oldJob != activeJob: finishedJobs.append(oldJob) sleep(self.sleepTime) self.currentRound += 1 return finishedJobs
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) """ finishedRounds = [self.nextRound()] while ...
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 JobClient """ crawlId = crawlId if crawlId else defaultCra...
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 :param jobClient: the JobClient to be used, i...
the crawl :return: a CrawlClient to monitor and control the crawl """ if seedClient is None: seedClient = self.Seeds() if jobClient is None: jobClient = self.Jobs() if type(seed) != Seed: seed = seedClient.create(jobClient.crawlId + '_seeds', seed) return CrawlClient(self.server, seed, jobClient, rounds, index)
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:300A||| user@mail...
'bytes_read': 2406.0, 'client_port': '48660', 'client_server': '1.1.1.1', 'feconn': 4, 'front_end': 'pre-staging~', 'haproxy_server': 'node', 'method': 'GET', 'resp_time': 271.0, 'retries': 0, 'srv_conn': 0, 'srv_queue': 0, 'status': '200', 'timestamp': '2019-04-24T00:00:02.358000'}, 'event': 'haproxy_event', 'timestam...
float(_line[9].split('/')[1].strip()) log['Tc'] = float(_line[9].split('/')[2].strip()) log['Tr'] = float(_line[9].split('/')[3].strip()) log['resp_time'] = float(_line[9].split('/')[-1].strip()) log['status'] = _line[10].strip() log['bytes_read'] = float(_line[11].strip()) log['_headers'] = re.findall(r'{(.*)}', line)...
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","http_referer": "-","http_user_agent": "python-requests/2.18.4", \ "http_x_f...
'event': 'nginx_event', 'timestamp': '2018-01-05T09:31:39.201000', 'type': 'metric'} >>> input_line2 = '{ \ "remote_addr": "192.158.0.51","remote_user": "-","timestamp": "1515143686.415", \ "request": "POST /mpub?topic=heartbeat HTTP/1.1","status": "404","request_time": "0.000", \ "body_bytes_sent": "152","http_referer...
'event': 'nginx_event', 'timestamp': '2018-01-05T09:14:46.415000', 'type': 'metric'} ''' #TODO Handle nginx error logs log = json.loads(line) timestamp_iso = datetime.datetime.utcfromtimestamp(float(log['timestamp'])).isoformat() log.update({'timestamp':timestamp_iso}) if '-' in log.get('upstream_response_time'): log['...
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': '[signalProcessingThread]', 'message': 'shuttin...
'[initandlisten]', 'message': 'No primary detected for set confsvr_repl1', 'severity': 'W', 'timestamp': '2017-08-17T07:56:33.515+0200'}, 'timestamp': '2017-08-17T07:56:33.515+0200', 'type': 'log'} ''' keys = ['timestamp', 'severity', 'component', 'context', 'message'] values = re.split(r'\s+', line, maxsplit=4) mongod...
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 = django(input_...
06:32:15] INFO [app.function:6022] {"UUID": "c47f3530-9f5f-11e7-a559-917d011459f7", "timestamp":1506061932546, "misc": {"status": 200, "ready_state": 4, "end_time_ms": 1506061932546, "url": "/api/function?", "start_time_ms": 1506061932113, "response_length": 31, "status_message": "OK", "request_time_ms": 433}, "user": ...
u'url': u'/api/function?'}, u'timestamp': 1506061932546L, u'user': u'root'}, 'timestamp': '2017-09-22T06:32:15'}, 'level': 'INFO', 'timestamp': '2017-09-22T06:32:15'} Case2: [18/Sep/2017 05:40:36] ERROR [app.apps:78] failed to get the record, collection = Collection(Database(MongoClient(host=['localhost:27017'], docume...
singleBatch: true } ''' #TODO we need to handle case2 logs data = {} log = re.findall(r'^(\[\d+/\w+/\d+ \d+:\d+:\d+\].*)', line) if len(log) == 1: data['timestamp'] = datetime.datetime.strptime(re.findall(r'(\d+/\w+/\d+ \d+:\d+:\d+)',\ log[0])[0],"%d/%b/%Y %H:%M:%S").isoformat() data['loglevel'] = re.findall('[A-Z]+', ...
= ''.join(message[2:]) data['message'] = message return dict( timestamp=data['timestamp'], level=data['loglevel'], data=data, ) else: return dict( timestamp=datetime.datetime.isoformat(datetime.datetime.utcnow()), data={raw:line} )
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/basescript/bas...
interrupt', 'id': u'20180207T063700_4d03fe800bd111e89ecb96000007bc65', 'level': u'warning', 'timestamp': u'2018-02-07T06:37:00.297610Z', 'type': u'log'} ''' log = json.loads(line) return dict( timestamp=log['timestamp'], data=log, id=log['id'], type=log['type'], level=log['level'], event=log['event'] )
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': {'garbage_collector': 'gc', 'gc...
java.nio.file.FileSystemException: /home/user/elasticsearch/data/nodes/0/indices/jsVSO6f3Rl-wwBpQyNRCbQ/3/index/_0.fdx: Too many open files at sun.nio.fs.UnixException.translateToIOException(UnixException.java:91) ~[?:?] ''' # TODO we need to handle case2 logs elasticsearch_log = line actuallog = re.findall(r'(\[\d+\-+...
continue if len(re.findall(r'.*s$', i)) > 0 and 's' in re.findall(r'.*s$', i)[0]: num = re.split('s', i)[0] values[index] = float(num) * 1000 continue data = dict(zip(keys,values)) if 'level' in data and data['level'][-1] == ' ': data['level'] = data['level'][:-1] if 'gc_count' in data: data['gc_count'] = float(data['g...
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 capacity [1000]'...
LOG_BEGIN_PATTERN: if re.match(p, line) != None: return False return True
def get(self, attr, default=None): """Get an attribute defined by this session""" attrs = self.body.get('attributes') or {} return attrs.get(attr, default)
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_from_db(cat)
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['value'], i['name']) for i in keylist]) return self.ITEM_CACHE[lang][catalog...
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 by Amazon. This can be usefulfor manually testing...
app, use_reloader=debug, use_debugger=debug)
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 object loaded from incoming request's POST ...
req_type == 'LaunchRequest': return self.launch_fn(session) elif req_type == 'IntentRequest': intent = body['request']['intent']['name'] intent_fn = self.intent_map.get(intent, self.unknown_intent_fn) slots = { slot['name']: slot.get('value') for _, slot in body['request']['intent'].get('slots', {}).items() } arity = i...
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. If no session was provided in the request,...
# nested decorator so we can have params. def _decorator(func): arity = func.__code__.co_argcount if arity not in [0, 2]: raise ValueError("expected 0 or 2 argument function") self.intent_map[intent_name] = func return func return _decorator
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)
def encrypt_password(self): """ encrypt password if not already encrypted """ if self.password and not self.password.startswith('$pbkdf2'): self.set_password(self.password)
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( channel_key=self.prv_exchange, body=message, title=title, typ=typ, url=url, sender=sender, receiver=self )
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_queue: queue name, """ mq_channel = self._connect_mq() if cmd: data['cmd'] = cmd...
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] if current_pos != new_pos: if current_pos == self._shifts[-1]: # reached the end of ...
to the beginning of the file self._file.seek(new_pos) else: if not self.__already_seeked: if self._shifts[0] < current_pos: # in the middle of the file self._data.send(True) self.__already_seeked = True self._file.seek(new_pos) else: raise IndexError('invalid offset') else: raise self._implement_error
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 elif t in self._shifts: return bisect_left(self._shifts, t) else: return bisect_left(self._shifts, t) - 1 ...
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. If there is a role assigned to it, it does not do any operation a...
displayed on the screen. .. code-block:: python # request: { 'task_inv_key': string, } """ task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_invitation.instance if not wfi.current_actor.exist: wfi.current_actor = self.current.role wfi.save() [inv.delete() for inv in TaskInvitation.object...
else.") self.current.msg_box(title=title, msg=msg)
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, m.__unicode__()) for m in RoleModel.objects.filter( abstract_role=self.current.role.abstract_role, unit=self.current.rol...
fields.Button(_(u"Send")) self.form_out(_form) else: title = _(u"Unsuccessful") msg = _(u"Assign role not found") self.current.msg_box(title=title, msg=msg)
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.current_actor == self.current.role: task_invitation.role = ...
_(u"Unsuccessful") msg = _(u"This workflow does not belong to you, you cannot assign it to someone else.") self.current.msg_box(title=title, msg=msg)
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.JsonForm(title="Postponed Workflow") _form.start_date = fields.DateTime("Start Date") _form.finish_date = fields.DateTime("Finis...
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.exist and wfi.current_actor == self.current.role: dt_start = datet...
= _(u"Unsuccessful") msg = _(u"This workflow does not belong to you.") self.current.msg_box(title=title, msg=msg)
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_key': string, } """ task_invitation = TaskInvitation.objects.get(self.task_invitation_key) wfi = task_i...
!= self.current.role: task_invitation.key = '' task_invitation.role = m task_invitation.save() wfi.current_actor = RoleModel() wfi.save() title = _(u"Successful") msg = _(u"You left the workflow.") else: title = _(u"Unsuccessful") msg = _(u"Unfortunately, this workflow does not belong to you or is already idle.") self....
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 == color.black and location.rank == 6)
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 \ (location.rank == 6 and self.color == color.white)
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()
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 add the move """ if self.would_move_be_promotion(): for move in self.create_promo...
of the pawn is empty add the move """ yield self.create_move( end_loc=self.square_in_front(self.square_in_front(self.location)), status=notation_const.MOVEMENT )
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_promotion_moves(status=notation_const.CAPTURE_AND_PROMOTE, location...
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): yield move except IndexError: pass try: left_diagonal = self.square_in_front(self....
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)
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 \ isinstance(pawn, Pawn) and \ pawn.color != self.color and \ position.piece_at_square(oppon...
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), position): yield self.create_move( end_loc=self.square_in_front(direction(s...
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(lambda x: x.shift_right(), position), self.add_one_en_passant_...
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.forward_moves(position), self.capture_moves(position), self...
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)
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 to be said by Alexa device. :...