text
stringlengths
81
112k
Finds square directly in front of Pawn :type: location: Location :rtype: Location def square_in_front(self, location=None): """ Finds square directly in front of Pawn :type: location: Location :rtype: Location """ location = location or self.location ...
Finds possible moves one step and two steps in front of Pawn. :type: position: Board :rtype: list def forward_moves(self, position): """ Finds possible moves one step and two steps in front of Pawn. :type: position: Board :rtype: list """ ...
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_pro...
Finds out all possible capture moves :rtype: list 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...
Finds out if pawn is on enemy center rank. :rtype: bool 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...
Finds if their opponent's pawn is next to this pawn :rtype: bool 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_lo...
Yields en_passant moves in given direction if it is legal. :type: direction: function :type: position: Board :rtype: gen def add_one_en_passant_move(self, direction, position): """ Yields en_passant moves in given direction if it is legal. :type: direction: function ...
Finds possible en passant moves. :rtype: list 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(): f...
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 def possible_moves(self, position): """ Finds out the locations of possible moves given board....
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. 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. :param ssml: Speech output in SSML form. :param attributes: Dictionary of attributes to store...
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 provided if any speech output is desired. :param text: Pla...
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: Maximum allowable difference in seconds between request time...
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) map of request headers. :param data: Raw POST...
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 ...
Check if version is already applied in the database. :param db_versions: 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 o...
Return a VersionMode for a mode name. When the mode is None, we are working with the 'base' mode. 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...
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 operation to add :type operation: :class:`marabunta.model.Operatio...
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 :type mode: String def add_backup_operation(self, bac...
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 =...
get copy of object :return: ReactionContainer 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.__pro...
remove explicit hydrogens if possible :return: number of removed hydrogens def implicify_hydrogens(self): """ remove explicit hydrogens if possible :return: number of removed hydrogens """ total = 0 for ml in (self.__reagents, self.__reactants, self.__products)...
set or reset hyb and neighbors marks to atoms. def reset_query_marks(self): """ set or reset hyb and neighbors marks to atoms. """ for ml in (self.__reagents, self.__reactants, self.__products): for m in ml: if hasattr(m, 'reset_query_marks'): ...
get CGR of reaction reagents will be presented as unchanged molecules :return: CGRContainer def compose(self): """ get CGR of reaction reagents will be presented as unchanged molecules :return: CGRContainer """ rr = self.__reagents + self.__reactants ...
recalculate 2d coordinates. currently rings can be calculated badly. :param force: ignore existing coordinates of atoms def calculate2d(self, force=True): """ recalculate 2d coordinates. currently rings can be calculated badly. :param force: ignore existing coordinates of atoms ...
fix coordinates of molecules in reaction def fix_positions(self): """ fix coordinates of molecules in reaction """ shift_x = 0 for m in self.__reactants: max_x = self.__fix_positions(m, shift_x, 0) shift_x = max_x + 1 arrow_min = shift_x ...
:param unit_key: Parent unit key :return: role keys of subunits def get_role_keys(cls, unit_key): """ :param unit_key: Parent unit key :return: role keys of subunits """ stack = Role.objects.filter(unit_id=unit_key).values_list('key', flatten=True) for unit_key i...
Permissions of the user. Returns: List of Permission objects. def get_permissions(self): """ Permissions of the user. Returns: List of Permission objects. """ user_role = self.last_login_role() if self.last_login_role_key else self.role_set[0].r...
Soyut role ait Permission nesnelerini bulur ve code değerlerini döner. Returns: list: Permission code değerleri def get_permissions(self): """ Soyut role ait Permission nesnelerini bulur ve code değerlerini döner. Returns: list: Permission code ...
Soyut Role Permission nesnesi tanımlamayı sağlar. Args: perm (object): def add_permission(self, perm): """ Soyut Role Permission nesnesi tanımlamayı sağlar. Args: perm (object): """ self.Permissions(permission=perm) PermissionCache.flus...
Adds a permission with given name. Args: code (str): Code name of the permission. save (bool): If False, does nothing. def add_permission_by_name(self, code, save=False): """ Adds a permission with given name. Args: code (str): Code name of the perm...
sends a message to user of this role's private mq exchange def send_notification(self, title, message, typ=1, url=None, sender=None): """ sends a message to user of this role's private mq exchange """ self.user.send_notification(title=title, message=message, typ=typ, url=url, ...
Finds if move from current location would be a promotion def would_move_be_promotion(self): """ Finds if move from current location would be a promotion """ return (self._end_loc.rank == 0 and not self.color) or \ (self._end_loc.rank == 7 and self.color)
Connect receiver to sender for signal. Arguments: receiver A function or an instance method which is to receive signals. Receivers must be hashable objects. If weak is True, then receiver must be weak referenceable. Receivers must b...
Disconnect receiver from sender for signal. If weak references are used, disconnect need not be called. The receiver will be remove from dispatch automatically. Arguments: receiver The registered receiver to disconnect. May be none if dispatch_uid i...
Perform a migration according to config. :param config: The configuration to be applied :type config: Config def migrate(config): """Perform a migration according to config. :param config: The configuration to be applied :type config: Config """ webapp = WebApp(config.web_host, config.web...
Parse the command line and run :func:`migrate`. def main(): """Parse the command line and run :func:`migrate`.""" parser = get_args_parser() args = parser.parse_args() config = Config.from_parse_args(args) migrate(config)
Generates permissions for all CrudView based class methods. Returns: List of Permission objects. def get_permissions(cls): """ Generates permissions for all CrudView based class methods. Returns: List of Permission objects. """ perms = [] ...
we need to create basic permissions for only CRUD enabled models def _get_object_menu_models(): """ we need to create basic permissions for only CRUD enabled models """ from pyoko.conf import settings enabled_models = [] for entry in settings.OBJECT_MENU.values(): for mdl in ent...
create a custom permission def add(cls, code_name, name='', description=''): """ create a custom permission """ if code_name not in cls.registry: cls.registry[code_name] = (code_name, name or code_name, description) return code_name
get self to other mapping def get_mapping(self, other): """ get self to other mapping """ m = next(self._matcher(other).isomorphisms_iter(), None) if m: return {v: k for k, v in m.items()}
get self to other substructure mapping :param limit: number of matches. if 0 return iterator for all possible; if 1 return dict or None; if > 1 return list of dicts def get_substructure_mapping(self, other, limit=1): """ get self to other substructure mapping :param limit:...
Creates a location from a two character string consisting of the file then rank written in algebraic notation. Examples: e4, b5, a7 :type: alg_str: str :rtype: Location def from_string(cls, alg_str): """ Creates a location from a two character string consistin...
Shifts in direction provided by ``Direction`` enum. :type: direction: Direction :rtype: Location def shift(self, direction): """ Shifts in direction provided by ``Direction`` enum. :type: direction: Direction :rtype: Location """ try: if dir...
Finds Location shifted up by 1 :rtype: Location def shift_up(self, times=1): """ Finds Location shifted up by 1 :rtype: Location """ try: return Location(self._rank + times, self._file) except IndexError as e: raise IndexError(e)
Finds Location shifted down by 1 :rtype: Location def shift_down(self, times=1): """ Finds Location shifted down by 1 :rtype: Location """ try: return Location(self._rank - times, self._file) except IndexError as e: raise IndexError(e)
Finds Location shifted right by 1 :rtype: Location def shift_right(self, times=1): """ Finds Location shifted right by 1 :rtype: Location """ try: return Location(self._rank, self._file + times) except IndexError as e: raise IndexError(e...
Finds Location shifted left by 1 :rtype: Location def shift_left(self, times=1): """ Finds Location shifted left by 1 :rtype: Location """ try: return Location(self._rank, self._file - times) except IndexError as e: raise IndexError(e)
Finds Location shifted up right by 1 :rtype: Location def shift_up_right(self, times=1): """ Finds Location shifted up right by 1 :rtype: Location """ try: return Location(self._rank + times, self._file + times) except IndexError as e: r...
Finds Location shifted up left by 1 :rtype: Location def shift_up_left(self, times=1): """ Finds Location shifted up left by 1 :rtype: Location """ try: return Location(self._rank + times, self._file - times) except IndexError as e: rais...
Finds Location shifted down right by 1 :rtype: Location def shift_down_right(self, times=1): """ Finds Location shifted down right by 1 :rtype: Location """ try: return Location(self._rank - times, self._file + times) except IndexError as e: ...
Finds Location shifted down left by 1 :rtype: Location def shift_down_left(self, times=1): """ Finds Location shifted down left by 1 :rtype: Location """ try: return Location(self._rank - times, self._file - times) except IndexError as e: ...
standardize functional groups :return: number of found groups def standardize(self): """ standardize functional groups :return: number of found groups """ self.reset_query_marks() seen = set() total = 0 for n, atom in self.atoms(): i...
Get all files staged for the current commit. def get_staged_files(): """Get all files staged for the current commit. """ proc = subprocess.Popen(('git', 'status', '--porcelain'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, _ = proc.commun...
Run Tornado server def runserver(host=None, port=None): """ Run Tornado server """ host = host or os.getenv('HTTP_HOST', '0.0.0.0') port = port or os.getenv('HTTP_PORT', '9001') zioloop = ioloop.IOLoop.instance() # setup pika client: pc = QueueManager(zioloop) app.pc = pc pc.co...
Called on new websocket connection. def open(self): """ Called on new websocket connection. """ sess_id = self._get_sess_id() if sess_id: self.application.pc.websockets[self._get_sess_id()] = self self.write_message(json.dumps({"cmd": "status", "status": ...
called on new websocket message, def on_message(self, message): """ called on new websocket message, """ log.debug("WS MSG for %s: %s" % (self._get_sess_id(), message)) self.application.pc.redirect_incoming_message(self._get_sess_id(), message, self.request)
Do response processing def _handle_headers(self): """ Do response processing """ origin = self.request.headers.get('Origin') if not settings.DEBUG: if origin in settings.ALLOWED_ORIGINS or not origin: self.set_header('Access-Control-Allow-Origin', ori...
login handler def post(self, view_name): """ login handler """ sess_id = None input_data = {} # try: self._handle_headers() # handle input input_data = json_decode(self.request.body) if self.request.body else {} input_data['path'] = view_...
>>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...> def load_formatter_fn(formatter): ''' >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...> ''' obj = util.load_object(formatter) if no...
Removes duplicate data from 'data' inside log dict and brings it out. >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> log = {'id' : 46846876, 'type' : 'log', ... 'data' : {'a' : 1, 'b' : 2, 'type' : 'metric'}} >>> lc._r...
>>> lc = LogCollector('file=/path/to/file.log:formatter=logagg.formatters.basescript', 30) >>> incomplete_log = {'data' : {'x' : 1, 'y' : 2}, ... 'raw' : 'Not all keys present'} >>> lc.validate_log_format(incomplete_log) 'failed' >>> redundant_log = {'one_in...
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> from pprint import pprint >>> formatter = 'logagg.formatters.mongodb' >>> fpath = '/var/log/mongodb/mongodb.log' >>> line = 'some log line here' >>> default_log = lc.assign_defaul...
For a list of given fpatterns, this starts a thread collecting log lines from file >>> os.path.isfile = lambda path: path == '/path/to/log_file.log' >>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30) >>> print(lc.fpaths) file=/path/to...
Prepare links of form by mimicing pyoko's get_links method's result Args: **kw: Returns: list of link dicts def get_links(self, **kw): """ Prepare links of form by mimicing pyoko's get_links method's result Args: **kw: Returns: list of link di...
Fills form with data Args: data (dict): Data to assign form fields. Returns: Self. Form object. def set_data(self, data): """ Fills form with data Args: data (dict): Data to assign form fields. Returns: Self. Form objec...
Converts the form/model into JSON ready dicts/lists compatible with `Ulakbus-UI API`_. Example: .. code-block:: json { "forms": { "constraints": {}, "model": { "code": null, ...
Caches some form details to lates process and validate incoming (response) form data Args: form: form dict def _cache_form_details(self, form): """ Caches some form details to lates process and validate incoming (response) form data Args: form: form dict ...
>>> mdbf = MongoDBForwarder('no_host', '27017', 'deadpool', ... 'chimichanga', 'logs', 'collection') >>> log = [{u'data': {u'_': {u'file': u'log.py', ... u'fn': u'start', ... u'ln': 8, ... u'name...
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool', ... 'chimichanga', 'logs', 'collection') >>> log = {u'data': {u'_': {u'file': u'log.py', ... u'fn': u'start', ... u'ln': 8, ... ...
>>> from logagg.forwarders import InfluxDBForwarder >>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool', ... 'chimichanga', 'logs', 'collection') >>> valid_log = [{u'data': {u'_force_this_as_field': 'CXNS CNS nbkbsd', ... u'a': 1, ....
Get input and process accordingly. Data can be: - a uncompressed, bgzip, bzip2 or gzip compressed fastq file - a uncompressed, bgzip, bzip2 or gzip compressed fasta file - a rich fastq containing additional key=value information in the description, as produced by MinKNOW and albacore with the sam...
Combine dataframes. Combination is either done simple by just concatenating the DataFrames or performs tracking by adding the name of the dataset as a column. def combine_dfs(dfs, names, method): """Combine dataframes. Combination is either done simple by just concatenating the DataFrames or perf...
Calculate the star_time per read. Time data is either a "time" (in seconds, derived from summary files) or a "timestamp" (in UTC, derived from fastq_rich format) and has to be converted appropriately in a datetime format time_arr For both the time_zero is the minimal value of the time_arr, whi...
Construct YamlParser from a file pointer. def parser_from_buffer(cls, fp): """Construct YamlParser from a file pointer.""" yaml = YAML(typ="safe") return cls(yaml.load(fp))
Check that we don't have unknown keys in a dictionary. It does not raise an error if we have less keys than expected. def check_dict_expected_keys(self, expected_keys, current, dict_name): """ Check that we don't have unknown keys in a dictionary. It does not raise an error if we have less ke...
Check input and return a :class:`Migration` instance. def parse(self): """Check input and return a :class:`Migration` instance.""" if not self.parsed.get('migration'): raise ParseError(u"'migration' key is missing", YAML_EXAMPLE) self.check_dict_expected_keys( {'options'...
Build a :class:`Migration` instance. def _parse_migrations(self): """Build a :class:`Migration` instance.""" migration = self.parsed['migration'] options = self._parse_options(migration) versions = self._parse_versions(migration, options) return Migration(versions, options)
Build :class:`MigrationOption` and :class:`MigrationBackupOption` instances. def _parse_options(self, migration): """Build :class:`MigrationOption` and :class:`MigrationBackupOption` instances.""" options = migration.get('options', {}) install_command = options.get('install_comm...
Sets user notification message. Args: title: Msg. title msg: Msg. text typ: Msg. type url: Additional URL (if exists) Returns: Message ID. def set_message(self, title, msg, typ, url=None): """ Sets user notification message....
A property that indicates if current user is logged in or not. Returns: Boolean. def is_auth(self): """ A property that indicates if current user is logged in or not. Returns: Boolean. """ if self.user_id is None: self.user_id = self...
Checks if current user (or role) has the given permission. Args: perm: Permmission code or object. Depends on the :attr:`~zengine.auth.auth_backend.AuthBackend` implementation. Returns: Boolean. def has_permission(self, perm): """ Checks if current...
Create a message box :param str msg: :param str title: :param str typ: 'info', 'error', 'warning' def msg_box(self, msg, title=None, typ='info'): """ Create a message box :param str msg: :param str title: :param str typ: 'info', 'error', 'warning' ...
Tell current user that s/he finished it's job for now. We'll notify if workflow arrives again to his/her WF Lane. def sendoff_current_user(self): """ Tell current user that s/he finished it's job for now. We'll notify if workflow arrives again to his/her WF Lane. """ msg...
Invites the next lane's (possible) owner(s) to participate def invite_other_parties(self, possible_owners): """ Invites the next lane's (possible) owner(s) to participate """ signals.lane_user_change.send(sender=self.user, current=self, ...
Assigns current task step to self.task then updates the task's data with self.task_data Args: task: Task object. def _update_task(self, task): """ Assigns current task step to self.task then updates the task's data with self.task_data Args: task...
This is method automatically called on each request and updates "object_id", "cmd" and "flow" client variables from current.input. "flow" and "object_id" variables will always exists in the task_data so app developers can safely check for their values in workflows. Thei...
Returns valid and legal move given position :type: position: Board :rtype: Move def generate_move(self, position): """ Returns valid and legal move given position :type: position: Board :rtype: Move """ while True: print(position) ...
Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool def in_check_as_result(self, pos, move): """ Finds if playing my move would make both kings meet. :type: pos: Board :type: move: Move :rtype: bool ...
Finds if 2 kings are touching given the position of one of the kings. :type: location: Location :type: position: Board :rtype: bool def loc_adjacent_to_opponent_king(self, location, position): """ Finds if 2 kings are touching given the position of one of the kings. :t...
Adds all 8 cardinal directions as moves for the King if legal. :type: function: function :type: position: Board :rtype: gen def add(self, func, position): """ Adds all 8 cardinal directions as moves for the King if legal. :type: function: function :type: positi...
Decides if given rook exists, is of this color, and has not moved so it is eligible to castle. :type: rook: Rook :rtype: bool def _rook_legal_for_castle(self, rook): """ Decides if given rook exists, is of this color, and has not moved so it is eligible to castle. ...
Checks if set of squares in between ``King`` and ``Rook`` are empty and safe for the king to castle. :type: position: Position :type: direction: function :type: times: int :rtype: bool def _empty_not_in_check(self, position, direction): """ Checks if set of squa...
Adds kingside and queenside castling moves if legal :type: position: Board def add_castle(self, position): """ Adds kingside and queenside castling moves if legal :type: position: Board """ if self.has_moved or self.in_check(position): return if se...
Generates list of possible moves :type: position: Board :rtype: list def possible_moves(self, position): """ Generates list of possible moves :type: position: Board :rtype: list """ # Chain used to combine multiple generators for move in itertoo...
Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool def in_check(self, position, location=None): """ Finds if the king is in check or if both kings are touching. :type: position: Board :return: bool """ loca...
Sets the keep-alive setting for the peer socket. :param sock: Socket to be configured. :param idle: Interval in seconds after which for an idle connection a keep-alive probes is start being sent. :param interval: Interval in seconds between probes. :param fails: Maximum number of failed probes. ...