INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
remove explicit hydrogens if possible | 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):
for m in ml:
if hasattr(m, 'implicify_hydrogens'):
... |
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'):
m.reset_query_marks()
self.flush_ca... |
get CGR of reaction | def compose(self):
"""
get CGR of reaction
reagents will be presented as unchanged molecules
:return: CGRContainer
"""
rr = self.__reagents + self.__reactants
if rr:
if not all(isinstance(x, (MoleculeContainer, CGRContainer)) for x in rr):
... |
recalculate 2d coordinates. currently rings can be calculated badly. | def calculate2d(self, force=True):
"""
recalculate 2d coordinates. currently rings can be calculated badly.
:param force: ignore existing coordinates of atoms
"""
for ml in (self.__reagents, self.__reactants, self.__products):
for m in ml:
m.calculate... |
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
if self.__reagents:
for m in s... |
: 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 in cls.objects.filter(parent_id=unit_key).values_list('key', flatten=True)... |
Permissions of the user. | 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].role
return user_role.get_permissions() |
Soyut role ait Permission nesnelerini bulur ve code değerlerini döner. | def get_permissions(self):
"""
Soyut role ait Permission nesnelerini bulur ve code değerlerini
döner.
Returns:
list: Permission code değerleri
"""
return [p.permission.code for p in self.Permissions if p.permission.code] |
Soyut Role Permission nesnesi tanımlamayı sağlar. | def add_permission(self, perm):
"""
Soyut Role Permission nesnesi tanımlamayı sağlar.
Args:
perm (object):
"""
self.Permissions(permission=perm)
PermissionCache.flush()
self.save() |
Adds a permission with given name. | def add_permission_by_name(self, code, save=False):
"""
Adds a permission with given name.
Args:
code (str): Code name of the permission.
save (bool): If False, does nothing.
"""
if not save:
return ["%s | %s" % (p.name, p.code) for p in
... |
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,
sender=sender) |
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. | def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
"""
Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
... |
Disconnect receiver from sender for signal. | def disconnect(self, receiver=None, sender=None, dispatch_uid=None):
"""
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
... |
Perform a migration according to 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_port,
custom_maintenance_file=config.web_custom_html)
webserver = WebServer(webapp)
webse... |
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. | def get_permissions(cls):
"""
Generates permissions for all CrudView based class methods.
Returns:
List of Permission objects.
"""
perms = []
for kls_name, kls in cls.registry.items():
for method_name in cls.__dict__.keys():
if met... |
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 entry:
if 'wf' not in mdl:
enabled_models.app... |
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 | def get_substructure_mapping(self, other, limit=1):
"""
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
"""
i = self._matcher(other).subgraph_isomorph... |
Creates a location from a two character string consisting of the file then rank written in algebraic notation. Examples: e4 b5 a7 | def from_string(cls, alg_str):
"""
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
"""
try:
return cls(int(alg_s... |
Shifts in direction provided by Direction enum. | def shift(self, direction):
"""
Shifts in direction provided by ``Direction`` enum.
:type: direction: Direction
:rtype: Location
"""
try:
if direction == Direction.UP:
return self.shift_up()
elif direction == Direction.DOWN:
... |
Finds Location shifted up by 1 | 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 | 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 | 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 | 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 | 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:
raise IndexError(e) |
Finds Location shifted up left by 1 | 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:
raise IndexError(e) |
Finds Location shifted down right by 1 | 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:
raise IndexError(e) |
Finds Location shifted down left by 1 | 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:
raise IndexError(e) |
standardize functional 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():
if n in seen:
continue
for k, center in centr... |
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.communicate()
staged_files = modified_re.findall... |
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.connect()
app.list... |
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": "open"}))
else:
s... |
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', origin)
else:
... |
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_name
#... |
>>> 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 not hasattr(obj, 'ispartial'):
obj.ispartial = util.ispartial
return obj |
Removes duplicate data from data inside log dict and brings it out. | def _remove_redundancy(self, log):
"""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, ... |
>>> lc = LogCollector ( file =/ path/ to/ file. log: formatter = logagg. formatters. basescript 30 ) | def validate_log_format(self, log):
'''
>>> 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... |
>>> lc = LogCollector ( file =/ path/ to/ log_file. log: formatter = logagg. formatters. basescript 30 ) >>> from pprint import pprint | def assign_default_log_values(self, fpath, line, formatter):
'''
>>> 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'
... |
For a list of given fpatterns this starts a thread collecting log lines from file | def _scan_fpatterns(self, state):
'''
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', 3... |
Prepare links of form by mimicing pyoko s get_links method s result | def get_links(self, **kw):
"""
Prepare links of form by mimicing pyoko's get_links method's result
Args:
**kw:
Returns: list of link dicts
"""
links = [a for a in dir(self) if isinstance(getattr(self, a), Model)
and not a.startswith('_mode... |
Fills form with data | def set_data(self, data):
"""
Fills form with data
Args:
data (dict): Data to assign form fields.
Returns:
Self. Form object.
"""
for name in self._fields:
setattr(self, name, data.get(name))
return self |
Converts the form/ model into JSON ready dicts/ lists compatible with Ulakbus - UI API _. | def serialize(self):
"""
Converts the form/model into JSON ready dicts/lists compatible
with `Ulakbus-UI API`_.
Example:
.. code-block:: json
{
"forms": {
"constraints": {},
"model": {
... |
Caches some form details to lates process and validate incoming ( response ) form data | def _cache_form_details(self, form):
"""
Caches some form details to lates process and validate incoming (response) form data
Args:
form: form dict
"""
cache = FormCache()
form['model']['form_key'] = cache.form_id
form['model']['form_name'] = self.__c... |
>>> 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: u __main__ }... u a: 1... u b: 2... u msg: u this is a dummy log }... u error: False... u error_tb: u... u event: u some_log... u file: u/ var/ lo... | def _parse_msg_for_mongodb(self, msgs):
'''
>>> mdbf = MongoDBForwarder('no_host', '27017', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = [{u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... ... |
>>> 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... u name: u __main__ }... u a: 1... u b: 2... u __ignore_this: some_string... u msg: u this is a dummy log }... u error: False... u error_tb: u... u event: u ... | def _tag_and_field_maker(self, event):
'''
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... ... |
>>> from logagg. forwarders import InfluxDBForwarder >>> idbf = InfluxDBForwarder ( no_host 8086 deadpool... chimichanga logs collection ) | def _parse_msg_for_influxdb(self, msgs):
'''
>>> from logagg.forwarders import InfluxDBForwarder
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> valid_log = [{u'data': {u'_force_this_as_field': ... |
Get input and process accordingly. | def get_input(source, files, threads=4, readtype="1D",
combine="simple", names=None, barcoded=False):
"""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 f... |
Combine dataframes. | def combine_dfs(dfs, names, method):
"""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."""
if method == "track":
res = list()
for df, identifier in zip(dfs, names):
... |
Calculate the star_time per read. | def calculate_start_time(df):
"""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 m... |
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. | 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 keys than expected.
"""
if not isinstance(current, dict):
raise ParseError(u"'{}' key must be a dict".... |
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', 'versions'}, self.parsed['migration'], 'migration',
... |
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_command')
backup = options.get('backup')
if backup:
self.check... |
Sets user notification message. | def set_message(self, title, msg, typ, url=None):
"""
Sets user notification message.
Args:
title: Msg. title
msg: Msg. text
typ: Msg. type
url: Additional URL (if exists)
Returns:
Message ID.
"""
return self.... |
A property that indicates if current user is logged in or not. | 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.session.get('user_id')
return bool(self.user_id) |
Checks if current user ( or role ) has the given permission. | def has_permission(self, perm):
"""
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.
"""
... |
Create a message box | 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'
"""
self.output['msgbox'] = {'type': typ, "title": title or msg[:20], "msg": msg} |
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.
"""
msgs = self.task_data.get('LANE_CHANGE_MSG', DEFAULT_LANE_CHANGE_MSG)
self.msg_box(title=msgs['title'], msg=msgs['body... |
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,
old_lane=self.old_lane,
... |
Assigns current task step to self. task then updates the task s data with self. task_data | def _update_task(self, task):
"""
Assigns current task step to self.task
then updates the task's data with self.task_data
Args:
task: Task object.
"""
self.task = task
self.task.data.update(self.task_data)
self.task_type = task.task_spec.__cla... |
This is method automatically called on each request and updates object_id cmd and flow client variables from current. input. | def set_client_cmds(self):
"""
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 ... |
Returns valid and legal move given position | def generate_move(self, position):
"""
Returns valid and legal move given position
:type: position: Board
:rtype: Move
"""
while True:
print(position)
raw = input(str(self.color) + "\'s move \n")
move = converter.short_alg(raw, self.co... |
Finds if playing my move would make both kings meet. | 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
"""
test = cp(pos)
test.update(move)
test_king = test.get_king(move.color)
return self.loc_... |
Finds if 2 kings are touching given the position of one of the kings. | def loc_adjacent_to_opponent_king(self, location, position):
"""
Finds if 2 kings are touching given the position of one of the kings.
:type: location: Location
:type: position: Board
:rtype: bool
"""
for fn in self.cardinal_directions:
try:
... |
Adds all 8 cardinal directions as moves for the King if legal. | def add(self, func, position):
"""
Adds all 8 cardinal directions as moves for the King if legal.
:type: function: function
:type: position: Board
:rtype: gen
"""
try:
if self.loc_adjacent_to_opponent_king(func(self.location), position):
... |
Decides if given rook exists is of this color and has not moved so it is eligible to castle. | 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.
:type: rook: Rook
:rtype: bool
"""
return rook is not None and \
type(rook) is Rook and \
rook.color... |
Checks if set of squares in between King and Rook are empty and safe for the king to castle. | def _empty_not_in_check(self, position, direction):
"""
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
"""
de... |
Adds kingside and queenside castling moves if legal | 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 self.color == color.white:
rook_rank = 0
else:
rook_ran... |
Generates list of possible moves | def possible_moves(self, position):
"""
Generates list of possible moves
:type: position: Board
:rtype: list
"""
# Chain used to combine multiple generators
for move in itertools.chain(*[self.add(fn, position) for fn in self.cardinal_directions]):
yie... |
Finds if the king is in check or if both kings are touching. | 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
"""
location = location or self.location
for piece in position:
if piece is not None and piece.color !=... |
Sets the keep - alive setting for the peer socket. | def set_keep_alive(sock, idle=10, interval=5, fails=5):
"""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 betwe... |
Creates a Board with the standard chess starting position. | def init_default(cls):
"""
Creates a ``Board`` with the standard chess starting position.
:rtype: Board
"""
return cls([
# First rank
[Rook(white, Location(0, 0)), Knight(white, Location(0, 1)), Bishop(white, Location(0, 2)),
Queen(white, Lo... |
Finds the advantage a particular side possesses given a value scheme. | def material_advantage(self, input_color, val_scheme):
"""
Finds the advantage a particular side possesses given a value scheme.
:type: input_color: Color
:type: val_scheme: PieceValues
:rtype: double
"""
if self.get_king(input_color).in_check(self) and self.no_... |
Calculates advantage after move is played | def advantage_as_result(self, move, val_scheme):
"""
Calculates advantage after move is played
:type: move: Move
:type: val_scheme: PieceValues
:rtype: double
"""
test_board = cp(self)
test_board.update(move)
return test_board.material_advantage(m... |
Checks if all the possible moves has already been calculated and is stored in possible_moves dictionary. If not it is calculated with _calc_all_possible_moves.: type: input_color: Color: rtype: list | def all_possible_moves(self, input_color):
"""
Checks if all the possible moves has already been calculated
and is stored in `possible_moves` dictionary. If not, it is calculated
with `_calc_all_possible_moves`.
:type: input_color: Color
:rtype: list
"""
... |
Returns list of all possible moves | def _calc_all_possible_moves(self, input_color):
"""
Returns list of all possible moves
:type: input_color: Color
:rtype: list
"""
for piece in self:
# Tests if square on the board is not empty
if piece is not None and piece.color == input_color:... |
Runs multiple processes in parallel. | def runInParallel(*fns):
"""
Runs multiple processes in parallel.
:type: fns: def
"""
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join() |
Finds Location of the first piece that matches piece. If none is found Exception is raised. | def find_piece(self, piece):
"""
Finds Location of the first piece that matches piece.
If none is found, Exception is raised.
:type: piece: Piece
:rtype: Location
"""
for i, _ in enumerate(self.position):
for j, _ in enumerate(self.position):
... |
Gets location of a piece on the board given the type and color.: type: piece_type: Piece: type: input_color: Color: rtype: Location | def get_piece(self, piece_type, input_color):
"""
Gets location of a piece on the board given the type and color.
:type: piece_type: Piece
:type: input_color: Color
:rtype: Location
"""
for loc in self:
piece = self.piece_at_square(loc)
... |
Places piece at given get_location | def place_piece_at_square(self, piece, location):
"""
Places piece at given get_location
:type: piece: Piece
:type: location: Location
"""
self.position[location.rank][location.file] = piece
piece.location = location |
Moves piece from one location to another | def move_piece(self, initial, final):
"""
Moves piece from one location to another
:type: initial: Location
:type: final: Location
"""
self.place_piece_at_square(self.piece_at_square(initial), final)
self.remove_piece_at_square(initial) |
Updates position by applying selected move | def update(self, move):
"""
Updates position by applying selected move
:type: move: Move
"""
if move is None:
raise TypeError("Move cannot be type None")
if self.king_loc_dict is not None and isinstance(move.piece, King):
self.king_loc_dict[move.... |
calc unbalanced charges and radicals for skin atoms | def _balance(self, ):
""" calc unbalanced charges and radicals for skin atoms
"""
meta = h.meta
for n in (skin_reagent.keys() | skin_product.keys()):
lost = skin_reagent[n]
cycle_lost = cycle(lost)
new = skin_product[n]
cycle_new = cycle(ne... |
search bond breaks and creations | def clone_subgraphs(self, g):
if not isinstance(g, CGRContainer):
raise InvalidData('only CGRContainer acceptable')
r_group = []
x_group = {}
r_group_clones = []
newcomponents = []
''' search bond breaks and creations
'''
components, lost_bon... |
get atoms paths from detached atom to attached | def __get_substitution_paths(g):
"""
get atoms paths from detached atom to attached
:param g: CGRContainer
:return: tuple of atoms numbers
"""
for n, nbrdict in g.adjacency():
for m, l in combinations(nbrdict, 2):
nms = nbrdict[m]['sp_bond']
... |
Read versions from the table | def versions(self):
""" Read versions from the table
The versions are kept in cache for the next reads.
"""
if self._versions is None:
with self.database.cursor_autocommit() as cursor:
query = """
SELECT number,
date_sta... |
Prepares menu entries for auto - generated model CRUD views. This is simple version of: attr: get_crud_menus () without Category support and permission control. Just for development purposes. | def simple_crud():
"""
Prepares menu entries for auto-generated model CRUD views.
This is simple version of :attr:`get_crud_menus()` without
Category support and permission control.
Just for development purposes.
Returns:
Dict of list of dicts (``{'':[{}],}``... |
Generates menu entries according to: attr: zengine. settings. OBJECT_MENU and permissions of current user. | def get_crud_menus(self):
"""
Generates menu entries according to
:attr:`zengine.settings.OBJECT_MENU` and permissions
of current user.
Returns:
Dict of list of dicts (``{'':[{}],}``). Menu entries.
"""
results = defaultdict(list)
for object_t... |
Creates a menu entry for given model data. Updates results in place. | def _add_crud(self, model_data, object_type, results):
"""
Creates a menu entry for given model data.
Updates results in place.
Args:
model_data: Model data.
object_type: Relation name.
results: Results dict.
"""
model = model_registry... |
Appends menu entries to dashboard quickmenu according to: attr: zengine. settings. QUICK_MENU | def _add_to_quick_menu(self, key, wf):
"""
Appends menu entries to dashboard quickmenu according
to :attr:`zengine.settings.QUICK_MENU`
Args:
key: workflow name
wf: workflow menu entry
"""
if key in settings.QUICK_MENU:
self.output['qu... |
Creates menu entries for custom workflows. | def _get_workflow_menus(self):
"""
Creates menu entries for custom workflows.
Returns:
Dict of list of dicts (``{'':[{}],}``). Menu entries.
"""
results = defaultdict(list)
from zengine.lib.cache import WFSpecNames
for name, title, category in WFSpecN... |
Do response processing | def process_response(self, request, response, resource):
"""
Do response processing
"""
origin = request.get_header('Origin')
if not settings.DEBUG:
if origin in settings.ALLOWED_ORIGINS or not origin:
response.set_header('Access-Control-Allow-Origin',... |
Do response processing | def process_request(self, req, resp):
"""
Do response processing
"""
if not req.client_accepts_json:
raise falcon.HTTPNotAcceptable(
'This API only supports responses encoded as JSON.',
href='http://docs.examples.com/api/json')
if req.m... |
Do response processing | def process_request(self, req, resp):
"""
Do response processing
"""
# req.stream corresponds to the WSGI wsgi.input environ variable,
# and allows you to read bytes from the request body.
#
# See also: PEP 3333
if req.content_length in (None, 0):
... |
Serializes req. context [ result ] to resp. body as JSON. | def process_response(self, req, resp, resource):
"""
Serializes ``req.context['result']`` to resp.body as JSON.
If :attr:`~zengine.settings.DEBUG` is True,
``sys._debug_db_queries`` (set by pyoko) added to response.
"""
if 'result' not in req.context:
return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.