Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
341,700 | def chi_magic2(path_to_file=, file_name=,
save=False, save_folder=, fmt=):
cont, FTinit, BTinit, k = "", 0, 0, 0
complete_path = os.path.join(path_to_file, file_name)
Tind, cont = 0, ""
EXP = ""
meas_data, file_type = pmag.magic_read(complete_path)
... | Generates plots that compare susceptibility to temperature at different
frequencies.
Optional Parameters (defaults are used if not specified)
----------
path_to_file : path to directory that contains file (default is current directory, '.')
file_name : name of file to be opened (default is 'magic_m... |
341,701 | def std(self, values, axis=0, weights=None, dtype=None):
unique, var = self.var(values, axis, weights, dtype)
return unique, np.sqrt(var) | standard deviation over each group
Parameters
----------
values : array_like, [keys, ...]
values to take standard deviation of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
... |
341,702 | def get_short_url(self, obj):
try:
url = obj.get_absolute_url()
except NoReverseMatch:
url = + obj.slug
return url | Get short URL of blog post like '/blog/<slug>/' using ``get_absolute_url`` if available.
Removes dependency on reverse URLs of Mezzanine views when deploying Mezzanine only as an API backend. |
341,703 | def new_array(state, element_type, size):
size_bounded = SimSootExpr_NewArray._bound_array_size(state, size)
return SimSootValue_ArrayBaseRef(heap_alloc_id=state.javavm_memory.get_new_uuid(),
element_type=element_type,
... | Allocates a new array in memory and returns the reference to the base. |
341,704 | def list_things_at(self, location, tclass=Thing):
"Return all things exactly at a given location."
return [thing for thing in self.things
if thing.location == location and isinstance(thing, tclass)] | Return all things exactly at a given location. |
341,705 | def complementary(clr):
clr = color(clr)
colors = colorlist(clr)
c = clr.copy()
if clr.brightness > 0.4:
c.brightness = 0.1 + c.brightness * 0.25
else:
c.brightness = 1.0 - c.brightness * 0.25
colors.append(c)
c = clr.copy()
c.brightness = 0.3 + c.brightn... | Returns a list of complementary colors.
The complement is the color 180 degrees across
the artistic RYB color wheel.
The list contains darker and softer contrasting
and complementing colors. |
341,706 | def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)
else:
k = mtf.halo_exchange(k, num_w_blocks, w_dim, ... | Halo exchange for keys and values for Local 1D attention. |
341,707 | def get(self, key):
validate_is_bytes(key)
return self._get(self.root_hash, encode_to_bin(key)) | Fetches the value with a given keypath from the given node.
Key will be encoded into binary array format first. |
341,708 | def get_changelog_date_packager(self):
try:
packager = subprocess.Popen(
, stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
packager = "John Doe <john@doe.com>"
logger.warn("Package rpmdevtools is ... | Returns part of the changelog entry, containing date and packager. |
341,709 | def draw_character_key(self, surface, key, special=False):
background_color = self.key_background_color
if special and self.special_key_background_color is not None:
background_color = self.special_key_background_color
pygame.draw.rect(surface, background_color[key.state], k... | Default drawing method for key.
Key is drawn as a simple rectangle filled using this
cell style background color attribute. Key value is printed
into drawn cell using internal font.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
... |
341,710 | def state(self, state):
allowed_values = ["draft", "scheduled", "allocatingquota", "allocatedquota", "quotaallocationfailed", "checkingmanifest", "checkedmanifest", "devicefetch", "devicecopy", "devicecheck", "publishing", "deploying", "deployed", "manifestremoved", "expired", "stopping", "autostopped"... | Sets the state of this UpdateCampaignPutRequest.
The state of the campaign
:param state: The state of this UpdateCampaignPutRequest.
:type: str |
341,711 | def graphStats(G, stats = (, , , , , ), makeString = True, sentenceString = False):
for sts in stats:
if sts not in [, , , , , ]:
raise RuntimeError(.format(sts))
if makeString:
stsData = []
else:
stsData = {}
if in stats:
if makeString:
if ... | Returns a string or list containing statistics about the graph _G_.
**graphStats()** gives 6 different statistics: number of nodes, number of edges, number of isolates, number of loops, density and transitivity. The ones wanted can be given to _stats_. By default a string giving each stat on a different line it ca... |
341,712 | def graph(self, ASres=conf.AS_resolver, padding=0, **kargs):
if (self.graphdef is None or
self.graphASres != ASres or
self.graphpadding != padding):
self.make_graph(ASres, padding)
return do_graph(self.graphdef, **kargs) | x.graph(ASres=conf.AS_resolver, other args):
ASres=None : no AS resolver => no clustering
ASres=AS_resolver() : default whois AS resolver (riswhois.ripe.net)
ASres=AS_resolver_cymru(): use whois.cymru.com whois database
ASres=AS_resolver(server="whois.ra.net")
type: outp... |
341,713 | def find_by(self, values={}, **kwargs):
try:
return self(
**self.select(
where=values,
limit=1,
**kwargs
).to_dict(orient=)[0]
)
except IndexError:
return None | Returns a single record matching the criteria in ``values`` found in the model's table in the replica database.
:param values: Criteria to find the record.
:type values: dict
:returns: an instance of the model. |
341,714 | def fully_scope_function_calls(node: ast.Tree, expression: ast.Expression, function_set: OrderedDict) -> ast.Expression:
expression_copy = copy.deepcopy(expression)
w = TreeWalker()
w.walk(FunctionExpander(node, function_set), expression_copy)
return expression_copy | Turns the function references in this expression into fully scoped
references (e.g. relative to absolute). The component references of all
referenced functions are put into the functions set.
:param node: collection for performing symbol lookup etc.
:param expression: original expression
:param fun... |
341,715 | def create_aql_text(*args):
aql_query_text = ""
for arg in args:
if isinstance(arg, dict):
arg = "({})".format(json.dumps(arg))
elif isinstance(arg, list):
arg = "({})".format(json.dumps(arg)).replace("[", "").replace("]", "")
... | Create AQL querty from string or list or dict arguments |
341,716 | def guess_minimum_encoding(text, charsets=(, , )):
text_in_unicode = text.decode(, )
for charset in charsets:
try:
return (text_in_unicode.encode(charset), charset)
except (UnicodeEncodeError, UnicodeDecodeError):
pass
return (text_in_unicode.encode(), ) | Try to guess the minimum charset that is able to represent.
Try to guess the minimum charset that is able to represent the given
text using the provided charsets. text is supposed to be encoded in utf8.
Returns (encoded_text, charset) where charset is the first charset
in the sequence being able to enc... |
341,717 | def wild_card_logs():
file_name =
z = get_zip_file(wild_card_url)
data = pd.read_csv(z.open(file_name), header=None, sep=, quotechar=)
data.columns = gamelog_columns
return data | Pull Retrosheet Wild Card Game Logs |
341,718 | def pop_item(self):
if self.is_empty():
raise KeyError("pop_item(): tree is empty")
node = self._root
while True:
if node.left is not None:
node = node.left
elif node.right is not None:
node = node.right
els... | T.pop_item() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if T is empty. |
341,719 | def ConvBPDNMaskOptions(opt=None, method=):
base = cbpdnmsk_class_label_lookup(method).Options
class ConvBPDNMaskOptions(base):
def __init__(self, opt):
super(ConvBPDNMaskOptions, self).__init__(opt)
_fix_dynamic_class_lookup(ConvBPDNMaskOptions, method)
... | A wrapper function that dynamically defines a class derived from
the Options class associated with one of the implementations of
the Convolutional BPDN problem, and returns an object
instantiated with the provided parameters. The wrapper is designed
to allow the appropriate object to be created by calli... |
341,720 | def rpn2val(self, rdict):
kw_name = list(rdict.keys())[0]
kw_val = rdict[kw_name]
try:
kw_type = list(kw_val.keys())[0]
kw_param = list(kw_val.values())[0]
if kw_type != :
for k, v in kw_param.items():
v = self... | Resolve the rpn string into calulated float number
USAGE: rpn2val(rdict)
:param rdict: json like dict |
341,721 | def super_psql(self, args):
argv = [
PostgresFinder.find_root() / ,
,
, self.superuser,
, self.host,
, self.port,
] + args
subprocess.check_call(argv) | Just like .psql(), except that we connect as the database superuser
(and we connect to the superuser's database, not the user's database). |
341,722 | async def execute_with_timeout(self, timeout, subprocess):
if timeout is None:
return (False, await subprocess)
else:
th = self.scheduler.setTimer(timeout)
try:
tm = TimerEvent.createMatcher(th)
try:
r = awa... | Execute a subprocess with timeout. If time limit exceeds, the subprocess is terminated,
and `is_timeout` is set to True; otherwise the `is_timeout` is set to False.
You can uses `execute_with_timeout` with other help functions to create time limit for them::
timeout, result... |
341,723 | def delete_user_avatar(self, username, avatar):
params = {: username}
url = self._get_url( + avatar)
return self._session.delete(url, params=params) | Delete a user's avatar.
:param username: the user to delete the avatar from
:param avatar: ID of the avatar to remove |
341,724 | def get_fields(self, strip_labels=False):
if strip_labels:
return [
f[0] if type(f) in (tuple, list) else f for f in self.fields
]
return self.fields | Hook to dynamically change the fields that will be displayed |
341,725 | def code_block(self, code, language, indent=0):
if language not in [None, "console", "python", "ruby", "c"]:
raise
prefix = "\t" * indent
code_prefix = "\t" * (indent + 1)
lines = list()
lines.append(prefix + ".. code-block:: %s" % language)
lines.app... | Example::
.. code-block:: python
from __future__ import print_function
import math
print(math.sqrt(10.0)) |
341,726 | def _transform_coordinates(
self,
func: Callable[[Union[int, float], Union[int, float]],
Tuple[Union[int, float], Union[int, float]]]
) -> None:
def func_x(x: Union[int, float]) -> Union[int, float]:
return func(x, 0)[0]
def f... | Helper method to transformer either row or column coordinates. |
341,727 | def run(self, args):
args = vars(args)
positionals = []
keywords = {}
for action in self.argparser._actions:
if not hasattr(action, ):
continue
if action.label == :
positionals.append(args[action.dest])
elif act... | Convert the unordered args into function arguments. |
341,728 | def get_modules(pkg_name, module_filter = None):
path = app_path(pkg_name)
py_filter = lambda f: all((fnmatch(f, "*.pyc") or fnmatch(f, "*.py"), not f.startswith("__"), module_filter and module_filter(f) or True))
names = [splitext(n)[0] for n in os.listdir(path) if py_filter(n)]
return [... | 返回包中所有符合条件的模块。
参数:
pkg_name 包名称
module_filter 模块名过滤器 def (module_name) |
341,729 | def _handle_create_cfn_template_request(self, app_id, semver, key, logical_id):
create_cfn_template = (lambda app_id, semver: self._sar_client.create_cloud_formation_template(
ApplicationId=self._sanitize_sar_str_param(app_id),
SemanticVersion=self._sanitize_sar_str_param(semver... | Method that handles the create_cloud_formation_template API call to the serverless application repo
:param string app_id: ApplicationId
:param string semver: SemanticVersion
:param string key: The dictionary key consisting of (ApplicationId, SemanticVersion)
:param string logical_id: th... |
341,730 | def insert(self, order_id, card_id, appid, card_ext):
return self._post(
,
data={
: order_id,
: card_id,
: appid,
: card_ext,
},
) | 制作发票卡券,并放入用户卡包
详情请参考
https://mp.weixin.qq.com/wiki?id=mp1497082828_r1cI2
:param order_id: 订单id,在商户内单笔开票请求的唯一识别号
:param card_id: 发票卡券模板的编号
:param appid: 商户 AppID
:param card_ext: 发票具体内容
:type card_ext: dict
:return: 随机防重字符串,以及用户 Open ID |
341,731 | def get_hum(self, raw = False):
self.bus.write_byte(self.address, self.TRIG_RH_noHOLD);
time.sleep(0.1)
data = self.bus.read_i2c_block(self.address, 2)
value = data[0]<<8 | data[1]
value &= ~0b11
humidity = (-6.0 + 125.0*(value/65536.0))
if raw: ... | The physical value RH given above corresponds to the
relative humidity above liquid water according to World
Meteorological Organization (WMO) |
341,732 | def bind_pale_to_webapp2(pale_app_module,
webapp_wsgiapplication,
route_prefix=None):
if not isinstance(webapp_wsgiapplication, webapp2.WSGIApplication):
raise TypeError("pale.adapters.webapp2.bind_pale_to_webapp2 expected "
"the passed in webapp_wsgiapplication to be a... | Binds a Pale API implementation to a webapp2 WSGIApplication |
341,733 | def collect_impl(self):
ldata = self.get_ldata()
rdata = self.get_rdata()
for change_type in self.change_types:
yield change_type(ldata, rdata) | instantiates each of the entries in in the overriden change_types
field with the left and right data |
341,734 | def time_v_terminal_Stokes(D, rhop, rho, mu, V0, tol=1e-14):
rs regime only to
reach terminal velocity (approximately). An infinitely long period is
required theoretically, but with floating points, it is possible to
calculate the time required to come within a specified `tol` of that
terminal vel... | r'''Calculates the time required for a particle in Stoke's regime only to
reach terminal velocity (approximately). An infinitely long period is
required theoretically, but with floating points, it is possible to
calculate the time required to come within a specified `tol` of that
terminal velocity.
... |
341,735 | def get_gradebook_columns_by_gradebook(self, gradebook_id):
mgr = self._get_provider_manager(, local=True)
lookup_session = mgr.get_gradebook_column_lookup_session_for_gradebook(gradebook_id, proxy=self._proxy)
lookup_session.use_isolated_gradebook_view()
retur... | Gets the list of gradebook columns associated with a ``Gradebook``.
arg: gradebook_id (osid.id.Id): ``Id`` of the ``Gradebook``
return: (osid.grading.GradebookColumnList) - list of related
gradebook columns
raise: NotFound - ``gradebook_id`` is not found
raise: Null... |
341,736 | def group_by(self, *args, **kwds):
self._group_by.group_by(*args, **kwds)
return self | Default ordering is ``ASC``.
``group_by`` accept ``dict`` as you would expect, but note that ``dict``
does not have same order. Same for named arguments.
.. code-block:: python
>>> sqlpuzzle.select('c').from_('t').group_by('a', ('b', 'desc'))
<Select: SELECT "c" FROM "... |
341,737 | def as_bel(self) -> str:
res = .format(self.range)
if FRAGMENT_DESCRIPTION in self:
res += .format(self[FRAGMENT_DESCRIPTION])
return .format(res) | Return this fragment variant as a BEL string. |
341,738 | async def revoke(self, username, acl=):
controller_facade = client.ControllerFacade.from_connection(
self.connection())
user = tag.user(username)
changes = client.ModifyControllerAccess(, , user)
return await controller_facade.ModifyControllerAccess([changes]) | Removes some or all access of a user to from a controller
If 'login' access is revoked, the user will no longer have any
permissions on the controller. Revoking a higher privilege from
a user without that privilege will have no effect.
:param str username: username
:param str ac... |
341,739 | def put(url, data=None, **kwargs):
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and data is not None:
data = dumps(data)
_log_request(, url, kwargs, data)
response = requests.put(url, data, **kwargs)
_log_response(response)
return response | A wrapper for ``requests.put``. Sends a PUT request. |
341,740 | def Initialize(self):
super(GRRFlow, self).Initialize()
self._client_version = None
self._client_os = None
self._client_knowledge_base = None
if "r" in self.mode:
state = self.Get(self.Schema.FLOW_STATE_DICT)
self.context = self.Get(self.Schema.FLOW_CONTEXT)
self.runner_args ... | The initialization method. |
341,741 | def register(self, node, vendorSpecific=None):
response = self.registerResponse(node, vendorSpecific)
return self._read_boolean_response(response) | See Also: registerResponse()
Args:
node:
vendorSpecific:
Returns: |
341,742 | def upgrade(config, revision, **kwargs):
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.upgrade(alembic_config, revision, **kwargs) | Upgrade database. |
341,743 | def _ratelimited_get(self, *args, **kwargs):
with self._ratelimiter:
resp = self.session.get(*args, **kwargs)
if resp.status_code == 500:
if in resp.text:
until = time.time() + self._ratelimiter.period... | Perform get request, handling rate limiting. |
341,744 | def to_datetime(date_key):
key
match = re.search(r, date_key)
formatter =
if len(match.group()) == 10:
formatter +=
return datetime.strptime(
match.group(), formatter).replace(tzinfo=pytz.UTC) | Extract the first date from 'key' matching YYYY-MM-DD
or YYYY-MM, and convert to datetime. |
341,745 | def _set_cinema_params(self, cinema_mode, fps):
if re.match("1.5|2.0", version.openjpeg_version) is not None:
msg = ("Writing Cinema2K or Cinema4K files is not supported with "
"OpenJPEG library versions less than 2.1.0. The installed "
"version of Ope... | Populate compression parameters structure for cinema2K.
Parameters
----------
params : ctypes struct
Corresponds to compression parameters structure used by the
library.
cinema_mode : {'cinema2k', 'cinema4k}
Use either Cinema2K or Cinema4K profile.
... |
341,746 | def get_dashboard(context, location):
if location == :
return get_index_dashboard(context)
elif location == :
return get_app_index_dashboard(context)
raise ValueError( % location) | Returns the dashboard that match the given ``location``
(index or app_index). |
341,747 | def _generate_cpu_stats():
cpu_name = urwid.Text("CPU Name N/A", align="center")
try:
cpu_name = urwid.Text(get_processor_name().strip(), align="center")
except OSError:
logging.info("CPU name not available")
return [urwid.Text((, "CPU Detected"),
... | Read and display processor name |
341,748 | def plot_pseudodepths(configs, nr_electrodes, spacing=1, grid=None,
ctypes=None, dd_merge=False, **kwargs):
pseudo_d_functions = {
: _pseudodepths_dd_simple,
: _pseudodepths_schlumberger,
: _pseudodepths_wenner,
}
titles = {
: ,
:... | Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
configs: :class:`numpy.ndarray`
Nx4 array containing the quadrupoles for different measurements
nr_electrodes: int
... |
341,749 | def map_keys(f, dct):
f_dict = {}
for k, v in dct.items():
f_dict[f(k)] = v
return f_dict | Calls f with each key of dct, possibly returning a modified key. Values are unchanged
:param f: Called with each key and returns the same key or a modified key
:param dct:
:return: A dct with keys possibly modifed but values unchanged |
341,750 | def piece_type_at(self, square: Square) -> Optional[PieceType]:
mask = BB_SQUARES[square]
if not self.occupied & mask:
return None
elif self.pawns & mask:
return PAWN
elif self.knights & mask:
return KNIGHT
elif self.bishops & mask:... | Gets the piece type at the given square. |
341,751 | def _split_generators(self, dl_manager):
image_tar_file = os.path.join(dl_manager.manual_dir,
self.builder_config.file_name)
if not tf.io.gfile.exists(image_tar_file):
msg = "You must download the dataset files manually and place them in: "
msg +=... | Returns SplitGenerators. |
341,752 | def slurm_params(self):
result = OrderedDict()
for param, info in self.slurm_headers.items():
if not info[] and not param in self.kwargs: continue
if param in self.kwargs: result[param] = self.kwargs.get(param)
else: result[param] ... | The list of parameters to give to the `sbatch` command. |
341,753 | def temperature_hub(self, weather_df):
r
if self.power_plant.hub_height in weather_df[]:
temperature_hub = weather_df[][
self.power_plant.hub_height]
elif self.temperature_model == :
logging.debug(
)
closest_height = w... | r"""
Calculates the temperature of air at hub height.
The temperature is calculated using the method specified by
the parameter `temperature_model`.
Parameters
----------
weather_df : pandas.DataFrame
DataFrame with time series for temperature `temperature` ... |
341,754 | def get_dashboards(self):
if self.dashboards:
registered = copy.copy(self._registry)
dashboards = []
for item in self.dashboards:
dashboard = self._registered(item)
dashboards.append(dashboard)
registered.pop(dashboard.... | Returns an ordered tuple of :class:`~horizon.Dashboard` modules.
Orders dashboards according to the ``"dashboards"`` key in
``HORIZON_CONFIG`` or else returns all registered dashboards
in alphabetical order.
Any remaining :class:`~horizon.Dashboard` classes registered with
Hori... |
341,755 | def namespace(self, key, glob=False):
if not self.name:
self.name = os.environ[]
ns = .join([key, self._glob]) if glob else .join([self.name, self._glob])
return ns | Return a namespace for keyring |
341,756 | def getSiblings(self, retracted=False):
worksheet = self.getWorksheet()
requestuid = self.getRequestUID()
if not requestuid or not worksheet:
return []
siblings = []
retracted_states = [STATE_RETRACTED, STATE_REJECTED]
analyses = worksheet.getAnalyse... | Return the list of duplicate analyses that share the same Request and
are included in the same Worksheet as the current analysis. The current
duplicate is excluded from the list.
:param retracted: If false, retracted/rejected siblings are dismissed
:type retracted: bool
:return: ... |
341,757 | def _whole_basis_types(basis):
all_types = set()
for v in basis[].values():
if in v:
for sh in v[]:
all_types.add(sh[])
if in v:
for pot in v[]:
all_types.add(pot[])
return sorted(list(all_types)) | Get a list of all the types of features in this basis set. |
341,758 | def dimensions(self, full=0):
nDims, dimLen = self.info()[1:3]
if isinstance(dimLen, int):
dimLen = [dimLen]
unlim = self.isrecord()
res = {}
for n in range(nDims):
d = self.dim(n)
... | Return a dictionnary describing every dataset dimension.
Args::
full true to get complete info about each dimension
false to report only each dimension length
Returns::
Dictionnary where each key is a dimension name. If no name
has been given to... |
341,759 | def _need_check_tokens(self):
if self.n_tokens <= 1 or self.rate_limit is None:
return False
elif self.last_rate_limit_checked is None:
self.last_rate_limit_checked = self.rate_limit
return True
approaching_limit = float(self.min_rate_to_sl... | Check if we need to switch GitHub API tokens |
341,760 | def open_log_file(self):
f = open(os.path.expanduser())
self.uiLog.textEdit.setPlainText(str(f.read()))
self.log_window.show() | The following opens the log file of PlanarRad. |
341,761 | def add(self, _mapping=None, **kwargs):
if _mapping is not None:
_mapping.update(kwargs)
mapping = _mapping
else:
mapping = _mapping
return self.database.zadd(self.key, mapping) | Add the given item/score pairs to the ZSet. Arguments are
specified as ``item1, score1, item2, score2...``. |
341,762 | def logDict(self,d):
keys = list(d.keys())
keys.sort()
s = "\n"+"-"*78+"\n"+" "*20+"dictionary provided contains:\n"+"-"*78+"\n"
for key in keys:
s+=key+" = "+repr(d[key])+"\n"
self.fileonly(s+"-"*78+"\n") | Log all Key=value for every key in a dictionary.
Args:
d (dictionary): A standard python dictionary. |
341,763 | def insert_abs (self, r, c, ch):
if isinstance(ch, bytes):
ch = self._decode(ch)
r = constrain (r, 1, self.rows)
c = constrain (c, 1, self.cols)
for ci in range (self.cols, c, -1):
self.put_abs (r,ci, self.get_abs(r,ci-1))
self.put_abs (r,c,ch) | This inserts a character at (r,c). Everything under
and to the right is shifted right one character.
The last character of the line is lost. |
341,764 | def program_unit_name(line:str) -> str:
match = RE_PGM_UNIT_START.match(line)
assert match != None
return match.group(2) | Given a line that starts a program unit, i.e., a program, module,
subprogram, or function, this function returns the name associated
with that program unit. |
341,765 | def fit_lines(self, window=1500, break_thresh=1500):
window /= 1000
hop = window/3
break_thresh /= 1000
i = 0
break_indices = []
count = 0
while i < len(self.pitch):
if self.pitch[i] == -10000:
count = 1
... | Fits lines to pitch contours.
:param window: size of each chunk to which linear equation is to be fit (in milliseconds).
To keep it simple, hop is chosen to be one third of the window.
:param break_thresh: If there is silence beyond this limit (in milliseconds),
the contour will be brok... |
341,766 | def show_in_notebook(self,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
from IPython.core.display import display, HTML
display(HTML(self.as_html(labels=labels,
... | Shows html explanation in ipython notebook.
See as_html() for parameters.
This will throw an error if you don't have IPython installed |
341,767 | def setText(self, text):
self._text = nativestring(text)
if self.showRichText():
self.richTextLabel().setText(text)
else:
super(XPushButton, self).setText(text) | Sets the text for this button. If it is set to show rich text, then
it will update the label text, leaving the root button text blank,
otherwise it will update the button.
:param text | <str> |
341,768 | def list_set_bits(r, expected_length):
set_bit_numbers = []
bit_index = 0x1
assert (len(r) == expected_length + 1)
for b in r[1:]:
for i in range(8):
if ((b >> i) & 1) == 1:
set_bit_numbers.append(bit_index)
bit_index += 1
return set_bit_numbers | Return list of positions of bits set to one in given data.
This method is used to read e.g. violated zones. They are marked by ones
on respective bit positions - as per Satel manual. |
341,769 | def get_team_push_restrictions(self):
if self._team_push_restrictions is github.GithubObject.NotSet:
return None
return github.PaginatedList.PaginatedList(
github.Team.Team,
self._requester,
self._team_push_restrictions,
None
) | :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team` |
341,770 | def gibbs_sampling_step(self, visible, n_features):
hprobs, hstates = self.sample_hidden_from_visible(visible)
vprobs = self.sample_visible_from_hidden(hprobs, n_features)
hprobs1, hstates1 = self.sample_hidden_from_visible(vprobs)
return hprobs, hstates, vprobs, hprobs1, hstat... | Perform one step of gibbs sampling.
:param visible: activations of the visible units
:param n_features: number of features
:return: tuple(hidden probs, hidden states, visible probs,
new hidden probs, new hidden states) |
341,771 | def Kawahara(x, rhol, rhog, D):
r
if D > 250E-6:
return Armand(x, rhol, rhog)
elif D > 75E-6:
C1, C2 = 0.03, 0.97
else:
C1, C2 = 0.02, 0.98
alpha_h = homogeneous(x, rhol, rhog)
return C1*alpha_h**0.5/(1. - C2*alpha_h**0.5) | r'''Calculates void fraction in two-phase flow according to the model
presented in [1]_, also reviewed in [2]_ and [3]_. This expression is for
microchannels.
.. math::
\alpha = \frac{C_1 \alpha_h^{0.5}}{1 - C_2\alpha_h^{0.5}}
Parameters
----------
x : float
Quality at ... |
341,772 | def plot(self,*args,**kwargs):
if (kwargs.get(,False) \
and kwargs.get(,self._roSet)) or \
(not in kwargs \
and kwargs.get(,self._roSet)):
labeldict= {:r,:r,
:r,
:r,
... | NAME:
plot
PURPOSE:
plot aspects of an Orbit
INPUT:
bovy_plot args and kwargs
ro= (Object-wide default) physical scale for distances to use to convert
vo= (Object-wide default) physical scale for velocities to use to convert
use_physical=... |
341,773 | def group_modes(modes):
if len(modes) > 0:
previous = modes[0]
grouped = []
for changep in modes[1:]:
if changep[] != previous[]:
previous[] = changep[]
grouped.append(previous)
previous = changep
previous[] = modes[-... | Groups consecutive transportation modes with same label, into one
Args:
modes (:obj:`list` of :obj:`dict`)
Returns:
:obj:`list` of :obj:`dict` |
341,774 | def map_metabolite2kegg(metabolite):
logger.debug("Looking for KEGG compound identifier for %s.", metabolite.id)
kegg_annotation = metabolite.annotation.get("kegg.compound")
if kegg_annotation is None:
... | Return a KEGG compound identifier for the metabolite if it exists.
First see if there is an unambiguous mapping to a single KEGG compound ID
provided with the model. If not, check if there is any KEGG compound ID in
a list of mappings. KEGG IDs may map to compounds, drugs and glycans. KEGG
compound IDs... |
341,775 | def load_genotypes(self):
if DataParser.compressed_pedigree:
self.genotype_file = gzip.open("%s.gz" % self.tped_file, )
else:
self.genotype_file = open(self.tped_file)
self.filter_missing() | This really just intializes the file by opening it up. |
341,776 | def get(self, name, default=None):
try:
return self._get(name, default)
except KeyError:
return default | Get the value at ``name`` for this :class:`Config` container
The returned value is obtained from:
* the value at ``name`` in the :attr:`settings` dictionary
if available.
* the value at ``name`` in the :attr:`params` dictionary if available.
* the ``default`` value. |
341,777 | def convertallfields(data, commdct, block=None):
for key in list(data.dt.keys()):
objs = data.dt[key]
for i, obj in enumerate(objs):
key_i = data.dtls.index(key)
key_comm = commdct[key_i]
try:
inblock = block[key_i]
except Typ... | docstring for convertallfields |
341,778 | def canonical_chimera_labeling(G, t=None):
adj = G.adj
if t is None:
if hasattr(G, ):
num_edges = len(G.edges)
else:
num_edges = len(G.quadratic)
t = _chimera_shore_size(adj, num_edges)
chimera_indices = {}
row = col = 0
root = min(adj, key=lam... | Returns a mapping from the labels of G to chimera-indexed labeling.
Parameters
----------
G : NetworkX graph
A Chimera-structured graph.
t : int (optional, default 4)
Size of the shore within each Chimera tile.
Returns
-------
chimera_indices: dict
A mapping from th... |
341,779 | def writeMesh(self, vertices, faces, normals, values,
name=, reshape_faces=True):
self._hasNormals = normals is not None
self._hasValues = values is not None
self._hasFaces = faces is not None
if faces is None:
faces = np.arange(... | Write the given mesh instance. |
341,780 | async def _on_websocket_disconnect(self, _event):
self.logger.info()
conns = self._connections.copy()
for conn_id in conns:
conn_string = self._get_property(conn_id, )
self._teardown_connection(conn_id)
self.notify_event(conn_string, , "Websocket co... | Callback function called when we have been disconnected from the server (by error or not).
Allows to clean all if the disconnection was unexpected. |
341,781 | def create_parser():
parser = argparse.ArgumentParser(
prog=constants.PROGRAM_NAME, description=constants.PROGRAM_DESCRIPTION
)
parser.add_argument(
"-cd",
"--%s" % constants.LABEL_CONFIG_DIR,
help="the directory for configuration file lookup",
)
parser.add_argum... | construct the program options |
341,782 | def get_bundles_from_transaction_hashes(
adapter,
transaction_hashes,
inclusion_states,
):
transaction_hashes = list(transaction_hashes)
if not transaction_hashes:
return []
my_bundles = []
tail_transaction_hashes = set()
non_tail_bundle_hashes = se... | Given a set of transaction hashes, returns the corresponding bundles,
sorted by tail transaction timestamp. |
341,783 | def features_of_type(self, featuretype, limit=None, strand=None,
order_by=None, reverse=False,
completely_within=False):
query, args = helpers.make_query(
args=[],
limit=limit,
featuretype=featuretype,
ord... | Returns an iterator of :class:`gffutils.Feature` objects.
Parameters
----------
{_method_doc} |
341,784 | def qualified_name(self):
if self.module == self:
return self.module.name
else:
if "." not in self.name:
return .format(self.module.name, self.name)
else:
return self.name | return the fully qualified name (`<module>.<name>`) |
341,785 | def putkeyword(self, keyword, value, makesubrecord=False):
return self._table.putcolkeyword(self._column, keyword, value, makesubrecord) | Put the value of a column keyword.
(see :func:`table.putcolkeyword`) |
341,786 | def process_file(filename, timeshift):
print("Processing %s" % filename)
mlog = mavutil.mavlink_connection(filename, notimestamps=args.notimestamps, zero_time_base=args.zero_time_base, dialect=args.dialect)
vars = {}
while True:
msg = mlog.recv_match(args.condition)
if msg is None:... | process one file |
341,787 | def router_deleted(self, context, routers):
LOG.debug(, routers)
self._update_removed_routers_cache(routers) | Deal with router deletion RPC message. |
341,788 | def write(self, data, groupname=, append=False):
if append and groupname in self.h5file:
group = self.h5file[groupname]
if not is_same_version(self.version, group):
raise IOError(
.format(group.name))
... | Write h5features data in a specified group of the file.
:param dict data: A `h5features.Data` instance to be writed on disk.
:param str groupname: Optional. The name of the group in which
to write the data.
:param bool append: Optional. This parameter has no effect if
t... |
341,789 | def listdir(self, path, ignore_directories=False, ignore_files=False,
include_size=False, include_type=False, include_time=False,
recursive=False):
bite = self.get_bite()
for entry in bite.ls(self.list_path(path), recurse=recursive):
if ignore_directo... | Use snakebite.ls to get the list of items in a directory.
:param path: the directory to list
:type path: string
:param ignore_directories: if True, do not yield directory entries
:type ignore_directories: boolean, default is False
:param ignore_files: if True, do not yield file ... |
341,790 | def set_vertex_colors(self, colors, indexed=None):
colors = _fix_colors(np.asarray(colors))
if indexed is None:
if colors.ndim != 2:
raise ValueError()
if colors.shape[0] != self.n_vertices:
raise ValueError(
... | Set the vertex color array
Parameters
----------
colors : array
Array of colors. Must have shape (Nv, 4) (indexing by vertex)
or shape (Nf, 3, 4) (vertices indexed by face).
indexed : str | None
Should be 'faces' if colors are indexed by faces. |
341,791 | def rate_limit_ensembl_requests(self):
current_time = time.time()
diff_time = current_time - self.prior_time
if diff_time < self.rate_limit:
time.sleep(self.rate_limit - diff_time)
self.prior_time = time.time() | limit ensembl requests to one per 0.067 s |
341,792 | def get_tag_version(nrml_node):
version, tag = re.search(r, nrml_node.tag).groups()
return tag, version | Extract from a node of kind NRML the tag and the version. For instance
from '{http://openquake.org/xmlns/nrml/0.4}fragilityModel' one gets
the pair ('fragilityModel', 'nrml/0.4'). |
341,793 | def emit(self, *args, **kwargs):
if self.hard_subscribers is not None:
for callback, user_args, user_kwargs in self.hard_subscribers:
kwargs.update(user_kwargs)
result = callback(*args + user_args, **kwargs)
if result is not None:
... | Emits the signal, passing the given arguments to the callbacks.
If one of the callbacks returns a value other than None, no further
callbacks are invoked and the return value of the callback is
returned to the caller of emit().
:type args: tuple
:param args: Optional arguments ... |
341,794 | def start(builtins=False, profile_threads=True):
if profile_threads:
threading.setprofile(_callback)
_yappi.start(builtins, profile_threads) | Start profiler. |
341,795 | def attachfile(self, idlist, attachfile, description, **kwargs):
if isinstance(attachfile, str):
f = open(attachfile, "rb")
elif hasattr(attachfile, ):
f = attachfile
else:
raise TypeError("attachfile must be filename or file-like object")
... | Attach a file to the given bug IDs. Returns the ID of the attachment
or raises XMLRPC Fault if something goes wrong.
attachfile may be a filename (which will be opened) or a file-like
object, which must provide a 'read' method. If it's not one of these,
this method will raise a TypeErro... |
341,796 | def is_abstract(self, pass_is_abstract=True):
if self.decorators:
for node in self.decorators.nodes:
try:
inferred = next(node.infer())
except exceptions.InferenceError:
continue
if inferred and inferred... | Check if the method is abstract.
A method is considered abstract if any of the following is true:
* The only statement is 'raise NotImplementedError'
* The only statement is 'pass' and pass_is_abstract is True
* The method is annotated with abc.astractproperty/abc.abstractmethod
... |
341,797 | def extra_html_properties(self, prefix=None, postfix=None, template_type=None):
prefix = prefix if prefix else "django-plotly-dash"
post_part = "-%s" % postfix if postfix else ""
template_type = template_type if template_type else "iframe"
slugified_id = self.slugified_id()
... | Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates. |
341,798 | def get_stp_mst_detail_output_msti_port_oper_root_guard(self, **kwargs):
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "mst... | Auto Generated Code |
341,799 | def export(self, class_name, method_name, export_data=False,
export_dir=, export_filename=,
export_append_checksum=False, **kwargs):
self.class_name = class_name
self.method_name = method_name
est = self.estimator
self.output_act... | Port a trained estimator to the syntax of a chosen programming language.
Parameters
----------
:param class_name : string
The name of the class in the returned result.
:param method_name : string
The name of the method in the returned result.
:param expor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.