code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def Open(self):
self.h_process = kernel32.OpenProcess(
PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, self.pid)
if not self.h_process:
raise process_error.ProcessError(
"Failed to open process (pid %d)." % self.pid)
if self.Is64bit():
si = self.GetNativeSystemInfo()
self... | Opens the process for reading. |
def to_str(self):
return etree.tostring(self.root, xml_declaration=True,
standalone=True,
pretty_print=True) | Returns a string of the SVG figure. |
def datetime2unix(T):
T = atleast_1d(T)
ut1_unix = empty(T.shape, dtype=float)
for i, t in enumerate(T):
if isinstance(t, (datetime, datetime64)):
pass
elif isinstance(t, str):
try:
ut1_unix[i] = float(t)
continue
except Val... | converts datetime to UT1 unix epoch time |
def _chain_forks(elements):
for element in reversed(elements):
if element.chain_fork:
return True
elif element.chain_join:
return False
return False | Detect whether a sequence of elements leads to a fork of streams |
def show_inputs(client, workflow):
for input_ in workflow.inputs:
click.echo(
'{id}: {default}'.format(
id=input_.id,
default=_format_default(client, input_.default),
)
)
sys.exit(0) | Show workflow inputs and exit. |
def _set_setting(self, settings):
for key, value in settings.items():
_validate_setting(key, value)
try:
self._settings_request(method="patch", json_data=settings)
self.update(settings_json=settings)
except SkybellException as exc:
_LOGGER.warning(... | Validate the settings and then send the PATCH request. |
def visit_listcomp(self, node, parent):
newnode = nodes.ListComp(node.lineno, node.col_offset, parent)
newnode.postinit(
self.visit(node.elt, newnode),
[self.visit(child, newnode) for child in node.generators],
)
return newnode | visit a ListComp node by returning a fresh instance of it |
def create_single_weather(df, rename_dc):
my_weather = weather.FeedinWeather()
data_height = {}
name = None
weather_df = pd.DataFrame(index=df.time_series.iloc[0].index)
for row in df.iterrows():
key = rename_dc[row[1].type]
weather_df[key] = row[1].time_series
data_height[ke... | Create an oemof weather object for the given geometry |
def wheel_metadata(self):
if not self.is_wheel:
raise TypeError("Requirement is not a wheel distribution!")
for distribution in find_distributions(self.source_directory):
return distribution
msg = "pkg_resources didn't find a wheel distribution in %s!"
raise Excep... | Get the distribution metadata of an unpacked wheel distribution. |
def load_bookmarks_without_file(filename):
bookmarks = _load_all_bookmarks()
return {k: v for k, v in bookmarks.items() if v[0] != filename} | Load all bookmarks but those from a specific file. |
def ajax_recalculate_size(self):
reports = self.get_reports()
attachments = self.get_attachments()
total_size = self.get_total_size(reports, attachments)
return {
"files": len(reports) + len(attachments),
"size": "%.2f" % total_size,
"limit": self.max_... | Recalculate the total size of the selected attachments |
def add_path(searchpath, encoding='utf-8', followlinks=False):
if not _has_jinja:
raise RuntimeError(_except_text)
_jload.add_loader(FileSystemLoader(searchpath, encoding, followlinks)) | Adds the given path to the template search routine |
def _get_bandfilenames(self):
for band in self.bandnames:
LOG.debug("Band = %s", str(band))
self.filenames[band] = os.path.join(self.path,
self.options[self.platform_name + '-' +
... | Get the instrument rsr filenames |
def place_market_order(self, side: Side, amount: Number) -> Order:
return self.place_order(side, OrderType.MARKET, amount) | Place a market order. |
def _generate_hash(self):
self.hash = None
str_hash = ''
for key, val in self._get_params().iteritems():
str_hash += smart_str(val)
str_hash += self._service.encryption_key
self.hash = hashlib.md5(str_hash).hexdigest() | Generates a hash based on the specific fields for the method. |
def _apply_all_time_reductions(self, data):
logging.info(self._print_verbose("Applying desired time-"
"reduction methods."))
reduc_specs = [r.split('.') for r in self.dtype_out_time]
reduced = {}
for reduc, specs in zip(self.dtype_out_time, reduc_... | Apply all requested time reductions to the data. |
def GetRequestFormatMode(request, method_metadata):
if request.path.startswith("/api/v2/"):
return JsonMode.PROTO3_JSON_MODE
if request.args.get("strip_type_info", ""):
return JsonMode.GRR_TYPE_STRIPPED_JSON_MODE
for http_method, unused_url, options in method_metadata.http_methods:
if (http_method == ... | Returns JSON format mode corresponding to a given request and method. |
def _calc_density(
x: np.ndarray,
y: np.ndarray,
):
xy = np.vstack([x,y])
z = gaussian_kde(xy)(xy)
min_z = np.min(z)
max_z = np.max(z)
scaled_z = (z-min_z)/(max_z-min_z)
return(scaled_z) | Function to calculate the density of cells in an embedding. |
def requestUnOrdered(self, key: str):
now = time.perf_counter()
if self.acc_monitor:
self.acc_monitor.update_time(now)
self.acc_monitor.request_received(key)
self.requestTracker.start(key, now) | Record the time at which request ordering started. |
def main():
args = docopt(__doc__, version=__version__)
if args.get('backup'):
backup_database(args)
if args.get('backup_all'):
backup_all(args)
if args.get('decrypt'):
decrypt_file(args.get('<path>'))
if args.get('configure'):
configure(service='all')
if args.get... | Main entry point for the mongo_backups CLI. |
def transport_jabsorbrpc(self):
self.context.install_bundle(
"pelix.remote.transport.jabsorb_rpc"
).start()
with use_waiting_list(self.context) as ipopo:
ipopo.add(
rs.FACTORY_TRANSPORT_JABSORBRPC_EXPORTER,
"pelix-jabsorbrpc-exporter",
... | Installs the JABSORB-RPC transport bundles and instantiates components |
def get(self):
now = time.time()
if self.bucket >= self.burst:
self.last_update = now
return self.bucket
bucket = self.rate * (now - self.last_update)
self.mutex.acquire()
if bucket > 1:
self.bucket += bucket
if self.bucket > self.b... | Get the number of tokens in bucket |
def unregister_key_binding(self, keydef):
binding_name = MPV._binding_name(keydef)
self.command('disable-section', binding_name)
self.command('define-section', binding_name, '')
if binding_name in self._key_binding_handlers:
del self._key_binding_handlers[binding_name]
... | Unregister a key binding by keydef. |
def tuple(self):
return tuple(getattr(self, k) for k in self.__class__.defaults) | Return values as a tuple. |
def _compute(self):
delta = 2 * pi / self._len if self._len else 0
self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)]
for serie in self.all_series:
serie.points = [(v, self._x_pos[i])
for i, v in enumerate(serie.values)]
if self.... | Compute r min max and labels position |
def post_tweet(user_id, message, additional_params={}):
url = "https://api.twitter.com/1.1/statuses/update.json"
params = { "status" : message }
params.update(additional_params)
r = make_twitter_request(url, user_id, params, request_type='POST')
print (r.text)
return "Successfully posted a t... | Helper function to post a tweet |
def registered(self, driver, frameworkId, masterInfo):
log.debug("Registered with framework ID %s", frameworkId.value)
self.frameworkId = frameworkId.value | Invoked when the scheduler successfully registers with a Mesos master |
def trigger_script(self):
if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED,):
return [1]
try:
self.remote_bridge.parsed_script = UpdateScript.FromBinary(self._device.script)
self.remote_bridge.status = BRIDGE_STATUS.IDLE
except Exception as exc:
... | Actually process a script. |
def create_async_sns_topic(self, lambda_name, lambda_arn):
topic_name = get_topic_name(lambda_name)
topic_arn = self.sns_client.create_topic(
Name=topic_name)['TopicArn']
self.sns_client.subscribe(
TopicArn=topic_arn,
Protocol='lambda',
Endpoint=la... | Create the SNS-based async topic. |
def OR(*fns):
if len(fns) < 2:
raise TypeError('At least two functions must be passed')
@chainable
def validator(v):
for fn in fns:
last = None
try:
return fn(v)
except ValueError as err:
last = err
if last:
... | Validate with any of the chainable valdator functions |
def remove_link_button(self):
if self.link is not None:
self.info_box.remove(self.link)
self.link.destroy()
self.link = None | Function removes link button from Run Window |
def modify_job(self, name, schedule, persist=True):
if name in self.opts['schedule']:
self.delete_job(name, persist)
elif name in self._get_schedule(include_opts=False):
log.warning("Cannot modify job %s, it's in the pillar!", name)
return
self.opts['schedule'... | Modify a job in the scheduler. Ignores jobs from pillar |
def clean_url(self):
raw_url = self.request['url']
parsed_url = urlparse(raw_url)
qsl = parse_qsl(parsed_url.query)
for qs in qsl:
new_url = self._join_url(parsed_url,
[i for i in qsl if i is not qs])
new_request = deepcopy(sel... | Only clean the url params and return self. |
def data(self):
if self._resources is None:
self.__init()
if "data" in self._resources:
url = self._url + "/data"
return _data.Data(url=url,
securityHandler=self._securityHandler,
initialize=True,
... | returns the reference to the data functions as a class |
def zoom_to_ligand(self):
cmd.center(self.ligname)
cmd.orient(self.ligname)
cmd.turn('x', 110)
if 'AllBSRes' in cmd.get_names("selections"):
cmd.zoom('%s or AllBSRes' % self.ligname, 3)
else:
if self.object_exists(self.ligname):
cmd.zoom(se... | Zoom in too ligand and its interactions. |
def _set_all_axis_color(self, axis, color):
for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks', 'title',
'labels']:
prop_set = getattr(axis.properties, prop)
if color and prop in ['title', 'labels']:
prop_set.fill = ValueRef(value=color)
... | Set axis ticks, title, labels to given color |
def __ensure_directory_in_path(filename: Path) -> None:
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory)) | Ensures that a file's directory is in the Python path. |
def _thumbnail_resize(self, image, thumb_size, crop=None, bg=None):
if crop == 'fit':
img = ImageOps.fit(image, thumb_size, Image.ANTIALIAS)
else:
img = image.copy()
img.thumbnail(thumb_size, Image.ANTIALIAS)
if bg:
img = self._bg_square(img, bg)
... | Performs the actual image cropping operation with PIL. |
def _startServiceJobs(self):
self.issueQueingServiceJobs()
while True:
serviceJob = self.serviceManager.getServiceJobsToStart(0)
if serviceJob is None:
break
logger.debug('Launching service job: %s', serviceJob)
self.issueServiceJob(service... | Start any service jobs available from the service manager |
def send_patch_document(self, event):
msg = self.protocol.create('PATCH-DOC', [event])
return self._socket.send_message(msg) | Sends a PATCH-DOC message, returning a Future that's completed when it's written out. |
def create_from_roi_data(cls, datafile):
data = np.load(datafile).flat[0]
roi = cls()
roi.load_sources(data['sources'].values())
return roi | Create an ROI model. |
def _open_file(self, filename):
if not self._os_is_windows:
self._fh = open(filename, "rb")
self.filename = filename
self._fh.seek(0, os.SEEK_SET)
self.oldsize = 0
return
import win32file
import msvcrt
handle = win32file.CreateF... | Open a file to be tailed |
def Backtrace(self, to_string=False):
if self.inferior.is_running:
res = self.inferior.Backtrace()
if to_string:
return res
print res
else:
logging.error('Not attached to any process.') | Get a backtrace of the current position. |
def action_listlocal(all_details=True):
" select a file from the local repo "
options = get_localontologies()
counter = 1
if not options:
printDebug(
"Your local library is empty. Use 'ontospy lib --bootstrap' to add some ontologies to it."
)
return
else:... | select a file from the local repo |
def resolve_content_type(type_resolvers, request):
for resolver in type_resolvers:
content_type = parse_content_type(resolver(request))
if content_type:
return content_type | Resolve content types from a request. |
def import_from_string(self, text, title=None):
data = self.model.get_data()
if not hasattr(data, "keys"):
return
editor = ImportWizard(self, text, title=title,
contents_title=_("Clipboard contents"),
varname=fix_refer... | Import data from string |
def _log_message(self, level, process_name, timeperiod, msg):
self.timetable.add_log_entry(process_name, timeperiod, msg)
self.logger.log(level, msg) | method performs logging into log file and Timetable's tree node |
def rm(self, path, cycle=';*'):
rdir = self
with preserve_current_directory():
dirname, objname = os.path.split(os.path.normpath(path))
if dirname:
rdir = rdir.Get(dirname)
rdir.Delete(objname + cycle) | Delete an object at `path` relative to this directory |
def _clean_string(v, sinfo):
if isinstance(v, (list, tuple)):
return [_clean_string(x, sinfo) for x in v]
else:
assert isinstance(v, six.string_types), v
try:
if hasattr(v, "decode"):
return str(v.decode("ascii"))
else:
return str(v... | Test for and clean unicode present in template CSVs. |
def symlink_to_bin(self, name, path):
self.__symlink_dir("bin", name, path)
os.chmod(os.path.join(self.root_dir, "bin", name), os.stat(path).st_mode | stat.S_IXUSR | stat.S_IRUSR) | Symlink an object at path to name in the bin folder. |
def window_size(self):
the_size = self.app_window.baseSize()
return the_size.width(), the_size.height() | returns render window size |
def _infer_precision(base_precision, bins):
for precision in range(base_precision, 20):
levels = [_round_frac(b, precision) for b in bins]
if algos.unique(levels).size == bins.size:
return precision
return base_precision | Infer an appropriate precision for _round_frac |
def register(self):
result = requests.post(urljoin(self.tracker, 'models'), data=json.dumps(self.metadata))
logger.debug("registered at server %s: %s", self.tracker, result)
self.metadata["tracker"] = result.json() | register model at tracking server |
def snaql_migration(ctx, db_uri, migrations, app, config):
if config:
migrations_config = _parse_config(config)
else:
if db_uri and migrations and app:
migrations_config = _generate_config(db_uri, migrations, app)
else:
raise click.ClickException('If --config is n... | Lightweight SQL Schema migration tool based on Snaql queries |
def sbo_version_source(self, slackbuilds):
sbo_versions, sources = [], []
for sbo in slackbuilds:
status(0.02)
sbo_ver = "{0}-{1}".format(sbo, SBoGrep(sbo).version())
sbo_versions.append(sbo_ver)
sources.append(SBoGrep(sbo).source())
return [sbo_ve... | Create sbo name with version |
def fieldspec_subset_by_name(
fieldspeclist: FIELDSPECLIST_TYPE,
fieldnames: Container[str]) -> FIELDSPECLIST_TYPE:
result = []
for x in fieldspeclist:
if x["name"] in fieldnames:
result.append(x)
return result | Returns a subset of the fieldspecs matching the fieldnames list. |
def new(self, name=None, stack='cedar', region=None):
payload = {}
if name:
payload['app[name]'] = name
if stack:
payload['app[stack]'] = stack
if region:
payload['app[region]'] = region
r = self._h._http_resource(
method='POST',
... | Creates a new app. |
def find_version():
version_file = read_file('__init__.py')
version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']',
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError('Unable to find version string.') | Only define version in one place |
def all_derived (type):
assert isinstance(type, basestring)
result = [type]
for d in __types [type]['derived']:
result.extend (all_derived (d))
return result | Returns type and all classes that derive from it, in the order of their distance from type. |
def _stop_transport(self):
try:
self._check_is_started()
except (BaseSSHTunnelForwarderError,
HandlerSSHTunnelForwarderError) as e:
self.logger.warning(e)
for _srv in self._server_list:
tunnel = _srv.local_address
if self.tunnel_is_... | Close the underlying transport when nothing more is needed |
def ConvertFromWireFormat(self, value, container=None):
result = AnyValue()
ReadIntoObject(value[2], 0, result)
if self._type is not None:
converted_value = self._type(container)
else:
converted_value = self._TypeFromAnyValue(result)
if result.type_url.startswith("type.googleapis.com/goo... | The wire format is an AnyValue message. |
def _mixed_join(iterable, sentinel):
iterator = iter(iterable)
first_item = next(iterator, sentinel)
if isinstance(first_item, bytes):
return first_item + b''.join(iterator)
return first_item + u''.join(iterator) | concatenate any string type in an intelligent way. |
def db_manager(self):
rc_create = self.create_db()
try:
self.load_db()
except Exception as e:
_logger.debug("*** %s" % str(e))
try:
self.recover_db(self.backup_json_db_path)
except Exception:
pass
else:
... | " Do series of DB operations. |
def qzordered(A,B,crit=1.0):
"Eigenvalues bigger than crit are sorted in the top-left."
TOL = 1e-10
def select(alpha, beta):
return alpha**2>crit*beta**2
[S,T,alpha,beta,U,V] = ordqz(A,B,output='real',sort=select)
eigval = abs(numpy.diag(S)/numpy.diag(T))
return [S,T,U,V,eigval] | Eigenvalues bigger than crit are sorted in the top-left. |
def nonver_name(self):
nv = self.as_version(None)
if not nv:
import re
nv = re.sub(r'-[^-]+$', '', self.name)
return nv | Return the non versioned name |
def _check_section_option(self, section, option):
if section is None:
section = self.DEFAULT_SECTION_NAME
elif not is_text_string(section):
raise RuntimeError("Argument 'section' must be a string")
if not is_text_string(option):
raise RuntimeError("Argum... | Private method to check section and option types |
def Is64bit(self):
if "64" not in platform.machine():
return False
iswow64 = ctypes.c_bool(False)
if IsWow64Process is None:
return False
if not IsWow64Process(self.h_process, ctypes.byref(iswow64)):
raise process_error.ProcessError("Error while calling IsWow64Process.")
return not... | Returns true if this is a 64 bit process. |
def initialize_experiment_package(path):
init_py = os.path.join(path, "__init__.py")
if not os.path.exists(init_py):
open(init_py, "a").close()
if sys.modules.get("dallinger_experiment") is not None:
return
dirname = os.path.dirname(path)
basename = os.path.basename(path)
sys.pat... | Make the specified directory importable as the `dallinger_experiment` package. |
def do_counter_conversion(self):
if self.is_counter:
if self._previous_counter_value is None:
prev_value = self.latest_value
else:
prev_value = self._previous_counter_value
self._previous_counter_value = self.latest_value
self.lates... | Update latest value to the diff between it and the previous value |
def read(self):
if not isfile(PROJECT_FILENAME):
print('Info: No {} file'.format(PROJECT_FILENAME))
return
board = self._read_board()
self.board = board
if not board:
print('Error: invalid {} project file'.format(
PROJECT_FILENAME))
... | Read the project config file |
def clear(self):
if not self.connected:
raise QueueNotConnectedError("Queue is not Connected")
self.__db.delete(self._key)
self.__db.delete(self._lock_key) | Clear all Tasks in the queue. |
def disconnect_network_gateway(self, gateway_id, body=None):
base_uri = self.network_gateway_path % gateway_id
return self.put("%s/disconnect_network" % base_uri, body=body) | Disconnect a network from the specified gateway. |
def output_package(dist):
if dist_is_editable(dist):
return '%s (%s, %s)' % (
dist.project_name,
dist.version,
dist.location,
)
return '%s (%s)' % (dist.project_name, dist.version) | Return string displaying package information. |
def hexstr(x, onlyasc=0, onlyhex=0, color=False):
x = bytes_encode(x)
_sane_func = sane_color if color else sane
s = []
if not onlyasc:
s.append(" ".join("%02X" % orb(b) for b in x))
if not onlyhex:
s.append(_sane_func(x))
return " ".join(s) | Build a fancy tcpdump like hex from bytes. |
def _encoder(self, obj):
return {'__class__': obj.__class__.__name__,
'ident': obj.ident,
'group': obj.group,
'name': obj.name,
'ctype': obj.ctype,
'pytype': obj.pytype,
'access': obj.access}
raise TypeError(... | Encode a toc element leaf-node |
def indentsize(line):
expline = string.expandtabs(line)
return len(expline) - len(string.lstrip(expline)) | Return the indent size, in spaces, at the start of a line of text. |
def writerow(self, row):
json_text = json.dumps(row)
if isinstance(json_text, bytes):
json_text = json_text.decode('utf-8')
self._out.write(json_text)
self._out.write(u'\n') | Write a single row. |
def hex_encode_abi_type(abi_type, value, force_size=None):
validate_abi_type(abi_type)
validate_abi_value(abi_type, value)
data_size = force_size or size_of_type(abi_type)
if is_array_type(abi_type):
sub_type = sub_type_of_array_type(abi_type)
return "".join([remove_0x_prefix(hex_encode_... | Encodes value into a hex string in format of abi_type |
def send_file(service, file, fileName=None, password=None, ignoreVersion=False):
if checkServerVersion(service, ignoreVersion=ignoreVersion) == False:
print('\033[1;41m!!! Potentially incompatible server version !!!\033[0m')
fileName = fileName if fileName != None else os.path.basename(file.name)
pr... | Encrypt & Upload a file to send and return the download URL |
def load_mode_validator(obs_mode, node):
nval = node.get('validator')
if nval is None:
pass
elif isinstance(nval, str):
obs_mode.validator = import_object(nval)
else:
raise TypeError('validator must be None or a string')
return obs_mode | Load observing mode validator |
def find_start(self, **kwargs):
week = kwargs.get('week', False)
month = kwargs.get('month', False)
year = kwargs.get('year', False)
days = kwargs.get('days', 0)
start = timezone.now() - relativedelta(months=1, day=1)
if week:
start = utils.get_week_start()
... | Determine the starting point of the query using CLI keyword arguments |
def to_debug_point(self, point: Union[Unit, Point2, Point3]) -> common_pb.Point:
if isinstance(point, Unit):
point = point.position3d
return common_pb.Point(x=point.x, y=point.y, z=getattr(point, "z", 0)) | Helper function for point conversion |
def sort_csv(in_file):
out_file = "%s.sort" % in_file
if not (os.path.exists(out_file) and os.path.getsize(out_file) > 0):
cl = ["sort", "-k", "1,1", in_file]
with open(out_file, "w") as out_handle:
child = subprocess.Popen(cl, stdout=out_handle)
child.wait()
return o... | Sort a CSV file by read name, allowing direct comparison. |
def get(self, key, default=None, with_age=False):
" Return the value for key if key is in the dictionary, else default. "
try:
return self.__getitem__(key, with_age)
except KeyError:
if with_age:
return default, None
else:
retur... | Return the value for key if key is in the dictionary, else default. |
def fill(text, delimiter="", width=70):
texts = []
for i in xrange(0, len(text), width):
t = delimiter.join(text[i:i + width])
texts.append(t)
return "\n".join(texts) | Wrap text with width per line |
def _WaitForStatusNotRunning(self):
time.sleep(2.0)
time_slept = 2.0
while self._status_is_running:
time.sleep(0.5)
time_slept += 0.5
if time_slept >= self._PROCESS_JOIN_TIMEOUT:
break | Waits for the status is running to change to false. |
def register(dlgr_id, snapshot=None):
try:
config.get("osf_access_token")
except KeyError:
pass
else:
osf_id = _create_osf_project(dlgr_id)
_upload_assets_to_OSF(dlgr_id, osf_id) | Register the experiment using configured services. |
def _call(self, x, out=None):
if out is None:
out = self.range.element()
x_arr = x.asarray()
ndim = self.domain.ndim
dx = self.domain.cell_sides
for axis in range(ndim):
with writable_array(out[axis]) as out_arr:
finite_diff(x_arr, axis=axi... | Calculate the spatial gradient of ``x``. |
def getDate():
_ltime = _time.localtime(_time.time())
date_str = _time.strftime('%Y-%m-%dT%H:%M:%S',_ltime)
return date_str | Returns a formatted string with the current date. |
def disconnect(self):
self.log("Disconnecting broker %r.", self)
d = defer.succeed(None)
if self.is_master():
if self.listener is not None:
d.addCallback(defer.drop_param, self.listener.stopListening)
d.addCallback(defer.drop_param, self.factory.discon... | This is called as part of the agency shutdown. |
def download_profile(self):
profile_file = os.path.join(self.output_path, 'profile.txt')
size = 0
try:
stats = os.stat(profile_file)
size = stats.st_size
except FileNotFoundError:
pass
if not os.path.isfile(profile_file) or size <= 100:
... | Download the profile from the database |
def find_urls(self, site, frametype, gpsstart, gpsend,
match=None, on_gaps='warn'):
span = Segment(gpsstart, gpsend)
cache = [e for e in self._read_ffl_cache(site, frametype) if
e.observatory == site and e.description == frametype and
e.segment.interse... | Find all files of the given type in the [start, end) GPS interval. |
def resizeToContents(self):
if self._toolbar.isVisible():
doc = self.document()
h = doc.documentLayout().documentSize().height()
offset = 34
edit = self._attachmentsEdit
if self._attachments:
edit.move(2, self.height() - edit.hei... | Resizes this toolbar based on the contents of its text. |
def list_config_agents_handling_hosting_device(
self, client, hosting_device_id, **_params):
resource_path = '/dev_mgr/hosting_devices/%s'
return client.get((resource_path + HOSTING_DEVICE_CFG_AGENTS) %
hosting_device_id, params=_params) | Fetches a list of config agents handling a hosting device. |
def add_router_to_l3_agent(self, l3_agent, body):
return self.post((self.agent_path + self.L3_ROUTERS) % l3_agent,
body=body) | Adds a router to L3 agent. |
def Load(file):
with open(file, 'rb') as file:
model = dill.load(file)
return model | Loads a model from specified file |
def verify(self, tool):
if os.path.isfile(tool['file']):
print('Toolbox: program exists = TOK :: ' + tool['file'])
return True
else:
print('Toolbox: program exists = FAIL :: ' + tool['file'])
return False | check that the tool exists |
def _segment(cls, segment):
return property(
fget=lambda x: cls._get_segment(x, segment),
fset=lambda x, v: cls._set_segment(x, segment, v),
) | Returns a property capable of setting and getting a segment. |
def _get_simple(self, name):
for item in reversed(self._stack):
result = _get_value(item, name)
if result is not _NOT_FOUND:
return result
raise KeyNotFoundError(name, "part missing") | Query the stack for a non-dotted name. |
def _get_groups(network_id, template_id=None):
extras = {'types':[], 'attributes':[]}
group_qry = db.DBSession.query(ResourceGroup).filter(
ResourceGroup.network_id==network_id,
ResourceGroup.status=='A').options(
... | Get all the resource groups in a network |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.