Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,300 | def _deleteRangeFromKNN(self, start=0, end=None):
classifier = self.htm_prediction_model._getAnomalyClassifier()
knn = classifier.getSelf()._knn
prototype_idx = numpy.array(
classifier.getSelf().getParameter())
if end is None:
end = prototype_idx.max() + 1
idsIdxToDelete = numpy.... | This method will remove any stored records within the range from start to
end. Noninclusive of end.
parameters
------------
start - integer representing the ROWID of the start of the deletion range,
end - integer representing the ROWID of the end of the deletion range,
if None, it will defaul... |
360,301 | def from_files(path_dir, dos_spin=1):
run_type, warning, efermi, gap, doping_levels = \
BoltztrapAnalyzer.parse_outputtrans(path_dir)
vol = BoltztrapAnalyzer.parse_struct(path_dir)
intrans = BoltztrapAnalyzer.parse_intrans(path_dir)
if run_type == "BOLTZ":
... | get a BoltztrapAnalyzer object from a set of files
Args:
path_dir: directory where the boltztrap files are
dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down
Returns:
a BoltztrapAnalyzer object |
360,302 | def context_setting(self):
if self.unlock_password == "":
raise Exception("请先配置交易解锁密码! password: {}".format(
self.unlock_password))
quote_ctx = ft.OpenQuoteContext(
host=self.api_svr_ip, port=self.api_svr_port)
if in self.stock:
tra... | API trading and quote context setting
:returns: trade context, quote context |
360,303 | def show_inline_matplotlib_plots():
if not in sys.modules:
flush_figures() | Show matplotlib plots immediately if using the inline backend.
With ipywidgets 6.0, matplotlib plots don't work well with interact when
using the inline backend that comes with ipykernel. Basically, the inline
backend only shows the plot after the entire cell executes, which does not
play well with dra... |
360,304 | def get_strain(cryst, refcell=None):
if refcell is None:
refcell = cryst
du = cryst.get_cell()-refcell.get_cell()
m = refcell.get_cell()
m = inv(m)
u = dot(m, du)
u = (u+u.T)/2
return array([u[0, 0], u[1, 1], u[2, 2], u[2, 1], u[2, 0], u[1, 0]]) | Calculate strain tensor in the Voight notation
Computes the strain tensor in the Voight notation as a conventional
6-vector. The calculation is done with respect to the crystal
geometry passed in refcell parameter.
:param cryst: deformed structure
:param refcell: reference, undeformed structure
... |
360,305 | def set_position(cls, resource_id, to_position, db_session=None, *args, **kwargs):
db_session = get_db_session(db_session)
resource = ResourceService.lock_resource_for_update(
resource_id=resource_id, db_session=db_session
)
cls.check_node_position(
... | Sets node position for new node in the tree
:param resource_id: resource to move
:param to_position: new position
:param db_session:
:return:def count_children(cls, resource_id, db_session=None): |
360,306 | def ContentFilesRelative(self):
return (os.path.relpath(path, self.ProjectHome) for path in sorted(self.ContentFiles, key=self.lower)) | Returns a generator iterating over the each file in :attr:`ContentFiles` relative to :attr:`ProjectHome` directory. |
360,307 | def translate(self, text):
self.count = 0
return self._make_regex().sub(self, text) | Translate text, returns the modified text. |
360,308 | def n1ql_index_build_deferred(self, other_buckets=False):
info = N1qlIndex()
if not other_buckets:
info.keyspace = self._cb.bucket
return IxmgmtRequest(self._cb, , info).execute() | Instruct the server to begin building any previously deferred index
definitions.
This method will gather a list of all pending indexes in the cluster
(including those created using the `defer` option with
:meth:`create_index`) and start building them in an efficient manner.
:pa... |
360,309 | def _unpack_bin(self, packed):
output = struct.unpack(, packed)
bits16 = output[0]
r = (bits16 & 0xF800) >> 11
g = (bits16 & 0x7E0) >> 5
b = (bits16 & 0x1F)
return [int(r << 3), int(g << 2), int(b << 3)] | Internal. Decodes 16 bit RGB565 into python list [R,G,B] |
360,310 | def get_slug(self, language_code, lang_name):
title = self.get_title(language_code, lang_name)
assert title != ""
title = str(title)
slug = slugify(title)
assert slug != "", "Title %r results in empty slug!" % title
return slug | Notes:
- slug must be unique!
- slug is used to check if page already exists!
:return: 'slug' string for cms.api.create_page() |
360,311 | def get_normalized_terms(term_id: str) -> dict:
canonical = term_id
decanonical = term_id
canonical_namespace_targets = config["bel"]["lang"]["canonical"]
decanonical_namespace_targets = config["bel"]["lang"]["decanonical"]
results = get_equivalents(term_id)
equivalents = results["equival... | Get normalized terms - canonical/decanonical forms |
360,312 | def files_in_directory(db, user_id, db_dirname):
fields = _file_default_fields()
rows = db.execute(
select(
fields,
).where(
_is_in_directory(files, user_id, db_dirname),
).order_by(
files.c.user_id,
files.c.parent_name,
fi... | Return files in a directory. |
360,313 | def to_madeline(self):
self.logger.debug("Returning madeline info")
if self.sex == 1:
madeline_gender =
elif self.sex == 2:
madeline_gender =
else:
madeline_gender =
if self.father == :
madeline_father ... | Return the individual info in a madeline formated string |
360,314 | def tee(self, *args):
d console output
is still verbosity filtered
tee(): returns the current syslog flag
tee(True|False): sets the flag to True|False
'
if len(args):
self._b_tee = args[0]
else:
return self... | get/set the tee flag.
The tee flag toggles any output that is directed to non-console
destinations to also appear on the console. Tee'd console output
is still verbosity filtered
tee(): returns the current syslog flag
tee(True|False): sets the fl... |
360,315 | def has_name_in(cls, names):
return cls.sha512.in_({
cls.hash_name(name)
for name in names
}) | Build a filter if the author has any of the given names. |
360,316 | def dump(obj, root_file, proto=0, key=None):
if isinstance(root_file, string_types):
root_file = root_open(root_file, )
own_file = True
else:
own_file = False
ret = Pickler(root_file, proto).dump(obj, key)
if own_file:
root_file.Close()
return ret | Dump an object into a ROOT TFile.
`root_file` may be an open ROOT file or directory, or a string path to an
existing ROOT file. |
360,317 | def _str_to_ord(content, weights):
ordinal = 0
for i, c in enumerate(content):
ordinal += weights[i] * _ALPHABET.index(c) + 1
return ordinal | Converts a string to its lexicographical order.
Args:
content: the string to convert. Of type str.
weights: weights from _get_weights.
Returns:
an int or long that represents the order of this string. "" has order 0. |
360,318 | def GetMACBRepresentationFromDescriptions(self, timestamp_descriptions):
macb_representation = []
if ( in timestamp_descriptions or
definitions.TIME_DESCRIPTION_MODIFICATION in timestamp_descriptions):
macb_representation.append()
else:
macb_representation.append()
if ( in tim... | Determines the MACB representation from the timestamp descriptions.
MACB representation is a shorthand for representing one or more of
modification, access, change, birth timestamp descriptions as the letters
"MACB" or a "." if the corresponding timestamp is not set.
Note that this is an output format... |
360,319 | def checkbox(message: Text,
choices: List[Union[Text, Choice, Dict[Text, Any]]],
default: Optional[Text] = None,
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
merged_style = merge_styles([DEFAU... | Ask the user to select from a list of items.
This is a multiselect, the user can choose one, none or many of the
items.
Args:
message: Question text
choices: Items shown in the selection, this can contain `Choice` or
or `Separator` objects or simple items as strings. Pass... |
360,320 | def example3():
n_data = 100
imgs_file_list = [] * n_data
train_targets = [np.ones(1)] * n_data
def generator():
if len(imgs_file_list) != len(train_targets):
raise RuntimeError()
for _input, _target in zip(imgs_file_list, train_targets):
yield _input, _targ... | Example 3: Using TF dataset API to load and process image for training |
360,321 | def value(self):
if not self.filled:
raise SlotNotFilledError(
% (self.name, self.key))
return self._value | Returns the current value of this slot.
Returns:
The value of the slot (a serializable Python type).
Raises:
SlotNotFilledError if the value hasn't been filled yet. |
360,322 | def retrieve_split_adjustment_data_for_sid(self,
dates,
sid,
split_adjusted_asof_idx):
adjustments = self._split_adjustments.get_adjustments_for_sid(
... | dates : pd.DatetimeIndex
The calendar dates.
sid : int
The sid for which we want to retrieve adjustments.
split_adjusted_asof_idx : int
The index in `dates` as-of which the data is split adjusted.
Returns
-------
pre_adjustments : tuple(list(f... |
360,323 | def _clean_message(message):
message = message.replace(, )
message = message.splitlines()
for line in message:
if line.startswith():
message.remove(line)
return "\n".join(message) | Internal helper to sanitize message output |
360,324 | def timeseries(self):
if self._timeseries is None:
if isinstance(self.grid, MVGrid):
voltage_level =
elif isinstance(self.grid, LVGrid):
voltage_level =
ts_total = None
for sector in self.consumption.keys():
... | Load time series
It returns the actual time series used in power flow analysis. If
:attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries()` looks for time series of the according sector in
:class:`~.grid.network.TimeSeries` object.
Returns
... |
360,325 | def __update_binding(
self, dependency, service, reference, old_properties, new_value
):
if new_value:
setattr(
self.instance, dependency.get_field(), dependency.get_value()
)
self.__safe_field_callback(
... | Calls back component binding and field binding methods when the
properties of an injected dependency have been updated.
:param dependency: The dependency handler
:param service: The injected service
:param reference: The reference of the injected service
:param old_properties: P... |
360,326 | def use_plenary_objective_bank_view(self):
self._objective_bank_view = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_objective_bank_view()
except AttributeError:
pass | Pass through to provider ObjectiveObjectiveBankSession.use_plenary_objective_bank_view |
360,327 | def _get_triplets_reciprocal_mesh_at_q(fixed_grid_number,
mesh,
rotations,
is_time_reversal=True,
swappable=True):
import phono3py._phono3py as phono3c
... | Search symmetry reduced triplets fixing one q-point
Triplets of (q0, q1, q2) are searched.
Parameters
----------
fixed_grid_number : int
Grid point of q0
mesh : array_like
Mesh numbers
dtype='intc'
shape=(3,)
rotations : array_like
Rotation matrices in r... |
360,328 | async def get_or_create(cls, lang: str, *,
client_token: str = None,
mounts: Iterable[str] = None,
envs: Mapping[str, str] = None,
resources: Mapping[str, int] = None,
cluster_size... | Get-or-creates a compute session.
If *client_token* is ``None``, it creates a new compute session as long as
the server has enough resources and your API key has remaining quota.
If *client_token* is a valid string and there is an existing compute session
with the same token and the same... |
360,329 | def fill_value(dtype):
if np.issubdtype(dtype, np.floating) or np.issubdtype(dtype, np.complexfloating):
return dtype(np.nan)
return dtype(0) | Get a fill-value for a given dtype
Parameters
----------
dtype : type
Returns
-------
`np.nan` if `dtype` is real or complex
0 otherwise |
360,330 | def _revcheck(self, func, version):
t accidentally make a call to something that
doesnt exist.
lt<=gt>=eq=equals'):
return check == current
else:
return False | Internal function to see if a version is func than what we have
determined to be talking to. This is very useful for newer API calls
to make sure we don't accidentally make a call to something that
doesnt exist. |
360,331 | def is_executable(command):
paths = os.environ.get("PATH", "").split(os.path.pathsep)
candidates = [command] + [os.path.join(p, command) for p in paths]
return any(os.access(path, os.X_OK) for path in candidates) | Returns if a command matches an executable on the PATH |
360,332 | def draw_capitan_score_bitmap(self, export_path: ExportPath) -> None:
with Image.fromarray(self.image_data, mode=) as image:
image.save(export_path.get_full_path()) | Draws the 30x30 symbol into the given file
:param export_path: The path, where the symbols should be created on disk |
360,333 | def new(params, num_components, event_shape=(),
validate_args=False, name=None):
return MixtureSameFamily.new(
params,
num_components,
IndependentLogistic(
event_shape, validate_args=validate_args, name=name),
validate_args=validate_args,
name=name) | Create the distribution instance from a `params` vector. |
360,334 | def n_day(date_string):
today = datetime.date.today()
match = re.match(r, date_string)
groups = match.groups()
if groups:
decrement = groups[0]
if decrement == :
decrement = 1
return today - datetime.timedelta(days=int(decremen... | date_string string in format "(number|a) day(s) ago" |
360,335 | def scaleBy(self, value, origin=None, width=False, height=False):
value = normalizers.normalizeTransformationScale(value)
if origin is None:
origin = (0, 0)
origin = normalizers.normalizeCoordinateTuple(origin)
if origin != (0, 0) and (width or height):
r... | %s
**width** indicates if the glyph's width should be scaled.
**height** indicates if the glyph's height should be scaled.
The origin must not be specified when scaling the width or height. |
360,336 | def _get_ds_descriptions_unsorted(
cls, data, ignore_keys=[, ], nums=None):
ds_description = {, , , , }
if in data:
data[].psy.num
keys_in_data = ds_description.intersection(data)
if keys_in_data:
return {key: data[key] for key i... | Recursive method to get all the file names or datasets out of a
dictionary `data` created with the :meth`array_info` method |
360,337 | def from_fp(self, file_pointer, comment_lead=[]):
self.nv = 0
self.hard = []
self.atms = []
self.soft = []
self.wght = []
self.topw = 0
self.comments = []
comment_lead = tuple() + tuple(comment_lead)
for line in file_pointer:
... | Read a WCNF+ formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:param file_pointer: a file pointer to read the formula from.
:pa... |
360,338 | async def _get(self, url: str) -> str:
async with self.session.get(url, headers=self.HEADERS) as r:
if r.status == 200:
return await r.text()
else:
raise RuneConnectionError(r.status) | A small wrapper method which makes a quick GET request
Parameters
----------
url : str
The URL to get.
Returns
-------
str
The raw html of the requested page.
Raises
------
RuneConnectionError
If the GET respo... |
360,339 | def parseAttributes(self, attributes=None, **kwAttributes):
attributes = attributes if attributes is not None else {}
if attributes:
kwAttributes.update(attributes)
self.cssBuilder.beginInline()
try:
properties = []
try:
for p... | Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr |
360,340 | def r2_score(df, col_true, col_pred=None):
if not col_pred:
col_pred = get_field_name_by_role(df, FieldRole.PREDICTED_VALUE)
return _run_evaluation_node(df, col_true, col_pred)[] | Compute determination coefficient (R2) of a predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFrame
:param col_true: column name of true value
:type col_true: str
:param col_true: column name of predicted value, '... |
360,341 | def find_teradata_home():
if platform.system() == :
if is_64bit():
return latest_teradata_version("C:/Program Files/Teradata/Client")
else:
return latest_teradata_version("C:/Program Files (x86)/Teradata/Client")
... | Attempts to find the Teradata install directory with the defaults
for a given platform. Should always return `None` when the defaults
are not present and the TERADATA_HOME environment variable wasn't
explicitly set to the correct install location. |
360,342 | def stream_by_method_name(name):
if name == u:
name = u
module = mitogen.core.import_module(u + name)
return module.Stream | Given the name of a Mitogen connection method, import its implementation
module and return its Stream subclass. |
360,343 | def is_installed(self):
return self.is_configured() and os.access(self.bin(), os.X_OK) | Check if the tool is installed.
Returns
-------
is_installed : bool
True if the tool is installed. |
360,344 | def _getattr_path(obj, path):
if not path:
return None
for attr in path.split():
obj = getattr(obj, attr, None)
return obj | getattr for a dot separated path
If an AttributeError is raised, it will return None. |
360,345 | def save(diff, stream=sys.stdout, compact=False):
"Serialize a patch object."
flags = {: True}
if not compact:
flags[] = 2
json.dump(diff, stream, **flags) | Serialize a patch object. |
360,346 | def preemphasis(signal, shift=1, cof=0.98):
rolled_signal = np.roll(signal, shift)
return signal - cof * rolled_signal | preemphasising on the signal.
Args:
signal (array): The input signal.
shift (int): The shift step.
cof (float): The preemphasising coefficient. 0 equals to no filtering.
Returns:
array: The pre-emphasized signal. |
360,347 | def getGenoIndex(self,pos0=None,pos1=None,chrom=None,pos_cum0=None,pos_cum1=None):
if (pos0 is not None) & (pos1 is not None) & (chrom is not None):
I = self.gneoChrom==chrom
I = I & (self.genoPos>=p0) & (self.genoPos<p1)
I = SP.nonzero(I)[0]
i0 = I.min()... | computes 0-based genotype index from position of cumulative position.
Positions can be given in one out of two ways:
- position (pos0-pos1 on chrom)
- cumulative position (pos_cum0-pos_cum1)
If all these are None (default), then all genotypes are returned
Args:
pos... |
360,348 | def execute_async(self, output_options=None, sampling=None, context=None, query_params=None):
if output_options is None:
output_options = QueryOutput.table()
batch = output_options.priority ==
append = output_options.table_mode ==
overwrite = output_options.table_mode ==
ta... | Initiate the query and return a QueryJob.
Args:
output_options: a QueryOutput object describing how to execute the query
sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling
context: an optional Context object providing project_id and credentials. If a specific
... |
360,349 | def transitions(self, return_matrix=True):
if return_matrix:
mat = np.zeros((self.nV, self.nV))
for v in self.g.nodes():
ind = [e[1] for e in sorted(self.g.out_edges(v))]
mat[v, ind] = self._route_probs[v]
else:
mat = {
... | Returns the routing probabilities for each vertex in the
graph.
Parameters
----------
return_matrix : bool (optional, the default is ``True``)
Specifies whether an :class:`~numpy.ndarray` is returned.
If ``False``, a dict is returned instead.
Returns
... |
360,350 | def pipe_strregex(context=None, _INPUT=None, conf=None, **kwargs):
splits = get_splits(_INPUT, conf[], **cdicts(opts, kwargs))
parsed = utils.dispatch(splits, *get_dispatch_funcs(first=convert_func))
_OUTPUT = starmap(parse_result, parsed)
return _OUTPUT | A string module that replaces text using regexes. Each has the general
format: "In [field] replace [regex pattern] with [text]". Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : iterable of items or strings
conf : {
'RULE': [
{
'match... |
360,351 | def set_tweights_all(self, tweights):
r
for node, (twsource, twsink) in enumerate(tweights):
self.set_tweight(node, twsource, twsink) | r"""
Set all t-weights at once.
Parameters
----------
tweights : iterable
Containing a pair of numeric values for each of the graphs nodes.
Notes
-----
Since this method overrides already existing t-weights, it is strongly
rec... |
360,352 | def _shapeletOutput(self, x, y, beta, shapelets, precalc=True):
n = len(np.atleast_1d(x))
if n <= 1:
values = 0.
else:
values = np.zeros(len(x[0]))
n = 0
k = 0
i = 0
num_n = len(shapelets)
while i < num_n * (num_n+1)/2:
... | returns the the numerical values of a set of shapelets at polar coordinates
:param shapelets: set of shapelets [l=,r=,a_lr=]
:type shapelets: array of size (n,3)
:param coordPolar: set of coordinates in polar units
:type coordPolar: array of size (n,2)
:returns: array of same si... |
360,353 | def set_fan_timer(self, timer):
desired_state = {"timer": timer}
resp = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})
self._update_state_from_response(resp) | :param timer: an int between fan_timer_range
:return: nothing |
360,354 | def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,
scope=None, state=None, **kwargs):
if not is_secure_transport(uri):
raise InsecureTransportError()
params = [((, response_type)),
((, client_id))]
if redirect_uri:
params.append... | Prepare the authorization grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the ``application/x-www-form-urlencoded`` format as defined by
[`W3C.REC-html401-19991224`_]:
:param uri:
:param ... |
360,355 | def aux_moveTree(offset, tree):
if tree.x1 != None and tree.x2 != None :
tree.x1, tree.x2 = tree.x1+offset, tree.x2+offset
for c in tree.children:
aux_moveTree(offset, c) | This a private recursive (You shouldn't have to call it) function that translates tree(and it's children) to a given x1 |
360,356 | def download(fname, input_dir, dl_dir=None):
try:
manager = _get_storage_manager(fname)
except ValueError:
return fname
return manager.download(fname, input_dir, dl_dir) | Download the resource from the storage. |
360,357 | def collinear(args):
p = OptionParser(collinear.__doc__)
p.set_beds()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
anchorfile, = args
qbed, sbed, qorder, sorder, is_self = check_beds(anchorfile, p, opts)
af = AnchorFile(anchorfile)
newa... | %prog collinear a.b.anchors
Reduce synteny blocks to strictly collinear, use dynamic programming in a
procedure similar to DAGchainer. |
360,358 | def _load_gui_setting(self, key, d=None):
pop_value = False
if pop_value: d.pop(key)
except:
print("ERROR: Could not load gui setting "+repr(key)) | Safely reads the header setting and sets the appropriate control
value.
Parameters
----------
key
Key string of the format 'self.controlname'.
d = None
Databox instance or dictionary, presumably containing the aforementioned
key. If d... |
360,359 | def reload(self, message):
self.phone = message.get()
self.level = message.get()
self.utype = message.get()
self.coins = message.get()
self.wechat_id = message.get()
self.coins_history = message.get()
self.money = message.get()
self._subscribed_s... | 恢复方法
Arguments:
message {[type]} -- [description] |
360,360 | def find_log_dir(log_dir=None):
if log_dir:
dirs = [log_dir]
elif FLAGS[].value:
dirs = [FLAGS[].value]
else:
dirs = [, ]
for d in dirs:
if os.path.isdir(d) and os.access(d, os.W_OK):
return d
_absl_logger.fatal("Can't find a writable directory for logs, tried %s... | Returns the most suitable directory to put log files into.
Args:
log_dir: str|None, if specified, the logfile(s) will be created in that
directory. Otherwise if the --log_dir command-line flag is provided,
the logfile will be created in that directory. Otherwise the logfile
will be crea... |
360,361 | def add_group(group, user=None):
user = get_user(user)
if user is None:
raise ValueError("User not found".format(repr(user)))
if isinstance(group, basestring):
group = [group]
elif isinstance(group, GroupData):
group = [group]
portal_groups = get_tool("portal_groups"... | Add the user to the group |
360,362 | def _expand(self, explore_iterable):
if self.v_locked:
raise pex.ParameterLockedException( % self.v_full_name)
if not self.f_has_range():
raise TypeError(
% self._name)
data_list = self._data_sanity_checks(explore_iterable)
... | Explores the parameter according to the iterable and appends to the exploration range.
Raises ParameterLockedException if the parameter is locked.
Raises TypeError if the parameter does not support the data,
the types of the data in the iterable are not the same as the type of the default value... |
360,363 | def make_bar(percentage):
bars = [, , , , , , , , , ]
tens = int(percentage / 10)
ones = int(percentage) - tens * 10
result = tens *
if(ones >= 1):
result = result + bars[ones]
result = result + (10 - len(result)) *
return result | Draws a bar made of unicode box characters.
:param percentage: A value between 0 and 100
:returns: Bar as a string |
360,364 | def get_record_rdd_from_rdd(
self,
rdd: ,
data_processor: DataProcessor = SimpleDictionaryDataProcessor(),
) -> :
return rdd.mapPartitions(
lambda x: self.get_per_identity_records(x, data_processor)).groupByKey().mapValues(list) | Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is
used to process the per row data to convert them into `Record`.
:param rdd: RDD containing the raw events.
:param data_processor: `DataProcessor` to process each row in the given `rdd`.
:return: R... |
360,365 | def _at_import(self, calculator, rule, scope, block):
sass_paths = calculator.evaluate_expression(block.argument)
css_imports = []
for sass_path in sass_paths:
if (
... | Implements @import
Load and import mixins and functions and rules |
360,366 | async def from_href(self):
if not hasattr(self, ):
raise TypeError()
elif hasattr(self, ):
return await self.http.request((, self.href))
else:
cls = type(self)
try:
client = getattr(self, .format(cls.__name__))
except At... | Get the full object from spotify with a `href` attribute. |
360,367 | def fix_keys(self):
if not self.valid:
return
for hit in self._results[][]:
for key, item in list(hit.items()):
if key.startswith("_"):
hit[key[1:]] = item
del hit[key] | Remove the _ from the keys of the results |
360,368 | def write_byte(self, address, data):
buf = [
self.WriteCommandWord,
address // 256,
address % 256,
self.EndMark,
self.WriteCommandWord,
data,
0,
self.EndMark,
]
if not self.dev.write_data... | Write a single byte to the weather station.
:param address: address to write to.
:type address: int
:param data: the value to write.
:type data: int
:return: success status.
:rtype: bool |
360,369 | def _wrap_type_instantiation(self, type_cls):
def wrapper(*args, **kwargs):
return type_cls(stream=self._null_stream)
return wrapper | Wrap the creation of the type so that we can provide
a null-stream to initialize it |
360,370 | def default_jardiff_options(updates=None):
parser = create_optparser()
options, _args = parser.parse_args(list())
if updates:
options._update_careful(updates)
return options | generate an options object with the appropriate default values in
place for API usage of jardiff features. overrides is an optional
dictionary which will be used to update fields on the options
object. |
360,371 | def connect(self, keyspace=None, wait_for_all_pools=False):
with self._lock:
if self.is_shutdown:
raise DriverException("Cluster is already shut down")
if not self._is_setup:
log.debug("Connecting to cluster, contact points: %s; protocol version:... | Creates and returns a new :class:`~.Session` object. If `keyspace`
is specified, that keyspace will be the default keyspace for
operations on the ``Session``. |
360,372 | def object_links(self, multihash, **kwargs):
args = (multihash,)
return self._client.request(, args,
decoder=, **kwargs) | Returns the links pointed to by the specified object.
.. code-block:: python
>>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D')
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ug... |
360,373 | def run_scheduler(args):
if not args.local:
raise ValueError("The execute command can only be used with the command line option")
jm = setup(args)
jm.run_scheduler(parallel_jobs=args.parallel, job_ids=get_ids(args.job_ids), sleep_time=args.sleep_time, die_when_finished=args.die_when_finished, no_log=args.... | Runs the scheduler on the local machine. To stop it, please use Ctrl-C. |
360,374 | def importcmd(self, image_path, input_source):
from spython.utils import check_install
check_install()
cmd = [, , image_path, input_source]
output = self.run_command(cmd, sudo=False)
self.println(output)
return image_path | import will import (stdin) to the image
Parameters
==========
image_path: path to image to import to.
input_source: input source or file
import_type: if not specified, imports whatever function is given |
360,375 | def disable_requiretty_on_sudoers(log=False):
if log:
bookshelf2.logging_helpers.log_green(
)
comment_line(,
, use_sudo=True)
return True | allow sudo calls through ssh without a tty |
360,376 | def group_norm(x, filters=None, num_groups=8, epsilon=1e-5):
x_shape = shape_list(x)
if filters is None:
filters = x_shape[-1]
assert len(x_shape) == 4
assert filters % num_groups == 0
scale = tf.get_variable(
"group_norm_scale", [filters], initializer=tf.ones_initializer())
bias = tf.get_va... | Group normalization as in https://arxiv.org/abs/1803.08494. |
360,377 | def _handle_book(self, dtype, data, ts):
self.log.debug("_handle_book: %s - %s - %s", dtype, data, ts)
channel_id, *data = data
log.debug("ts: %s\tchan_id: %s\tdata: %s", ts, channel_id, data)
channel_identifier = self.channel_directory[channel_id]
entry = (data, ts)
... | Updates the order book stored in self.books[chan_id].
:param dtype:
:param data:
:param ts:
:return: |
360,378 | def prepare_input(self, extracted_str):
if self.options[]:
optimized_str = re.sub(, , extracted_str)
else:
optimized_str = extracted_str
if self.options[]:
optimized_str = unidecode(optimized_str)
if self.options[... | Input raw string and do transformations, as set in template file. |
360,379 | def init_validator(required, cls, *additional_validators):
validator = validators.instance_of(cls)
if additional_validators:
additional_validators = list(additional_validators)
additional_validators.append(validator)
validator = composite(*additional_validators)
return validat... | Create an attrs validator based on the cls provided and required setting.
:param bool required: whether the field is required in a given model.
:param cls: the expected class type of object value.
:return: attrs validator chained correctly (e.g. optional(instance_of)) |
360,380 | def print_lh(self, joint=True):
try:
u_lh = self.tree.unconstrained_sequence_LH
if joint:
s_lh = self.tree.sequence_joint_LH
t_lh = self.tree.positional_joint_LH
c_lh = self.tree.coalescent_joint_LH
else:
... | Print the total likelihood of the tree given the constrained leaves
Parameters
----------
joint : bool
If true, print joint LH, else print marginal LH |
360,381 | def onKeyInCommandEntry(self, event):
if event.char == :
self.onSendCommand()
self.canvas.focus_set() | Called when a key is pressed when the command entry box has focus. |
360,382 | def _emit(self, event):
if (event.get() is not iaxiom.IStatEvent and
not in event and
not in event):
return
out = []
for k, v in event.iteritems():
if k in (, , , ):
continue
if not isinstance(v, unicode):
... | If the given event is a stat event, send a I{StatUpdate} command. |
360,383 | def wrap_with_try(self, node):
handlers = []
if self.ignore_exceptions is None:
handlers.append(ast.ExceptHandler(type=None,
name=None,
body=[ast.Raise()]))
else:
ignore... | Wrap an ast node in a 'try' node to enter debug on exception. |
360,384 | def _generate_full_recipe_message(self, destination, message, add_path_step):
if add_path_step and self.recipe_pointer:
recipe_path = self.recipe_path + [self.recipe_pointer]
else:
recipe_path = self.recipe_path
return {
"environment": self.environme... | Factory function to generate independent message objects for
downstream recipients with different destinations. |
360,385 | def from_frame_summary(cls, f):
return cls(filename=f.filename, lineno=f.lineno, name=f.name, f_locals=f.locals) | :param FrameSummary f:
:rtype: DummyFrame |
360,386 | def is_equal_type(type_a: GraphQLType, type_b: GraphQLType):
if type_a is type_b:
return True
if is_non_null_type(type_a) and is_non_null_type(type_b):
return is_equal_type(type_a.of_type, type_b.of_type)
if is_list_type(type_a) and is_list_type(type_b):
... | Check whether two types are equal.
Provided two types, return true if the types are equal (invariant). |
360,387 | def create_backends_from_settings(self):
config = getattr(settings, DJANGO_BACKEND_SETTING_NAME, {})
backends = self.instantiate_objects(config)
return backends | Expects the Django setting "EVENT_TRACKING_BACKENDS" to be defined and point
to a dictionary of backend engine configurations.
Example::
EVENT_TRACKING_BACKENDS = {
'default': {
'ENGINE': 'some.arbitrary.Backend',
'OPTIONS': {
... |
360,388 | def run_bot(bot_class, host, port, nick, channels=None, ssl=None):
conn = IRCConnection(host, port, nick, ssl)
bot_instance = bot_class(conn)
while 1:
if not conn.connect():
break
channels = channels or []
for channel in channels:
conn.join(channel)
... | \
Convenience function to start a bot on the given network, optionally joining
some channels |
360,389 | def _set_redistribute_isis(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=redistribute_isis.redistribute_isis, is_container=, presence=True, yang_name="redistribute-isis", rest_name="isis", parent=self, path_helper=self._path_helper, extmethods=self.... | Setter method for redistribute_isis, mapped from YANG variable /routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_ipv6_uc_and_vrf_cmds_call_point_holder/redistribute/redistribute_isis (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redi... |
360,390 | def _merge_by_type(lhs, rhs, type_):
merger = _MERGE_BY_TYPE[type_.code]
return merger(lhs, rhs, type_) | Helper for '_merge_chunk'. |
360,391 | def post(self, pid, record):
uploaded_file = request.files[]
key = secure_filename(
request.form.get() or uploaded_file.filename
)
if key in record.files:
raise FileAlreadyExists()
record.files[key] = uploaded_f... | Handle POST deposit files.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid. |
360,392 | def printFieldsHeader(self, f, d):
fstr = "Field Name"
dstr = "Description"
f = max(f, len(fstr))
d = max(d, len(dstr))
print(.format(fstr, * (f - len(fstr)), dstr, * (d - len(dstr))))
print(.format( * (f - 1), * (d - 1)))
return (f, d) | Prints out table header based on the size of the data in columns |
360,393 | def vm_diskstats(vm_=None):
your-vmio_read_kbsio_write_kbs*
with _get_xapi_session() as xapi:
def _info(vm_):
ret = {}
vm_uuid = _get_label_uuid(xapi, , vm_)
if vm_uuid is False:
return False
for vbd in xapi.VM.get_VBDs(vm_uuid):
... | Return disk usage counters used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'io_read_kbs' : 0,
'io_write_kbs' : 0
},
...
]
If you pass a VM name in as an argument then it ... |
360,394 | def setup_prjs_page(self, ):
self.prjs_tablev.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)
log.debug("Loading projects for projects page.")
rootdata = treemodel.ListItemData([, , , , , , , , ])
rootitem = treemodel.TreeItem(rootdata)
prjs = djadap... | Create and set the model on the projects page
:returns: None
:rtype: None
:raises: None |
360,395 | def check_output_variable(self, variable):
match = False
if variable in self.out_variables:
match = True
return match | Check to see if output variable was requested by downstream app.
Using the auto generated dictionary of output variables check to see if provided
variable was requested by downstream app.
Args:
variable (string): The variable name, not the full variable.
Returns:
... |
360,396 | def set(self, instance, value, **kw):
if value:
try:
value = DateTime(value)
except SyntaxError:
logger.warn("Value is not a valid DateTime string"
.format(value))
return False
self._set(instan... | Converts the value into a DateTime object before setting. |
360,397 | def name(self):
poss_deflist = sorted(
self.bulk_structure.get_sites_in_sphere(self.site.coords, 2, include_index=True), key=lambda x: x[1])
defindex = poss_deflist[0][2]
return "Sub_{}_on_{}_mult{}".format(self.site.specie, self.bulk_structure[defindex].specie, self.multipl... | Returns a name for this defect |
360,398 | def getEstTraitCovar(self,term_i=None):
assert self.P>1,
if term_i==None:
RV=SP.zeros((self.P,self.P))
for term_i in range(self.n_terms): RV+=self.vd.getTerm(term_i).getTraitCovar().K()
else:
assert term_i<self.n_terms,
RV = sel... | Returns explicitly the estimated trait covariance matrix
Args:
term_i: index of the term we are interested in |
360,399 | def rollback(self, date):
if self.onOffset(date):
return date
else:
return date - YearBegin(month=self.month) | Roll date backward to nearest start of year |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.