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.max_addr = si.lpMaximumApplicationAddress
else:
si = self.GetSystemInfo()
self.max_addr = 2147418111
self.min_addr = si.lpMinimumApplicationAddress | 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 ValueError:
t = parse(t)
elif isinstance(t, (float, int)):
return T
else:
raise TypeError('I only accept datetime or parseable date string')
ut1_unix[i] = forceutc(t).timestamp()
return ut1_unix | 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("Exception changing settings: %s", settings)
_LOGGER.warning(exc) | 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[key] = row[1].height if not np.isnan(row[1].height) else 0
name = row[1].gid
my_weather.data = weather_df
my_weather.timezone = weather_df.index.tz
my_weather.longitude = df.geom_point.iloc[0].x
my_weather.latitude = df.geom_point.iloc[0].y
my_weather.geometry = df.geom_point.iloc[0]
my_weather.data_height = data_height
my_weather.name = name
return my_weather | 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 Exception(msg % self.source_directory) | 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_email_size,
"limit_exceeded": total_size > self.max_email_size,
} | 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 + '-' +
self.instrument][band])
LOG.debug(self.filenames[band])
if not os.path.exists(self.filenames[band]):
LOG.warning("Couldn't find an existing file for this band: %s",
str(self.filenames[band])) | 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_specs):
func = specs[-1]
if 'reg' in specs:
reduced.update({reduc: self.region_calcs(data, func)})
else:
reduced.update({reduc: self._time_reduce(data, func)})
return OrderedDict(sorted(reduced.items(), key=lambda t: t[0])) | 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 == request.method and
options.get("strip_root_types", False)):
return JsonMode.GRR_ROOT_TYPES_STRIPPED_JSON_MODE
return JsonMode.GRR_JSON_MODE | 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('configure-aws'):
configure(service='aws')
if args.get('configure-dropbox'):
configure(service='dropbox')
if args.get('configure-swift'):
configure(service='swift')
if args.get('download_all'):
download_all() | 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",
)
ipopo.add(
rs.FACTORY_TRANSPORT_JABSORBRPC_IMPORTER,
"pelix-jabsorbrpc-importer",
) | 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.burst:
self.bucket = self.burst
self.last_update = now
self.mutex.release()
return self.bucket | 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]
if not self._key_binding_handlers:
self.unregister_message_handler('key-binding') | 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.interpolate:
extended_x_pos = ([.5 * pi - delta] + self._x_pos)
extended_vals = (serie.values[-1:] + serie.values)
serie.interpolated = list(
map(
tuple,
map(
reversed,
self._interpolate(extended_x_pos, extended_vals)
)
)
)
self._box.margin *= 2
self._rmin = self.zero
self._rmax = self._max or 1
self._box.set_polar_box(self._rmin, self._rmax)
self._self_close = True | 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 tweet {}".format(message) | 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:
self._logger.exception("Error parsing script streamed to device")
self.remote_bridge.script_error = exc
self.remote_bridge.error = 1
return [0] | 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=lambda_arn
)
self.create_event_permission(
lambda_name=lambda_name,
principal='sns.amazonaws.com',
source_arn=topic_arn
)
add_event_source(
event_source={
"arn": topic_arn,
"events": ["sns:Publish"]
},
lambda_arn=lambda_arn,
target_function="zappa.asynchronous.route_task",
boto_session=self.boto_session
)
return topic_arn | 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:
raise last
return validator | 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'][name] = schedule
if persist:
self.persist() | 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(self.request)
new_request['url'] = new_url
self._add_task('qsl', qs, new_request)
return self | 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,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
else:
return None | 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(self.ligname, 3)
cmd.origin(self.ligname) | 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)
elif color and prop in ['axis', 'major_ticks', 'minor_ticks',
'ticks']:
prop_set.stroke = 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)
return img | 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(serviceJob) | 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.CreateFile(filename,
win32file.GENERIC_READ,
win32file.FILE_SHARE_DELETE |
win32file.FILE_SHARE_READ |
win32file.FILE_SHARE_WRITE,
None,
win32file.OPEN_EXISTING,
0,
None)
detached_handle = handle.Detach()
file_descriptor = msvcrt.open_osfhandle(
detached_handle, os.O_RDONLY)
self._fh = open(file_descriptor, "rb")
self.filename = filename
self._fh.seek(0, os.SEEK_SET)
self.oldsize = 0 | 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:
if all_details:
_print_table_ontologies()
else:
_print2cols_ontologies()
while True:
printDebug(
"------------------\nSelect a model by typing its number: (enter=quit)",
"important")
var = input()
if var == "" or var == "q":
return None
else:
try:
_id = int(var)
ontouri = options[_id - 1]
printDebug(
"---------\nYou selected: " + ontouri + "\n---------",
"green")
return ontouri
except:
printDebug("Please enter a valid option.", "comment")
continue | 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_reference_name("data",
blacklist=list(data.keys())))
if editor.exec_():
var_name, clip_data = editor.get_data()
self.new_value(var_name, clip_data) | 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.encode("ascii").decode("ascii"))
except UnicodeDecodeError as msg:
raise ValueError("Found unicode character in template CSV line %s:\n%s" % (sinfo, str(msg))) | 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 not set, then --db-uri, --migrations and --app must be provided')
ctx.obj = {
'config': migrations_config
}
try:
ctx.obj['db'] = DBWrapper(ctx.obj['config']['db_uri'])
except Exception as e:
raise click.ClickException('Unable to connect to database, exception is "{0}"'.format(str(e))) | 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_versions, sources] | 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',
resource=('apps',),
data=payload
)
name = json.loads(r.content).get('name')
return self._h.apps.get(name) | 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_up[tunnel]:
self.logger.info('Shutting down tunnel {0}'.format(tunnel))
_srv.shutdown()
_srv.server_close()
if isinstance(_srv, _UnixStreamForwardServer):
try:
os.unlink(_srv.local_address)
except Exception as e:
self.logger.error('Unable to unlink socket {0}: {1}'
.format(self.local_address, repr(e)))
self.is_alive = False
if self.is_active:
self._transport.close()
self._transport.stop_thread()
self.logger.debug('Transport is closed') | 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/google.protobuf."):
wrapper_cls = self.__class__.WRAPPER_BY_TYPE[
converted_value.data_store_type]
wrapper_value = wrapper_cls()
wrapper_value.ParseFromString(result.value)
return converted_value.FromDatastoreValue(wrapper_value.value)
else:
return converted_value.FromSerializedString(result.value) | 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:
if rc_create is True:
self.db_status = "factory"
else:
self.db_status = "existing"
return True
try:
self.load_db()
except Exception as b:
_logger.debug("*** %s" % str(b))
self.recover_db(self.factory_json_db_path)
self.load_db()
self.db_status = "factory"
else:
self.db_status = "backup"
finally:
return True | " 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("Argument 'option' must be a string")
return section | 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 iswow64.value | 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.path.insert(0, dirname)
package = __import__(basename)
if path not in package.__path__:
raise Exception("Package was not imported from the requested path!")
sys.modules["dallinger_experiment"] = package
package.__package__ = "dallinger_experiment"
sys.path.pop(0) | 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.latest_value = self.latest_value - prev_value | 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))
print('No \'board\' field defined in project file')
sys.exit(1) | 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(repr(obj) + ' is not JSON serializable') | 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_abi_type(sub_type, v, 256)) for v in value])
elif is_bool_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_uint_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_int_type(abi_type):
return to_hex_twos_compliment(value, data_size)
elif is_address_type(abi_type):
return pad_hex(value, data_size)
elif is_bytes_type(abi_type):
if is_bytes(value):
return encode_hex(value)
else:
return value
elif is_string_type(abi_type):
return to_hex(text=value)
else:
raise ValueError(
"Unsupported ABI type: {0}".format(abi_type)
) | 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)
print('Encrypting data from "' + fileName + '"')
keys = secretKeys()
encData = encrypt_file(file, keys)
encMeta = encrypt_metadata(keys, fileName)
print('Uploading "' + fileName + '"')
secretUrl, fileId, fileNonce, owner_token = api_upload(service, encData, encMeta, keys)
if password != None:
print('Setting password')
sendclient.password.set_password(secretUrl, owner_token, password)
return secretUrl, fileId, owner_token | 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()
if month:
start = timezone.now() - relativedelta(day=1)
if year:
start = timezone.now() - relativedelta(day=1, month=1)
if days:
start = timezone.now() - relativedelta(days=days)
start -= relativedelta(hour=0, minute=0, second=0, microsecond=0)
return 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 out_file | 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:
return default | 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=axis, dx=dx[axis], method=self.method,
pad_mode=self.pad_mode,
pad_const=self.pad_const,
out=out_arr)
return out | 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.disconnect)
elif self.is_slave():
d = defer.maybeDeferred(self.factory.disconnect)
elif self._cmp_state(BrokerRole.disconnected):
return defer.succeed(None)
d.addCallback(defer.drop_param, self.become_disconnected)
return d | 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:
session = OAuth1Session(self.consumer_key,
self.consumer_secret,
access_token=self.session_token,
access_token_secret=self.session_secret)
r = session.get(self.profile + '/1/profiles_csv')
if r.status_code == 200 or r.status_code == 201:
if re.search('json', r.headers['content-type'], flags=0):
decoded = r.json()
else:
decoded = r.text
with open(profile_file, 'w') as profile:
profile.write(decoded) | 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.intersects(span)]
urls = [e.path for e in cache]
missing = SegmentList([span]) - cache_segments(cache)
if match:
match = re.compile(match)
urls = list(filter(match.search, urls))
if on_gaps == 'ignore' or not missing:
return urls
msg = 'Missing segments: \n{0}'.format('\n'.join(map(str, missing)))
if on_gaps == 'warn':
warnings.warn(msg)
return urls
raise RuntimeError(msg) | 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.height() - 31)
edit.setTags(sorted(self._attachments.keys()))
edit.show()
offset = 34 + edit.height()
else:
edit.hide()
offset = 34
self.setFixedHeight(h + offset)
self._toolbar.move(2, self.height() - 32)
else:
super(XCommentEdit, self).resizeToContents() | 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(
noload('network')
)
if template_id is not None:
group_qry = group_qry.filter(ResourceType.group_id==ResourceGroup.id,
TemplateType.id==ResourceType.type_id,
TemplateType.template_id==template_id)
group_res = db.DBSession.execute(group_qry.statement).fetchall()
groups = []
for g in group_res:
groups.append(JSONObject(g, extras=extras))
return groups | 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.