Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
353,100 | def _convert_batch_to_json(batch_requests):
batch_boundary = b + _new_boundary()
changeset_boundary = b + _new_boundary()
body = [b + batch_boundary + b,
b,
changeset_boundary + b]
content_id = 1
for _, request in batch_requests:
body.append(b + changeset... | Create json to send for an array of batch requests.
batch_requests:
an array of requests |
353,101 | def printSequence(x, formatString="%d"):
numElements = len(x)
s = ""
for j in range(numElements):
s += formatString % x[j]
print s | Compact print a list or numpy array. |
353,102 | def get_token_credentials(cls, username, request):
try:
user = cls.get_item(username=username)
except Exception as ex:
log.error(str(ex))
forget(request)
else:
if user:
return user.api_key.token | Get api token for user with username of :username:
Used by Token-based auth as `credentials_callback` kwarg. |
353,103 | def parse(self, data):
method = getattr(self, .format(self._format))
return method(data) | Calls the right method depending on the format,
which can be one of the wollowing:
* alfred_vis
* txtinfo |
353,104 | def resolve_targetfile(self, args, require_sim_name=False):
ttype = args.get()
if is_null(ttype):
sys.stderr.write()
return (None, None)
sim = args.get()
if is_null(sim):
if require_sim_name:
sys.stderr.write()
... | Get the name of the targetfile based on the job arguments |
353,105 | def ped_parser(self, family_info):
for line in family_info:
if not line.startswith() and not all(c in whitespace for c in line.rstrip()):
splitted_line = line.rstrip().split()
if len(splitted_line) != 6:
... | Parse .ped formatted family info.
Add all family info to the parser object
Arguments:
family_info (iterator): An iterator with family info |
353,106 | def list_candidate_adapter_ports(self, full_properties=False):
sg_cpc = self.cpc
adapter_mgr = sg_cpc.adapters
port_list = []
port_uris = self.get_property()
if port_uris:
for port_uri in port_uris:
m = re.match(r, port_uri)
a... | Return the current candidate storage adapter port list of this storage
group.
The result reflects the actual list of ports used by the CPC, including
any changes that have been made during discovery. The source for this
information is the 'candidate-adapter-port-uris' property of the
... |
353,107 | def get_signal_models(self):
base = self.db.Model
return [
cls for cls in base._decl_class_registry.values() if (
isinstance(cls, type)
and issubclass(cls, base)
and hasattr(cls, )
)
] | Return all signal types in a list.
:rtype: list(`signal-model`) |
353,108 | def deserialize(self, value, **kwargs):
compartment = value
if self.compartment is not None:
compartment = value[self.compartment]
try:
value = self.accessor.get(compartment, **kwargs)
except (KeyError, AttributeError):
if not hasattr(self, ... | Deserialize the attribute from a HAL structure.
Get the value from the HAL structure from the attribute's compartment
using the attribute's name as a key, convert it using the attribute's
type. Schema will either return it to parent schema or will assign
to the output value if specifie... |
353,109 | def change_username_view(self):
form = self.ChangeUsernameFormClass(request.form)
if request.method == and form.validate():
new_username = form.new_username.data
current_user.username=new_username
self.db_manager.save_object... | Prompt for new username and old password and change the user's username. |
353,110 | def action_webimport(hrlinetop=False):
DIR_OPTIONS = {1: "http://lov.okfn.org", 2: "http://prefix.cc/popular/"}
selection = None
while True:
if hrlinetop:
printDebug("----------")
text = "Please select which online directory to scan: (enter=quit)\n"
for x in ... | select from the available online directories for import |
353,111 | def rand_str(length, allowed=CHARSET_ALPHA_DIGITS):
res = list()
for _ in range(length):
res.append(random.choice(allowed))
return "".join(res) | Generate fixed-length random string from your allowed character pool.
:param length: total length of this string.
:param allowed: allowed charset.
Example::
>>> import string
>>> rand_str(32)
H6ExQPNLzb4Vp3YZtfpyzLNPFwdfnwz6 |
353,112 | def topic_coupling(model, threshold=None, **kwargs):
if not threshold:
threshold = 3./model.Z
select = lambda f, v, c, dc: v > threshold
graph = coupling(model.corpus, , filter=select, **kwargs)
graph.name =
return graph | Two papers are coupled if they both contain a shared topic above a
``threshold``.
Parameters
----------
model : :class:`.LDAModel`
threshold : float
Default: ``3./model.Z``
kwargs : kwargs
Passed on to :func:`.coupling`\.
Returns
-------
:ref:`networkx.Graph <networ... |
353,113 | def _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir):
with open(argfile, "w") as out_handle:
if argfile.endswith(".json"):
record_name, record_attrs = _get_record_attrs(out_keys)
if record_name:
if parallel in ["multi-batch"]:
... | Write output argfile, preparing a CWL ready JSON or YAML representation of the world. |
353,114 | def get_projects(self, **kwargs):
_login = kwargs.get(, self._login)
search_url = SEARCH_URL.format(login=_login)
return self._request_api(url=search_url).json() | Get a user's project.
:param str login: User's login (Default: self._login)
:return: JSON |
353,115 | def QA_indicator_DDI(DataFrame, N=13, N1=26, M=1, M1=5):
H = DataFrame[]
L = DataFrame[]
DMZ = IF((H + L) > (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
DMF = IF((H + L) < (REF(H, 1) + REF(L, 1)),
MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0... | '方向标准离差指数'
分析DDI柱状线,由红变绿(正变负),卖出信号参考;由绿变红,买入信号参考。 |
353,116 | def get_key(cls, k, default=None):
k = cls.__name__ + "__" + k
if k in session:
return session[k]
else:
return default | Matching get method for ``set_key`` |
353,117 | def p_formal_parameter_list(self, p):
if len(p) == 2:
p[0] = [p[1]]
else:
p[1].append(p[3])
p[0] = p[1] | formal_parameter_list : identifier
| formal_parameter_list COMMA identifier |
353,118 | def failed(self, fail_on_warnings=True):
return bool(self.errors) or (fail_on_warnings and bool(self.warnings)) | Returns a boolean value describing whether the validation
succeeded or not. |
353,119 | def query(self, sql):
try:
self.connect()
with self.con.cursor() as cursor:
cursor.execute(sql)
self.con.commit()
res = cursor.fetchall()
return res
except Exception as e:
print(e)
re... | 根据sql查询
Args:
sql: sql 语句 str
return:
成功: 查询的结果
失败: -1 并打印返回报错信息 |
353,120 | def job_list():
args = dict((key, value) for key, value in flask.request.args.items())
limit = args.pop(, 100)
offset = args.pop(, 0)
select = sql.select(
[db.JOBS_TABLE.c.job_id],
from_obj=[db.JOBS_TABLE.outerjoin(
db.METADATA_TABLE,
db.JOBS_TABLE.c.job_id ... | List all jobs.
:param _limit: maximum number of jobs to show (default 100)
:type _limit: int
:param _offset: how many jobs to skip before showin the first one (default 0)
:type _offset: int
:param _status: filter jobs by status (complete, error)
:type _status: string
Also, you can filter t... |
353,121 | def iter_links_meta_element(cls, element):
if element.attrib.get(, ).lower() == :
content_value = element.attrib.get()
if content_value:
link = parse_refresh(content_value)
if link:
yield LinkInfo(
ele... | Iterate the ``meta`` element for links.
This function handles refresh URLs. |
353,122 | def writefile(openedfile, newcontents):
openedfile.seek(0)
openedfile.truncate()
openedfile.write(newcontents) | Set the contents of a file. |
353,123 | def invert(self, invert=True):
if(isinstance(invert, (tuple, list)) and
len(self.channels) != len(invert)):
raise ValueError(
"Number of channels and invert components differ.")
logger.debug("Applying invert with parameters %s", str(invert))
if is... | Inverts all the channels of a image according to *invert*. If invert is a tuple or a list, elementwise
invertion is performed, otherwise all channels are inverted if *invert* is true (default).
Note: 'Inverting' means that black becomes white, and vice-versa, not that the values are negated ! |
353,124 | def _gather_configs_in(directory):
try:
return sorted([
os.path.join(directory, fname)
for fname in os.listdir(directory)
if fname.endswith()
])
except OSError:
return [] | Return list of fully qualified python filenames in the given dir |
353,125 | def me(show_all=False, show_inprogress=False, show_open=False, quiet=False):
default = not [arg for arg in sys.argv[2:] if arg not in (, )]
status_exclusions = [, , ]
status_inclusions = []
if show_inprogress or default:
status_inclusions.append()
if show_open:
status_exclusio... | Prints a list of the users tickets and provides filtering options |
353,126 | def rfc2425encode(name,value,parameters=None,charset="utf-8"):
if not parameters:
parameters={}
if type(value) is unicode:
value=value.replace(u"\r\n",u"\\n")
value=value.replace(u"\n",u"\\n")
value=value.replace(u"\r",u"\\n")
value=value.encode(charset,"replace")
... | Encodes a vCard field into an RFC2425 line.
:Parameters:
- `name`: field type name
- `value`: field value
- `parameters`: optional parameters
- `charset`: encoding of the output and of the `value` (if not
`unicode`)
:Types:
- `name`: `str`
- `value`: `u... |
353,127 | def delete_metadata_value(metadata_source, key: str) -> None:
desc = session_key_map.get(key)
if desc is not None:
d0 = getattr(metadata_source, "session_metadata", dict())
d = d0
for k in desc[][:-1]:
d = d.setdefault(k, dict()) if d is not None else None
if d ... | Delete the metadata value for the given key.
There are a set of predefined keys that, when used, will be type checked and be interoperable with other
applications. Please consult reference documentation for valid keys.
If using a custom key, we recommend structuring your keys in the '<dotted>.<group>.<att... |
353,128 | def reverse_transform(self, tables, table_metas=None, missing=None):
if missing is None:
missing = self.missing
else:
self.missing = missing
warnings.warn(DEPRECATION_MESSAGE.format(), DeprecationWarning)
reverse = {}
for table_name in tab... | Transform data back to its original format.
Args:
tables(dict): mapping of table names to `tuple` where each tuple is on the form
(`pandas.DataFrame`, `dict`). The `DataFrame` contains the transformed
data and the `dict` the corresponding me... |
353,129 | def pivot(self, column_):
if isinstance(column_, str):
try:
return self.data.reset_index().pivot(
index=,
columns=,
values=column_
)
except:
return self.data.reset_index()... | 增加对于多列的支持 |
353,130 | def add_category(self, name):
category = BayesCategory(name)
self.categories[name] = category
return category | Adds a bayes category that we can later train
:param name: name of the category
:type name: str
:return: the requested category
:rtype: BayesCategory |
353,131 | def save_downloaded_file(filename, save_file_at, file_stream):
filename = os.path.join(save_file_at, filename)
with open(filename, ) as f:
f.write(file_stream)
f.flush() | Save Downloaded File to Disk Helper Function
:param save_file_at: Path of where to save the file.
:param file_stream: File stream
:param filename: Name to save the file. |
353,132 | def modify_area(self, pid, xmin, xmax, zmin, zmax, value):
area_polygon = shapgeo.Polygon(
((xmin, zmax), (xmax, zmax), (xmax, zmin), (xmin, zmin))
)
self.modify_polygon(pid, area_polygon, value) | Modify the given dataset in the rectangular area given by the
parameters and assign all parameters inside this area the given value.
Partially contained elements are treated as INSIDE the area, i.e., they
are assigned new values.
Parameters
----------
pid: int
... |
353,133 | def _assign_ascii_character(self, y_prev, y, y_next):
char =
if y_next > y and y_prev > y:
char =
elif y_next < y and y_prev < y:
char =
elif y_prev < y and y == y_next:
char =
elif y_prev == y... | Assign the character to be placed into the graph |
353,134 | def ns(self, value):
if value == self._defaults[] and in self._values:
del self._values[]
else:
self._values[] = value | The ns property.
Args:
value (string). the property value. |
353,135 | def guessImageMetadataFromData(img_data):
format, width, height = None, None, None
img_stream = io.BytesIO(img_data)
try:
img = PIL.Image.open(img_stream)
except IOError:
format = imghdr.what(None, h=img_data)
format = SUPPORTED_IMG_FORMATS.get(format, None)
else:
format... | Identify an image format and size from its first bytes. |
353,136 | def get_opt_attr(obj_pyxb, attr_str, default_val=None):
v = getattr(obj_pyxb, attr_str, default_val)
return v if v is not None else default_val | Get an optional attribute value from a PyXB element.
The attributes for elements that are optional according to the schema and
not set in the PyXB object are present and set to None.
PyXB validation will fail if required elements are missing.
Args:
obj_pyxb: PyXB object
attr_str: str
... |
353,137 | def focusedWindow(cls):
x, y, w, h = PlatformManager.getWindowRect(PlatformManager.getForegroundWindow())
return Region(x, y, w, h) | Returns a Region corresponding to whatever window is in the foreground |
353,138 | def get_transition_chempots(self, element):
if element not in self.elements:
raise ValueError("get_transition_chempots can only be called with "
"elements in the phase diagram.")
critical_chempots = []
for facet in self.facets:
chemp... | Get the critical chemical potentials for an element in the Phase
Diagram.
Args:
element: An element. Has to be in the PD in the first place.
Returns:
A sorted sequence of critical chemical potentials, from less
negative to more negative. |
353,139 | def deserialize(self, value, environment=None):
value = self._resolve_value(value, environment)
try:
value = self._deserialize(value, environment)
if self._validator is not None:
value = self._validator(self, value, environment)
except ex... | Deserialize a value into a special application specific format or type.
`value` can be `Missing`, `None` or something else.
:param value: the value to be deserialized
:param environment: additional environment |
353,140 | def get_killer(args):
if POSIX:
log.debug()
from killer.killer_posix import KillerPosix
return KillerPosix(config_path=args.config, debug=args.debug)
elif WINDOWS:
log.debug()
from killer.killer_windows import KillerWindows
return KillerWindows(config_path=ar... | Returns a KillerBase instance subclassed based on the OS. |
353,141 | def find_threshold(errors, z_range=(0, 10)):
mean = errors.mean()
std = errors.std()
min_z, max_z = z_range
best_z = min_z
best_cost = np.inf
for z in range(min_z, max_z):
best = fmin(z_cost, z, args=(errors, mean, std), full_output=True, disp=False)
z, cost = best[0:2]
... | Find the ideal threshold.
The ideal threshold is the one that minimizes the z_cost function. |
353,142 | def spin_sy(self):
return conversions.secondary_spin(self.mass1, self.mass2, self.spin1y,
self.spin2y) | Returns the y-component of the spin of the secondary mass. |
353,143 | def gen_token():
return .join(
random.choice(
string.ascii_uppercase + string.ascii_lowercase + string.digits)
for _ in range(32)) | Generate a new Skybellpy token. |
353,144 | async def get_locale(self) -> Text:
if self._locale_override:
return self._locale_override
else:
return await self.user.get_locale() | Get the locale to use for this request. It's either the overridden
locale or the locale provided by the platform.
:return: Locale to use for this request |
353,145 | def number_format(self):
number_format = self._number_format
if number_format is None:
return self._chart_data.number_format
return number_format | The formatting template string that determines how a number in this
series is formatted, both in the chart and in the Excel spreadsheet;
for example '#,##0.0'. If not specified for this series, it is
inherited from the parent chart data object. |
353,146 | def resolve_namespace(self, qname):
if in qname:
prefix, name = qname.split(, 1)
uri = self._ns[prefix]
else:
name = qname
if None in self._ns:
uri = self._ns[None]
else:
uri = None
return (uri,... | Obtain (uri, name) from a qualified name |
353,147 | def get_delta(self, branch, turn_from, tick_from, turn_to, tick_to):
from functools import partial
if turn_from == turn_to:
return self.get_turn_delta(branch, turn_from, tick_from, tick_to)
delta = {}
graph_objs = self._graph_objs
if turn_to < turn_from:
... | Get a dictionary describing changes to all graphs.
The keys are graph names. Their values are dictionaries of the graphs'
attributes' new values, with ``None`` for deleted keys. Also in those graph
dictionaries are special keys 'node_val' and 'edge_val' describing changes
to node and ed... |
353,148 | def _set_fcoe_fcport_group_config(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=fcoe_fcport_group_config.fcoe_fcport_group_config, is_container=, presence=False, yang_name="fcoe-fcport-group-config", rest_name="fcport-group", parent=self, path_helpe... | Setter method for fcoe_fcport_group_config, mapped from YANG variable /fcoe/fcoe_fabric_map/fcoe_fcport_group_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_fcport_group_config is considered as a private
method. Backends looking to populate this vari... |
353,149 | def canonical_fix_name(fix, avail_fixes):
if ".fix_" in fix:
return fix
else:
if fix.startswith():
fix = fix[4:]
found = [f for f in avail_fixes
if f.endswith(.format(fix))]
if len(found) > 1:
raise ValueErr... | Examples:
>>> canonical_fix_name('fix_wrap_text_literals')
'libfuturize.fixes.fix_wrap_text_literals'
>>> canonical_fix_name('wrap_text_literals')
'libfuturize.fixes.fix_wrap_text_literals'
>>> canonical_fix_name('wrap_te')
ValueError("unknown fixer name")
>>> canonical_fix_name('wrap')
... |
353,150 | def tmpfile (dir=None, prefix="temp", suffix=None):
return tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)[1] | Return a temporary file. |
353,151 | def resolve_to_objects_or_project(path, all_matching_results=False):
t match a
data object path.
Returns either a list of results or a single result (depending on
how many is expected; if only one, then an interactive picking of
a choice will be initiated if input is a tty, or else throw an error).... | :param path: Path to resolve
:type path: string
:param all_matching_results: Whether to return a list of all matching results
:type all_matching_results: boolean
A thin wrapper over :meth:`resolve_existing_path` which throws an
error if the path does not look like a project and doesn't match a
... |
353,152 | def compile_with_symbol(self, func, theano_args=None, owner=None):
if theano_args is None:
theano_args = []
upc = UpdateCollector()
theano_ret = func(*theano_args) if owner is None \
else func(owner, *theano_args)
out = copy.... | Compile the function with theano symbols |
353,153 | def get_coords(data):
for category, vtypes in [("LOH", {"LOSS", "HETEROZYGOSITY"}),
("amplification", {"AMPLIFICATION"})]:
out = tz.get_in([category, dd.get_genome_build(data)], _COORDS, {})
priority_file = dd.get_svprioritize(data)
if priority_file:
... | Retrieve coordinates of genes of interest for prioritization.
Can read from CIViC input data or a supplied BED file of chrom, start, end
and gene information. |
353,154 | def add_data_point(self, value, number_format=None):
data_point = CategoryDataPoint(self, value, number_format)
self.append(data_point)
return data_point | Return a CategoryDataPoint object newly created with value *value*,
an optional *number_format*, and appended to this sequence. |
353,155 | def network_expansion(network, method = , ext_min=0.1,
ext_width=False, filename=None, boundaries=[]):
cmap = plt.cm.jet
overlay_network = network.copy()
overlay_network.lines = overlay_network.lines[
overlay_network.lines.s_nom_extendable & ((
... | Plot relative or absolute network extension of AC- and DC-lines.
Parameters
----------
network: PyPSA network container
Holds topology of grid including results from powerflow analysis
method: str
Choose 'rel' for extension relative to s_nom and 'abs' for
absolute extension... |
353,156 | def fromstring(data) -> :
box.obj
vert = []
text = []
norm = []
face = []
data = RE_COMMENT.sub(, data)
for line in data.splitlines():
line = line.strip()
if not line:
continue
match = RE_VERT.match(line)
... | Args:
data (str): The obj file content.
Returns:
Obj: The object.
Examples:
.. code-block:: python
import ModernGL
from ModernGL.ext import obj
content = open('box.obj').read()
... |
353,157 | def skip(mapping):
found = set()
for m in mapping:
matched_atoms = set(m.values())
if found.intersection(matched_atoms):
continue
found.update(matched_atoms)
yield m | :param mapping: generator
:return: filtered generator |
353,158 | def fetch_presences(data_dir, deputies, date_start, date_end):
presences = PresencesDataset()
df = presences.fetch(deputies, date_start, date_end)
save_to_csv(df, data_dir, "presences")
log.info("Presence records:", len(df))
log.info("Records of deputies present on a session:", len(df[df.prese... | :param data_dir: (str) directory in which the output file will be saved
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) a date in the format dd/mm/yyyy
:param date_end: (str) a date in the format dd/mm/yyyy |
353,159 | def whiten(self, fftlength=None, overlap=0, method=DEFAULT_FFT_METHOD,
window=, detrend=, asd=None,
fduration=2, highpass=None, **kwargs):
fftlength = fftlength if fftlength else _fft_length_default(self.dt)
if asd is None:
asd = self.asd(fftle... | Whiten this `TimeSeries` using inverse spectrum truncation
Parameters
----------
fftlength : `float`, optional
FFT integration length (in seconds) for ASD estimation,
default: choose based on sample rate
overlap : `float`, optional
number of seconds ... |
353,160 | def add(self, word):
if not word or word.strip() == :
return
self.words[word]=word | Add a word to the dictionary |
353,161 | def _finalize(self, dtype=np.uint8):
channels = []
if self.mode == "P":
self.convert("RGB")
if self.mode == "PA":
self.convert("RGBA")
for chn in self.channels:
if isinstance(chn, np.ma.core.MaskedArray):
final_data = chn.data... | Finalize the image, that is put it in RGB mode, and set the channels
in unsigned 8bit format ([0,255] range) (if the *dtype* doesn't say
otherwise). |
353,162 | def get_user_name():
if sys.platform == :
user = os.getenv()
else:
user = os.getenv()
return user | Get user name provide by operating system |
353,163 | def add_otp_style(self, zip_odp, style_file):
style = zipwrap.Zippier(style_file)
for picture_file in style.ls("Pictures"):
zip_odp.write(picture_file, style.cat(picture_file, True))
xml_data = style.cat("styles.xml", False)
xml_data = self.override_styles(x... | takes the slide content and merges in the style_file |
353,164 | def metered_meta(metrics, base=type):
class _MeteredMeta(base):
def __new__(meta, name, bases, dict_):
new_dict = dict(**dict_)
for attr_name, template, factory in metrics:
new_dict[attr_name] = factory(template.format(name))
return super(_MeteredMeta... | Creates a metaclass that will add the specified metrics at a path parametrized on the dynamic class name.
Prime use case is for base classes if all subclasses need separate metrics and / or the metrics need to be
used in base class methods, e.g., Tornado's ``RequestHandler`` like::
import tapes
... |
353,165 | def nunpack(s, default=0):
l = len(s)
if not l:
return default
elif l == 1:
return ord(s)
elif l == 2:
return struct.unpack(, s)[0]
elif l == 3:
return struct.unpack(, b+s)[0]
elif l == 4:
return struct.unpack(, s)[0]
else:
raise TypeError... | Unpacks 1 to 4 byte integers (big endian). |
353,166 | def read_squad_examples(input_file, is_training, version_2_with_negative):
with open(input_file, "r", encoding=) as reader:
input_data = json.load(reader)["data"]
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
r... | Read a SQuAD json file into a list of SquadExample. |
353,167 | def set_entry(self, entry_name, key, value):
self.cache[entry_name][key] = value | Replaces entire cache entry parameter data by its name with new data.
:param str|unicode entry_name:
:param key:
:param value: |
353,168 | def delete(self, service, path, **kwargs):
return self.make_request(Methods.DELETE, service, path, **kwargs) | Make a delete requests (this returns a coroutine) |
353,169 | def submit(fn, io_loop, *args, **kwargs):
future = Future()
def execute():
try:
result = gen.maybe_future(fn(*args, **kwargs))
except Exception:
f = gen.Future()
f.set_exc_info(sys.exc_info())
on_done(f)
... | Submit Tornado Coroutine to IOLoop.current().
:param fn: Tornado Coroutine to execute
:param io_loop: Tornado IOLoop where to schedule the coroutine
:param args: Args to pass to coroutine
:param kwargs: Kwargs to pass to coroutine
:returns tornado.concurrent.Future: future result of coroutine |
353,170 | def fft(t, y, pow2=False, window=None, rescale=False):
if pow2:
keep = 2**int(_n.log2(len(y)))
y.resize(keep)
t.resize(keep)
if not window in [None, False, 0]:
try:
w = eval("_n."+window, dict(_n=_n))(len(y))
... | FFT of y, assuming complex or real-valued inputs. This goes through the
numpy fourier transform process, assembling and returning (frequencies,
complex fft) given time and signal data y.
Parameters
----------
t,y
Time (t) and signal (y) arrays with which to perform the fft. Note the t
... |
353,171 | def on_step_end(self, step, logs):
episode = logs[]
self.observations[episode].append(logs[])
self.rewards[episode].append(logs[])
self.actions[episode].append(logs[])
self.metrics[episode].append(logs[])
self.step += 1 | Update statistics of episode after each step |
353,172 | def get_note(self, noteid, version=None):
params_version = ""
if version is not None:
params_version = + str(version)
params = % (str(noteid), params_version)
request = Request(DATA_URL+params)
request.add_header(self.header, self.get_token())
... | Method to get a specific note
Arguments:
- noteid (string): ID of the note to get
- version (int): optional version of the note to get
Returns:
A tuple `(note, status)`
- note (dict): note object
- status (int): 0 on success and -1 otherwise |
353,173 | def render_te_response(self, data):
if in data and not in data:
data[] = self.request.get_full_path()
return JsonResponse(data) | Render data to JsonResponse |
353,174 | def getImage(self, body, imageScalar=2, plotShape="circle", imageEncoding="base64/png", sparsity=1.0):
return self._image.getImageForExpression(self._retina, body, imageScalar, plotShape, imageEncoding, sparsity) | Get images for expressions
Args:
body, ExpressionOperation: The JSON encoded expression to be evaluated (required)
imageScalar, int: The scale of the image (optional)
plotShape, str: The image shape (optional)
imageEncoding, str: The encoding of the returned image... |
353,175 | def iteritems(self):
current_buf = self.ptr.contents.buffer
length = self.ptr.contents.length
seen_length = 0
header = c_size_t()
position = c_uint32()
arraylength = c_size_t()
arrayptr = FloatPtr()
header_ = byref(header)
position_ = byre... | Get a generator which yields (offset, array) |
353,176 | def _create_sponge(self, index):
seed = self.seed_as_trits[:]
sponge = Kerl()
sponge.absorb(add_trits(seed, trits_from_int(index)))
sponge.squeeze(seed)
sponge.reset()
sponge.absorb(seed)
return sponge | Prepares the hash sponge for the generator. |
353,177 | def get_one_required(self, name):
locator = self._locate(name)
if locator == None:
raise ReferenceException(None, name)
return self._references.get_one_required(locator) | Gets one required dependency by its name.
At least one dependency must present. If the dependency was found it throws a [[ReferenceException]]
:param name: the dependency name to locate.
:return: a dependency reference |
353,178 | def import_module(module_name):
try:
return importlib.import_module(module_name)
except ImportError as err:
raise UnknownModuleError(str(err)) | Given a dotted Python path, imports & returns the module.
If not found, raises ``UnknownModuleError``.
Ex::
mod = import_module('random')
:param module_name: The dotted Python path
:type module_name: string
:returns: module |
353,179 | def _dlinear_seaborn_(self, label=None, style=None, opts=None):
color, size = self._get_color_size(style)
try:
fig = sns.jointplot(self.x, self.y, color=color,
size=size, data=self.df, kind="reg")
fig = self._set_with_height(fig, opts)
... | Returns a Seaborn linear regression plot with marginal distribution |
353,180 | def print_diff(diff, color=True):
import colorama
if not diff:
return
if not color:
colorama.init = lambda autoreset: None
colorama.Fore.RED =
colorama.Back.RED =
colorama.Fore.GREEN =
colorama.deinit = lambda: None
colorama.init(autoreset=True)... | Pretty printing for a diff, if color then we use a simple color scheme
(red for removed lines, green for added lines). |
353,181 | def _collect_by_key(self,specs):
allkeys = itertools.chain.from_iterable(
[[(k, run[k]) for k in run] for run in specs])
collection = defaultdict(list)
for (k,v) in allkeys: collection[k].append(v)
return collection | Returns a dictionary like object with the lists of values
collapsed by their respective key. Useful to find varying vs
constant keys and to find how fast keys vary. |
353,182 | def get_connection(self, request):
protocol = request.protocol_override \
if request.protocol_override else self.protocol
protocol = protocol.lower()
target_host = request.host
connection = _RequestsConnection(
target_host, protocol, self.reques... | Create connection for the request. |
353,183 | def as4_capability(self, **kwargs):
enabled = kwargs.pop(, True)
callback = kwargs.pop(, self._callback)
if not isinstance(enabled, bool):
raise ValueError( % repr(enabled))
as4_capability_args = dict(vrf_name=kwargs.pop(, ),
rbri... | Set Spanning Tree state.
Args:
enabled (bool): Is AS4 Capability enabled? (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
``ElementTree`` `config`.
Returns... |
353,184 | def format_author_ed(citation_elements):
for el in citation_elements:
if el[] == :
el[] = el[].replace(, )
el[] = el[].replace(, )
return citation_elements | Standardise to (ed.) and (eds.)
e.g. Remove extra space in (ed. ) |
353,185 | def classifySPoutput(targetOutputColumns, outputColumns):
numTargets, numDims = targetOutputColumns.shape
overlap = np.zeros((numTargets,))
for i in range(numTargets):
overlap[i] = percentOverlap(outputColumns, targetOutputColumns[i, :])
classLabel = np.argmax(overlap)
return classLabel | Classify the SP output
@param targetOutputColumns (list) The target outputs, corresponding to
different classes
@param outputColumns (array) The current output
@return classLabel (int) classification outcome |
353,186 | def _sanitize_column(self, key, value, broadcast=True):
def reindexer(value):
if value.index.equals(self.index) or not len(self.index):
value = value._values.copy()
else:
try:
value = value.rein... | Ensures new columns (which go into the BlockManager as new blocks) are
always copied and converted into an array.
Parameters
----------
key : object
value : scalar, Series, or array-like
broadcast : bool, default True
If ``key`` matches multiple duplicate col... |
353,187 | def packet_events(packet: dict) -> Generator:
field_abbrev = {v: k for k, v in PACKET_FIELDS.items()}
packet_id = serialize_packet_id(packet)
events = {f: v for f, v in packet.items() if f in field_abbrev}
if in events or in events:
yield dict(id=packet_id, **events)
else:
... | Return list of all events in the packet.
>>> x = list(packet_events({
... 'protocol': 'alecto v1',
... 'id': 'ec02',
... 'temperature': 1.0,
... 'temperature_unit': '°C',
... 'humidity': 10,
... 'humidity_unit': '%',
... }))
>>> assert {
... 'id': 'al... |
353,188 | def setup_ui(self, ):
labels = self.reftrack.get_option_labels()
self.browser = ComboBoxBrowser(len(labels), headers=labels)
self.browser_vbox.addWidget(self.browser) | Setup the ui
:returns: None
:rtype: None
:raises: None |
353,189 | def create(self, name, site_element):
site_element = element_resolver(site_element)
json = {
: name,
: site_element}
return ElementCreator(
self.__class__,
href=self.href,
json=json) | Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElementFailed: create element failed with reason
:return: href of new element
... |
353,190 | def stop_supporting_containers(get_container_name, extra_containers):
docker.remove_container(get_container_name())
docker.remove_container(get_container_name())
for container in extra_containers:
docker.remove_container(get_container_name(container)) | Stop postgres and solr containers, along with any specified extra containers |
353,191 | def read_plain_int96(file_obj, count):
items = struct.unpack(b"<" + b"qi" * count, file_obj.read(12 * count))
return [q << 32 | i for (q, i) in zip(items[0::2], items[1::2])] | Read `count` 96-bit ints using the plain encoding. |
353,192 | def _readall(self):
return _handle_http_errors(
self._client.request(
, self.name, timeout=self._TIMEOUT)).content | Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content |
353,193 | def exists(Name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
events = conn.list_rules(NamePrefix=Name)
if not events:
return {: False}
for rule in events.get(, []):
if rule.get... | Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent region=us-east-1 |
353,194 | def get_state(self, key):
_data = self.state_db.get(key)
if not _data:
raise KeyError(key)
else:
return State().from_json(_data) | Get the state connected to a given key.
:param key: Key into the state database
:return: A :py:class:´oidcservice.state_interface.State` instance |
353,195 | def update(self, members):
if isinstance(members, RedisSet):
size = self.size
return (self.unionstore(
self.key_prefix, members.key_prefix) - size)
if self.serialized:
members = list(map(self._dumps, members))
if members:
r... | Adds @members to the set
@members: a :class:RedisSet object or #set
-> #int the number of @members that were added to the set,
excluding pre-existing members |
353,196 | def delete(self, obj, force=False):
if not force:
for fs in self:
try:
fs.get(obj)
except FieldSelectorException:
raise
for fs in self:
try:
fs.delete(obj)
excep... | Deletes all of the fields at the specified locations.
args:
``obj=``\ *OBJECT*
the object to remove the fields from
``force=``\ *BOOL*
if True, missing attributes do not raise errors. Otherwise,
the first failure raises an exception wit... |
353,197 | def can_delete_activities(self):
url_path = construct_url(,
bank_id=self._catalog_idstr)
return self._get_request(url_path)[][] | Tests if this user can delete Activities.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known deleting an Activity
will result in a PermissionDenied. This is intended as a hint
to an application that may opt not to offer delete opera... |
353,198 | def format_image(self, image, image_format, **kwargs):
if image_format in (, , , , , ):
if image_format != and FORCE_WEBP:
accept = self.request.META[].split()
if in accept:
image = image.convert()
i... | Returns an image in the request format |
353,199 | def _change_state(interface, new_state):
if __grains__[] == :
return _change_state_legacy(interface, new_state)
service = _interface_to_service(interface)
if not service:
raise salt.exceptions.CommandExecutionError(.format(interface))
connected = _connected(service)
if (not conn... | Enable or disable an interface
Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot.
:param interface: interface label
:param new_state: up or down
:return: True if the service was enabled, otherwise an exception will be thrown.
:rtype: bool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.