code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def iter_rows(self, start=None, end=None):
start = start or 0
end = end or self.nrows
for i in range(start, end):
yield self.iloc[i, :] | Iterate each of the Region rows in this region |
def debug(self, key):
return (not self.quiet and not self.debug_none and
(self.debug_all or getattr(self, "debug_%s" % key))) | Returns True if the debug setting is enabled. |
def logs(self):
for record in self.history:
if (record["when"] >= self.options.since.date
and record["when"] < self.options.until.date):
for change in record["changes"]:
yield record["who"], change | Return relevant who-did-what pairs from the bug history |
def _remap_tag_to_tag_id(cls, tag, new_data):
try:
value = new_data[tag]
except:
return
tag_id = tag + '_id'
try:
new_data[tag_id] = value['id']
except:
try:
new_data[tag_id] = value.id
except AttributeEr... | Remaps a given changed field from tag to tag_id. |
def task_detail(job_id=None, task_name=None):
jobs = get_jobs()
job = [job for job in jobs if str(job['job_id']) == job_id][0]
return render_template('task_detail.html',
job=job,
task_name=task_name,
task=[task for task in job[... | Show a detailed description of a specific task. |
def run(self, matches):
def _run(matches):
group_starting_pos = 0
for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)):
start_pos = current_pos + group_starting_pos
end_pos = current_pos + group_starti... | Run group functions over matches |
def value_for_key(membersuite_object_data, key):
key_value_dicts = {
d['Key']: d['Value'] for d
in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]}
return key_value_dicts[key] | Return the value for `key` of membersuite_object_data. |
def rotateX(self, angle):
rad = angle * math.pi / 180
cosa = math.cos(rad)
sina = math.sin(rad)
y = self.y * cosa - self.z * sina
z = self.y * sina + self.z * cosa
return Point3D(self.x, y, z) | Rotates the point around the X axis by the given angle in degrees. |
def send_invitation(request, project_id=None):
project = None
if project_id is not None:
project = get_object_or_404(Project, id=project_id)
if project is None:
if not is_admin(request):
return HttpResponseForbidden('<h1>Access Denied</h1>')
else:
if not project.can_e... | The logged in project leader wants to invite somebody to their project. |
def iter_components(self):
names = self.list_components()
for name in names:
yield self.get_component(name) | Iterate over all defined components yielding IOTile objects. |
def CollectionItemToClientPath(item, client_id=None):
if isinstance(item, rdf_flows.GrrMessage):
client_id = item.source
item = item.payload
elif isinstance(item, rdf_flow_objects.FlowResult):
client_id = item.client_id
item = item.payload
if client_id is None:
raise ValueError("Could not dete... | Converts given RDFValue to a ClientPath of a file to be downloaded. |
def choices(klass):
_choices = []
for attr in user_attributes(klass.Meta):
val = getattr(klass.Meta, attr)
setattr(klass, attr, val[0])
_choices.append((val[0], val[1]))
setattr(klass, 'CHOICES', tuple(_choices))
return klass | Decorator to set `CHOICES` and other attributes |
def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad):
ratio = clusteringmodel_gmm_good.score([parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value])
sigma = 0
return ratio, sigma | The ratio is smaller the better |
def check_cups_allowed(func):
@wraps(func)
def decorator(*args, **kwargs):
cups = kwargs.get('cups')
if (cups and current_user.is_authenticated()
and not current_user.allowed(cups, 'cups')):
return current_app.login_manager.unauthorized()
return func(*args, **... | Check if CUPS is allowd by token |
def Flow(self, flow_id):
return flow.FlowRef(
client_id=self.client_id, flow_id=flow_id, context=self._context) | Return a reference to a flow with a given id on this client. |
def _validate_args(self, args):
assert(args.bucket)
if args.subscribers:
for _subscriber in args.subscribers:
assert(isinstance(_subscriber, AsperaBaseSubscriber))
if (args.transfer_config):
assert(isinstance(args.transfer_config, AsperaConfig))
... | validate the user arguments |
def spawn_managed_host(config_file, manager, connect_on_start=True):
data = manager.request_host_status(config_file)
is_running = data['started']
if is_running:
host_status = json.loads(data['host']['output'])
logfile = data['host']['logfile']
else:
data = manager.start_host(conf... | Spawns a managed host, if it is not already running |
def input_to_phase(data, rate, data_type):
if data_type == "phase":
return data
elif data_type == "freq":
return frequency2phase(data, rate)
else:
raise Exception("unknown data_type: " + data_type) | Take either phase or frequency as input and return phase |
def setnx(self, key, value):
return self.set(key, value, nx=True) | Set the value of ``key`` to ``value`` if key doesn't exist |
def close(self):
close_command = StandardSend(self._address,
COMMAND_LIGHT_OFF_0X13_0X00)
self._send_method(close_command, self._close_message_received) | Send CLOSE command to device. |
def path_exists(self, path, follow_symlinks=True):
"test if path exists"
return (
self.file_exists(path, follow_symlinks)
or self.symlink_exists(path, follow_symlinks)
or self.directory_exists(path, follow_symlinks)
) | test if path exists |
def end_request(self):
if not self._chunked:
return
trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \
if self._trailer else None
ending = create_chunked_body_end(trailers)
self._protocol.writer.write(ending) | End the request body. |
def diffpow(self, x, rot=0):
N = len(x)
if rot:
x = rotate(x)
return sum(np.abs(x)**(2. + 4.*np.arange(N) / (N - 1.)))**0.5 | Diffpow test objective function |
def postprocessor(prediction):
prediction = prediction.data.numpy()[0]
top_predictions = prediction.argsort()[-3:][::-1]
return [labels[prediction] for prediction in top_predictions] | Map prediction tensor to labels. |
def order_module_dependencies(modules, parser):
result = []
for modk in modules:
if modk not in result:
result.append(modk)
recursed = list(result)
for i in range(len(result)):
module = result[i]
_process_module_order(parser, module, i, recursed)
return re... | Orders the specified list of modules based on their inter-dependencies. |
def remove_spin(self):
for site in self.sites:
new_sp = collections.defaultdict(float)
for sp, occu in site.species.items():
oxi_state = getattr(sp, "oxi_state", None)
new_sp[Specie(sp.symbol, oxidation_state=oxi_state)] += occu
site.species = ... | Removes spin states from a structure. |
def find_lt(a, x):
i = bisect.bisect_left(a, x)
if i:
return a[i-1]
raise ValueError | Find rightmost value less than x |
def build_tree(self, name, props, resource_name=None):
n = Node(name, props, resource_name)
prop_type_list = self._get_type_list(props)
if not prop_type_list:
return n
prop_type_list = sorted(prop_type_list)
for prop_name in prop_type_list:
if prop_name ==... | Build a tree of non-primitive typed dependency order. |
def after_scenario(context, scenario):
os.chdir(context.old_cwd)
context.directory.cleanup() | Leave the environment fresh after each scenario. |
async def list(source):
result = []
async with streamcontext(source) as streamer:
async for item in streamer:
result.append(item)
yield result | Generate a single list from an asynchronous sequence. |
def unpause_trial(self, trial):
assert trial.status == Trial.PAUSED, trial.status
self.set_status(trial, Trial.PENDING) | Sets PAUSED trial to pending to allow scheduler to start. |
def _wmi_to_ts(self, wmi_ts):
year, month, day, hour, minute, second, microsecond, tz = to_time(wmi_ts)
tz_delta = timedelta(minutes=int(tz))
if '+' in wmi_ts:
tz_delta = -tz_delta
dt = (
datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=s... | Convert a wmi formatted timestamp into an epoch. |
def find_link(cls, plot, link=None):
registry = Link.registry.items()
for source in plot.link_sources:
if link is None:
links = [
l for src, links in registry for l in links
if src is source or (src._plot_id is not None and
... | Searches a GenericElementPlot for a Link. |
def identify(self, obj):
hash_ = hash(obj)
type_id = self.to_id(type(obj))
return (hash_, TypeId(type_id)) | Return an Ident-shaped tuple for the given object. |
def umi_cycles(self) -> int:
return sum((int(re.sub(r'\D', '', op)) for op in self.umi_tokens)) | The number of cycles dedicated to UMI. |
def read(filename, loader=None, implicit_tuple=True, allow_errors=False):
with open(filename, 'r') as f:
return reads(f.read(),
filename=filename,
loader=loader,
implicit_tuple=implicit_tuple,
allow_errors=allow_errors) | Load but don't evaluate a GCL expression from a file. |
def sort_candidate_pairs(pairs, ice_controlling):
def pair_priority(pair):
return -candidate_pair_priority(pair.local_candidate,
pair.remote_candidate,
ice_controlling)
pairs.sort(key=pair_priority) | Sort a list of candidate pairs. |
def finite_datetimes(self, finite_start, finite_stop):
date_start = datetime(finite_start.year, finite_start.month, finite_start.day)
dates = []
for i in itertools.count():
t = date_start + timedelta(days=i)
if t >= finite_stop:
return dates
if... | Simply returns the points in time that correspond to turn of day. |
def info(self, i: int=None) -> str:
head = "[" + colors.blue("info") + "]"
if i is not None:
head = str(i) + " " + head
return head | Returns an info message |
def _add_custom_headers(self, dct):
if self.client_id is None:
self.client_id = os.environ.get("CLOUD_QUEUES_ID")
if self.client_id:
dct["Client-ID"] = self.client_id | Add the Client-ID header required by Cloud Queues |
def models_of_config(config):
resources = resources_of_config(config)
models = []
for resource in resources:
if not hasattr(resource, '__table__') and hasattr(resource, 'model'):
models.append(resource.model)
else:
models.append(resource)
return models | Return list of models from all resources in config. |
def run(host: Optional[str] = None, port: Optional[int] = None,
*args, **kwargs) -> None:
get_bot().run(host=host, port=port, *args, **kwargs) | Run the NoneBot instance. |
def cast_to_swimlane(self, value):
value = super(ListField, self).cast_to_swimlane(value)
if not value:
return None
value_ids = deepcopy(self._initial_value_to_ids_map)
return [self._build_list_item(item, value_ids[item].pop(0) if value_ids[item] else None) for item in value] | Restore swimlane format, attempting to keep initial IDs for any previously existing values |
def generateProjectFiles(self, dir=os.getcwd(), args=[]):
if os.path.exists(os.path.join(dir, 'Source')) == False:
Utility.printStderr('Pure Blueprint project, nothing to generate project files for.')
return
genScript = self.getGenerateScript()
projectFile = self.getProjectDescriptor(dir)
Utility.run([gen... | Generates IDE project files for the Unreal project in the specified directory |
def transcribe(decoder, audio_file, libdir=None):
decoder = get_decoder()
decoder.start_utt()
stream = open(audio_file, 'rb')
while True:
buf = stream.read(1024)
if buf:
decoder.process_raw(buf, False, False)
else:
break
decoder.end_utt()
return ev... | Decode streaming audio data from raw binary file on disk. |
def _strip(self, tokens, criteria, prop, rev=False):
num = len(tokens)
res = []
for i, token in enumerate(reversed(tokens) if rev else tokens):
if criteria(token) and num > i + 1:
res.insert(0, tokens.pop()) if rev else res.append(tokens.pop(0))
else:
... | Strip off contiguous tokens from the start or end of the list that meet the criteria. |
def annotate_diamond(fasta_path: 'path to fasta input',
diamond_path: 'path to Diamond taxonomic classification output'):
records = tictax.parse_seqs(fasta_path)
annotated_records = tictax.annotate_diamond(records, diamond_path)
SeqIO.write(annotated_records, sys.stdout, 'fasta') | Annotate fasta headers with taxonomy information from Diamond |
def convert_timestamp(timestamp):
timestamp = timestamp.strip()
chunk, millis = timestamp.split(',')
hours, minutes, seconds = chunk.split(':')
hours = int(hours)
minutes = int(minutes)
seconds = int(seconds)
seconds = seconds + hours * 60 * 60 + minutes * 60 + float(millis) / 1000
retur... | Convert an srt timestamp into seconds. |
def _parse_date_greek(dateString):
m = _greek_date_format_re.match(dateString)
if not m:
return
wday = _greek_wdays[m.group(1)]
month = _greek_months[m.group(3)]
rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \
{'wday': wday... | Parse a string according to a Greek 8-bit date format. |
def from_list(cls, database, key, data, clear=False):
arr = cls(database, key)
if clear:
arr.clear()
arr.extend(data)
return arr | Create and populate an Array object from a data dictionary. |
def load(self, filename=None):
DataFile.load(self, filename)
self.spectrum.filename = filename | Method was overriden to set spectrum.filename as well |
def selecttrue(table, field, complement=False):
return select(table, field, lambda v: bool(v), complement=complement) | Select rows where the given field evaluates `True`. |
def catch_timeout(f):
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except (requests.exceptions.ReadTimeout,
requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
log.warning("caught read timeout: %s", e)
self.connec... | A decorator to handle read timeouts from Twitter. |
def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None):
if not database:
database = DEFAULT_DB_ALIAS
if not changelog_file:
changelog_file = get_changelog_file_for_database(database)
try:
doc = minidom.parse(changelog_file)
except ExpatError as ex:
... | Finds best matching target migration file |
def mavset(self, mav, name, value, retries=3):
got_ack = False
while retries > 0 and not got_ack:
retries -= 1
mav.param_set_send(name.upper(), float(value))
tstart = time.time()
while time.time() - tstart < 1:
ack = mav.recv_match(type='PA... | set a parameter on a mavlink connection |
def fail(self, cmd, title=None, message=None):
if message is None:
message = self.handle_exc()
else:
message = escape(message)
self.db.send(
'Echo|%s' % dump({
'for': escape(title or '%s failed' % cmd),
'val': message
... | Send back captured exceptions |
def hasBidAsk(self) -> bool:
return (
self.bid != -1 and not isNan(self.bid) and self.bidSize > 0 and
self.ask != -1 and not isNan(self.ask) and self.askSize > 0) | See if this ticker has a valid bid and ask. |
def config(conf, confdefs):
conf = conf.copy()
for name, info in confdefs:
conf.setdefault(name, info.get('defval'))
return conf | Initialize a config dict using the given confdef tuples. |
def _get_alignment(self, pys_style):
alignment_styles = ["justification", "vertical_align", "angle"]
if not any(astyle in pys_style for astyle in alignment_styles):
return
def angle2xfrotation(angle):
if 0 <= angle <= 90:
return angle
elif -90 ... | Returns xlwt.Alignment for pyspread style |
def envelope(**kwargs):
e_oaipmh = Element(etree.QName(NS_OAIPMH, 'OAI-PMH'), nsmap=NSMAP)
e_oaipmh.set(etree.QName(NS_XSI, 'schemaLocation'),
'{0} {1}'.format(NS_OAIPMH, NS_OAIPMH_XSD))
e_tree = ElementTree(element=e_oaipmh)
if current_app.config['OAISERVER_XSL_URL']:
e_oaipmh.... | Create OAI-PMH envelope for response. |
def tci_path(self):
tci_paths = [
path for path in self.dataset._product_metadata.xpath(
".//Granule[@granuleIdentifier='%s']/IMAGE_FILE/text()"
% self.granule_identifier
) if path.endswith('TCI')
]
try:
tci_path = tci_paths[0]
... | Return the path to the granules TrueColorImage. |
def format_maxtime(self, maxtime):
minutes = maxtime.get("minutes", "0")
hours = maxtime.get("hours", "0")
days = maxtime.get("days", "0")
return u"{}: {} {}: {} {}: {}".format(
_("days"), days, _("hours"), hours, _("minutes"), minutes) | Formats the max time record to a days, hours, minutes string |
def _copy_database_data_clientside(self, tables, source, destination):
rows = self.get_database_rows(tables, source)
cols = self.get_database_columns(tables, source)
for r in list(rows.keys()):
assert r in tables
for c in list(cols.keys()):
assert c in tables
... | Copy the data from a table into another table. |
def getrefnames(idf, objname):
iddinfo = idf.idd_info
dtls = idf.model.dtls
index = dtls.index(objname)
fieldidds = iddinfo[index]
for fieldidd in fieldidds:
if 'field' in fieldidd:
if fieldidd['field'][0].endswith('Name'):
if 'reference' in fieldidd:
... | get the reference names for this object |
def format_decimal(self, altitude=None):
coordinates = [str(self.latitude), str(self.longitude)]
if altitude is None:
altitude = bool(self.altitude)
if altitude:
if not isinstance(altitude, string_compare):
altitude = 'km'
coordinates.append(se... | Format decimal degrees with altitude |
def zlines(f = None, sep = "\0", osep = None, size = 8192):
if f is None: f = sys.stdin
if osep is None: osep = sep
buf = ""
while True:
chars = f.read(size)
if not chars: break
buf += chars; lines = buf.split(sep); buf = lines.pop()
for line in lines: yield line + osep
if buf: yield buf | File iterator that uses alternative line terminators. |
def _clear_xauth(self):
os.remove(self._xauth_filename)
for varname in ['AUTHFILE', 'XAUTHORITY']:
if self._old_xauth[varname] is None:
del os.environ[varname]
else:
os.environ[varname] = self._old_xauth[varname]
self._old_xauth = None | Clear the Xauthority file and restore the environment variables. |
def smallest_signed_angle(source, target):
dth = target - source
dth = (dth + np.pi) % (2.0 * np.pi) - np.pi
return dth | Find the smallest angle going from angle `source` to angle `target`. |
def write_byte_data(self, address, register, value):
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | Write a byte value to a device's register. |
def inline(self):
tp_lines, tp_decl = self.get_decl_pair()
tp_lines = " ".join(tp_lines)
if tp_decl is None:
return tp_lines
else:
return "%s %s" % (tp_lines, tp_decl) | Return the declarator as a single line. |
def _calculate_sv_bins_gatk(data, cnv_group, size_calc_fn):
if dd.get_background_cnv_reference(data, "gatk-cnv"):
target_bed = gatkcnv.pon_to_bed(dd.get_background_cnv_reference(data, "gatk-cnv"), cnv_group.work_dir, data)
else:
target_bed = gatkcnv.prepare_intervals(data, cnv_group.region_file,... | Calculate structural variant bins using GATK4 CNV callers region or even intervals approach. |
def _server_error_message(url, message):
msg = _error_message.format(url=url, message=message)
log.error(msg)
return msg | Log and return a server error message. |
def element_not_contains(self, element_id, value):
elem = world.browser.find_elements_by_xpath(str(
'id("{id}")[contains(., "{value}")]'.format(
id=element_id, value=value)))
assert not elem, \
"Expected element not to contain the given text." | Assert provided content is not contained within an element found by ``id``. |
def protocol_names(self):
l = self.protocols()
retval = [str(k.name) for k in l]
return retval | Returns all registered protocol names |
def remove(self, tab_index):
_id = id(self.editor.tabs.widget(tab_index))
if _id in self.history:
self.history.remove(_id) | Remove the widget at the corresponding tab_index. |
def policy_error_scope(error, data):
err_path = list(error.absolute_path)
if err_path[0] != 'policies':
return error
pdata = data['policies'][err_path[1]]
pdata.get('name', 'unknown')
error.message = "Error on policy:{} resource:{}\n".format(
pdata.get('name', 'unknown'), pdata.get('... | Scope a schema error to its policy name and resource. |
def post_register_hook(self, verbosity=1):
if not getattr(settings, 'FLOW_DOCKER_DONT_PULL', False):
call_command('list_docker_images', pull=True, verbosity=verbosity) | Pull Docker images needed by processes after registering. |
def _filter_or_exclude(self, negate, *args, **kwargs):
from .models import Translation
new_args = self.get_cleaned_args(args)
new_kwargs = self.get_cleaned_kwargs(kwargs)
translation_args = self.get_translation_args(args)
translation_kwargs = self.get_translation_kwargs(kwargs)
... | Overrides default behavior to handle linguist fields. |
def _print_convergence(self):
if self.verbosity:
if (self.num_acquisitions == self.max_iter) and (not self.initial_iter):
print(' ** Maximum number of iterations reached **')
return 1
elif (self._distance_last_evaluations() < self.eps) and (not self.init... | Prints the reason why the optimization stopped. |
def getNodeByName(node, name):
if node is None:
raise Exception(
"Cannot search for a child '%s' in a None object" % (name,)
)
if not name:
raise Exception("Unspecified name to find node for.")
try:
childNode = node.xpath("*[local-name() = '%s']" % name)[0]
ex... | Get the first child node matching a given local name |
def pluralize(data_type):
known = {
u"address": u"addresses",
u"company": u"companies"
}
if data_type in known.keys():
return known[data_type]
else:
return u"%ss" % data_type | adds s to the data type or the correct english plural form |
def _find_new_partners(self):
open_channels = views.get_channelstate_open(
chain_state=views.state_from_raiden(self.raiden),
payment_network_id=self.registry_address,
token_address=self.token_address,
)
known = set(channel_state.partner_state.address for chann... | Search the token network for potential channel partners. |
def parse_command_line_args():
parser = argparse.ArgumentParser(description='PipApp. {}'.format(DESCRIPTION))
parser.add_argument(
'-d', '--dir',
metavar='DIR',
help='Root directory where to create new project files and dirs. Default is current directory.'
)
parser.add_argument(
... | parse command line args |
def collect_manifest_dependencies(manifest_data, lockfile_data):
output = {}
for dependencyName, dependencyConstraint in manifest_data.items():
output[dependencyName] = {
'source': 'example-package-manager',
'constraint': dependencyConstraint,
'available': [
... | Convert the manifest format to the dependencies schema |
def save(self, vs, filetype):
'Copy rows to the system clipboard.'
with tempfile.NamedTemporaryFile(suffix='.'+filetype) as temp:
saveSheets(temp.name, vs)
sync(1)
p = subprocess.Popen(
self.command,
stdin=open(temp.name, 'r', encoding=... | Copy rows to the system clipboard. |
def _check_index(self):
assert 0 <= self._index <= len(self._history) - 1
assert len(self._history) >= 1 | Check that the index is without the bounds of _history. |
def descendents(self):
for c in self.children:
yield c
for d in c.descendents:
yield d | Iterate over all descendent terms |
def distance_measure_common(A, func, alpha, R, k, epsilon):
x = relaxation_vectors(A, R, k, alpha)
d = func(x)
(rows, cols) = A.nonzero()
weak = np.where(rows == cols)[0]
d[weak] = 0
C = sparse.csr_matrix((d, (rows, cols)), shape=A.shape)
C.eliminate_zeros()
amg_core.apply_distance_filte... | Create strength of connection matrixfrom a function applied to relaxation vectors. |
def show_metering_label_rule(self, metering_label_rule, **_params):
return self.get(self.metering_label_rule_path %
(metering_label_rule), params=_params) | Fetches information of a certain metering label rule. |
def generate_kubernetes(self):
example = {}
example['spec'] = {}
example['spec']['containers'] = []
example['spec']['containers'].append({"name": '', "image": '', "env": []})
for key, value in self.spec.items():
if value['type'] in (dict, list):
kvalue... | Generate a sample kubernetes |
async def _get_protocol(self):
if self._protocol is None:
self._protocol = asyncio.Task(Context.create_client_context(
loop=self._loop))
return (await self._protocol) | Get the protocol for the request. |
def symbols():
symbols = []
for line in symbols_stream():
symbols.append(line.decode('utf-8').strip())
return symbols | Return a list of symbols. |
def open_datasets(path, backend_kwargs={}, no_warn=False, **kwargs):
if not no_warn:
warnings.warn("open_datasets is an experimental API, DO NOT RELY ON IT!", FutureWarning)
fbks = []
datasets = []
try:
datasets.append(open_dataset(path, backend_kwargs=backend_kwargs, **kwargs))
exce... | Open a GRIB file groupping incompatible hypercubes to different datasets via simple heuristics. |
def reload_webservers():
if env.verbosity:
print env.host, "RELOADING apache2"
with settings(warn_only=True):
a = sudo("/etc/init.d/apache2 reload")
if env.verbosity:
print '',a
if env.verbosity:
print env.host,"RELOADING nginx"
with settings(warn_only... | Reload apache2 and nginx |
def extract_image_size(self):
width, _ = self._extract_alternative_fields(
['Image ImageWidth', 'EXIF ExifImageWidth'], -1, int)
height, _ = self._extract_alternative_fields(
['Image ImageLength', 'EXIF ExifImageLength'], -1, int)
return width, height | Extract image height and width |
def lookup(img, **kwargs):
luts = np.array(kwargs['luts'], dtype=np.float32) / 255.0
def func(band_data, luts=luts, index=-1):
lut = luts[:, index] if len(luts.shape) == 2 else luts
band_data = band_data.clip(0, lut.size - 1).astype(np.uint8)
new_delay = dask.delayed(_lookup_delayed)(lut... | Assign values to channels based on a table. |
def extract_cookies(self, response, request):
_debug("extract_cookies: %s", response.info())
self._cookies_lock.acquire()
try:
self._policy._now = self._now = int(time.time())
for cookie in self.make_cookies(response, request):
if self._policy.set_ok(cooki... | Extract cookies from response, where allowable given the request. |
def on(self, group):
asyncio.ensure_future(self._send_led_on_off_request(group, 1),
loop=self._loop) | Turn the LED on for a group. |
def _list_superclasses(class_def):
superclasses = class_def.get('superClasses', [])
if superclasses:
return list(superclasses)
sup = class_def.get('superClass', None)
if sup:
return [sup]
else:
return [] | Return a list of the superclasses of the given class |
def mark_good(self, proxy):
if proxy not in self.proxies:
logger.warn("Proxy <%s> was not found in proxies list" % proxy)
return
if proxy not in self.good:
logger.debug("Proxy <%s> is GOOD" % proxy)
self.unchecked.discard(proxy)
self.dead.discard(proxy... | Mark a proxy as good |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.