code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def sort_depth(vals, reverse=False):
lst = [[float(price), quantity] for price, quantity in vals.items()]
lst = sorted(lst, key=itemgetter(0), reverse=reverse)
return lst | Sort bids or asks by price |
def metrics_for_mode(self, mode):
if mode not in self._values:
logging.info("Mode %s not found", mode)
return []
return sorted(list(self._values[mode].keys())) | Metrics available for a given mode. |
def add_network_to_bgp_speaker(self, speaker_id, body=None):
return self.put((self.bgp_speaker_path % speaker_id) +
"/add_gateway_network", body=body) | Adds a network to BGP speaker. |
def pypirc_temp(index_url):
pypirc_file = tempfile.NamedTemporaryFile(suffix='.pypirc', delete=False)
print(pypirc_file.name)
with open(pypirc_file.name, 'w') as fh:
fh.write(PYPIRC_TEMPLATE.format(index_name=PYPIRC_TEMP_INDEX_NAME, index_url=index_url))
return pypirc_file.name | Create a temporary pypirc file for interaction with twine |
def create_signature(secret, value, digestmod='sha256', encoding='utf-8'):
if isinstance(secret, str):
secret = secret.encode(encoding)
if isinstance(value, str):
value = value.encode(encoding)
if isinstance(digestmod, str):
digestmod = getattr(hashlib, digestmod, hashlib.sha1)
h... | Create HMAC Signature from secret for value. |
def send_confirmation_email(self):
form = self._get_form('SECURITY_SEND_CONFIRMATION_FORM')
if form.validate_on_submit():
self.security_service.send_email_confirmation_instructions(form.user)
self.flash(_('flask_unchained.bundles.security:flash.confirmation_request',
... | View function which sends confirmation token and instructions to a user. |
def _stub_tag(constructor, node):
seen = getattr(constructor, "_stub_seen", None)
if seen is None:
seen = constructor._stub_seen = set()
if node.tag not in seen:
print("YAML tag {} is not supported".format(node.tag))
seen.add(node.tag)
return {} | Stub a constructor with a dictionary. |
def build_absolute_uri(self, uri):
request = self.context.get('request', None)
return (
request.build_absolute_uri(uri) if request is not None else uri
) | Return a fully qualified absolute url for the given uri. |
def read_index(self):
if not isinstance(self.tree, dict):
self.tree = dict()
self.tree.clear()
for path, metadata in self.read_index_iter():
self.tree[path] = metadata | Reads the index and populates the directory tree |
def insort_no_dup(lst, item):
import bisect
ix = bisect.bisect_left(lst, item)
if lst[ix] != item:
lst[ix:ix] = [item] | If item is not in lst, add item to list at its sorted position |
def RedirectDemo(handler, t):
t.redirect(SIP_PHONE)
json = t.RenderJson()
logging.info ("RedirectDemo json: %s" % json)
handler.response.out.write(json) | Demonstration of redirecting to another number. |
def resolve_indices(self, index, start_val):
channels = self.vertices[index].meta['channels']
base_channel = start_val
rot_ind = -np.ones(3, dtype=int)
pos_ind = -np.ones(3, dtype=int)
for i in range(len(channels)):
if channels[i]== 'Xrotation':
rot_i... | Get indices for the skeleton from the channels when loading in channel data. |
def _init_action_list(self, action_filename):
self.actions = list()
self.hiid_to_action_index = dict()
f = codecs.open(action_filename, 'r', encoding='latin-1')
first_line = True
for line in f:
line = line.rstrip()
if first_line:
first_line... | Parses the file and populates the data. |
def bytes_array(self):
assert len(self.dimensions) == 2, \
'{}: cannot get value as bytes array!'.format(self.name)
l, n = self.dimensions
return [self.bytes[i*l:(i+1)*l] for i in range(n)] | Get the param as an array of raw byte strings. |
def _timeseries_component(self, series):
return lambda: np.interp(self.time(), series.index, series.values) | Internal function for creating a timeseries model element |
def _wrap_data(data: Union[str, bytes]):
MsgType = TextMessage if isinstance(data, str) else BytesMessage
return MsgType(data=data, frame_finished=True, message_finished=True) | Wraps data into the right event. |
def _dump_date(d, delim):
if d is None:
d = gmtime()
elif isinstance(d, datetime):
d = d.utctimetuple()
elif isinstance(d, (integer_types, float)):
d = gmtime(d)
return "%s, %02d%s%s%s%s %02d:%02d:%02d GMT" % (
("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[d.tm_wday],... | Used for `http_date` and `cookie_date`. |
def _read_stderr(self):
f = open(self.stderr_file, 'rb')
try:
stderr_text = f.read()
if not stderr_text:
return ''
encoding = get_coding(stderr_text)
stderr_text = to_text_string(stderr_text, encoding)
return stderr_text... | Read the stderr file of the kernel. |
def _get_future_expected_model(self, core_element):
for model in self.expected_future_models:
if model.core_element is core_element:
self.expected_future_models.remove(model)
return model
return None | Hand model for an core element from expected model list and remove the model from this list |
def _init_logs_table():
_logs_table = sqlalchemy.Table(
'logs', _METADATA,
sqlalchemy.Column(
'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
nullable=False),
sqlalchemy.Column('timestamp', sqlalchemy.DateTime),
sqlalchemy.Column('message',... | Initialise the "logs" table in the db. |
def unregister_dependent_on(self, tree):
if tree in self.dependent_on:
self.dependent_on.remove(tree) | unregistering tree that we are dependent on |
def GroupEncoder(field_number, is_repeated, is_packed):
start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)
end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(... | Returns an encoder for a group field. |
def upload_collection_configs(self, collection, fs_path):
coll_path = fs_path
if not os.path.isdir(coll_path):
raise ValueError("{} Doesn't Exist".format(coll_path))
self._upload_dir(coll_path, '/configs/{}'.format(collection)) | Uploads collection configurations from a specified directory to zookeeper. |
def OnCellTextRotation(self, event):
with undo.group(_("Rotation")):
self.grid.actions.toggle_attr("angle")
self.grid.ForceRefresh()
self.grid.update_attribute_toolbar()
if is_gtk():
try:
wx.Yield()
except:
pass
... | Cell text rotation event handler |
def action(self, relationship):
action_obj = FileAction(self._indicator_data.get('xid'), relationship)
self._file_actions.append(action_obj)
return action_obj | Add a File Action. |
def relabel_squeeze(data):
palette, index = np.unique(data, return_inverse=True)
data = index.reshape(data.shape)
return data | Makes relabeling of data if there are unused values. |
def _load_physical_network_mappings(self, phys_net_vswitch_mappings):
for mapping in phys_net_vswitch_mappings:
parts = mapping.split(':')
if len(parts) != 2:
LOG.debug('Invalid physical network mapping: %s', mapping)
else:
pattern = re.escape(... | Load all the information regarding the physical network. |
def do_directives(self, line):
for name, cmd in self.adapter.directives.items():
with colorize('blue'):
print('bot %s:' % name)
if cmd.__doc__:
for line in cmd.__doc__.split('\n'):
print(' %s' % line)
else:
... | List all directives supported by the bot |
def list(self):
queue = self._pebble.get_endpoint_queue(DataLogging)
self._pebble.send_packet(DataLogging(data=DataLoggingReportOpenSessions(sessions=[])))
sessions = []
while True:
try:
result = queue.get(timeout=2).data
except TimeoutError:
... | List all available data logging sessions |
def _add_implied_commands(self):
if len(self.get_added_columns()) and not self._creating():
self._commands.insert(0, self._create_command("add"))
if len(self.get_changed_columns()) and not self._creating():
self._commands.insert(0, self._create_command("change"))
return s... | Add the commands that are implied by the blueprint. |
def main():
log_level = os.environ.get('LOG_LEVEL', 'INFO')
logging.basicConfig(level=getattr(logging, log_level),
format='%(asctime)s %(name)s[%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
current_path = os.path.abspath('.')
if current_path no... | Entry point of rw cli |
def _validate_mandatory_keys(mandatory, validated, data, to_validate):
errors = []
for key, sub_schema in mandatory.items():
if key not in data:
errors.append('missing key: %r' % (key,))
continue
try:
validated[key] = sub_schema(data[key])
except NotVa... | Validate the manditory keys. |
def sub_description(self):
gd = self.geo_description
td = self.time_description
if gd and td:
return '{}, {}. {} Rows.'.format(gd, td, self._p.count)
elif gd:
return '{}. {} Rows.'.format(gd, self._p.count)
elif td:
return '{}. {} Rows.'.format... | Time and space dscription |
def runGetExpressionLevel(self, id_):
compoundId = datamodel.ExpressionLevelCompoundId.parse(id_)
dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
rnaQuantificationSet = dataset.getRnaQuantificationSet(
compoundId.rna_quantification_set_id)
rnaQuantificati... | Runs a getExpressionLevel request for the specified ID. |
def clear_cache():
fsb_cachedir = os.path.join(__opts__['cachedir'], 'svnfs')
list_cachedir = os.path.join(__opts__['cachedir'], 'file_lists/svnfs')
errors = []
for rdir in (fsb_cachedir, list_cachedir):
if os.path.exists(rdir):
try:
shutil.rmtree(rdir)
ex... | Completely clear svnfs cache |
def field_uuid(self, attr, options):
options['validators'].append(validators.UUIDValidator(attr.entity))
return wtf_fields.StringField, options | Creates a form element for the UUID type. |
def interpret(code, in_vars):
try:
result = eval(code, in_vars)
except SyntaxError:
pass
else:
if result is not None:
print(ascii(result))
return
exec_func(code, in_vars) | Try to evaluate the given code, otherwise execute it. |
def optwrap(self, text):
if not self.body_width:
return text
assert wrap, "Requires Python 2.3."
result = ''
newlines = 0
for para in text.split("\n"):
if len(para) > 0:
if not skipwrap(para):
result += "\n".join(wrap(pa... | Wrap all paragraphs in the provided text. |
def add_action(self, name, parent, action):
if iskeyword(name):
name = '_' + name
self._actions[name] = parent.new_action(**action)
setattr(self, name, self._actions[name].execute) | Add a single Action to the APIObject. |
def _processDML(self, dataset_name, cols, reader):
sql_template = self._generateInsertStatement(dataset_name, cols)
c = self.conn.cursor()
c.executemany(sql_template, reader)
self.conn.commit() | Overridden version of create DML for SQLLite |
def apply_texture(self, image):
self.image = image.convert_alpha()
self.untransformed_image = self.image.copy()
self.source.x = 0
self.source.y = 0
self.source.width = self.image.get_width()
self.source.height = self.image.get_height()
center = Vector2(self.source... | Place a preexisting texture as the sprite's texture. |
def box_iter(self):
for i in utils.range_(self.order):
for j in utils.range_(self.order):
yield self.box(i * 3, j * 3) | Get an iterator over all boxes in the Sudoku |
def _run(self):
self.set_state(self.STATE_INITIALIZING)
self.ioloop = ioloop.IOLoop.current()
self.consumer_lock = locks.Lock()
self.sentry_client = self.setup_sentry(
self._kwargs['config'], self.consumer_name)
try:
self.setup()
except (AttributeE... | Run method that can be profiled |
def mkdirs(filename, mode=0o777):
dirname = os.path.dirname(filename)
if not dirname:
return
_compat.makedirs(dirname, mode=mode, exist_ok=True) | Recursively create directories up to the path of ``filename`` as needed. |
def _smooth(values: List[float], beta: float) -> List[float]:
avg_value = 0.
smoothed = []
for i, value in enumerate(values):
avg_value = beta * avg_value + (1 - beta) * value
smoothed.append(avg_value / (1 - beta ** (i + 1)))
return smoothed | Exponential smoothing of values |
def quil_to_program(quil: str) -> Program:
pyquil_instructions = pyquil.parser.parse(quil)
return pyquil_to_program(pyquil_instructions) | Parse a quil program and return a Program object |
def collection_options(self, **kwargs):
methods = self._get_handled_methods(self._collection_actions)
return self._set_options_headers(methods) | Handle collection item OPTIONS request. |
def open_current_in_browser(self):
if self.impact_path is None:
html = self.page().mainFrame().toHtml()
html_to_file(html, open_browser=True)
else:
if self.action_show_report.isEnabled():
open_in_browser(self.log_path)
else:
... | Open current selected impact report in browser. |
def filter_fh_by_metadata(self, filehandlers):
for filehandler in filehandlers:
filehandler.metadata['start_time'] = filehandler.start_time
filehandler.metadata['end_time'] = filehandler.end_time
if self.metadata_matches(filehandler.metadata, filehandler):
yie... | Filter out filehandlers using provide filter parameters. |
def connection_lost(self, reason):
LOG.info(
'Connection to peer %s lost, reason: %s Resetting '
'retry connect loop: %s' %
(self._neigh_conf.ip_address, reason,
self._connect_retry_event.is_set()),
extra={
'resource_name': self._neigh... | Protocols connection lost handler. |
def getinfo(ee_obj, n=4):
output = None
for i in range(1, n):
try:
output = ee_obj.getInfo()
except ee.ee_exception.EEException as e:
if 'Earth Engine memory capacity exceeded' in str(e):
logging.info(' Resending query ({}/10)'.format(i))
... | Make an exponential back off getInfo call on an Earth Engine object |
def _handle_type(self, other):
if isinstance(other, Int):
return Int
elif isinstance(other, Float):
return Float
else:
raise TypeError(
f"Unsuported operation between `{type(self)}` and `{type(other)}`."
) | Helper to handle the return type. |
def _graphql_request_count_per_sliding_window(self, query_hash: str) -> int:
if self.is_logged_in:
max_reqs = {'1cb6ec562846122743b61e492c85999f': 20, '33ba35852cb50da46f5b5e889df7d159': 20}
else:
max_reqs = {'1cb6ec562846122743b61e492c85999f': 200, '33ba35852cb50da46f5b5e889df7d... | Return how many GraphQL requests can be done within the sliding window. |
def dot(v1, v2):
x1, y1, z1 = v1
x2, y2, z2 = v2
return x1 * x2 + y1 * y2 + z1 * z2 | Computes the dot product of two vectors. |
def connect(self):
try:
for group in ('inlets', 'receivers', 'outlets', 'senders'):
self._connect_subgroup(group)
except BaseException:
objecttools.augment_excmessage(
'While trying to build the node connection of the `%s` '
'sequen... | Connect the link sequences of the actual model. |
def _get_loss_fn(self):
criteria = self.criteria.to(self.config["device"])
loss_fn = lambda X, Y: sum(
criteria(Y_tp, Y_t) for Y_tp, Y_t in zip(self.forward(X), Y)
)
return loss_fn | Returns the loss function to use in the train_model routine |
def unwrap(self):
return [v.unwrap() if hasattr(v, 'unwrap') and not hasattr(v, 'no_unwrap') else v for v in self] | Return a deep copy of myself as a list, and unwrap any wrapper objects in me. |
def handle_action(self, channel, nick, msg):
"Core message parser and dispatcher"
messages = ()
for handler in Handler.find_matching(msg, channel):
exception_handler = functools.partial(
self._handle_exception,
handler=handler,
)
rest = handler.process(msg)
client = connection = event = None
... | Core message parser and dispatcher |
def fetch(cls, id, incident=None, endpoint=None, *args, **kwargs):
if incident is None and endpoint is None:
raise InvalidArguments(incident, endpoint)
if endpoint is None:
iid = incident['id'] if isinstance(incident, Entity) else incident
endpoint = 'incidents/{0}/al... | Customize fetch because this is a nested resource. |
def _update_submodules(repo_dir):
subprocess.check_call("git submodule init", cwd=repo_dir, shell=True)
subprocess.check_call(
"git submodule update --recursive", cwd=repo_dir, shell=True) | update submodules in a repo |
def _bp_static_url(blueprint):
u = six.u('%s%s' % (blueprint.url_prefix or '', blueprint.static_url_path or ''))
return u | builds the absolute url path for a blueprint's static folder |
def save(self, commit=True):
if getattr(self.instance,'instructor',None):
self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.instance.instructor.availableForPrivates)
self.instance.instructor.save(update_fields=['availableForPrivates',])
... | If the staff member is an instructor, also update the availableForPrivates field on the Instructor record. |
def _create_field_mapping_action(self):
icon = resources_path('img', 'icons', 'show-mapping-tool.svg')
self.action_field_mapping = QAction(
QIcon(icon),
self.tr('InaSAFE Field Mapping Tool'),
self.iface.mainWindow())
self.action_field_mapping.setStatusTip(self... | Create action for showing field mapping dialog. |
def _find_devices_win(self):
self._find_xinput()
self._detect_gamepads()
self._count_devices()
if self._raw_device_counts['keyboards'] > 0:
self.keyboards.append(Keyboard(
self,
"/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"))
if self... | Find devices on Windows. |
def document_endpoint(endpoint):
descr = clean_description(py_doc_trim(endpoint.__doc__))
docs = {
'name': endpoint._route_name,
'http_method': endpoint._http_method,
'uri': endpoint._uri,
'description': descr,
'arguments': extract_endpoint_arguments(endpoint),
'r... | Extract the full documentation dictionary from the endpoint. |
def enabled_flags(self):
if not self.value:
yield self.__flags_members__[0]
return
val = self.value
while val:
lowest_bit = val & -val
val ^= lowest_bit
yield self.__flags_members__[lowest_bit] | Return the objects for each individual set flag. |
def _apply_validator_chain(chain, value, handler):
if hasattr(chain, 'validate'):
chain = [chain, ]
for validator in chain:
if hasattr(validator, 'validate'):
value = validator.validate(value, handler)
else:
raise web.HTTPError(500)
return value | Apply validators in sequence to a value. |
def _fusion_legacy_handler(_, __, tokens):
if RANGE_5P not in tokens:
tokens[RANGE_5P] = {FUSION_MISSING: '?'}
if RANGE_3P not in tokens:
tokens[RANGE_3P] = {FUSION_MISSING: '?'}
return tokens | Handle a legacy fusion. |
def check_help():
know = set(('-h', '--help', '-v', '--version'))
args = set(sys.argv[1:])
return len(know.intersection(args)) > 0 | check know args in argv. |
def add_janitor(self, janitor):
if not self.owner and not self.admin:
raise RuntimeError("Not enough street creed to do this")
janitor = janitor.strip().lower()
if not janitor:
raise ValueError("Empty strings cannot be janitors")
if janitor in self.config.janitors... | Add janitor to the room |
def _clear(self):
self._finished = False
self._measurement = None
self._message = None
self._message_body = None | Resets all assigned data for the current message. |
def parse_for(self):
lineno = self.stream.expect('name:for').lineno
target = self.parse_assign_target(extra_end_rules=('name:in',))
self.stream.expect('name:in')
iter = self.parse_tuple(with_condexpr=False,
extra_end_rules=('name:recursive',))
test... | Parse a for loop. |
def to_header(self):
if self.star_tag:
return "*"
return ", ".join(
['"%s"' % x for x in self._strong] + ['W/"%s"' % x for x in self._weak]
) | Convert the etags set into a HTTP header string. |
def view(input_file, plane, backend):
if backend == 'matplotlib':
from neurom.viewer import draw
kwargs = {
'mode': '3d' if plane == '3d' else '2d',
}
if plane != '3d':
kwargs['plane'] = plane
draw(load_neuron(input_file), **kwargs)
else:
f... | A simple neuron viewer |
def wait_all_tasks_done(self, timeout=None, delay=0.5, interval=0.1):
timeout = self._timeout if timeout is None else timeout
timeout = timeout or float("inf")
start_time = time.time()
time.sleep(delay)
while 1:
if not self.todo_tasks:
return self.all_... | Block, only be used while loop running in a single non-main thread. |
def _get_orig_items(data):
if isinstance(data, dict):
if dd.get_align_bam(data) and tz.get_in(["metadata", "batch"], data) and "group_orig" in data:
return vmulti.get_orig_items(data)
else:
return [data]
else:
return data | Retrieve original items in a batch, handling CWL and standard cases. |
def options(self, url: StrOrURL, *, allow_redirects: bool=True,
**kwargs: Any) -> '_RequestContextManager':
return _RequestContextManager(
self._request(hdrs.METH_OPTIONS, url,
allow_redirects=allow_redirects,
**kwargs)) | Perform HTTP OPTIONS request. |
def download_file_job(entry, directory, checksums, filetype='genbank', symlink_path=None):
pattern = NgdConfig.get_fileending(filetype)
filename, expected_checksum = get_name_and_checksum(checksums, pattern)
base_url = convert_ftp_url(entry['ftp_path'])
full_url = '{}/{}'.format(base_url, filename)
... | Generate a DownloadJob that actually triggers a file download. |
def _Execute(self, options):
whitelist = dict(
name=options["name"],
description=options.get("description", "<empty>"))
return self._agent.client.compute.security_groups.create(**whitelist) | Handles security groups operations. |
def play(self):
self.t = 1
while self.t <= self.T:
for i in range(self.N):
for j in range(self.N):
live = self.live_neighbours(i, j)
if (self.old_grid[i][j] == 1 and live < 2):
self.new_grid[i][j] = 0
... | Play Conway's Game of Life. |
def do_workers(self, args):
workers = self.task_master.workers(alive=not args.all)
for k in sorted(workers.iterkeys()):
self.stdout.write('{0} ({1})\n'.format(k, workers[k]))
if args.details:
heartbeat = self.task_master.get_heartbeat(k)
for hk, hv... | list all known workers |
def _delete(self, c, context, hm):
pools = hm.get("pools", [])
for pool in pools:
pool_id = pool.get("pool_id")
self._dissociate(c, context, hm, pool_id)
self._delete_unused(c, context, hm) | Delete a healthmonitor and ALL its pool associations |
def monitor(self, name, ip, port, quorum):
fut = self.execute(b'MONITOR', name, ip, port, quorum)
return wait_ok(fut) | Add a new master to Sentinel to be monitored. |
def add_uniform_precip_event(self, intensity, duration):
self.project_manager.setCard('PRECIP_UNIF', '')
self.project_manager.setCard('RAIN_INTENSITY', str(intensity))
self.project_manager.setCard('RAIN_DURATION', str(duration.total_seconds()/60.0)) | Add a uniform precip event |
def _index_resized(self, col, old_width, new_width):
self.table_index.setColumnWidth(col, new_width)
self._update_layout() | Resize the corresponding column of the index section selected. |
def _parse_lobby_chat(self, messages, source, timestamp):
for message in messages:
if message.message_length == 0:
continue
chat = ChatMessage(message.message, timestamp, self._players(), source=source)
self._parse_chat(chat) | Parse a lobby chat message. |
def DrawIconAndLabel(self, dc, node, x, y, w, h, depth):
if w-2 < self._em_size_//2 or h-2 < self._em_size_ //2:
return
dc.SetClippingRegion(x+1, y+1, w-2, h-2)
try:
icon = self.adapter.icon(node, node==self.selectedNode)
if icon and h >= icon.GetHeight() and ... | Draw the icon, if any, and the label, if any, of the node. |
def assign_routes(self, app):
for grp in self.filters:
for f in self.filters[grp]:
if f.route_func:
f.register_route(app)
for c in self.charts:
if c.route_func:
c.register_route(app) | Register routes with the app. |
def update_gol(self):
updated_grid = [[self.update_cell(row, col) \
for col in range(self.get_grid_width())] \
for row in range(self.get_grid_height())]
self.replace_grid(updated_grid) | Function that performs one step of the Game of Life |
def info(cabdir, header=False):
pfile = "{}/parameters.json".format(cabdir)
if not os.path.exists(pfile):
raise RuntimeError("Cab could not be found at : {}".format(cabdir))
cab_definition = cab.CabDefinition(parameter_file=pfile)
cab_definition.display(header) | prints out help information about a cab |
def memoize_methodcalls(func, pickle=False, dumps=pickle.dumps):
cache = func._memoize_cache = {}
@functools.wraps(func)
def memoizer(self, *args, **kwargs):
if pickle:
key = dumps((args, kwargs))
else:
key = args
if key not in cache:
cache[key] = ... | Cache the results of the function for each input it gets called with. |
def _get_pooling_layers(self, start_node_id, end_node_id):
layer_list = []
node_list = [start_node_id]
assert self._depth_first_search(end_node_id, layer_list, node_list)
ret = []
for layer_id in layer_list:
layer = self.layer_list[layer_id]
if is_layer(la... | Given two node IDs, return all the pooling layers between them. |
def reader(f):
return unicodecsv.reader(f, encoding='utf-8', delimiter=b',', quotechar=b'"') | CSV Reader factory for CADA format |
def patch(self, path, data, **options):
data, options = self._update_request(data, options)
return self.request('patch', path, data=data, **options) | Parses PATCH request options and dispatches a request |
def distance(self, other):
return math.acos(self._pos3d.dot(other.vector)) | Distance to another point on the sphere |
def validate_obj(keys, obj):
msg = ''
for k in keys:
if isinstance(k, str):
if k not in obj or (not isinstance(obj[k], list) and not obj[k]):
if msg:
msg = "%s," % msg
msg = "%s%s" % (msg, k)
elif isinstance(k, list):
fo... | Super simple "object" validation. |
def save(self, *args, **kwargs):
if not self.status:
self.status == Event.RegStatus.hidden
super(PrivateLessonEvent,self).save(*args,**kwargs) | Set registration status to hidden if it is not specified otherwise |
def visit_const(self, node, parent):
return nodes.Const(
node.value,
getattr(node, "lineno", None),
getattr(node, "col_offset", None),
parent,
) | visit a Const node by returning a fresh instance of it |
def morrison_and_stephenson_2004_table():
import pandas as pd
f = load.open('http://eclipse.gsfc.nasa.gov/SEcat5/deltat.html')
tables = pd.read_html(f.read())
df = tables[0]
return pd.DataFrame({'year': df[0], 'delta_t': df[1]}) | Table of smoothed Delta T values from Morrison and Stephenson, 2004. |
def init_debug(self):
import signal
def debug_trace(sig, frame):
self.log('Trace signal received')
self.log(''.join(traceback.format_stack(frame)))
signal.signal(signal.SIGUSR2, debug_trace) | Initialize debugging features, such as a handler for USR2 to print a trace |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.