code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|
def _augment_observation_files(self, e):
e.file_records = [self._augment_file(f) for f in e.file_records]
return e | Augment all the file records in an event
:internal: |
def Backup(self, duration=0):
total = 0
duration_total = duration * 4
children = self.GetChildrenIndexes()
notes = 0
for voice in children:
v = self.GetChild(voice)
indexes = v.GetChildrenIndexes()
if len(indexes) > 1:
... | method to use when a backup tag is encountered in musicXML. Moves back in the bar by <duration>
:param duration:
:return: |
def pickle_encode(session_dict):
"Returns the given session dictionary pickled and encoded as a string."
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
return base64.encodestring(pickled + get_query_hash(pickled).encode()) | Returns the given session dictionary pickled and encoded as a string. |
def transform(self, y):
if isinstance(y, pd.DataFrame):
x = y.ix[:,0]
y = y.ix[:,1]
else:
x = y[:,0]
y = y[:,1]
if self.transform_type == :
return pd.DataFrame(np.add(x, y))
elif self.transform_type == :
ret... | Transform features per specified math function.
:param y:
:return: |
def find_harpoon_options(self, configuration, args_dict):
d = lambda r: {} if r in (None, "", NotSpecified) else r
return MergedOptions.using(
dict(d(configuration.get()).items())
, dict(d(args_dict.get("harpoon")).items())
).as_dict() | Return us all the harpoon options |
def hash_file_contents(requirements_option: RequirementsOptions, path: Path) -> str:
return hashlib.sha256(path.read_bytes() + bytes(
requirements_option.name + arca.__version__, "utf-8"
)).hexdigest() | Returns a SHA256 hash of the contents of ``path`` combined with the Arca version. |
def is_valid_camel(cls, input_string, strcmp=None, ignore=):
if not input_string:
return False
input_string = .join([c for c in input_string if c.isalpha()])
matches = cls._get_regex_search(input_string,
cls.REGEX_CAMEL.forma... | Checks to see if an input string is valid for use in camel casing
This assumes that all lowercase strings are not valid camel case situations and no camel string
can just be a capitalized word. Took ideas from here:
http://stackoverflow.com/questions/29916065/how-to-do-camelcase-spl... |
def ring_is_planar(ring, r_atoms):
normals = []
for a in r_atoms:
adj = pybel.ob.OBAtomAtomIter(a.OBAtom)
n_coords = [pybel.Atom(neigh).coords for neigh in adj if ring.IsMember(neigh)]
vec1, vec2 = vector(a.coords, n_coords[0]), vector(a.coords, n_coords[1])
normals... | Given a set of ring atoms, check if the ring is sufficiently planar
to be considered aromatic |
def coil_combine(data, w_idx=[1,2,3], coil_dim=2, sampling_rate=5000.):
w_data, w_supp_data = separate_signals(data, w_idx)
fft_w = np.fft.fftshift(fft.fft(w_data))
fft_w_supp = np.fft.fftshift(fft.fft(w_supp_data))
freqs_w = np.linspace(-sampling_rate/2.0,
sampling_rate/... | Combine data across coils based on the amplitude of the water peak,
according to:
.. math::
X = \sum_{i}{w_i S_i}
Where X is the resulting combined signal, $S_i$ are the individual coil
signals and $w_i$ are calculated as:
.. math::
w_i = mean(S_i) / var (S_i)
... |
def GetSOAPHeaders(self, create_method):
header = create_method(self._SOAP_HEADER_CLASS)
header.networkCode = self._ad_manager_client.network_code
header.applicationName = .join([
self._ad_manager_client.application_name,
googleads.common.GenerateLibSig(self._PRODUCT_SIG)])
return h... | Returns the SOAP headers required for request authorization.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers. |
def immutable_worker(worker, state, pre_state, created):
return WorkerData._make(chain(
(getattr(worker, f) for f in WORKER_OWN_FIELDS),
(state, pre_state, created),
(worker.heartbeats[-1] if worker.heartbeats else None,),
)) | Converts to an immutable slots class to handle internally. |
def _get_asam_configuration(driver_url=):
asam_config = __opts__[] if in __opts__ else None
if asam_config:
try:
for asam_server, service_config in six.iteritems(asam_config):
username = service_config.get(, None)
password = service_config.get(, None)
... | Return the configuration read from the master configuration
file or directory |
def _increment(self, n=1):
if self._cur_position >= self.num_tokens-1:
self._cur_positon = self.num_tokens - 1
self._finished = True
else:
self._cur_position += n | Move forward n tokens in the stream. |
def _get_result_constructor(self):
if not self._values_list:
return self.model._construct_instance
elif self._flat_values_list:
key = self._only_fields[0]
return lambda row: row[key]
else:
return lambda row: [row[f] for f in self._only... | Returns a function that will be used to instantiate query results |
def save_diskspace(fname, reason, config):
if config["algorithm"].get("save_diskspace", False):
for ext in ["", ".bai"]:
if os.path.exists(fname + ext):
with open(fname + ext, "w") as out_handle:
out_handle.write("File removed to save disk space: %s" % re... | Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message. |
def cast(self, method, args={}, declare=None, retry=None,
retry_policy=None, type=None, exchange=None, **props):
retry = self.retry if retry is None else retry
body = {: self.name, : method, : args}
_retry_policy = self.retry_policy
if retry_policy:
_... | Send message to actor. Discarding replies. |
def pass_to_pipeline_if_article(
self,
response,
source_domain,
original_url,
rss_title=None
):
if self.helper.heuristics.is_article(response, original_url):
return self.pass_to_pipeline(
response, source_domain... | Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
:param str original_url: the url set in the json file
:param ... |
def update_service(self, service_id, **kwargs):
body = self._formdata(kwargs, FastlyService.FIELDS)
content = self._fetch("/service/%s" % service_id, method="PUT", body=body)
return FastlyService(self, content) | Update a service. |
def get_template_name(self):
template = self.get_template()
page_templates = settings.get_page_templates()
for t in page_templates:
if t[0] == template:
return t[1]
return template | Get the template name of this page if defined or if a closer
parent has a defined template or
:data:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise. |
def score(package_path):
python_files = find_files(package_path, )
total_counter = Counter()
for python_file in python_files:
output = run_pylint(python_file)
counter = parse_pylint_output(output)
total_counter += counter
score_value = 0
for count, stat in enumerate(... | Runs pylint on a package and returns a score
Lower score is better
:param package_path: path of the package to score
:return: number of score |
def replace_vcf_info(keyword, annotation, variant_line=None, variant_dict=None):
new_info = .format(keyword, annotation)
logger.debug("Replacing the variant information {0}".format(new_info))
fixed_variant = None
new_info_list = []
if variant_line:
logger.debug("Adding in... | Replace the information of a info field of a vcf variant line or a
variant dict.
Arguments:
variant_line (str): A vcf formatted variant line
variant_dict (dict): A variant dictionary
keyword (str): The info field key
annotation (str): If the annotation is a key, value p... |
def primitive(self, primitive):
self.entry_number = primitive[]
self.item_hash = primitive[]
self.timestamp = primitive[] | Entry from Python primitive. |
def interpolate_exe(self, testString):
testString = testString.strip()
if not (testString.startswith() and testString.endswith()):
return testString
newString = testString
testString = testString[2:-1]
testList = testStr... | Replace testString with a path to an executable based on the format.
If this looks like
${which:lalapps_tmpltbank}
it will return the equivalent of which(lalapps_tmpltbank)
Otherwise it will return an unchanged string.
Parameters
-----------
testString : stri... |
def client_get(self, url, **kwargs):
response = requests.get(self.make_url(url), headers=self.headers)
if not response.ok:
raise Exception(
.format(
status=response.status_code, reason=response.reason))
return response.json() | Send GET request with given url. |
def fstab_present(name, fs_file, fs_vfstype, fs_mntops=,
fs_freq=0, fs_passno=0, mount_by=None,
config=, mount=True, match_on=):
UUID=xxx
ret = {
: name,
: False,
: {},
: [],
}
if fs_mntops == :
if __grains__[] in [, ]:
... | Makes sure that a fstab mount point is pressent.
name
The name of block device. Can be any valid fs_spec value.
fs_file
Mount point (target) for the filesystem.
fs_vfstype
The type of the filesystem (e.g. ext4, xfs, btrfs, ...)
fs_mntops
The mount options associated w... |
def do_PROPPATCH(self, environ, start_response):
path = environ["PATH_INFO"]
res = self._davProvider.get_resource_inst(path, environ)
environ.setdefault("HTTP_DEPTH", "0")
if environ["HTTP_DEPTH"] != "0":
self._fail(HTTP_BAD_REQUEST, "Depth must be .")
... | Handle PROPPATCH request to set or remove a property.
@see http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH |
def _add_image_part(self, image):
partname = self._next_image_partname(image.ext)
image_part = ImagePart.from_image(image, partname)
self.append(image_part)
return image_part | Return an |ImagePart| instance newly created from image and appended
to the collection. |
def generate_ucsm_handle(hostname, username, password):
ucs_handle = UcsHandle()
try:
success = ucs_handle.Login(hostname, username, password)
except UcsException as e:
print("Cisco client exception %(msg)s" % (e.message))
raise exception.UcsConnectionError(message=e.message)
... | Creates UCS Manager handle object and establishes a session with
UCS Manager.
:param hostname: UCS Manager hostname or IP-address
:param username: Username to login to UCS Manager
:param password: Login user password
:raises UcsConnectionError: In case of error. |
def recursive_cov(self, cov, length, mean, chain, scaling=1, epsilon=0):
r
n = length + len(chain)
k = length
new_mean = self.recursive_mean(mean, length, chain)
t0 = k * np.outer(mean, mean)
t1 = np.dot(chain.T, chain)
t2 = n * np.outer(new_mean, new_mean)
... | r"""Compute the covariance recursively.
Return the new covariance and the new mean.
.. math::
C_k & = \frac{1}{k-1} (\sum_{i=1}^k x_i x_i^T - k\bar{x_k}\bar{x_k}^T)
C_n & = \frac{1}{n-1} (\sum_{i=1}^k x_i x_i^T + \sum_{i=k+1}^n x_i x_i^T - n\bar{x_n}\bar{x_n}^T)
... |
def get_next_step(self):
if self.parent.is_selected_layer_keywordless:
self.parent.parent_step = self
self.parent.existing_keywords = None
self.parent.set_mode_label_to_keywords_creation()
new_step = self.parent.step_kw_purpose
else:
... | Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep instance or None |
def printer(self, message, color_level=):
if self.job_args.get():
print(cloud_utils.return_colorized(msg=message, color=color_level))
else:
print(message) | Print Messages and Log it.
:param message: item to print to screen |
def _get_col_dimstr(tdim, is_string=False):
dimstr =
if tdim is None:
dimstr =
else:
if is_string:
if len(tdim) > 1:
dimstr = [str(d) for d in tdim[1:]]
else:
if len(tdim) > 1 or tdim[0] > 1:
dimstr = [str(d) for d in tdi... | not for variable length |
def show_disk(name=None, kwargs=None, call=None):
if not kwargs or not in kwargs:
log.error(
)
return False
conn = get_conn()
return _expand_disk(conn.ex_get_volume(kwargs[])) | Show the details of an existing disk.
CLI Example:
.. code-block:: bash
salt-cloud -a show_disk myinstance disk_name=mydisk
salt-cloud -f show_disk gce disk_name=mydisk |
def get_environment(self):
environment = {}
cpu_cmd =
mem_cmd =
temp_cmd =
output = self._send_command(cpu_cmd)
environment.setdefault(, {})
environment[][0] = {}
environment[][0][] = 0.0
for line in output.splitlines():
if... | Get environment facts.
power and fan are currently not implemented
cpu is using 1-minute average
cpu hard-coded to cpu0 (i.e. only a single CPU) |
def loadScopeGroupbyID(self, id, callback=None, errback=None):
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, id=id)
return scope_group.load(callback=callback, errback=errback) | Load an existing Scope Group by ID into a high level Scope Group object
:param int id: id of an existing ScopeGroup |
def mean(self, values, axis=0, weights=None, dtype=None):
values = np.asarray(values)
if weights is None:
result = self.reduce(values, axis=axis, dtype=dtype)
shape = [1] * values.ndim
shape[axis] = self.groups
weights = self.count.reshape(shape)
... | compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for e... |
def create(self, name, data):
return self._update( %
urlparse.quote(name.encode()), data,
, dump_json=False) | Create a Job Binary Internal.
:param str data: raw data of script text |
def update(request, ident, stateless=False, **kwargs):
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode())
if app.use_dash_dispatch():
view_func = app.locate_endpoint_function()
import flask
with app.test_request_con... | Generate update json response |
def processes(self, processes):
if self._processes > 1:
self._pool.close()
self._pool.join()
self._pool = multiprocessing.Pool(processes)
else:
self._pool = None
self._logger.log(, .format(
processes
)) | Set the number of concurrent processes the ABC will utilize for
fitness function evaluation; if <= 1, single process is used
Args:
processes (int): number of concurrent processes |
def load_path(path, overrides=None, **kwargs):
f = open(path, )
content = .join(f.readlines())
f.close()
if not isinstance(content, str):
raise AssertionError("Expected content to be of type str but it is "+str(type(content)))
return load(content, **kwargs) | Convenience function for loading a YAML configuration from a file.
Parameters
----------
path : str
The path to the file to load on disk.
overrides : dict, optional
A dictionary containing overrides to apply. The location of
the override is specified in the key as a dot-delimite... |
def stop_app(self):
try:
if self._conn:
finally:
self.clear_host_port() | Overrides superclass. |
def get_evidence_by_hash(self, evidence_hash: str) -> Optional[Evidence]:
return self.session.query(Evidence).filter(Evidence.sha512 == evidence_hash).one_or_none() | Look up an evidence by its hash. |
def reduce_data_frame (df, chunk_slicers,
avg_cols=(),
uavg_cols=(),
minmax_cols=(),
nchunk_colname=,
uncert_prefix=,
min_points_per_chunk=3):
subds = [df.iloc[idx] for idx ... | Reduce" a DataFrame by collapsing rows in grouped chunks. Returns another
DataFrame with similar columns but fewer rows.
Arguments:
df
The input :class:`pandas.DataFrame`.
chunk_slicers
An iterable that returns values that are used to slice *df* with its
:meth:`pandas.DataFrame.iloc`... |
def invoke_ssh_shell(cls, *args, **kwargs):
pty = kwargs.pop(, True)
echo = kwargs.pop(, False)
client = cls.connect_ssh(*args, **kwargs)
f = client.invoke_shell(pty=pty, echo=echo)
f.client = client
return f | invoke_ssh(arguments..., pty=False, echo=False)
Star a new shell on a remote server. It first calls
:meth:`Flow.connect_ssh` using all positional and keyword
arguments, then calls :meth:`SSHClient.invoke_shell` with the
pty / echo options.
Args:
arguments...: The op... |
def post_fork_child(self):
entry_point = .format(__name__)
exec_env = combined_dict(os.environ, dict(PANTS_ENTRYPOINT=entry_point))
cmd = [sys.executable] + sys.argv
self._logger.debug(.format(entry_point, .join(cmd)))
os.spawnve(os.P_NOWAIT, sys.executable, cmd, env=exec_env) | Post-fork() child callback for ProcessManager.daemon_spawn(). |
def indication(self, pdu):
if _debug: StreamToPacket._debug("indication %r", pdu)
for packet in self.packetize(pdu, self.downstreamBuffer):
self.request(packet) | Message going downstream. |
def assignMgtKey(self, CorpNum, MgtKeyType, ItemKey, MgtKey, UserID=None):
if MgtKeyType == None or MgtKeyType == :
raise PopbillException(-99999999, "세금계산서 발행유형이 입력되지 않았습니다.")
if ItemKey == None or ItemKey == :
raise PopbillException(-99999999, "아이템키가 입력되지 않았습니다.")
... | 관리번호할당
args
CorpNum : 팝빌회원 사업자번호
MgtKeyType : 세금계산서 유형, SELL-매출, BUY-매입, TRUSTEE-위수탁
ItemKey : 아이템키 (Search API로 조회 가능)
MgtKey : 세금계산서에 할당할 파트너 관리 번호
UserID : 팝빌회원 아이디
return
처리결과. consist of code and... |
def get_conditional_probs(self, source=None):
c_probs = np.zeros((self.m * (self.k + 1), self.k))
mu = self.mu.detach().clone().numpy()
for i in range(self.m):
mu_i = mu[i * self.k : (i + 1) * self.k, :]
c_probs[i * (self.k... | Returns the full conditional probabilities table as a numpy array,
where row i*(k+1) + ly is the conditional probabilities of source i
emmiting label ly (including abstains 0), conditioned on different
values of Y, i.e.:
c_probs[i*(k+1) + ly, y] = P(\lambda_i = ly | Y = y)
... |
def _build_register_function(universe: bool, in_place: bool):
def register(func):
return _register_function(func.__name__, func, universe, in_place)
return register | Build a decorator function to tag transformation functions.
:param universe: Does the first positional argument of this function correspond to a universe graph?
:param in_place: Does this function return a new graph, or just modify it in-place? |
def p_expr_usr(p):
if p[2].type_ == TYPE.string:
p[0] = make_builtin(p.lineno(1), , p[2], type_=TYPE.uinteger)
else:
p[0] = make_builtin(p.lineno(1), ,
make_typecast(TYPE.uinteger, p[2], p.lineno(1)),
type_=TYPE.uinteger) | bexpr : USR bexpr %prec UMINUS |
def WaitHotKeyReleased(hotkey: tuple) -> None:
mod = {ModifierKey.Alt: Keys.VK_MENU,
ModifierKey.Control: Keys.VK_CONTROL,
ModifierKey.Shift: Keys.VK_SHIFT,
ModifierKey.Win: Keys.VK_LWIN
}
while True:
time.sleep(0.05)
if IsKeyPressed(h... | hotkey: tuple, two ints tuple(modifierKey, key) |
def _separate(self):
if self.total_free_space is None:
return 0
else:
sepa = self.default_column_space
if self.default_column_space_remainder > 0:
sepa += 1
self.default_column_space_remainder -= 1
logg... | get a width of separator for current column
:return: int |
def p_expression_sla(self, p):
p[0] = Sll(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression LSHIFTA expression |
def _cb_inform_interface_change(self, msg):
self._logger.debug(, msg)
self._interface_changed.set() | Update the sensors and requests available. |
def to_dict(mapreduce_yaml):
all_configs = []
for config in mapreduce_yaml.mapreduce:
out = {
"name": config.name,
"mapper_input_reader": config.mapper.input_reader,
"mapper_handler": config.mapper.handler,
}
if config.mapper.params_validator:
out["ma... | Converts a MapReduceYaml file into a JSON-encodable dictionary.
For use in user-visible UI and internal methods for interfacing with
user code (like param validation). as a list
Args:
mapreduce_yaml: The Pyton representation of the mapreduce.yaml document.
Returns:
A list of configuration... |
def explained_variance(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Explained variance between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
var_pct = torch.var(targ - pred) / torch.var(targ)
return 1 - var_pct | Explained variance between `pred` and `targ`. |
def tracefunc_xml(func):
funcname = meta_util_six.get_funcname(func)
def wrp_tracefunc2(*args, **kwargs):
verbose = kwargs.get(, True)
if verbose:
print( % (funcname,))
with util_print.Indenter():
ret = func(*args, **kwargs)
if verbose:
pr... | Causes output of function to be printed in an XML style block |
def tokenize_sents(string):
string = six.text_type(string)
spans = []
for match in re.finditer(, string):
spans.append(match)
spans_count = len(spans)
rez = []
off = 0
for i in range(spans_count):
tok = string[spans[i].start():spans[i].end()]
if i == spans_cou... | Tokenize input text to sentences.
:param string: Text to tokenize
:type string: str or unicode
:return: sentences
:rtype: list of strings |
def turb_ice(turbice: [str], unit: str = ) -> str:
if not turbice:
return
if turbice[0][0] == :
conditions = TURBULANCE_CONDITIONS
elif turbice[0][0] == :
conditions = ICING_CONDITIONS
else:
return
split = []
for item in turbice:
if len(... | Translate the list of turbulance or icing into a readable sentence
Ex: Occasional moderate turbulence in clouds from 3000ft to 14000ft |
def by_position(self, position):
try:
return self.filter_by(position=position).one()
except sa.orm.exc.NoResultFound:
return None | Like `.get()`, but by position number. |
def get_tables(self):
url = self.build_url(self._endpoints.get())
response = self.session.get(url)
if not response:
return []
data = response.json()
return [self.table_constructor(parent=self, **{self._cloud_data_key: table})
for table in ... | Returns a collection of this worksheet tables |
def to_vcf(self, path, rename=None, number=None, description=None,
fill=None, write_header=True):
r
write_vcf(path, callset=self, rename=rename, number=number,
description=description, fill=fill,
write_header=write_header) | r"""Write to a variant call format (VCF) file.
Parameters
----------
path : string
File path.
rename : dict, optional
Rename these columns in the VCF.
number : dict, optional
Override the number specified in INFO headers.
description :... |
def scale_dtype(arr, dtype):
max_int = np.iinfo(dtype).max
return (arr * max_int).astype(dtype) | Convert an array from 0..1 to dtype, scaling up linearly |
def index():
institute_objs = user_institutes(store, current_user)
institutes_count = ((institute_obj, store.cases(collaborator=institute_obj[]).count())
for institute_obj in institute_objs if institute_obj)
return dict(institutes=institutes_count) | Display a list of all user institutes. |
def conv_elems_1d(x, factor, out_depth=None):
out_depth = out_depth or x.get_shape().as_list()[-1]
x = tf.expand_dims(x, 1)
x = layers().Conv2D(
filters=out_depth,
kernel_size=(1, factor),
strides=(1, factor),
padding="valid",
data_format="channels_last",
)(x)
x = tf... | Decrease the length and change the dimensionality.
Merge/restore/compress factors positions of dim depth of the input into
a single position of dim out_depth.
This is basically just a strided convolution without overlap
between each strides. The original length has to be divided by factor.
Args:
x (tf.T... |
def _make_request(session, url, argument=None, params=None, raw=False):
if not params:
params = {}
params[] = session.auth.key
try:
if argument:
request_url = .format(session.auth.base_url, VOOBLY_API_URL, url, argument)
else:
request_url = .format(VOOBLY... | Make a request to API endpoint. |
def tokenize(self, s, pattern=None, active=None):
if pattern is None:
if self.tokenize_pattern is None:
pattern = r
else:
pattern = self.tokenize_pattern
if active is None:
active = self.active
return self.group.tokeniz... | Rewrite and tokenize the input string *s*.
Args:
s (str): the input string to process
pattern (str, optional): the regular expression pattern on
which to split tokens; defaults to `[ \t]+`
active (optional): a collection of external module names
... |
def conv_block(name, x, mid_channels, dilations=None, activation="relu",
dropout=0.0):
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_shape = common_layers.shape_list(x)
is_2d = len(x_shape) == 4
num_steps = x_shape[1]
if is_2d:
first_filter = [3, 3]
second_filter ... | 2 layer conv block used in the affine coupling layer.
Args:
name: variable scope.
x: 4-D or 5-D Tensor.
mid_channels: Output channels of the second layer.
dilations: Optional, list of integers.
activation: relu or gatu.
If relu, the second layer is relu(W*x)
If gatu, the second layer ... |
def inverse_transform(self, maps):
out = {}
xi1 = conversions.primary_xi(
maps[parameters.mass1], maps[parameters.mass2],
maps[parameters.spin1x], maps[parameters.spin1y],
maps[parameters.spin2x], m... | This function transforms from component masses and cartesian spins to
mass-weighted spin parameters perpendicular with the angular momentum.
Parameters
----------
maps : a mapping object
Returns
-------
out : dict
A dict with key as parameter name an... |
def run(*args):
import os
import sys
import argparse
import pkg_resources
parser = argparse.ArgumentParser(prog=, description=)
parser.add_argument(, help=)
parser.add_argument(, dest=, action=,
help=)
parser.add_argument(, dest=, action=,
help=)
ver = pkg... | Run the normal shovel functionality |
def remove(self, first, count):
if first < 0 or count < 1:
return
new_range = []
last = first + count - 1
for r in self.__range:
if first <= r.last and r.first <= last:
if r.first < first:
ne... | Remove a range of count consecutive ids starting at id first
from all the ranges in the set. |
def _get_current_object(self):
if not hasattr(self.__local, ):
return self.__local()
try:
return getattr(self.__local, self.__name__)
except AttributeError:
raise RuntimeError( % self.__name__) | Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context. |
def days_in_month(year, month):
eom = _days_per_month[month - 1]
if is_leap_year(year) and month == 2:
eom += 1
return eom | returns number of days for the given year and month
:param int year: calendar year
:param int month: calendar month
:return int: |
def get_map_values(self, lons, lats, ibin=None):
pix_idxs = self.get_pixel_indices(lons, lats, ibin)
idxs = copy.copy(pix_idxs)
m = np.empty_like(idxs[0], dtype=bool)
m.fill(True)
for i, p in enumerate(pix_idxs):
m &= (pix_idxs[i] >= 0) & (pix_idxs[i] < self... | Return the map values corresponding to a set of coordinates.
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-like
Extract data only for a given energy bin. No... |
def _add_url(self, chunk):
if in chunk:
return chunk
public_path = chunk.get()
if public_path:
chunk[] = public_path
else:
fullpath = posixpath.join(self.state.static_view_path,
chunk[])
chunk... | Add a 'url' property to a chunk and return it |
def chunks(iterable, n):
for i in range(0, len(iterable), n):
yield iterable[i:i + n] | Yield successive n-sized chunks from iterable object. https://stackoverflow.com/a/312464 |
def unmodified_isinstance(*bases):
class UnmodifiedIsInstance(type):
if sys.version_info[0] == 2 and sys.version_info[1] <= 6:
@classmethod
def __instancecheck__(cls, instance):
if cls.__name__ in (str(base.__name__) for base in bases):
retur... | When called in the form
MyOverrideClass(unmodified_isinstance(BuiltInClass))
it allows calls against passed in built in instances to pass even if there not a subclass |
def write(self, buffer):
if type(buffer) == type(0):
buffer = chr(buffer)
elif not isinstance(buffer, bytes):
buffer = buffer.encode(self.encoding)
if IAC in buffer:
buffer = buffer.replace(IAC, IAC+IAC)
self.msg("send %s", repr(buffer))
... | Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
socket.error if the connection is closed. |
def first_interval_starting(self, start: datetime.datetime) -> \
Optional[Interval]:
for i in self.intervals:
if i.start == start:
return i
return None | Returns our first interval that starts with the ``start`` parameter, or
``None``. |
def _convert(cls, record):
if not record:
return {}
converted_dict = {}
for field in cls.conversion:
key = field[0]
if len(field) >= 2 and field[1]:
converted_key = field[1]
else:
converted_key = key
... | Core method of the converter. Converts a single dictionary into another dictionary. |
def _set_link_error_disable(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=link_error_disable.link_error_disable, is_container=, presence=False, yang_name="link-error-disable", rest_name="link-error-disable", parent=self, path_helper=self._path_helpe... | Setter method for link_error_disable, mapped from YANG variable /interface/ethernet/link_error_disable (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_link_error_disable is considered as a private
method. Backends looking to populate this variable should
do s... |
def _locate_free_sectors(self, ignore_chunk=None):
sectors = self._sectors(ignore_chunk=ignore_chunk)
return [not i for i in sectors] | Return a list of booleans, indicating the free sectors. |
def handleGetValue(self, topContainer):
value = self.__referenceDict if self.__referenceDict is not None else topContainer
for key in self.__dictKeyChain:
value = value[key]
return value | This method overrides ValueGetterBase's "pure virtual" method. It
returns the referenced value. The derived class is NOT responsible for
fully resolving the reference'd value in the event the value resolves to
another ValueGetterBase-based instance -- this is handled automatically
within ValueGetterBa... |
def installed(name,
cyg_arch=,
mirrors=None):
ret = {: name, : None, : , : {}}
if cyg_arch not in [, ]:
ret[] = False
ret[] = cyg_arch\x86\x86_64\
return ret
LOG.debug(, mirrors)
if not __salt__[](name,
... | Make sure that a package is installed.
name
The name of the package to install
cyg_arch : x86_64
The cygwin architecture to install the package into.
Current options are x86 and x86_64
mirrors : None
List of mirrors to check.
None will use a default mirror (kernel.... |
def loads(cls, s):
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) | Load an instance of this class from YAML. |
def cmd_func(self, command: str) -> Optional[Callable]:
func_name = self.cmd_func_name(command)
if func_name:
return getattr(self, func_name) | Get the function for a command
:param command: the name of the command |
def get_vcs_root(path):
previous_path = path
while get_vcs_info(path) is None:
path = abspardir(path)
if path == previous_path:
return
else:
previous_path = path
return osp.abspath(path) | Return VCS root directory path
Return None if path is not within a supported VCS repository |
def _do_multipart_upload(self, stream, metadata, size, num_retries):
data = stream.read(size)
if len(data) < size:
msg = _READ_LESS_THAN_SIZE.format(size, len(data))
raise ValueError(msg)
headers = _get_upload_headers(self._connection.USER_AGENT)
upload... | Perform a multipart upload.
:type stream: IO[bytes]
:param stream: A bytes IO object open for reading.
:type metadata: dict
:param metadata: The metadata associated with the upload.
:type size: int
:param size: The number of bytes to be uploaded (which will be read
... |
def to_dict(self):
rv = {: self.code}
if not self.is_native():
rv[] = self.issuer
rv[] = self.type
else:
rv[] =
return rv | Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset` |
def cli(debug, cache, incremental):
settings.HTTP_CACHE = cache
settings.INCREMENTAL = incremental
settings.DEBUG = debug
if settings.DEBUG:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
init_memorious() | Crawler framework for documents and structured scrapers. |
def ensure_dir(self, mode=0777):
if not self.exists() or not self.isdir():
os.makedirs(self, mode) | Make sure the directory exists, create if necessary. |
def feed_interval_get(feed_id, parameters):
val = cache.get(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) ))
return val if isinstance(val, tuple) else (val, None) | Get adaptive interval between checks for a feed. |
def impulse_noise(x, severity=1):
c = [.03, .06, .09, 0.17, 0.27][severity - 1]
x = tfds.core.lazy_imports.skimage.util.random_noise(
np.array(x) / 255., mode=, amount=c)
x_clip = np.clip(x, 0, 1) * 255
return around_and_astype(x_clip) | Impulse noise corruption to images.
Args:
x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255].
severity: integer, severity of corruption.
Returns:
numpy array, image with uint8 pixels in [0,255]. Added impulse noise. |
def _open(self, name=None, fileobj=None, mymap=None, block=None):
if block is not None:
if not name:
name =
self.unpack_from(block)
if fileobj:
fileobj.close()
return self
if mymap is not None:
blo... | The _open function takes some form of file identifier and creates
an :py:class:`CpioFile` instance from it.
:param :py:class:`str` name: a file name
:param :py:class:`file` fileobj: if given, this overrides *name*
:param :py:class:`mmap.mmap` mymap: if given, this overrides *fileobj*
... |
def vectorize(self, sentence_list):
test_observed_arr = self.__setup_dataset(sentence_list, self.__token_master_list, self.__seq_len)
inferenced_arr = self.__rbm.inference(
test_observed_arr,
training_count=1,
r_batch_size=-1
)
return infer... | Args:
sentence_list: The list of tokenized sentences.
[[`token`, `token`, `token`, ...],
[`token`, `token`, `token`, ...],
[`token`, `token`, `token`, ...]]
Returns:
`np.ndarray` of tokens.
... |
def obj(self):
if not getattr(self, , None):
self._obj = self.get_object()
if self._obj is None and not self.allow_none:
self.return_error(404)
return self._obj | Returns the value of :meth:`ObjectMixin.get_object` and sets a private
property called _obj. This property ensures the logic around allow_none
is enforced across Endpoints using the Object interface.
:raises: :class:`werkzeug.exceptions.BadRequest`
:returns: The result of :meth:ObjectM... |
def relabel_non_zero(label_image, start = 1):
r
if start <= 0: raise ArgumentError()
l = list(scipy.unique(label_image))
if 0 in l: l.remove(0)
mapping = dict()
mapping[0] = 0
for key, item in zip(l, list(range(start, len(l) + start))):
mapping[key] = item
return relabe... | r"""
Relabel the regions of a label image.
Re-processes the labels to make them consecutively and starting from start.
Keeps all zero (0) labels, as they are considered background.
Parameters
----------
label_image : array_like
A nD label map.
start : integer
The id of ... |
def register(self, request, **cleaned_data):
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
create_user = RegistrationProfile.objects.create_inactive_user
new_user = create_user(
clean... | Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to that ``User``, containing the activation key which
will be ... |
def _join_factory(cls, gap, pad):
if issubclass(cls, dict):
def _join(data):
out = cls()
data = list(data)
while data:
tsd = data.pop(0)
out.append(tsd, gap=gap, pad=pad)
del tsd
return out
else:
... | Build a joiner for the given cls, and the given padding options |
def chi2(T1, T2):
rs2 = T2.sum(axis=1)
rs1 = T1.sum(axis=1)
rs2nz = rs2 > 0
rs1nz = rs1 > 0
dof1 = sum(rs1nz)
dof2 = sum(rs2nz)
rs2 = rs2 + (rs2 == 0)
dof = (dof1 - 1) * (dof2 - 1)
p = np.diag(1 / rs2) * np.matrix(T2)
E = np.diag(rs1) * np.matrix(p)
num = T1 - E
num ... | chi-squared test of difference between two transition matrices.
Parameters
----------
T1 : array
(k, k), matrix of transitions (counts).
T2 : array
(k, k), matrix of transitions (counts) to use to form the
probabilities under the null.
Returns
-------
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.