code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def line(line_def, **kwargs):
def replace(s):
return "(%s)" % ansi.aformat(s.group()[1:], attrs=["bold", ])
return ansi.aformat(
re.sub('@.?', replace, line_def),
**kwargs) | Highlights a character in the line |
async def on_raw_join(self, message):
await super().on_raw_join(message)
nick, metadata = self._parse_user(message.source)
channels = message.params[0].split(',')
if self.is_same_nick(self.nickname, nick):
if 'WHOX' in self._isupport and self._isupport['WHOX']:
await self.rawmsg('WHO', ','.join(channels), '%tnurha,{id}'.format(id=WHOX_IDENTIFIER))
else:
pass | Override JOIN to send WHOX. |
def tweets_default(*args):
query_type = settings.TWITTER_DEFAULT_QUERY_TYPE
args = (settings.TWITTER_DEFAULT_QUERY,
settings.TWITTER_DEFAULT_NUM_TWEETS)
per_user = None
if query_type == QUERY_TYPE_LIST:
per_user = 1
return tweets_for(query_type, args, per_user=per_user) | Tweets for the default settings. |
def watch_processes(self):
for process in list(self.processes):
self.watch_process(process)
self.processes = [p for p in self.processes if not p.get("dead")]
if self.stopping and len(self.processes) == 0:
self.stop_watch() | Manages the status of all the known processes |
def extractRuntime(runtime_dirs):
names = [str(item) for name in runtime_dirs for item in os.listdir(name)]
string = '\n'.join(names)
result = extract(RUNTIME_PATTERN, string, condense=True)
return result | Used to find the correct static lib name to pass to gcc |
def handle_join(self, connection, event):
nickname = self.get_nickname(event)
self.joined[nickname] = datetime.now() | Store join time for a nickname when it joins. |
def region_calcs(self, arr, func):
bool_pfull = (self.def_vert and self.dtype_in_vert ==
internal_names.ETA_STR and self.dtype_out_vert is False)
if bool_pfull:
pfull_data = self._get_input_data(_P_VARS[self.dtype_in_vert],
self.start_date,
self.end_date)
pfull = self._full_to_yearly_ts(
pfull_data, arr[internal_names.TIME_WEIGHTS_STR]
).rename('pressure')
reg_dat = {}
for reg in self.region:
if 'av' in self.dtype_in_time:
data_out = reg.ts(arr)
else:
method = getattr(reg, func)
data_out = method(arr)
if bool_pfull:
if func not in ['av', 'ts']:
method = reg.ts
coord = method(pfull) * 1e-2
data_out = data_out.assign_coords(
**{reg.name + '_pressure': coord}
)
reg_dat.update(**{reg.name: data_out})
return xr.Dataset(reg_dat) | Perform a calculation for all regions. |
def sparse_counts_map(self):
if self.hpx._ipix is None:
flatarray = self.data.flattern()
else:
flatarray = self.expanded_counts_map()
nz = flatarray.nonzero()[0]
data_out = flatarray[nz]
return (nz, data_out) | return a counts map with sparse index scheme |
def _make_wrapper(f):
@wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
wrapper._pecan = f._pecan.copy()
return wrapper | return a wrapped function with a copy of the _pecan context |
def copy_with(self, geometry=None, properties=None, assets=None):
def copy_assets_object(asset):
obj = asset.get("__object")
if hasattr("copy", obj):
new_obj = obj.copy()
if obj:
asset["__object"] = new_obj
geometry = geometry or self.geometry.copy()
new_properties = copy.deepcopy(self.properties)
if properties:
new_properties.update(properties)
if not assets:
assets = copy.deepcopy(self.assets)
map(copy_assets_object, assets.values())
else:
assets = {}
return self.__class__(geometry, new_properties, assets) | Generate a new GeoFeature with different geometry or preperties. |
def traverse(path, request, resource):
path = path.lstrip(b"/")
for component in path and path.split(b"/"):
if getattr(resource, "is_leaf", False):
break
resource = resource.get_child(name=component, request=request)
return resource | Traverse a root resource, retrieving the appropriate child for the request. |
def choice_default_add_related_pks(self, obj):
if not hasattr(obj, '_voter_pks'):
obj._voter_pks = obj.voters.values_list('pk', flat=True) | Add related primary keys to a Choice instance. |
def new_temp_file(directory=None, hint=''):
return tempfile.NamedTemporaryFile(
prefix='tmp-wpull-{0}-'.format(hint), suffix='.tmp', dir=directory) | Return a new temporary file. |
def renamed(self, source, dest):
filename = osp.abspath(to_text_string(source))
index = self.editorstacks[0].has_filename(filename)
if index is not None:
for editorstack in self.editorstacks:
editorstack.rename_in_data(filename,
new_filename=to_text_string(dest)) | File was renamed in file explorer widget or in project explorer |
def last_modified():
files = model.FileFingerprint.select().order_by(
orm.desc(model.FileFingerprint.file_mtime))
for file in files:
return file.file_mtime, file.file_path
return None, None | information about the most recently modified file |
def create_load():
load = upkey("load").setResultsName("action")
return (
load
+ Group(filename).setResultsName("load_file")
+ upkey("into")
+ table
+ Optional(throttle)
) | Create the grammar for the 'load' statement |
def _pool(input_layer, pool_fn, kernel, stride, edges, name):
input_layer.get_shape().assert_has_rank(4)
if input_layer.get_shape().ndims not in (None, 4):
raise ValueError('Pooling requires a rank 4 tensor: %s' %
input_layer.get_shape())
kernel = _kernel(kernel)
stride = _stride(stride)
size = [1, kernel[0], kernel[1], 1]
new_head = pool_fn(input_layer.tensor, size, stride, edges, name=name)
return input_layer.with_tensor(new_head) | Applies a pooling function. |
def do_logStream(self,args):
parser = CommandArgumentParser("logStream")
parser.add_argument(dest='logStream',help='logStream index.');
args = vars(parser.parse_args(args))
print "loading log stream {}".format(args['logStream'])
index = int(args['logStream'])
logStream = self.logStreams[index]
print "logStream:{}".format(logStream)
self.childLoop(AwsLogStream.AwsLogStream(logStream,self)) | Go to the specified log stream. logStream -h for detailed help |
def nonalpha_split(string):
return re.findall(r'[%s]+|[^%s]+' % (A, A), string, flags=FLAGS) | Split 'string' along any punctuation or whitespace. |
def handle_message(self, data):
msg = json.loads(data)
print("Dev server message: {}".format(msg))
handler_name = 'do_{}'.format(msg['type'])
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
result = handler(msg)
return {'ok': True, 'result': result}
else:
err = "Warning: Unhandled message: {}".format(msg)
print(err)
return {'ok': False, 'message': err} | When we get a message |
def convert_response_to_text(response):
errorlines = response.text.encode("utf-8").split("\n")
error = []
pattern = re.compile(r"<p.*>(.*)</p>")
for line in errorlines:
content_line = re.search(pattern, line)
if content_line:
error.append(content_line.group(1))
return ". ".join(error) | Convert a JSS HTML response to plaintext. |
def cli(ctx, ftdi_enable, ftdi_disable, serial_enable, serial_disable):
exit_code = 0
if ftdi_enable:
exit_code = Drivers().ftdi_enable()
elif ftdi_disable:
exit_code = Drivers().ftdi_disable()
elif serial_enable:
exit_code = Drivers().serial_enable()
elif serial_disable:
exit_code = Drivers().serial_disable()
else:
click.secho(ctx.get_help())
ctx.exit(exit_code) | Manage FPGA boards drivers. |
def subscribe(self, topic, channel):
self.send(nsq.subscribe(topic, channel)) | Subscribe to a nsq `topic` and `channel`. |
def adjustText(self):
pos = self.cursorPosition()
self.blockSignals(True)
super(XLineEdit, self).setText(self.formatText(self.text()))
self.setCursorPosition(pos)
self.blockSignals(False) | Updates the text based on the current format options. |
def _cmd_line_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--path',
help=('path to test files, '
'if not provided the script folder is used'))
parser.add_argument('--text_output',
action='store_true',
help='option to save the results to text file')
parser.add_argument('--format',
default='rst',
nargs='?',
choices=['rst', 'md'],
help='text formatting')
return parser | return a command line parser. It is used when generating the documentation |
def unload_module(self, module_name):
module = self.loaded_modules.get(module_name)
if not module:
_log.warning("Ignoring request to unload non-existant module '%s'",
module_name)
return False
module.stop(reloading=False)
del self.loaded_modules[module_name]
self.module_ordering.remove(module_name)
return True | Unload the specified module, if it is loaded. |
def createHorizonPolygons(self):
vertsTop = [[-1,0],[-1,1],[1,1],[1,0],[-1,0]]
self.topPolygon = Polygon(vertsTop,facecolor='dodgerblue',edgecolor='none')
self.axes.add_patch(self.topPolygon)
vertsBot = [[-1,0],[-1,-1],[1,-1],[1,0],[-1,0]]
self.botPolygon = Polygon(vertsBot,facecolor='brown',edgecolor='none')
self.axes.add_patch(self.botPolygon) | Creates the two polygons to show the sky and ground. |
def merge_text_nodes_on(self, node):
if not isinstance(node, ContainerNode) or not node.children:
return
new_children = []
text_run = []
for i in node.children:
if isinstance(i, Text) and not i.translatable:
text_run.append(i.escaped())
else:
if text_run:
new_children.append(EscapedText(''.join(text_run)))
text_run = []
new_children.append(i)
if text_run:
new_children.append(EscapedText(''.join(text_run)))
node.children = new_children
for i in node.children:
self.merge_text_nodes_on(i) | Merges all consecutive non-translatable text nodes into one |
def _check_roSet(orb,kwargs,funcName):
if not orb._roSet and kwargs.get('ro',None) is None:
warnings.warn("Method %s(.) requires ro to be given at Orbit initialization or at method evaluation; using default ro which is %f kpc" % (funcName,orb._ro),
galpyWarning) | Function to check whether ro is set, because it's required for funcName |
async def delete_user(name):
app_log.info("Deleting user %s", name)
await api_request('users/{}/server'.format(name), method='DELETE')
await api_request('users/{}'.format(name), method='DELETE') | Stop a user's server and delete the user |
def make_unistream(stream):
unistream = lambda: 'I am an unistream!'
for attr_name in dir(stream):
if not attr_name.startswith('_'):
setattr(unistream, attr_name, getattr(stream, attr_name))
unistream.write = lambda b: stream.write(
unescape(to_bytes(b, unistream.encoding), unistream.encoding)
)
return unistream | Make a stream which unescapes string literals before writes out. |
def claim(typ, **info):
stack = s_task.varget('provstack')
if len(stack) > 256:
raise s_exc.RecursionLimitHit(mesg='Hit global recursion limit')
stack.push(typ, **info)
try:
yield
finally:
stack.pop() | Add an entry to the provenance stack for the duration of the context |
def _translate(self, input_filename, output_filename):
command = [
self.translate_binary,
'-f', 'GeoJSON',
output_filename,
input_filename
]
result = self._runcommand(command)
self.log('Result (Translate): ', result, lvl=debug) | Translate KML file to geojson for import |
def _create_projects_file(project_name, data_source, items):
repositories = []
for item in items:
if item['origin'] not in repositories:
repositories.append(item['origin'])
projects = {
project_name: {
data_source: repositories
}
}
projects_file, projects_file_path = tempfile.mkstemp(prefix='track_items_')
with open(projects_file_path, "w") as pfile:
json.dump(projects, pfile, indent=True)
return projects_file_path | Create a projects file from the items origin data |
def clean_recently_opened_state_machines(self):
state_machine_paths = self.get_config_value('recently_opened_state_machines', [])
filesystem.clean_file_system_paths_from_not_existing_paths(state_machine_paths)
self.set_config_value('recently_opened_state_machines', state_machine_paths) | Remove state machines who's file system path does not exist |
def _nested_output(obj):
nested.__opts__ = __opts__
ret = nested.output(obj).rstrip()
return ret | Serialize obj and format for output |
def batch_start(job, input_args):
shared_files = ['ref.fa', 'ref.fa.amb', 'ref.fa.ann', 'ref.fa.bwt', 'ref.fa.pac', 'ref.fa.sa', 'ref.fa.fai']
shared_ids = {}
for fname in shared_files:
url = input_args[fname]
shared_ids[fname] = job.addChildJobFn(download_from_url, url, fname).rv()
job.addFollowOnJobFn(spawn_batch_jobs, shared_ids, input_args) | Downloads shared files that are used by all samples for alignment and places them in the jobstore. |
def safe_log_info(self, *info: str):
self.__do_safe(lambda: self.logger.info(*info)) | Log info failing silently on error |
def to_json(self):
self.logger.debug("Returning json info")
individual_info = {
'family_id': self.family,
'id':self.individual_id,
'sex':str(self.sex),
'phenotype': str(self.phenotype),
'mother': self.mother,
'father': self.father,
'extra_info': self.extra_info
}
return individual_info | Return the individual info in a dictionary for json. |
def backup_mediafiles(self):
extension = "tar%s" % ('.gz' if self.compress else '')
filename = utils.filename_generate(extension,
servername=self.servername,
content_type=self.content_type)
tarball = self._create_tar(filename)
if self.encrypt:
encrypted_file = utils.encrypt_file(tarball, filename)
tarball, filename = encrypted_file
self.logger.debug("Backup size: %s", utils.handle_size(tarball))
tarball.seek(0)
if self.path is None:
self.write_to_storage(tarball, filename)
else:
self.write_local_file(tarball, self.path) | Create backup file and write it to storage. |
def _walk_through(job_dir, display_progress=False):
serial = salt.payload.Serial(__opts__)
for top in os.listdir(job_dir):
t_path = os.path.join(job_dir, top)
for final in os.listdir(t_path):
load_path = os.path.join(t_path, final, '.load.p')
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
if not os.path.isfile(load_path):
continue
with salt.utils.files.fopen(load_path, 'rb') as rfh:
job = serial.load(rfh)
jid = job['jid']
if display_progress:
__jid_event__.fire_event(
{'message': 'Found JID {0}'.format(jid)},
'progress'
)
yield jid, job, t_path, final | Walk through the job dir and return jobs |
def add(self, obj=None, filename=None, data=None, info={}, html=None):
"Similar to FileArchive.add but accepts html strings for substitution"
initial_last_key = list(self._files.keys())[-1] if len(self) else None
if self._auto:
exporters = self.exporters[:]
for exporter in exporters:
self.exporters = [exporter]
super(NotebookArchive, self).add(obj, filename, data,
info=dict(info,
notebook=self.notebook_name))
new_last_key = list(self._files.keys())[-1] if len(self) else None
if new_last_key != initial_last_key:
self._replacements[new_last_key] = html
self.exporters = exporters | Similar to FileArchive.add but accepts html strings for substitution |
def list_docs(self, options=None):
if options is None:
raise ValueError("Please pass in an options dict")
default_options = {
"page": 1,
"per_page": 100,
"raise_exception_on_failure": False,
"user_credentials": self.api_key,
}
options = dict(list(default_options.items()) + list(options.items()))
raise_exception_on_failure = options.pop("raise_exception_on_failure")
resp = requests.get(
"%sdocs" % (self._url), params=options, timeout=self._timeout
)
if raise_exception_on_failure and resp.status_code != 200:
raise DocumentListingFailure(resp.content, resp.status_code)
return resp | Return list of previously created documents. |
def snapshot_identifier(prefix, db_identifier):
now = datetime.now()
return '%s-%s-%s' % (prefix, db_identifier, now.strftime('%Y-%m-%d-%H-%M')) | Return an identifier for a snapshot of a database or cluster. |
def delay_or_eager(self, *args, **kwargs):
return self.async_or_eager(args=args, kwargs=kwargs) | Wrap async_or_eager with a convenience signiture like delay |
def register_gatt_table(self):
services = [BLEService, TileBusService]
characteristics = [
NameChar,
AppearanceChar,
ReceiveHeaderChar,
ReceivePayloadChar,
SendHeaderChar,
SendPayloadChar,
StreamingChar,
HighSpeedChar,
TracingChar
]
self.bable.set_gatt_table(services, characteristics) | Register the GATT table into baBLE. |
def from_stub(cls, data, udas=None):
udas = udas or {}
fields = cls.FIELDS.copy()
fields.update(udas)
processed = {}
for k, v in six.iteritems(data):
processed[k] = cls._serialize(k, v, fields)
return cls(processed, udas) | Create a Task from an already deserialized dict. |
def ping(self, message=None):
return self.write(self.parser.ping(message), encode=False) | Write a ping ``frame``. |
def write_to_local(self, filepath_from, filepath_to, mtime_dt=None):
self.__log.debug("Writing R[%s] -> L[%s]." % (filepath_from,
filepath_to))
with SftpFile(self, filepath_from, 'r') as sf_from:
with open(filepath_to, 'wb') as file_to:
while 1:
part = sf_from.read(MAX_MIRROR_WRITE_CHUNK_SIZE)
file_to.write(part)
if len(part) < MAX_MIRROR_WRITE_CHUNK_SIZE:
break
if mtime_dt is None:
mtime_dt = datetime.now()
mtime_epoch = mktime(mtime_dt.timetuple())
utime(filepath_to, (mtime_epoch, mtime_epoch)) | Open a remote file and write it locally. |
def _StartStatusUpdateThread(self):
self._status_update_active = True
self._status_update_thread = threading.Thread(
name='Status update', target=self._StatusUpdateThreadMain)
self._status_update_thread.start() | Starts the status update thread. |
def strptime(cls, data, format, scale=DEFAULT_SCALE):
return cls(datetime.strptime(data, format), scale=scale) | Convert a string representation of a date to a Date object |
def foreach(self, argv, func):
if len(argv) == 0:
error("Command requires a search specifier.", 2)
for item in argv:
job = self.lookup(item)
if job is None:
error("Search job '%s' does not exist" % item, 2)
func(job) | Apply the function to each job specified in the argument vector. |
def remove(self, participant):
for topic, participants in list(self._participants_by_topic.items()):
self.unsubscribe(participant, topic)
if not participants:
del self._participants_by_topic[topic] | Unsubscribe this participant from all topic to which it is subscribed. |
def _subtoken_ids_to_tokens(self, subtokens):
escaped_tokens = "".join([
self.subtoken_list[s] for s in subtokens
if s < len(self.subtoken_list)])
escaped_tokens = escaped_tokens.split("_")
ret = []
for token in escaped_tokens:
if token:
ret.append(_unescape_token(token))
return ret | Convert list of int subtoken ids to a list of string tokens. |
def _check_image(self, image_nD):
self.input_image = load_image_from_disk(image_nD)
if len(self.input_image.shape) < 3:
raise ValueError('Input image must be atleast 3D')
if np.count_nonzero(self.input_image) == 0:
raise ValueError('Input image is completely filled with zeros! '
'Must be non-empty') | Sanity checks on the image data |
def clean_build(self):
import shutil
if self.build_fs.exists:
try:
shutil.rmtree(self.build_fs.getsyspath('/'))
except NoSysPathError:
pass | Delete the build directory and all ingested files |
def saveCertPem(self, cert, path):
with s_common.genfile(path) as fd:
fd.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) | Save a certificate in PEM format to a file outside the certdir. |
def rates_for_location(self, postal_code, location_deets=None):
request = self._get("rates/" + postal_code, location_deets)
return self.responder(request) | Shows the sales tax rates for a given location. |
def delete(self, id):
run = self.backend_store.get_run(id)
if not run:
return abort(http_client.NOT_FOUND,
message="Run {} doesn't exist".format(id))
if not self.manager.delete_run(run):
return abort(http_client.BAD_REQUEST,
message="Failed to find the task queue "
"manager of run {}.".format(id))
return '', http_client.NO_CONTENT | Delete run by id |
def to_match(self):
template = u'({field_name} BETWEEN {lower_bound} AND {upper_bound})'
return template.format(
field_name=self.field.to_match(),
lower_bound=self.lower_bound.to_match(),
upper_bound=self.upper_bound.to_match()) | Return a unicode object with the MATCH representation of this BetweenClause. |
def to_string(node):
with io.BytesIO() as f:
write([node], f)
return f.getvalue().decode('utf-8') | Convert a node into a string in NRML format |
def default_roles(*role_list):
def selectively_attach(func):
if not env.roles and not env.hosts:
return roles(*role_list)(func)
else:
if env.hosts:
func = hosts(*env.hosts)(func)
if env.roles:
func = roles(*env.roles)(func)
return func
return selectively_attach | Decorate task with these roles by default, but override with -R, -H |
def format_time_event_json(self):
time_event = {}
time_event['time'] = self.timestamp
if self.annotation is not None:
time_event['annotation'] = self.annotation.format_annotation_json()
if self.message_event is not None:
time_event['message_event'] = \
self.message_event.format_message_event_json()
return time_event | Convert a TimeEvent object to json format. |
def sanitize_mount(mount):
sanitized_mount = mount
if sanitized_mount.startswith('/'):
sanitized_mount = sanitized_mount[1:]
if sanitized_mount.endswith('/'):
sanitized_mount = sanitized_mount[:-1]
sanitized_mount = sanitized_mount.replace('//', '/')
return sanitized_mount | Returns a quote-unquote sanitized mount path |
def _move_before(xpath, target):
query = {'type': 'config',
'action': 'move',
'xpath': xpath,
'where': 'before',
'dst': target}
response = __proxy__['panos.call'](query)
return _validate_response(response) | Moves an xpath to the bottom of its section. |
def font_width(self):
return self.get_font_width(font_name=self.font_name, font_size=self.font_size) | Return the badge font width. |
def _send_dweet(payload, url, params=None, session=None):
data = json.dumps(payload)
headers = {'Content-type': 'application/json'}
return _request('post', url, data=data, headers=headers, params=params, session=session) | Send a dweet to dweet.io |
async def anext(self):
try:
f = next(self._iter)
except StopIteration as exc:
raise StopAsyncIteration() from exc
return await f | Fetch the next value from the iterable. |
def _set_up_object_manager(self):
if self.path == '/':
cond = 'k != \'/\''
else:
cond = 'k.startswith(\'%s/\')' % self.path
self.AddMethod(OBJECT_MANAGER_IFACE,
'GetManagedObjects', '', 'a{oa{sa{sv}}}',
'ret = {dbus.ObjectPath(k): objects[k].props ' +
' for k in objects.keys() if ' + cond + '}')
self.object_manager = self | Set up this mock object as a D-Bus ObjectManager. |
def _global_step(hparams):
step = tf.to_float(tf.train.get_or_create_global_step())
multiplier = hparams.optimizer_multistep_accumulate_steps
if not multiplier:
return step
tf.logging.info("Dividing global step by %d for multi-step optimizer."
% multiplier)
return step / tf.to_float(multiplier) | Adjust global step if a multi-step optimizer is used. |
def membership_request_notifications(user):
orgs = [o for o in user.organizations if o.is_admin(user)]
notifications = []
for org in orgs:
for request in org.pending_requests:
notifications.append((request.created, {
'id': request.id,
'organization': org.id,
'user': {
'id': request.user.id,
'fullname': request.user.fullname,
'avatar': str(request.user.avatar)
}
}))
return notifications | Notify user about pending membership requests |
def _GetBytes(partition_key):
if isinstance(partition_key, six.string_types):
return bytearray(partition_key, encoding='utf-8')
else:
raise ValueError("Unsupported " + str(type(partition_key)) + " for partitionKey.") | Gets the bytes representing the value of the partition key. |
def touching(self, other):
if self.top < other.bottom: return False
if self.bottom > other.top: return False
if self.left > other.right: return False
if self.right < other.left: return False
return True | Return true if this rectangle is touching the given shape. |
def _add_relations(self, relations):
for k, v in six.iteritems(relations):
self.d.relate(k, v) | Add all of the relations for the services. |
def _exclude(self, member):
if isinstance(member, string_types):
return None
for item in self.opts['spm_build_exclude']:
if member.name.startswith('{0}/{1}'.format(self.formula_conf['name'], item)):
return None
elif member.name.startswith('{0}/{1}'.format(self.abspath, item)):
return None
return member | Exclude based on opts |
def setup(app):
app.connect('html-page-context', add_html_link)
app.connect('build-finished', create_sitemap)
app.set_translator('html', HTMLTranslator)
app.sitemap_links = [] | Setup conntects events to the sitemap builder |
def do(self, arg):
".exchain - Show the SEH chain"
thread = self.get_thread_from_prefix()
print "Exception handlers for thread %d" % thread.get_tid()
print
table = Table()
table.addRow("Block", "Function")
bits = thread.get_bits()
for (seh, seh_func) in thread.get_seh_chain():
if seh is not None:
seh = HexDump.address(seh, bits)
if seh_func is not None:
seh_func = HexDump.address(seh_func, bits)
table.addRow(seh, seh_func)
print table.getOutput() | .exchain - Show the SEH chain |
def purge_old_logs(delete_before_days=7):
delete_before_date = timezone.now() - timedelta(days=delete_before_days)
logs_deleted = Log.objects.filter(
created_on__lte=delete_before_date).delete()
return logs_deleted | Purges old logs from the database table |
def init(opts):
NETWORK_DEVICE.update(salt.utils.napalm.get_device(opts))
DETAILS['initialized'] = True
return True | Opens the connection with the network device. |
def job_listener(event):
job_id = event.job.args[0]
if event.code == events.EVENT_JOB_MISSED:
db.mark_job_as_missed(job_id)
elif event.exception:
if isinstance(event.exception, util.JobError):
error_object = event.exception.as_dict()
else:
error_object = "\n".join(traceback.format_tb(event.traceback) +
[repr(event.exception)])
db.mark_job_as_errored(job_id, error_object)
else:
db.mark_job_as_completed(job_id, event.retval)
api_key = db.get_job(job_id)["api_key"]
result_ok = send_result(job_id, api_key)
if not result_ok:
db.mark_job_as_failed_to_post_result(job_id)
if "_TEST_CALLBACK_URL" in app.config:
requests.get(app.config["_TEST_CALLBACK_URL"]) | Listens to completed job |
async def get_update_info(self, from_network=True) -> SoftwareUpdateInfo:
if from_network:
from_network = "true"
else:
from_network = "false"
info = await self.services["system"]["getSWUpdateInfo"](network=from_network)
return SoftwareUpdateInfo.make(**info) | Get information about updates. |
def log_exception(exc_info=None, stream=None):
exc_info = exc_info or sys.exc_info()
stream = stream or sys.stderr
try:
from traceback import print_exception
print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream)
stream.flush()
finally:
exc_info = None | Log the 'exc_info' tuple in the server log. |
def add_cluster(
self,
name,
server=None,
certificate_authority_data=None,
**attrs):
if self.cluster_exists(name):
raise KubeConfError("Cluster with the given name already exists.")
clusters = self.get_clusters()
new_cluster = {'name': name, 'cluster':{}}
attrs_ = new_cluster['cluster']
if server is not None:
attrs_['server'] = server
if certificate_authority_data is not None:
attrs_['certificate-authority-data'] = certificate_authority_data
attrs_.update(attrs)
clusters.append(new_cluster) | Add a cluster to config. |
def cli(ctx, path, renku_home, use_external_storage):
ctx.obj = LocalClient(
path=path,
renku_home=renku_home,
use_external_storage=use_external_storage,
) | Check common Renku commands used in various situations. |
def create_session_entity_type(project_id, session_id, entity_values,
entity_type_display_name, entity_override_mode):
import dialogflow_v2 as dialogflow
session_entity_types_client = dialogflow.SessionEntityTypesClient()
session_path = session_entity_types_client.session_path(
project_id, session_id)
session_entity_type_name = (
session_entity_types_client.session_entity_type_path(
project_id, session_id, entity_type_display_name))
entities = [
dialogflow.types.EntityType.Entity(value=value, synonyms=[value])
for value in entity_values]
session_entity_type = dialogflow.types.SessionEntityType(
name=session_entity_type_name,
entity_override_mode=entity_override_mode,
entities=entities)
response = session_entity_types_client.create_session_entity_type(
session_path, session_entity_type)
print('SessionEntityType created: \n\n{}'.format(response)) | Create a session entity type with the given display name. |
def _detect_loop(self):
for source, dests in self.flowtable.items():
if source in dests:
raise conferr('Loops detected: %s --> %s' % (source, source)) | detect loops in flow table, raise error if being present |
def validate(self):
if not (isinstance(self.target_class, set) and
all(isinstance(x, six.string_types) for x in self.target_class)):
raise TypeError(u'Expected set of string target_class, got: {} {}'.format(
type(self.target_class).__name__, self.target_class))
for cls in self.target_class:
validate_safe_string(cls) | Ensure that the CoerceType block is valid. |
def list_to_1d_numpy(data, dtype=np.float32, name='list'):
if is_numpy_1d_array(data):
if data.dtype == dtype:
return data
else:
return data.astype(dtype=dtype, copy=False)
elif is_1d_list(data):
return np.array(data, dtype=dtype, copy=False)
elif isinstance(data, Series):
return data.values.astype(dtype)
else:
raise TypeError("Wrong type({0}) for {1}.\n"
"It should be list, numpy 1-D array or pandas Series".format(type(data).__name__, name)) | Convert data to 1-D numpy array. |
def _read_index_file(self):
param_file = os.path.join(self.index_dir, self.param_file)
with open(param_file) as f:
for line in f.readlines():
(name, fasta_file, index_file, line_size, total_size) = line.strip().split("\t")
self.size[name] = int(total_size)
self.fasta_file[name] = fasta_file
self.index_file[name] = index_file
self.line_size[name] = int(line_size) | read the param_file, index_dir should already be set |
def _forget_page(self, page):
pid = id(page)
if pid in self._page_refs:
self._page_refs[pid] = None | Remove a page from document page dict. |
def _repr_html_(self):
out = "<table class='taqltable' style='overflow-x:auto'>\n"
if not(all([colname[:4] == "Col_" for colname in self.colnames()])):
out += "<tr>"
for colname in self.colnames():
out += "<th><b>"+colname+"</b></th>"
out += "</tr>"
cropped = False
rowcount = 0
for row in self:
rowout = _format_row(row, self.colnames(), self)
rowcount += 1
out += rowout
if "\n" in rowout:
out += "\n"
out += "\n"
if rowcount >= 20:
cropped = True
break
if out[-2:] == "\n\n":
out = out[:-1]
out += "</table>"
if cropped:
out += ("<p style='text-align:center'>(" +
str(self.nrows()-20)+" more rows)</p>\n")
return out | Give a nice representation of tables in notebooks. |
def category_helper(form_tag=True):
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
helper.layout = Layout(
Row(
Column(
'title',
css_class='small-12'
),
),
Row(
Column(
'slug',
css_class='small-12 medium-10'
),
Column(
'order',
css_class='small-12 medium-2'
),
),
Row(
Column(
'description',
css_class='small-12'
),
),
Row(
Column(
'visible',
css_class='small-12'
),
),
ButtonHolderPanel(
Submit('submit', _('Submit')),
css_class='text-right',
),
)
return helper | Category's form layout helper |
def create_notebook(self, data):
r = requests.post('http://{0}/api/notebook'.format(self.zeppelin_url),
json=data)
self.notebook_id = r.json()['body'] | Create notebook under notebook directory. |
def cfunc(name, result, *args):
atypes = []
aflags = []
for arg in args:
atypes.append(arg[1])
aflags.append((arg[2], arg[0]) + arg[3:])
return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags)) | Build and apply a ctypes prototype complete with parameter flags. |
def property_schema(self, key):
schema = self.__class__.SCHEMA
plain_schema = schema.get("properties", {}).get(key)
if plain_schema is not None:
return plain_schema
pattern_properties = schema.get("patternProperties", {})
for pattern, pattern_schema in pattern_properties.items():
if match(pattern, key):
return pattern_schema
return schema.get("additionalProperties", True) | Lookup the schema for a specific property. |
def LL(n):
if (n<=0):return Context('0')
else:
LL1=LL(n-1)
r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1
r2 = LL1 - LL1 - LL1
return r1 + r2 | constructs the LL context |
def cast(keys, data):
matrix = Matrix()
matrix.keys = keys
matrix.data = data
return matrix | Cast a set of keys and an array to a Matrix object. |
def _GetTimelineStatEntriesRelDB(api_client_id, file_path, with_history=True):
path_type, components = rdf_objects.ParseCategorizedPath(file_path)
client_id = str(api_client_id)
try:
root_path_info = data_store.REL_DB.ReadPathInfo(client_id, path_type,
components)
except db.UnknownPathError:
return
path_infos = []
for path_info in itertools.chain(
[root_path_info],
data_store.REL_DB.ListDescendentPathInfos(client_id, path_type,
components),
):
if path_info.directory:
continue
categorized_path = rdf_objects.ToCategorizedPath(path_info.path_type,
path_info.components)
if with_history:
path_infos.append(path_info)
else:
yield categorized_path, path_info.stat_entry, path_info.hash_entry
if with_history:
hist_path_infos = data_store.REL_DB.ReadPathInfosHistories(
client_id, path_type, [tuple(pi.components) for pi in path_infos])
for path_info in itertools.chain(*hist_path_infos.itervalues()):
categorized_path = rdf_objects.ToCategorizedPath(path_info.path_type,
path_info.components)
yield categorized_path, path_info.stat_entry, path_info.hash_entry | Gets timeline entries from REL_DB. |
def make_new_semver(current_semver, all_triggers, **overrides):
new_semver = {}
bumped = False
for sig_fig in SemVerSigFig:
value = getattr(current_semver, sig_fig)
override = overrides.get(sig_fig)
if override is not None:
new_semver[sig_fig] = override
if int(override) > int(value):
bumped = True
elif bumped:
new_semver[sig_fig] = "0"
elif sig_fig in all_triggers:
new_semver[sig_fig] = str(int(value) + 1)
bumped = True
else:
new_semver[sig_fig] = value
return SemVer(**new_semver) | Defines how to increment semver based on which significant figure is triggered |
def _thumbnail_div(target_dir, src_dir, fname, snippet, is_backref=False,
check=True):
thumb, _ = _find_image_ext(
os.path.join(target_dir, 'images', 'thumb',
'sphx_glr_%s_thumb.png' % fname[:-3]))
if check and not os.path.isfile(thumb):
raise RuntimeError('Could not find internal sphinx-gallery thumbnail '
'file:\n%s' % (thumb,))
thumb = os.path.relpath(thumb, src_dir)
full_dir = os.path.relpath(target_dir, src_dir)
thumb = thumb.replace(os.sep, "/")
ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')
template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE
return template.format(snippet=escape(snippet),
thumbnail=thumb, ref_name=ref_name) | Generates RST to place a thumbnail in a gallery |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.