code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def _parse_throttle(self, tablename, throttle):
amount = []
desc = self.describe(tablename)
throughputs = [desc.read_throughput, desc.write_throughput]
for value, throughput in zip(throttle[1:], throughputs):
if value == "*":
amount.append(0)
elif value[-1] == "%":
amount.append(throughput * float(value[:-1]) / 100.0)
else:
amount.append(float(value))
cap = Capacity(*amount)
return RateLimit(total=cap, callback=self._on_throttle) | Parse a 'throttle' statement and return a RateLimit |
def randomPairsMatch(n_records_A, n_records_B, sample_size):
n = int(n_records_A * n_records_B)
if sample_size >= n:
random_pairs = numpy.arange(n)
else:
random_pairs = numpy.array(random.sample(range(n), sample_size),
dtype=int)
i, j = numpy.unravel_index(random_pairs, (n_records_A, n_records_B))
return zip(i, j) | Return random combinations of indices for record list A and B |
def ensure_security_header(envelope, queue):
(header,) = HEADER_XPATH(envelope)
security = SECURITY_XPATH(header)
if security:
for timestamp in TIMESTAMP_XPATH(security[0]):
queue.push_and_mark(timestamp)
return security[0]
else:
nsmap = {
'wsu': ns.wsuns[1],
'wsse': ns.wssens[1],
}
return _create_element(header, 'wsse:Security', nsmap) | Insert a security XML node if it doesn't exist otherwise update it. |
def unhook_drag(self):
widget = self.widget
del widget.mousePressEvent
del widget.mouseMoveEvent
del widget.mouseReleaseEvent | Remove the hooks for drag operations. |
def handler(self, environ, start_response):
if environ['REQUEST_METHOD'] == 'POST':
return self.handle_POST(environ, start_response)
else:
start_response("400 Bad request", [('Content-Type', 'text/plain')])
return [''] | XMLRPC service for windmill browser core to communicate with |
def _convert_np_data(data, data_type, num_elems):
if (data_type == 51 or data_type == 52):
if (data == ''):
return ('\x00'*num_elems).encode()
else:
return data.ljust(num_elems, '\x00').encode('utf-8')
elif (data_type == 32):
data_stream = data.real.tobytes()
data_stream += data.imag.tobytes()
return data_stream
else:
return data.tobytes() | Converts a single np data into byte stream. |
def LateBind(self, target=None):
self.type = target
self._GetPrimitiveEncoder()
self.late_bound = False
self.owner.AddDescriptor(self) | Bind the field descriptor to the owner once the target is defined. |
def include(self, node):
result = None
if isinstance(node, ScalarNode):
result = Loader.include_file(self.construct_scalar(node))
else:
raise RuntimeError("Not supported !include on type %s" % type(node))
return result | Include the defined yaml file. |
def loss(self, xs, ys):
return float(
self.sess.run(
self.cross_entropy, feed_dict={
self.x: xs,
self.y_: ys
})) | Computes the loss of the network. |
def render_glitchgram(path, cp):
filename = os.path.basename(path)
slug = filename.replace('.', '_')
template_dir = pycbc.results.__path__[0] + '/templates/files'
env = Environment(loader=FileSystemLoader(template_dir))
env.globals.update(abs=abs)
template = env.get_template(cp.get(filename, 'template'))
context = {'filename' : filename,
'slug' : slug,
'cp' : cp}
output = template.render(context)
return output | Render a glitchgram file template. |
def canceled_plan_summary_for(self, year, month):
return (
self.canceled_during(year, month)
.values("plan")
.order_by()
.annotate(count=models.Count("plan"))
) | Return Subscriptions canceled within a time range with plan counts annotated. |
def roll(vari, shift, axis=None):
if isinstance(vari, Poly):
core = vari.A.copy()
for key in vari.keys:
core[key] = roll(core[key], shift, axis)
return Poly(core, vari.dim, None, vari.dtype)
return numpy.roll(vari, shift, axis) | Roll array elements along a given axis. |
def issuers(self):
issuers = self._get_property('issuers') or []
result = {
'_embedded': {
'issuers': issuers,
},
'count': len(issuers),
}
return List(result, Issuer) | Return the list of available issuers for this payment method. |
def _match(self, struct1, struct2, fu, s1_supercell=True, use_rms=False,
break_on_match=False):
ratio = fu if s1_supercell else 1/fu
if len(struct1) * ratio >= len(struct2):
return self._strict_match(
struct1, struct2, fu, s1_supercell=s1_supercell,
break_on_match=break_on_match, use_rms=use_rms)
else:
return self._strict_match(
struct2, struct1, fu, s1_supercell=(not s1_supercell),
break_on_match=break_on_match, use_rms=use_rms) | Matches one struct onto the other |
def str_traceback(error, tb):
if not isinstance(tb, types.TracebackType):
return tb
return ''.join(traceback.format_exception(error.__class__, error, tb)) | Returns a string representation of the traceback. |
def validate_address(address: Any) -> None:
if not is_address(address):
raise ValidationError(f"Expected an address, got: {address}")
if not is_canonical_address(address):
raise ValidationError(
"Py-EthPM library only accepts canonicalized addresses. "
f"{address} is not in the accepted format."
) | Raise a ValidationError if an address is not canonicalized. |
def acp_users_delete():
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = UserDeleteForm()
if not form.validate():
return error("Bad Request", 400)
user = get_user(int(request.form['uid']))
direction = request.form['direction']
if not user:
return error("User does not exist.", 404)
else:
for p in PERMISSIONS:
setattr(user, p, False)
user.active = direction == 'undel'
write_user(user)
return redirect(url_for('acp_users') + '?status={_del}eted'.format(
_del=direction)) | Delete or undelete an user account. |
def transformToNative(obj):
if not obj.isNative:
object.__setattr__(obj, '__class__', RecurringComponent)
obj.isNative = True
return obj | Turn a recurring Component into a RecurringComponent. |
def _python_to_mod_modify(changes: Changeset) -> Dict[str, List[Tuple[Operation, List[bytes]]]]:
table: LdapObjectClass = type(changes.src)
changes = changes.changes
result: Dict[str, List[Tuple[Operation, List[bytes]]]] = {}
for key, l in changes.items():
field = _get_field_by_name(table, key)
if field.db_field:
try:
new_list = [
(operation, field.to_db(value))
for operation, value in l
]
result[key] = new_list
except ValidationError as e:
raise ValidationError(f"{key}: {e}.")
return result | Convert a LdapChanges object to a modlist for a modify operation. |
def insert(self, value):
i = 0
n = len(self._tree)
while i < n:
cur = self._tree[i]
self._counts[i] += 1
if value < cur:
i = 2 * i + 1
elif value > cur:
i = 2 * i + 2
else:
return
raise ValueError("Value %s not contained in tree." "Also, the counts are now messed up." % value) | Insert an occurrence of `value` into the btree. |
def draw_selection(self, surf):
select_start = self._select_start
if select_start:
mouse_pos = self.get_mouse_pos()
if (mouse_pos and mouse_pos.surf.surf_type & SurfType.SCREEN and
mouse_pos.surf.surf_type == select_start.surf.surf_type):
rect = point.Rect(select_start.world_pos, mouse_pos.world_pos)
surf.draw_rect(colors.green, rect, 1) | Draw the selection rectange. |
def Search(self,key):
results = []
for disk in self.disks:
if disk.id.lower().find(key.lower()) != -1: results.append(disk)
elif key.lower() in disk.partition_paths: results.append(disk)
return(results) | Search disk list by partial mount point or ID |
def collect_vocab(qp_pairs):
vocab = set()
for qp_pair in qp_pairs:
for word in qp_pair['question_tokens']:
vocab.add(word['word'])
for word in qp_pair['passage_tokens']:
vocab.add(word['word'])
return vocab | Build the vocab from corpus. |
def _flush(self):
for consumer in self.consumers:
if not getattr(consumer, "closed", False):
consumer.flush() | Flushes all registered consumer streams. |
def edit_channel_info(self, new_ch_name, ch_dct):
self.ch_name = new_ch_name
self.dct = ch_dct
if ch_dct['type'] == 'analog':
fmter = fmt.green
else:
fmter = fmt.blue
self.ch_name_label.setText(fmt.b(fmter(self.ch_name)))
self.generateToolTip() | Parent widget calls this whenever the user edits channel info. |
def parameter(self, parser):
return (Suppress(self.syntax.params_start).leaveWhitespace() +
Group(parser) + Suppress(self.syntax.params_stop)) | Return a parser the parses parameters. |
def recent(self, check_language=True, language=None, limit=3, exclude=None,
kwargs=None, category=None):
if category:
if not kwargs:
kwargs = {}
kwargs['categories__in'] = [category]
qs = self.published(check_language=check_language, language=language,
kwargs=kwargs)
if exclude:
qs = qs.exclude(pk=exclude.pk)
return qs[:limit] | Returns recently published new entries. |
def unlink_reference(self, source, target):
target_uid = api.get_uid(target)
key = self.get_relationship_key(target)
backrefs = get_backreferences(source, relationship=None)
if key not in backrefs:
logger.warn(
"Referenced object {} has no backreferences for the key {}"
.format(repr(source), key))
return False
if target_uid not in backrefs[key]:
logger.warn("Target {} was not linked by {}"
.format(repr(target), repr(source)))
return False
backrefs[key].remove(target_uid)
return True | Unlink the target from the source |
def render(self, name=None, template=None, context={}):
if isinstance(template, Template):
_template = template
else:
_template = Template.objects.get(name=name)
response = self.env.from_string(
_template.content).render(context)
return response | Render Template meta from jinja2 templates. |
def getMonitorByName(self, monitorFriendlyName):
url = self.baseUrl
url += "getMonitors?apiKey=%s" % self.apiKey
url += "&noJsonCallback=1&format=json"
success, response = self.requestApi(url)
if success:
monitors = response.get('monitors').get('monitor')
for i in range(len(monitors)):
monitor = monitors[i]
if monitor.get('friendlyname') == monitorFriendlyName:
status = monitor.get('status')
alltimeuptimeratio = monitor.get('alltimeuptimeratio')
return status, alltimeuptimeratio
return None, None | Returns monitor status and alltimeuptimeratio for a MonitorFriendlyName. |
def ms_to_datetime(ms):
dt = datetime.datetime.utcfromtimestamp(ms / 1000)
return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc) | Converts a millisecond accuracy timestamp to a datetime |
def do_action_to_ancestors(analysis_request, transition_id):
parent_ar = analysis_request.getParentAnalysisRequest()
if parent_ar:
do_action_for(parent_ar, transition_id) | Promotes the transitiion passed in to ancestors, if any |
def read(self, **keys):
if self.is_scalar:
data = self.fitshdu.read_column(self.columns, **keys)
else:
c = keys.get('columns', None)
if c is None:
keys['columns'] = self.columns
data = self.fitshdu.read(**keys)
return data | Read the data from disk and return as a numpy array |
def fetch_api_by_name(api_name):
api_records = console.get_rest_apis()['items']
matches = filter(lambda x: x['name'] == api_name, api_records)
if not matches:
return None
return matches[0] | Fetch an api record by its name |
def on_step_begin(self, step, logs={}):
for callback in self.callbacks:
if callable(getattr(callback, 'on_step_begin', None)):
callback.on_step_begin(step, logs=logs)
else:
callback.on_batch_begin(step, logs=logs) | Called at beginning of each step for each callback in callbackList |
def create(self, project_name, template_name, substitutions):
self.project_name = project_name
self.template_name = template_name
for subs in substitutions:
current_sub = subs.split(',')
current_key = current_sub[0].strip()
current_val = current_sub[1].strip()
self.substitutes_dict[current_key] = current_val
self.term.print_info(u"Creating project '{0}' with template {1}"
.format(self.term.text_in_color(project_name, TERM_PINK), template_name))
self.make_directories()
self.make_files()
self.make_posthook() | Launch the project creation. |
def list_encoder(values, instance, field: Field):
return [field.to_db_value(element, instance) for element in values] | Encodes an iterable of a given field into a database-compatible format. |
def sort_name(self):
if self._record and self._record.sort_name:
return self._record.sort_name
return self.name | Get the sorting name of this category |
def _get_string_and_set_width(self, combination, mode):
show = "{}".format(self._separator(mode)).join(combination)
show = show.rstrip("{}".format(self._separator(mode)))
self.max_width = max([self.max_width, len(show)])
return show | Construct the string to be displayed and record the max width. |
def add_statement(self, line: str, lineno: Optional[int] = None) -> None:
if self.category() != 'statements':
self.values = [line]
else:
self.values.append(line)
if self.statements and self.statements[-1][0] == '!':
self.statements[-1][-1] += line
else:
self.statements.append(['!', line])
if lineno:
self.lineno = lineno | statements are regular python statements |
def Error(self, backtrace, client_id=None):
logging.error("Hunt Error: %s", backtrace)
self.hunt_obj.LogClientError(client_id, backtrace=backtrace) | Logs an error for a client but does not terminate the hunt. |
def delete(self, space_no, *args):
d = self.replyQueue.get()
packet = RequestDelete(self.charset, self.errors, d._ipro_request_id, space_no, 0, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charset, self.errors, None) | delete tuple by primary key |
def freeze(self):
self._lazy = False
for k, v in self.items():
if k in self._env:
continue
for _k, _v in v.items():
if isinstance(_v, Lazy):
if self.writable:
_v.get()
else:
try:
v.__setitem__(_k, _v.get(), replace=True)
except:
print "Error ini key:", _k
raise
del _v
self._globals = SortedDict() | Process all EvalValue to real value |
def replace_aliases(cut_dict, aliases):
for k, v in cut_dict.items():
for k0, v0 in aliases.items():
cut_dict[k] = cut_dict[k].replace(k0, '(%s)' % v0) | Substitute aliases in a cut dictionary. |
def check_animated(cls, raw_image):
"Checks whether the gif is animated."
try:
raw_image.seek(1)
except EOFError:
isanimated= False
else:
isanimated= True
raise cls.AnimatedImageException | Checks whether the gif is animated. |
def build_headers(self):
if not 'Content-Type' in self.headers:
content_type = self.content_type
if self.encoding != DEFAULT_ENCODING:
content_type += '; charset=%s' % self.encoding
self.headers['Content-Type'] = content_type
headers = list(self.headers.items())
headers += [
('Set-Cookie', cookie.OutputString())
for cookie in self.cookies.values()
]
return headers | Return the list of headers as two-tuples |
def _get_ldap_msg(e):
msg = e
if hasattr(e, 'message'):
msg = e.message
if 'desc' in e.message:
msg = e.message['desc']
elif hasattr(e, 'args'):
msg = e.args[0]['desc']
return msg | Extract LDAP exception message |
def _filter_markdown(source, filters):
lines = source.splitlines()
headers = [_replace_header_filter(filter) for filter in filters]
lines = [line for line in lines if line.startswith(tuple(headers))]
return '\n'.join(lines) | Only keep some Markdown headers from a Markdown string. |
def click(self):
if self.is_checkable():
if self.is_checked(): self.set_checked(False)
else: self.set_checked(True)
self.signal_clicked.emit(self.is_checked())
else:
self.signal_clicked.emit(True)
return self | Pretends to user clicked it, sending the signal and everything. |
def pack_bytes(self, obj_dict, encoding=None):
assert self.dict_to_bytes or self.dict_to_string
encoding = encoding or self.default_encoding or 'utf-8'
LOGGER.debug('%r encoding dict with encoding %s', self, encoding)
if self.dict_to_bytes:
return None, self.dict_to_bytes(obj_dict)
try:
return encoding, self.dict_to_string(obj_dict).encode(encoding)
except LookupError as error:
raise web.HTTPError(
406, 'failed to encode result %r', error,
reason='target charset {0} not found'.format(encoding))
except UnicodeEncodeError as error:
LOGGER.warning('failed to encode text as %s - %s, trying utf-8',
encoding, str(error))
return 'utf-8', self.dict_to_string(obj_dict).encode('utf-8') | Pack a dictionary into a byte stream. |
def getChildWithDefault(self, path, request):
cached_resource = self.getCachedResource(request)
if cached_resource:
reactor.callInThread(
responseInColor,
request,
'200 OK',
cached_resource,
'Cached',
'underscore'
)
return cached_resource
if path in self.children:
return self.children[path]
return self.getChild(path, request) | Retrieve a static or dynamically generated child resource from me. |
def deserialize(data):
try:
module = import_module(data.get('class').get('module'))
cls = getattr(module, data.get('class').get('name'))
except ImportError:
raise ImportError("No module named: %r" % data.get('class').get('module'))
except AttributeError:
raise ImportError("module %r does not contain class %r" % (
data.get('class').get('module'),
data.get('class').get('name')
))
class_params = cls.class_params(hidden=True)
params = dict(
(name, class_params[name].deserialize(value))
for (name, value) in data.get('params').items()
)
return cls(**params) | Create instance from serial data |
def read_header(filename):
header = {}
in_header = False
data = nl.universal_read(filename)
lines = [x.strip() for x in data.split('\n')]
for line in lines:
if line=="*** Header Start ***":
in_header=True
continue
if line=="*** Header End ***":
return header
fields = line.split(": ")
if len(fields)==2:
header[fields[0]] = fields[1] | returns a dictionary of values in the header of the given file |
def hdel(self, key, field, *fields):
return self.execute(b'HDEL', key, field, *fields) | Delete one or more hash fields. |
def jupytext_cli(args=None):
try:
jupytext(args)
except (ValueError, TypeError, IOError) as err:
sys.stderr.write('[jupytext] Error: ' + str(err) + '\n')
exit(1) | Entry point for the jupytext script |
def read_int(self):
format = '!I'
length = struct.calcsize(format)
info = struct.unpack(format,
self.data[self.offset:self.offset + length])
self.offset += length
return info[0] | Reads an integer from the packet |
def validate_digit(value, start, end):
if not str(value).isdigit() or int(value) < start or int(value) > end:
raise ValueError('%s must be a digit from %s to %s' % (value, start, end)) | validate if a digit is valid |
def parse(self):
if self.rorg in [RORG.RPS, RORG.BS1, RORG.BS4]:
self.status = self.data[-1]
if self.rorg == RORG.VLD:
self.status = self.optional[-1]
if self.rorg in [RORG.RPS, RORG.BS1, RORG.BS4]:
self.repeater_count = enocean.utils.from_bitarray(self._bit_status[4:])
return self.parsed | Parse data from Packet |
def log_sum_exp(self,x, axis):
x_max = np.max(x, axis=axis)
if axis == 1:
return x_max + np.log( np.sum(np.exp(x-x_max[:,np.newaxis]), axis=1) )
else:
return x_max + np.log( np.sum(np.exp(x-x_max), axis=0) ) | Compute the log of a sum of exponentials |
def error(self, request, message, extra_tags='', fail_silently=False):
add(self.target_name, request, constants.ERROR, message, extra_tags=extra_tags,
fail_silently=fail_silently) | Add a message with the ``ERROR`` level. |
def in_cache(self, zenpy_object):
object_type = get_object_type(zenpy_object)
cache_key_attr = self._cache_key_attribute(object_type)
return self.get(object_type, getattr(zenpy_object, cache_key_attr)) is not None | Determine whether or not this object is in the cache |
def document(schema):
teleport_schema = from_val(schema)
return json.dumps(teleport_schema, sort_keys=True, indent=2) | Print a documented teleport version of the schema. |
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs):
try:
self.driver.set_page_load_timeout(timeout)
self.driver.get(url)
header_data = self.get_selenium_header()
status_code = header_data['status-code']
self.status_code = status_code
self.url = self.driver.current_url
except TimeoutException:
logger.warning("Page timeout: {}".format(url))
try:
scraper_monitor.failed_url(url, 'Timeout')
except (NameError, AttributeError):
pass
except Exception:
logger.exception("Unknown problem with scraper_monitor sending a failed url")
except Exception as e:
raise e.with_traceback(sys.exc_info()[2])
else:
if status_code < 400:
return self.driver.page_source
else:
raise SeleniumHTTPError("Status code >= 400", status_code=status_code) | Try and return page content in the requested format using selenium |
def popup(self, title, callfn, initialdir=None, filename=None):
self.cb = callfn
self.filew.set_title(title)
if initialdir:
self.filew.set_current_folder(initialdir)
if filename:
self.filew.set_current_name(filename)
self.filew.show() | Let user select and load file. |
def THUMBNAIL_OPTIONS(self):
from django.core.exceptions import ImproperlyConfigured
size = self._setting('DJNG_THUMBNAIL_SIZE', (200, 200))
if not (isinstance(size, (list, tuple)) and len(size) == 2 and isinstance(size[0], int) and isinstance(size[1], int)):
raise ImproperlyConfigured("'DJNG_THUMBNAIL_SIZE' must be a 2-tuple of integers.")
return {'crop': True, 'size': size} | Set the size as a 2-tuple for thumbnailed images after uploading them. |
def post(self, ddata, url=SETUP_ENDPOINT, referer=SETUP_ENDPOINT):
headers = HEADERS.copy()
if referer is None:
headers.pop('Referer')
else:
headers['Referer'] = referer
if 'csrfmiddlewaretoken' not in ddata.keys():
ddata['csrfmiddlewaretoken'] = self._parent.csrftoken
req = self._parent.client.post(url, headers=headers, data=ddata)
if req.status_code == 200:
self.update() | Method to update some attributes on namespace. |
def animation_add(sequence_number, animation_id, name):
return MessageWriter().string("animation.add").uint64(sequence_number).uint32(animation_id).string(name).get() | Create a animation.add message |
def _get_queue_batch_size(self, queue):
batch_queues = self.config['BATCH_QUEUES']
batch_size = 1
for part in dotted_parts(queue):
if part in batch_queues:
batch_size = batch_queues[part]
return batch_size | Get queue batch size. |
def consulta(self, endereco, primeiro=False,
uf=None, localidade=None, tipo=None, numero=None):
if uf is None:
url = 'consultaEnderecoAction.do'
data = {
'relaxation': endereco.encode('ISO-8859-1'),
'TipoCep': 'ALL',
'semelhante': 'N',
'cfm': 1,
'Metodo': 'listaLogradouro',
'TipoConsulta': 'relaxation',
'StartRow': '1',
'EndRow': '10'
}
else:
url = 'consultaLogradouroAction.do'
data = {
'Logradouro': endereco.encode('ISO-8859-1'),
'UF': uf,
'TIPO': tipo,
'Localidade': localidade.encode('ISO-8859-1'),
'Numero': numero,
'cfm': 1,
'Metodo': 'listaLogradouro',
'TipoConsulta': 'logradouro',
'StartRow': '1',
'EndRow': '10'
}
h = self._url_open(url, data)
html = h.read()
if primeiro:
return self.detalhe()
else:
return self._parse_tabela(html) | Consulta site e retorna lista de resultados |
def _make_S_curve(x, range=(-0.75, 0.75)):
assert x.ndim == 1
x = x - x.min()
theta = 2 * np.pi * (range[0] + (range[1] - range[0]) * x / x.max())
X = np.empty((x.shape[0], 2), dtype=float)
X[:, 0] = np.sign(theta) * (1 - np.cos(theta))
X[:, 1] = np.sin(theta)
X *= x.max() / (2 * np.pi * (range[1] - range[0]))
return X | Make a 2D S-curve from a 1D vector |
def _update_classmethod(self, oldcm, newcm):
self._update(None, None, oldcm.__get__(0), newcm.__get__(0)) | Update a classmethod update. |
def add_translation_field(self, field, translation_field):
self.local_fields[field].add(translation_field)
self.fields[field].add(translation_field) | Add a new translation field to both fields dicts. |
def _one_exists(input_files):
for f in input_files:
if os.path.exists(f):
return True
return False | at least one file must exist for multiqc to run properly |
def _serialize_items(self, serializer, kind, items):
if self.request and self.request.query_params.get('hydrate_{}'.format(kind), False):
serializer = serializer(items, many=True, read_only=True)
serializer.bind(kind, self)
return serializer.data
else:
return [item.id for item in items] | Return serialized items or list of ids, depending on `hydrate_XXX` query param. |
def from_lal(cls, lalfs, copy=True):
from ..utils.lal import from_lal_unit
try:
unit = from_lal_unit(lalfs.sampleUnits)
except TypeError:
unit = None
channel = Channel(lalfs.name, unit=unit,
dtype=lalfs.data.data.dtype)
return cls(lalfs.data.data, channel=channel, f0=lalfs.f0,
df=lalfs.deltaF, epoch=float(lalfs.epoch),
dtype=lalfs.data.data.dtype, copy=copy) | Generate a new `FrequencySeries` from a LAL `FrequencySeries` of any type |
def _handle_table_row(self):
self._head += 2
if not self._can_recurse():
self._emit_text("|-")
self._head -= 1
return
self._push(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
padding = self._handle_table_style("\n")
style = self._pop()
self._head += 1
row = self._parse(contexts.TABLE_OPEN | contexts.TABLE_ROW_OPEN)
self._emit_table_tag("|-", "tr", style, padding, None, row, "")
self._head -= 1 | Parse as style until end of the line, then continue. |
def list_prefix(self):
attr = XhrController.extract_prefix_attr(request.json)
try:
prefixes = Prefix.list(attr)
except NipapError, e:
return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__})
return json.dumps(prefixes, cls=NipapJSONEncoder) | List prefixes and return JSON encoded result. |
def server_args(self, parsed_args):
args = {
arg: value
for arg, value in vars(parsed_args).items()
if not arg.startswith('_') and value is not None
}
args.update(vars(self))
return args | Return keyword args for Server class. |
def process_report(request):
if config.EMAIL_ADMINS:
email_admins(request)
if config.LOG:
log_report(request)
if config.SAVE:
save_report(request)
if config.ADDITIONAL_HANDLERS:
run_additional_handlers(request) | Given the HTTP request of a CSP violation report, log it in the required ways. |
def reset_formatter(self):
for handler in self.handlers:
formatter = self.get_formatter(handler)
handler.setFormatter(formatter) | Rebuild formatter for all handlers. |
def check_format(inputfile):
t = word_embedding.classify_format(inputfile)
if t == word_embedding._glove:
_echo_format_result('glove')
elif t == word_embedding._word2vec_bin:
_echo_format_result('word2vec-binary')
elif t == word_embedding._word2vec_text:
_echo_format_result('word2vec-text')
else:
assert not "Should not get here!" | Check format of inputfile. |
def _macs2_cmd(method="chip"):
if method.lower() == "chip":
cmd = ("{macs2} callpeak -t {chip_bam} -c {input_bam} {paired} "
" {genome_size} -n {name} -B {options}")
elif method.lower() == "atac":
cmd = ("{macs2} callpeak -t {chip_bam} --nomodel "
" {paired} {genome_size} -n {name} -B {options}"
" --nolambda --keep-dup all")
else:
raise ValueError("chip_method should be chip or atac.")
return cmd | Main command for macs2 tool. |
def sentences(ctx, input, output):
log.info('chemdataextractor.read.elements')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for raw_sentence in element.raw_sentences:
output.write(raw_sentence.strip())
output.write(u'\n') | Read input document, and output sentences. |
def _filter_records(self, records, rtype=None, name=None, content=None, identifier=None):
if not records:
return []
if identifier is not None:
LOGGER.debug('Filtering %d records by id: %s', len(records), identifier)
records = [record for record in records if record['id'] == identifier]
if rtype is not None:
LOGGER.debug('Filtering %d records by type: %s', len(records), rtype)
records = [record for record in records if record['type'] == rtype]
if name is not None:
LOGGER.debug('Filtering %d records by name: %s', len(records), name)
if name.endswith('.'):
name = name[:-1]
records = [record for record in records if name == record['name']]
if content is not None:
LOGGER.debug('Filtering %d records by content: %s', len(records), content.lower())
records = [record for record in records if
record['content'].lower() == content.lower()]
return records | Filter dns entries based on type, name or content. |
def merge_datetime(date, time='', date_format='%d/%m/%Y', time_format='%H:%M'):
day = datetime.strptime(date, date_format)
if time:
time = datetime.strptime(time, time_format)
time = datetime.time(time)
day = datetime.date(day)
day = datetime.combine(day, time)
return day | Create ``datetime`` object from date and time strings. |
def parse_isotime(timestr):
try:
return iso8601.parse_date(timestr)
except iso8601.ParseError as e:
raise ValueError(six.text_type(e))
except TypeError as e:
raise ValueError(six.text_type(e)) | Parse time from ISO 8601 format. |
def list_create(cls, datacenter=None, label=None):
options = {
'items_per_page': DISK_MAXLIST
}
if datacenter:
datacenter_id = int(Datacenter.usable_id(datacenter))
options['datacenter_id'] = datacenter_id
images = cls.safe_call('hosting.disk.list', options)
if not label:
return images
return [img for img in images
if label.lower() in img['name'].lower()] | List available disks for vm creation. |
def key_to_path(self, key):
return os.path.join(self.cache_dir, key[:2], key[2:4],
key[4:] + '.pkl') | Return the fullpath to the file with sha1sum key. |
def read_vint32(self):
result = 0
count = 0
while True:
if count > 4:
raise ValueError("Corrupt VarInt32")
b = self.read_byte()
result = result | (b & 0x7F) << (7 * count)
count += 1
if not b & 0x80:
return result | This seems to be a variable length integer ala utf-8 style |
def DocbookHtml(env, target, source=None, *args, **kw):
target, source = __extend_targets_sources(target, source)
__init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_HTML', ['html','docbook.xsl'])
__builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder)
result = []
for t,s in zip(target,source):
r = __builder.__call__(env, __ensure_suffix(t,'.html'), s, **kw)
env.Depends(r, kw['DOCBOOK_XSL'])
result.extend(r)
return result | A pseudo-Builder, providing a Docbook toolchain for HTML output. |
def _check_collections(self):
self.collection_sizes = {}
self.collection_total = 0
for col in self.db.collection_names(include_system_collections=False):
self.collection_sizes[col] = self.db.command('collstats', col).get(
'storageSize', 0)
self.collection_total += self.collection_sizes[col]
sorted_x = sorted(self.collection_sizes.items(),
key=operator.itemgetter(1))
for item in sorted_x:
self.log("Collection size (%s): %.2f MB" % (
item[0], item[1] / 1024.0 / 1024),
lvl=verbose)
self.log("Total collection sizes: %.2f MB" % (self.collection_total /
1024.0 / 1024)) | Checks node local collection storage sizes |
def decls(
self,
name=None,
function=None,
decl_type=None,
header_dir=None,
header_file=None,
recursive=None,
allow_empty=None):
return (
self._find_multiple(
self._impl_matchers[
scopedef_t.decl],
name=name,
function=function,
decl_type=decl_type,
header_dir=header_dir,
header_file=header_file,
recursive=recursive,
allow_empty=allow_empty)
) | returns a set of declarations, that are matched defined criteria |
def _post_call(atdepth, package, fqdn, result, entry, bound, ekey, argl, argd):
from time import time
if not atdepth and entry is not None:
ek = ekey
if result is not None:
retid = _tracker_str(result)
if result is not None and not bound:
ek = retid
entry["r"] = None
else:
entry["r"] = retid
name = fqdn.split('.')[-1]
if filter_name(fqdn, package, "time"):
entry["e"] = time() - entry["s"]
if filter_name(fqdn, package, "analyze"):
entry["z"] = analyze(fqdn, result, argl, argd)
msg.info("{}: {}".format(ek, entry), 1)
record(ek, entry)
return (ek, entry)
else:
return (None, None) | Finishes constructing the log and records it to the database. |
def register(name, klass):
if rapport.config.get_int("rapport", "verbosity") >= 1:
print("Registered plugin: {0}".format(name))
_PLUGIN_CATALOG[name] = klass | Add a plugin to the plugin catalog. |
def setup(self):
super().setup()
self._start_time = self.clock.time
self.initialize_simulants() | Setup the simulation and initialize its population. |
def post_build(self, pkt, pay):
if self.length is None:
pkt = pkt[:4] + chb(len(pay)) + pkt[5:]
return pkt + pay | This will set the ByteField 'length' to the correct value. |
def sso_api_list():
ssourls = []
def collect(u, prefixre, prefixname):
_prefixname = prefixname + [u._regex, ]
urldisplayname = " ".join(_prefixname)
if hasattr(u.urlconf_module, "_MODULE_MAGIC_ID_") \
and getattr(u.urlconf_module, "_MODULE_MAGIC_ID_") == MAGIC_ID:
ssourls.append(urldisplayname)
rooturl = import_by_path(settings.ROOT_URLCONF + ".urlpatterns")
traverse_urls(rooturl, resolverFunc=collect)
finalQ = Q()
for prefix in ssourls:
finalQ |= Q(name__startswith=prefix)
return APIEntryPoint.objects.filter(finalQ) | return sso related API |
def mousePressEvent(self, event):
super(OutputWindow, self).mousePressEvent(event)
if self._link_match:
path = self._link_match.group('url')
line = self._link_match.group('line')
if line is not None:
line = int(line) - 1
else:
line = 0
self.open_file_requested.emit(path, line) | Handle file link clicks. |
def _set_content(self, value, oktypes):
if value is None:
value = []
self._content = ListContainer(*value, oktypes=oktypes, parent=self) | Similar to content.setter but when there are no existing oktypes |
def _module_refs(obj, named):
if obj.__name__ == __name__:
return ()
return _dict_refs(obj.__dict__, named) | Return specific referents of a module object. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.