Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
8,000 | def bed_to_bedpe(bedfile, bedpefile, pairsbedfile=None, matesfile=None, ca=False, strand=False):
fp = must_open(bedfile)
fw = must_open(bedpefile, "w")
if pairsbedfile:
fwpairs = must_open(pairsbedfile, "w")
clones = defaultdict(list)
for row in fp:
b = BedLine(row)
nam... | This converts the bedfile to bedpefile, assuming the reads are from CA. |
8,001 | def get_repository(self, entity_cls):
entity_record = self._get_entity_by_class(entity_cls)
provider = self.get_provider(entity_record.provider_name)
return provider.get_repository(entity_record.entity_cls) | Retrieve a Repository for the Model with a live connection |
8,002 | def list_upgrades(refresh=True, root=None, **kwargs):
*
if refresh:
refresh_db(root)
ret = dict()
cmd = []
if in kwargs:
repo_name = kwargs[]
if not isinstance(repo_name, six.string_types):
repo_name = six.text_type(repo_name)
cmd.extend([, repo_name])
... | List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.list... |
8,003 | def update_device(self, device_id, **kwargs):
api = self._get_api(device_directory.DefaultApi)
device = Device._create_request_map(kwargs)
body = DeviceDataPostRequest(**device)
return Device(api.device_update(device_id, body)) | Update existing device in catalog.
.. code-block:: python
existing_device = api.get_device(...)
updated_device = api.update_device(
existing_device.id,
certificate_fingerprint = "something new"
)
:param str device_id: The ID of the d... |
8,004 | def plot_trajectory_with_elegans(
obs, width=350, height=350, config=None, grid=True, wireframe=False,
max_count=10, camera_position=(-22, 23, 32), camera_rotation=(-0.6, 0.5, 0.6),
plot_range=None):
config = config or {}
from IPython.core.display import display, HTML
color_sc... | Generate a plot from received instance of TrajectoryObserver and show it
on IPython notebook.
Parameters
----------
obs : TrajectoryObserver
TrajectoryObserver to render.
width : float, default 350
Width of the plotting area.
height : float, default 350
Height of the plo... |
8,005 | def load_configuration_from_text_file(register, configuration_file):
logging.info("Loading configuration: %s" % configuration_file)
register.configuration_file = configuration_file
config_dict = parse_global_config(register.configuration_file)
if in config_dict:
flavor = config_d... | Loading configuration from text files to register object
Parameters
----------
register : pybar.fei4.register object
configuration_file : string
Full path (directory and filename) of the configuration file. If name is not given, reload configuration from file. |
8,006 | def save_firefox_profile(self, remove_old=False):
self.logger.info("Saving profile from %s to %s" % (self._profile.path, self._profile_path))
if remove_old:
if os.path.exists(self._profile_path):
try:
shutil.rmtree(self._profile_path)
... | Function to save the firefox profile to the permanant one |
8,007 | def _compute_betas_gwr(y, x, wi):
xT = (x * wi).T
xtx = np.dot(xT, x)
xtx_inv_xt = linalg.solve(xtx, xT)
betas = np.dot(xtx_inv_xt, y)
return betas, xtx_inv_xt | compute MLE coefficients using iwls routine
Methods: p189, Iteratively (Re)weighted Least Squares (IWLS),
Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2002).
Geographically weighted regression: the analysis of spatially varying relationships. |
8,008 | def enable_audit_device(self, device_type, description=None, options=None, path=None):
if path is None:
path = device_type
params = {
: device_type,
: description,
: options,
}
api_path = .format(path=path)
return self._... | Enable a new audit device at the supplied path.
The path can be a single word name or a more complex, nested path.
Supported methods:
PUT: /sys/audit/{path}. Produces: 204 (empty body)
:param device_type: Specifies the type of the audit device.
:type device_type: str | uni... |
8,009 | def check_timeseries_id(self, dataset):
timeseries_ids = dataset.get_variables_by_attributes(cf_role=)
if not timeseries_ids:
return
test_ctx = TestCtx(BaseCheck.MEDIUM, )
timeseries_variable = timeseries_ids[0]
test_ctx.assert_true(
geta... | Checks that if a variable exists for the time series id it has the appropriate attributes
:param netCDF4.Dataset dataset: An open netCDF dataset |
8,010 | def _AlignDecodedDataOffset(self, decoded_data_offset):
self._file_object.seek(0, os.SEEK_SET)
self._decoder = self._GetDecoder()
self._decoded_data = b
encoded_data_offset = 0
encoded_data_size = self._file_object.get_size()
while encoded_data_offset < encoded_data_size:
read_coun... | Aligns the encoded file with the decoded data offset.
Args:
decoded_data_offset (int): decoded data offset. |
8,011 | def notify_slack(title, content, attachment_color="
channel=None, mention_user=None, **kwargs):
import slackclient
cfg = Config.instance()
if not token:
token = cfg.get_expanded("notifications", "slack_token")
if not channel:
channel = cfg.get_expanded("notific... | Sends a slack notification and returns *True* on success. The communication with the slack API
might have some delays and is therefore handled by a thread. The format of the notification
depends on *content*. If it is a string, a simple text notification is sent. Otherwise, it
should be a dictionary whose f... |
8,012 | def FileEntryExistsByPathSpec(self, path_spec):
location = getattr(path_spec, , None)
if location is None:
return False
is_device = False
if platform.system() == :
try:
is_device = pysmdev.check_device(location)
except IOError as exception:
... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise. |
8,013 | def stft(func=None, **kwparams):
if func is None:
cfi = chain.from_iterable
mix_dict = lambda *dicts: dict(cfi(iteritems(d) for d in dicts))
result = lambda f=None, **new_kws: stft(f, **mix_dict(kwparams, new_kws))
return result
@tostream
@wraps(func)
def wrapper(sig, **kwargs):
kw... | Short Time Fourier Transform block processor / phase vocoder wrapper.
This function can be used in many ways:
* Directly as a signal processor builder, wrapping a spectrum block/grain
processor function;
* Directly as a decorator to a block processor;
* Called without the ``func`` parameter for a partial ... |
8,014 | def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []):
parent_feature = validate_feature (feature_name)
subfeature_name = __get_subfeature_name (subfeature, value_string)
if subfeature_name in __all_features[feature_name].subfeatures:
message = " already dec... | Declares a subfeature.
feature_name: Root feature that is not a subfeature.
value_string: An optional value-string specifying which feature or
subfeature values this subfeature is specific to,
if any.
subfeature: The name of the subfeature ... |
8,015 | def select_params_from_section_schema(section_schema, param_class=Param,
deep=False):
for name, value in inspect.getmembers(section_schema):
if name.startswith("__") or value is None:
continue
elif inspect.isclass(value) and deep:
... | Selects the parameters of a config section schema.
:param section_schema: Configuration file section schema to use.
:return: Generator of params |
8,016 | def _to_repeatmasker_string(pairwise_alignment, column_width=DEFAULT_COL_WIDTH,
m_name_width=DEFAULT_MAX_NAME_WIDTH):
s1 = pairwise_alignment.s1
s2 = pairwise_alignment.s2
s1_neg = not s1.is_positive_strand()
s2_neg = not s2.is_positive_strand()
size = pairwise_alignment.size()... | generate a repeatmasker formated representation of this pairwise alignment.
:param column_width: number of characters to output per line of alignment
:param m_name_width: truncate names on alignment lines to this length
(set to None for no truncation) |
8,017 | def _make_y_title(self):
if self._y_title:
yc = self.margin_box.top + self.view.height / 2
for i, title_line in enumerate(self._y_title, 1):
text = self.svg.node(
self.nodes[],
,
class_=,
... | Make the Y-Axis title |
8,018 | def check_bottleneck(text):
err = "mixed_metaphors.misc.bottleneck"
msg = u"Mixed metaphor — bottles with big necks are easy to pass through."
list = [
"biggest bottleneck",
"big bottleneck",
"large bottleneck",
"largest bottleneck",
"world-wide bottleneck",
... | Avoid mixing metaphors about bottles and their necks.
source: Sir Ernest Gowers
source_url: http://bit.ly/1CQPH61 |
8,019 | def beacon_link(variant_obj, build=None):
build = build or 37
url_template = ("https://beacon-network.org/
"chrom={this[chromosome]}&allele={this[alternative]}&"
"ref={this[reference]}&rs=GRCh37")
return url_template.format(this=variant_... | Compose link to Beacon Network. |
8,020 | def do_ams_put(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx"):
min_ds = dsversion_min
content_acceptformat = json_acceptformat
if rformat == "json_only":
min_ds = ds_min_version
content_acceptformat = json_only_acceptformat
headers = {"Content-Ty... | Do a AMS HTTP PUT request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services Content Body.
access_token (str): A valid Azure authentication token.
rformat (str): A req... |
8,021 | def expand_macros(raw_text, macros):
includes = {}
result = []
pattern = re.compile("
ipattern = re.compile("
for line in raw_text.split("\n"):
line = string.Template(line).safe_substitute(macros)
result.append(line)
if line.startswith("
mat... | this gets called before the sakefile is parsed. it looks for
macros defined anywhere in the sakefile (the start of the line
is '#!') and then replaces all occurences of '$variable' with the
value defined in the macro. it then returns the contents of the
file with the macros expanded. |
8,022 | def add_group_member(self, grp_name, user):
self.project_service.set_auth(self._token_project)
self.project_service.add_group_member(grp_name, user) | Add the given user to the named group.
Both group and user must already exist for this to succeed.
Args:
name (string): Name of group.
user_name (string): User to add to group.
Raises:
requests.HTTPError on failure. |
8,023 | def url(self):
if not self._url[2].endswith():
self._url[2] +=
return RestURL.url.__get__(self) | The URL as a string of the resource. |
8,024 | def _set_session_style(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 2}, u: {: 0}, u: ... | Setter method for session_style, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/session_style (session-reservation-style)
If this variable is read-only (config: false) in the
source YANG file, then _set_session_style is considered as a private
method. Backends looking to populate this variable sho... |
8,025 | def _ostaunicode(src):
if have_py_3:
bytename = src
else:
bytename = src.decode()
try:
enc = bytename.encode()
encbyte = b
except (UnicodeEncodeError, UnicodeDecodeError):
enc = bytename.encode()
encbyte = b
return encbyte + enc | Internal function to create an OSTA byte string from a source string. |
8,026 | def check_layer(layer, has_geometry=True):
if is_vector_layer(layer) or is_raster_layer(layer):
if not layer.isValid():
raise InvalidLayerError(
% layer.publicSource())
if is_vector_layer(layer):
sub_layers = layer.dataProvider().subLayers()
... | Helper to check layer validity.
This function wil; raise InvalidLayerError if the layer is invalid.
:param layer: The layer to check.
:type layer: QgsMapLayer
:param has_geometry: If the layer must have a geometry. True by default.
If it's a raster layer, we will no check this parameter. If w... |
8,027 | def cli(env, columns, sortby, volume_id):
block_manager = SoftLayer.BlockStorageManager(env.client)
access_list = block_manager.get_block_volume_access_list(
volume_id=volume_id)
table = formatting.Table(columns.columns)
table.sortby = sortby
for key, type_name in [(, ),
... | List ACLs. |
8,028 | def _select_best_remaining_qubit(self, prog_qubit):
reliab_store = {}
for hw_qubit in self.available_hw_qubits:
reliab = 1
for n in self.prog_graph.neighbors(prog_qubit):
if n in self.prog2hw:
reliab *= self.swap_costs[self.prog2hw[n]]... | Select the best remaining hardware qubit for the next program qubit. |
8,029 | def _fix_labels(self):
for s in self.systems:
mag0 = np.inf
n0 = None
for n in self.get_system(s):
if isinstance(n.parent, DummyObsNode):
continue
mag, _ = n.parent.value
if mag < mag0:
... | For each system, make sure tag _0 is the brightest, and make sure
system 0 contains the brightest star in the highest-resolution image |
8,030 | def fetch(self, addon_id, data={}, **kwargs):
return super(Addon, self).fetch(addon_id, data, **kwargs) | Fetch addon for given Id
Args:
addon_id : Id for which addon object has to be retrieved
Returns:
addon dict for given subscription Id |
8,031 | def MakeExecutableTemplate(self, output_file=None):
super(WindowsClientBuilder,
self).MakeExecutableTemplate(output_file=output_file)
self.MakeBuildDirectory()
self.BuildWithPyInstaller()
for module in EnumMissingModules():
logging.info("Copying additional dll %s.", module)
... | Windows templates also include the nanny. |
8,032 | def plot_station_mapping(
target_latitude,
target_longitude,
isd_station,
distance_meters,
target_label="target",
):
try:
import matplotlib.pyplot as plt
except ImportError:
raise ImportError("Plotting requires matplotlib.")
try:
import cartopy.crs as ccrs... | Plots this mapping on a map. |
8,033 | def call_bad_cb(self, tb):
with LiveExecution.lock:
if self.bad_cb and not self.bad_cb(tb):
self.bad_cb = None | If bad_cb returns True then keep it
:param tb: traceback that caused exception
:return: |
8,034 | def getExtensionArgs(self):
args = {}
if self.required:
args[] = .join(self.required)
if self.optional:
args[] = .join(self.optional)
if self.policy_url:
args[] = self.policy_url
return args | Get a dictionary of unqualified simple registration
arguments representing this request.
This method is essentially the inverse of
C{L{parseExtensionArgs}}. This method serializes the simple
registration request fields.
@rtype: {str:str} |
8,035 | def process_index(self, url, page):
def scan(link):
pkg = safe_name(parts[0])
ver = safe_version(parts[1])
self.package_pages.setdefault(pkg.lower(), {})[link] = True
return to_filename(pkg), to_filename(ver)
... | Process the contents of a PyPI page |
8,036 | def verify_exif(filename):
required_exif = required_fields()
exif = ExifRead(filename)
required_exif_exist = exif.fields_exist(required_exif)
return required_exif_exist | Check that image file has the required EXIF fields.
Incompatible files will be ignored server side. |
8,037 | def inspect_tables(conn, database_metadata):
" List tables and their row counts, excluding uninteresting tables. "
tables = {}
table_names = [
r["name"]
for r in conn.execute(
)
]
for table in table_names:
table_metadata = database_metadata.get("tables",... | List tables and their row counts, excluding uninteresting tables. |
8,038 | def schedule_job(self, job):
l = _reraise_with_traceback(job.get_lambda_to_execute())
future = self.workers.submit(l, update_progress_func=self.update_progress, cancel_job_func=self._check_for_cancel)
self.job_future_mapping[future] = job
self.future_job_mapping[job.j... | schedule a job to the type of workers spawned by self.start_workers.
:param job: the job to schedule for running.
:return: |
8,039 | def assert_reset(self, asserted):
try:
self._invalidate_cached_registers()
self._link.assert_reset(asserted)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | Assert or de-assert target reset line |
8,040 | def organization_users(self, id, permission_set=None, role=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users
api_path = "/api/v2/organizations/{id}/users.json"
api_path = api_path.format(id=id)
api_query = {}
if "query" in kwargs.keys():
api_que... | https://developer.zendesk.com/rest_api/docs/core/users#list-users |
8,041 | def _repr_categories_info(self):
category_strs = self._repr_categories()
dtype = getattr(self.categories, ,
str(self.categories.dtype))
levheader = "Categories ({length}, {dtype}): ".format(
length=len(self.categories), dtype=dtype)
width, h... | Returns a string representation of the footer. |
8,042 | def av(self, data, lon_str=LON_STR, lat_str=LAT_STR,
land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR):
ts = self.ts(data, lon_str=lon_str, lat_str=lat_str,
land_mask_str=land_mask_str, sfc_area_str=sfc_area_str)
if YEAR_STR not in ts.coords:
re... | Time-average of region-averaged data.
Parameters
----------
data : xarray.DataArray
The array to compute the regional time-average of
lat_str, lon_str, land_mask_str, sfc_area_str : str, optional
The name of the latitude, longitude, land mask, and surface area
... |
8,043 | def convert(outputfile, inputfile, to_format, from_format):
emb = word_embedding.WordEmbedding.load(
inputfile, format=_input_choices[from_format][1],
binary=_input_choices[from_format][2])
emb.save(outputfile, format=_output_choices[to_format][1],
binary=_output_choices[to_for... | Convert pretrained word embedding file in one format to another. |
8,044 | def liftover(args):
p = OptionParser(liftover.__doc__)
p.add_option("--checkvalid", default=False, action="store_true",
help="Check minscore, period and length")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
refbed, fastafile = args
... | %prog liftover lobstr_v3.0.2_hg38_ref.bed hg38.upper.fa
LiftOver CODIS/Y-STR markers. |
8,045 | def __safe_errback(self, room_data, err_condition, err_text):
method = room_data.errback
if method is not None:
try:
method(room_data.room, room_data.nick, err_condition, err_text)
except Exception as ex:
self.__logger.exception("Error cal... | Safe use of the callback method, to avoid errors propagation
:param room_data: A RoomData object
:param err_condition: Category of error
:param err_text: Description of the error |
8,046 | def log_errors(f, self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception:
self.log.error("Uncaught exception in %r" % f, exc_info=True) | decorator to log unhandled exceptions raised in a method.
For use wrapping on_recv callbacks, so that exceptions
do not cause the stream to be closed. |
8,047 | def stop_socket(self, conn_key):
if conn_key not in self._conns:
return
self._conns[conn_key].factory = WebSocketClientFactory(self.STREAM_URL + )
self._conns[conn_key].disconnect()
del(self._conns[conn_key])
if len(conn_key) >= 60 and con... | Stop a websocket given the connection key
:param conn_key: Socket connection key
:type conn_key: string
:returns: connection key string if successful, False otherwise |
8,048 | def readlines(self):
if self.grammar:
tot = []
while 1:
line = self.file.readline()
if not line:
break
tot.append(line)
return tot
return self... | Returns a list of all lines (optionally parsed) in the file. |
8,049 | def is_nameserver(self, path):
node = self.get_node(path)
if not node:
return False
return node.is_nameserver | Is the node pointed to by @ref path a name server (specialisation
of directory nodes)? |
8,050 | def get_fermi_interextrapolated(self, c, T, warn=True, c_ref=1e10, **kwargs):
try:
return self.get_fermi(c, T, **kwargs)
except ValueError as e:
if warn:
warnings.warn(str(e))
if abs(c) < c_ref:
if abs(c) < 1e-10:
... | Similar to get_fermi except that when get_fermi fails to converge,
an interpolated or extrapolated fermi (depending on c) is returned with
the assumption that the fermi level changes linearly with log(abs(c)).
Args:
c (float): doping concentration in 1/cm3. c<0 represents n-type
... |
8,051 | def compile(self, X, verbose=False):
if self.feature >= X.shape[1]:
raise ValueError(\
\
.format(self.feature, X.shape[1]))
if self.by is not None and self.by >= X.shape[1]:
raise ValueError(\
... | method to validate and prepare data-dependent parameters
Parameters
---------
X : array-like
Input dataset
verbose : bool
whether to show warnings
Returns
-------
None |
8,052 | def apply_relationships(self, data, obj):
relationships_to_apply = []
relationship_fields = get_relationships(self.resource.schema, model_field=True)
for key, value in data.items():
if key in relationship_fields:
related_model = getattr(obj.__class__, key).pr... | Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False |
8,053 | def _parse_caps_bank(bank):
result = {
: int(bank.get()),
: int(bank.get()),
: bank.get(),
: "{} {}".format(bank.get(), bank.get()),
: bank.get()
}
controls = []
for control in bank.findall():
unit = control.get()
result_control = {
... | Parse the <bank> element of the connection capabilities XML. |
8,054 | def water(target, temperature=, salinity=):
r
T = target[temperature]
if salinity in target.keys():
S = target[salinity]
else:
S = 0
a1 = -5.8002206E+03
a2 = 1.3914993E+00
a3 = -4.8640239E-02
a4 = 4.1764768E-05
a5 = -1.4452093E-08
a6 = 6.5459673E+00
Pv_w = np.... | r"""
Calculates vapor pressure of pure water or seawater given by [1] based on
Raoult's law. The pure water vapor pressure is given by [2]
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculate... |
8,055 | def sort_protein_group(pgroup, sortfunctions, sortfunc_index):
pgroup_out = []
subgroups = sortfunctions[sortfunc_index](pgroup)
sortfunc_index += 1
for subgroup in subgroups:
if len(subgroup) > 1 and sortfunc_index < len(sortfunctions):
pgroup_out.extend(sort_protein_group(subg... | Recursive function that sorts protein group by a number of sorting
functions. |
8,056 | def get_kgXref_hg19(self):
if self._kgXref_hg19 is None:
self._kgXref_hg19 = self._load_kgXref(self._get_path_kgXref_hg19())
return self._kgXref_hg19 | Get UCSC kgXref table for Build 37.
Returns
-------
pandas.DataFrame
kgXref table if loading was successful, else None |
8,057 | def ReadCronJobs(self, cronjob_ids=None, cursor=None):
query = ("SELECT job, UNIX_TIMESTAMP(create_time), enabled, "
"forced_run_requested, last_run_status, "
"UNIX_TIMESTAMP(last_run_time), current_run_id, state, "
"UNIX_TIMESTAMP(leased_until), leased_by "
... | Reads all cronjobs from the database. |
8,058 | def overwrite_file_check(args, filename):
if not args[] and os.path.exists(filename):
if args[]:
overwrite = False
else:
try:
overwrite = confirm_input(input(
.format(filename)))
except ... | If filename exists, overwrite or modify it to be unique. |
8,059 | def calculate_batch_normalization_output_shapes(operator):
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
check_input_and_output_types(operator, good_input_types=[FloatTensorType])
input_shape = operator.inputs[0].type.shape
if len(input_shape) not in [2, 4]:
... | Allowed input/output patterns are
1. [N, C] ---> [N, C]
2. [N, C, H, W] ---> [N, C, H, W]
This operator just uses the operator input shape as its output shape. |
8,060 | def _set_labels(self, catalogue):
with self._conn:
self._conn.execute(constants.UPDATE_LABELS_SQL, [])
labels = {}
for work, label in catalogue.items():
self._conn.execute(constants.UPDATE_LABEL_SQL, [label, work])
cursor = self._conn.... | Returns a dictionary of the unique labels in `catalogue` and the
count of all tokens associated with each, and sets the record
of each Text to its corresponding label.
Texts that do not have a label specified are set to the empty
string.
Token counts are included in the results... |
8,061 | def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
if file_or_dir_path.is_dir():
asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob("*")]
elif file_or_dir_path.is_file():
asset_data = [dummy_ipfs_pin(file_or_dir_path)]
else:
... | Return a dict containing the IPFS hash, file name, and size of a file. |
8,062 | def register_component(self, path):
component = foundations.strings.get_splitext_basename(path)
LOGGER.debug("> Current Component: .".format(component))
profile = Profile(file=path)
if profile.initializeProfile():
if os.path.isfile(os.path.join(profile.directory, pr... | Registers a Component using given path.
Usage::
>>> manager = Manager()
>>> manager.register_component("tests_component_a.rc")
True
>>> manager.components
{u'core.tests_component_a': <manager.components_manager.Profile object at 0x11c9eb0>}
... |
8,063 | def get_features(cls, entry):
features = []
for feature in entry.iterfind("./feature"):
feature_dict = {
: feature.attrib.get(),
: feature.attrib[],
: feature.attrib.get()
}
features.append(models.Feature(**f... | get list of `models.Feature` from XML node entry
:param entry: XML node entry
:return: list of :class:`pyuniprot.manager.models.Feature` |
8,064 | def get_sort_limit():
limit = _.convert(get("sort_limit"), _.to_int)
if (limit < 1):
limit = None
return limit | returns the 'sort_limit' from the request |
8,065 | def _match_iter_generic(self, path_elements, start_at):
length = len(path_elements)
if self.bound_start:
end = 1
else:
end = length - self.length + 1
if self.bound_end:
start = length - self.length
else:
... | Implementation of match_iter for >1 self.elements |
8,066 | def point_plane_distance(points,
plane_normal,
plane_origin=[0.0, 0.0, 0.0]):
points = np.asanyarray(points, dtype=np.float64)
w = points - plane_origin
distances = np.dot(plane_normal, w.T) / np.linalg.norm(plane_normal)
return distances | The minimum perpendicular distance of a point to a plane.
Parameters
-----------
points: (n, 3) float, points in space
plane_normal: (3,) float, normal vector
plane_origin: (3,) float, plane origin in space
Returns
------------
distances: (n,) float, distance from point to pl... |
8,067 | def add_edge(self, vertex1, vertex2, multicolor, merge=True, data=None):
self.__add_bgedge(BGEdge(vertex1=vertex1, vertex2=vertex2, multicolor=multicolor, data=data), merge=merge) | Creates a new :class:`bg.edge.BGEdge` object from supplied information and adds it to current instance of :class:`BreakpointGraph`.
Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__add_bgedge` method.
:param vertex1: first vertex instance out of two in current :class:`BreakpointGraph`
... |
8,068 | def _get_contours(self):
contours = []
current_contour = None
empty = True
for i, el in enumerate(self._get_elements()):
if el.cmd == MOVETO:
if not empty:
contours.append(current_contour)
current_contour =... | Returns a list of contours in the path, as BezierPath objects.
A contour is a sequence of lines and curves separated from the next contour by a MOVETO.
For example, the glyph "o" has two contours: the inner circle and the outer circle. |
8,069 | def keys(self, element=None, mode=None):
r
if mode is None:
return super().keys()
element = self._parse_element(element=element)
allowed = [, ]
if in mode:
mode = allowed
mode = self._parse_mode(mode=mode, allowed=allowed)
keys = super().k... | r"""
This subclass works exactly like ``keys`` when no arguments are passed,
but optionally accepts an ``element`` and/or a ``mode``, which filters
the output to only the requested keys.
The default behavior is exactly equivalent to the normal ``keys``
method.
Parameter... |
8,070 | def mail_message(smtp_server, message, from_address, rcpt_addresses):
if smtp_server[0] == :
p = os.popen(smtp_server, )
p.write(message)
p.close()
else:
import smtplib
server = smtplib.SMTP(smtp_server)
server.sendmail(from_address, rcpt_a... | Send mail using smtp. |
8,071 | def pre(*content, sep=):
return _md(_join(*content, sep=sep), symbols=MD_SYMBOLS[3]) | Make mono-width text block (Markdown)
:param content:
:param sep:
:return: |
8,072 | def lookup(cls, backend, obj):
ids = set([el for el in obj.traverse(lambda x: x.id) if el is not None])
if len(ids) == 0:
raise Exception("Object does not own a custom options tree")
elif len(ids) != 1:
idlist = ",".join([str(el) for el in sorted(ids)])
... | Given an object, lookup the corresponding customized option
tree if a single custom tree is applicable. |
8,073 | def geojson_polygon_to_mask(feature, shape, lat_idx, lon_idx):
import matplotlib
matplotlib.use()
import matplotlib.pyplot as plt
from matplotlib import patches
import numpy as np
if feature.geometry.type not in (, ):
raise ValueError("Cannot handle feature of type " + ... | Convert a GeoJSON polygon feature to a numpy array
Args:
feature (pygeoj.Feature): polygon feature to draw
shape (tuple(int, int)): shape of 2D target numpy array to draw polygon in
lat_idx (func): function converting a latitude to the (fractional) row index in the map
lon_idx (func... |
8,074 | def mark_error(self, dispatch, error_log, message_cls):
if message_cls.send_retry_limit is not None and (dispatch.retry_count + 1) >= message_cls.send_retry_limit:
self.mark_failed(dispatch, error_log)
else:
dispatch.error_log = error_log
self._st[].append(di... | Marks a dispatch as having error or consequently as failed
if send retry limit for that message type is exhausted.
Should be used within send().
:param Dispatch dispatch: a Dispatch
:param str error_log: error message
:param MessageBase message_cls: MessageBase heir |
8,075 | def lookup(values, name=None):
if name is None:
name =
if values is None:
raise ValueError()
try:
v = values.asList()
values = v
except AttributeError:
values = values
lookup_field = pp.oneOf(values)
lookup_field.setName(name)
look... | Creates the grammar for a Lookup (L) field, accepting only values from a
list.
Like in the Alphanumeric field, the result will be stripped of all heading
and trailing whitespaces.
:param values: values allowed
:param name: name for the field
:return: grammar for the lookup field |
8,076 | def _call(self, x, out=None):
if out is None:
return x * self.multiplicand
elif not self.__range_is_field:
if self.__domain_is_field:
out.lincomb(x, self.multiplicand)
else:
out.assign(self.multiplicand * x)
else:
... | Multiply ``x`` and write to ``out`` if given. |
8,077 | def u2ver(self):
try:
part = urllib2.__version__.split(, 1)
return float(.join(part))
except Exception, e:
log.exception(e)
return 0 | Get the major/minor version of the urllib2 lib.
@return: The urllib2 version.
@rtype: float |
8,078 | def callback(msg, _):
nlh = nlmsg_hdr(msg)
iface = ifinfomsg(nlmsg_data(nlh))
hdr = IFLA_RTA(iface)
remaining = ctypes.c_int(nlh.nlmsg_len - NLMSG_LENGTH(iface.SIZEOF))
while RTA_OK(hdr, remaining):
if hdr.rta_type == IFLA_IFNAME:
print(.format(i... | Callback function called by libnl upon receiving messages from the kernel.
Positional arguments:
msg -- nl_msg class instance containing the data sent by the kernel.
Returns:
An integer, value of NL_OK. It tells libnl to proceed with processing the next kernel message. |
8,079 | def find_templates(input_dir):
templates = []
def template_finder(result, dirname):
for obj in os.listdir(dirname):
if obj.endswith():
result.append(os.path.join(dirname, obj))
dir_visitor(
input_dir,
functools.partial(template_finder, templates)
... | _find_templates_
traverse the input_dir structure and return a list
of template files ending with .mustache
:param input_dir: Path to start recursive search for
mustache templates
:returns: List of file paths corresponding to templates |
8,080 | def _handle_result(self, result):
is_ephemeral = result.node.is_ephemeral_model
if not is_ephemeral:
self.node_results.append(result)
node = CompileResultNode(**result.node)
node_id = node.unique_id
self.manifest.nodes[node_id] = node
if result.erro... | Mark the result as completed, insert the `CompiledResultNode` into
the manifest, and mark any descendants (potentially with a 'cause' if
the result was an ephemeral model) as skipped. |
8,081 | def fill(self, color, start=0, end=-1):
start = max(start, 0)
if end < 0 or end >= self.numLEDs:
end = self.numLEDs - 1
for led in range(start, end + 1):
self._set_base(led, color) | Fill the entire strip with RGB color tuple |
8,082 | def set_widgets(self):
source = self.parent.get_existing_keyword()
if source or source == 0:
self.leSource.setText(source)
else:
self.leSource.clear()
source_scale = self.parent.get_existing_keyword()
if source_scale or source_scale == 0... | Set widgets on the Source tab. |
8,083 | def find_files(self):
if getattr(self, , None):
for path in walk_directory(os.path.join(self.path, self.blueprint_name), ignore=self.project.EXCLUDES):
yield , {: path}
for path in walk_directory(self.path, ignore=self.project.EXCLUDES):
... | Find all file paths for publishing, yield (urlname, kwargs) |
8,084 | def get_value(self, spreadsheet_id: str, range_name: str) -> dict:
service = self.__get_service()
result = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range_name).execute()
return result.get(, []) | get value by range
:param spreadsheet_id:
:param range_name:
:return: |
8,085 | def get_hmac(password):
salt = _security.password_salt
if salt is None:
raise RuntimeError(
% _security.password_hash)
h = hmac.new(encode_string(salt), encode_string(password), hashlib.sha512)
return base64.b64encode(h.digest()) | Returns a Base64 encoded HMAC+SHA512 of the password signed with
the salt specified by ``SECURITY_PASSWORD_SALT``.
:param password: The password to sign |
8,086 | def preprocess(string):
string = unicode(string, encoding="utf-8")
return regex.sub(, string).encode() | Preprocess string to transform all diacritics and remove other special characters than appropriate
:param string:
:return: |
8,087 | def most_read_creators_card(num=10):
if spectator_apps.is_enabled():
object_list = most_read_creators(num=num)
object_list = chartify(object_list, , cutoff=1)
return {
: ,
: ,
: object_list,
} | Displays a card showing the Creators who have the most Readings
associated with their Publications.
In spectator_core tags, rather than spectator_reading so it can still be
used on core pages, even if spectator_reading isn't installed. |
8,088 | def to_datetime(date_or_datetime):
if isinstance(date_or_datetime, date) and \
not isinstance(date_or_datetime, datetime):
d = date_or_datetime
return datetime.strptime(
% (d.year, d.month, d.day), )
return date_or_datetime | Convert a date object to a datetime object,
or return as it is if it's not a date object.
:param date_or_datetime: date or datetime object
:return: a datetime object |
8,089 | def profiler(sorting=(,), stripDirs=True,
limit=20, path=, autoclean=True):
def decorated(func):
@wraps(func)
def wrapped(*args, **kwds):
filename = os.path.join(path, % func.__name__)
prof = hotsho... | Creates a profile wrapper around a method to time out
all the operations that it runs through. For more
information, look into the hotshot Profile documentation
online for the built-in Python package.
:param sorting <tuple> ( <key>, .. )
:param stripDirs <bool>
:param ... |
8,090 | def as_set(self, include_weak=False):
rv = set(self._strong)
if include_weak:
rv.update(self._weak)
return rv | Convert the `ETags` object into a python set. Per default all the
weak etags are not part of this set. |
8,091 | def get_ISSNs(self):
invalid_issns = set(self.get_invalid_ISSNs())
return [
self._clean_isbn(issn)
for issn in self["022a"]
if self._clean_isbn(issn) not in invalid_issns
] | Get list of VALID ISSNs (``022a``).
Returns:
list: List with *valid* ISSN strings. |
8,092 | def compute_samples(channels, nsamples=None):
return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)), nsamples) | create a generator which computes the samples.
essentially it creates a sequence of the sum of each function in the channel
at each sample in the file for each channel. |
8,093 | def grid_str(self, path=None, start=None, end=None,
border=True, start_chr=, end_chr=,
path_chr=, empty_chr=, block_chr=,
show_weight=False):
data =
if border:
data = .format(*len(self.nodes[0]))
for y in range(len(self.nod... | create a printable string from the grid using ASCII characters
:param path: list of nodes that show the path
:param start: start node
:param end: end node
:param border: create a border around the grid
:param start_chr: character for the start (default "s")
:param end_ch... |
8,094 | def field2length(self, field, **kwargs):
attributes = {}
validators = [
validator
for validator in field.validators
if (
hasattr(validator, "min")
and hasattr(validator, "max")
and hasattr(validator, "equal")
... | Return the dictionary of OpenAPI field attributes for a set of
:class:`Length <marshmallow.validators.Length>` validators.
:param Field field: A marshmallow field.
:rtype: dict |
8,095 | def libvlc_video_set_logo_int(p_mi, option, value):
f = _Cfunctions.get(, None) or \
_Cfunction(, ((1,), (1,), (1,),), None,
None, MediaPlayer, ctypes.c_uint, ctypes.c_int)
return f(p_mi, option, value) | Set logo option as integer. Options that take a different type value
are ignored.
Passing libvlc_logo_enable as option value has the side effect of
starting (arg !0) or stopping (arg 0) the logo filter.
@param p_mi: libvlc media player instance.
@param option: logo option to set, values of libvlc_vi... |
8,096 | def select_name(source, name):
return filter(lambda x: x.xml_name == name, select_elements(source)) | Yields all the elements with the given name
source - if an element, starts with all child elements in order; can also be any other iterator
name - will yield only elements with this name |
8,097 | def with_preference_param(self):
user_hash = self._get_user_hash()
if user_hash:
return self.params(preference=user_hash)
return self | Add the preference param to the ES request and return a new Search.
The preference param avoids the bouncing effect with multiple
replicas, documented on ES documentation.
See: https://www.elastic.co/guide/en/elasticsearch/guide/current
/_search_options.html#_preference for more informa... |
8,098 | def glow_hparams():
hparams = common_hparams.basic_params1()
hparams.clip_grad_norm = None
hparams.weight_decay = 0.0
hparams.learning_rate_constant = 3e-4
hparams.batch_size = 32
hparams.add_hparam("level_scale", "prev_level")
hparams.add_hparam("n_levels", 3)
hparams.add_hparam("n_bits_x", 8)... | Glow Hparams. |
8,099 | def validate_name(self, name, agent):
if name in self.bot_names_to_agent_dict and self.bot_names_to_agent_dict[name] is not agent:
i = 0
while True:
if name + " (" + str(i) + ")" in self.bot_names_to_agent_dict and \
self.bot_names_to_agen... | Finds the modification of name which is not yet in the list
:param name: the (new) name for the agent
:param agent: the agent instance to allow the same name as the previous one if necessary
:return: the best modification of name not yet in a listwidget |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.