Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
337,300 | def attach_user(context, id, user_id):
result = remoteci.add_user(context, id=id,
user_id=user_id)
utils.format_output(result, context.format, [, ]) | attach_user(context, id, user_id)
Attach a user to a remoteci.
>>> dcictl remoteci-attach-user [OPTIONS]
:param string id: ID of the remoteci to attach the user to [required]
:param string user_id: ID of the user to attach [required] |
337,301 | def _get_num_of_documents(self):
parser = etree.XMLParser(target=XMLElementCountTarget())
num_of_documents = etree.parse(self.urml_file, parser)
self._num_of_documents = num_of_documents
return num_of_documents | counts the number of documents in an URML file.
adapted from Listing 2 on
http://www.ibm.com/developerworks/library/x-hiperfparse/ |
337,302 | def parse_result(cls, result):
if len(result) == 3:
items, count, context = result
else:
context = {}
items, count = result
return items, count, context | Parse an items + count tuple result.
May either be three item tuple containing items, count, and a context dictionary (see: relation convention)
or a two item tuple containing only items and count. |
337,303 | def Conditional(self, i, j, val, name=):
pmf = Pmf(name=name)
for vs, prob in self.Items():
if vs[j] != val: continue
pmf.Incr(vs[i], prob)
pmf.Normalize()
return pmf | Gets the conditional distribution of the indicated variable.
Distribution of vs[i], conditioned on vs[j] = val.
i: index of the variable we want
j: which variable is conditioned on
val: the value the jth variable has to have
Returns: Pmf |
337,304 | def refresh_token(self, subid):
if os.path.exists(self.data_base):
data_base = "%s/%s" %(self.data_base, subid)
if os.path.exists(data_base):
refreshed = "%s/%s" %(self.database, str(uuid.uuid4()))
os.rename(data_base, refreshed)
return refreshed
... | refresh or generate a new token for a user. If the user is finished,
this will also make the folder available again for using. |
337,305 | def base64_64format_decode(s: str) -> Optional[bytes]:
if len(s) < 4 or not s.startswith("64"):
return None
return base64.b64decode(s[3:-1]) | Reverse :func:`base64_64format_encode`.
Original purpose and notes:
- THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like
``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my
representation).
- regex from http://stackoverflow.com/questions/475074
- ... |
337,306 | def export_probability(outputname, **kwargs):
bbox = kwargs.get(, None)
nx, ny = kwargs.get(, None), kwargs.get(, None)
if bbox == None:
raise ValueError()
if nx == None or ny == None:
raise ValueError()
prob = compute_probability(**kwargs)
export_grid(outputname, prob, bbox... | Calculate probability and export to gis raster/grid
format.
export_probability(prob_out,
trajectory_files = [myfiles1.nc, myfiles2.nc],
bbox = [-75, 23, -60, 45],
nx = 1000, ny = 1000,
m... |
337,307 | def bibtex_run(self):
self.log.info()
try:
with open(os.devnull, ) as null:
Popen([, self.project_name], stdout=null).wait()
except OSError:
self.log.error(NO_LATEX_ERROR % )
sys.exit(1)
shutil.copy( % self.bib_file,
... | Start bibtex run. |
337,308 | def validate(self, fixerrors=True):
if not self._data:
return True
elif "type" not in self._data or "coordinates" not in self._data:
raise Exception("A geometry dictionary or instance must have the type and coordinates entries")
... | Validates that the geometry is correctly formatted according to the geometry type.
Parameters:
- **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True)
Returns:
- True if the geometry is valid.
Raises:
- An Exce... |
337,309 | def _is_compress_filetype(self, inpath):
if self._is_common_binary(inpath):
return False
elif self._is_common_text(inpath):
return True
else:
the_file_size = file_size(inpath)
if the_file_size > 10240:
... | private method that performs magic number and size check on file to determine whether to compress the file |
337,310 | def _SanitizeField(self, field):
if self._field_delimiter and isinstance(field, py2to3.STRING_TYPES):
return field.replace(self._field_delimiter, )
return field | Sanitizes a field for output.
This method replaces any field delimiters with a space.
Args:
field (str): name of the field to sanitize.
Returns:
str: value of the field. |
337,311 | def generate(self, api):
for namespace in api.namespaces.values():
with self.output_to_relative_path( % namespace.name):
self.emit( % namespace.name)
for data_type in namespace.linearize_data_types():
... | Main code generator entry point. |
337,312 | def auto_update_attrs_from_kwargs(method):
def wrapped(self, **kwargs):
argspec = inspect.getargspec(method)
defaults = argspec.defaults or ()
nb_args, nb_defaults = len(argspec.args), len(defaults)
options = dict(zip(argspec.args[nb_args - nb_defaults:], defa... | this decorator will update the attributes of an
instance object with all the kwargs of the decorated
method, updated with the kwargs of the actual call.
This saves you from boring typing:
self.xxxx = xxxx
self.yyyy = yyyy
...
in the decorated method (typically __init__) |
337,313 | def write_tables(target, tables, append=False, overwrite=False, **kwargs):
from ligo.lw.ligolw import (Document, LIGO_LW, LIGOLWContentHandler)
from ligo.lw import utils as ligolw_utils
if isinstance(target, (Document, LIGO_LW)):
xmldoc = target
elif append:
xmldoc = open... | Write an LIGO_LW table to file
Parameters
----------
target : `str`, `file`, :class:`~ligo.lw.ligolw.Document`
the file or document to write into
tables : `list`, `tuple` of :class:`~ligo.lw.table.Table`
the tables to write
append : `bool`, optional, default: `False`
if `T... |
337,314 | def DataProcessorsGet(self, parameters):
if self.__SenseApiCall__(, , parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False | List the users data processors.
@param parameters (dictonary) - Dictionary containing the parameters of the request.
@return (bool) - Boolean indicating whether this call was successful. |
337,315 | def _get_credentials(self, request):
authorization = request.headers.get()
if not authorization:
return None
try:
authmeth, authbytes = authorization.split(, 1)
except ValueError:
return None
if authmeth.lower() != :
retu... | Extract username and api key token from 'Authorization' header |
337,316 | def add_button(self, button):
self._buttons.append(button)
self._components[button.component_number] = button | Adds a button that's part of this keypad. We'll use this to
dispatch button events. |
337,317 | def raise_error(self, message=, errors=None, field_name=None):
field_name = field_name if field_name else self.field_name
raise ValidationError(message, errors=errors, field_name=field_name) | Raises a ValidationError. |
337,318 | def exportdb():
*
cmd =
udev_result = __salt__[](cmd, output_loglevel=)
if udev_result[]:
raise CommandExecutionError(udev_result[])
return _parse_udevadm_info(udev_result[]) | Return all the udev database
CLI Example:
.. code-block:: bash
salt '*' udev.exportdb |
337,319 | def long_running_recognize(
self,
config,
audio,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "long_running_recognize" not in self._inner_api_calls:
self._inn... | Performs asynchronous speech recognition: receive results via the
google.longrunning.Operations interface. Returns either an
``Operation.error`` or an ``Operation.response`` which contains a
``LongRunningRecognizeResponse`` message.
Example:
>>> from google.cloud import spee... |
337,320 | def line_showLog(self):
if self.kernel.mva is None:
print("Can't show log because no session exists")
else:
return self.kernel.Display(HTML(self.kernel.cachedlog)) | SAS Kernel magic to show the SAS log for the previous submitted code.
This magic is only available within the SAS Kernel |
337,321 | def sign(filename):
if gnupg is None:
return
gpg = gnupg.GPG()
with open(filename, "rb") as signfile:
keyid = fingerprint2keyid(config["gpg_key_fingerprint"])
if keyid is None:
msg = "No private key for GPG fingerprint ."
raise ValueError(msg.format(c... | Returns detached signature for file |
337,322 | def get_item_abspath(self, identifier):
dataset_cache_abspath = os.path.join(
self._cache_abspath,
self.uuid
)
mkdir_parents(dataset_cache_abspath)
manifest = self.get_manifest()
relpath = manifest[][identifier][]
_, ext = os.path.splite... | Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed |
337,323 | def merge_corpus(self, corpus):
merging_corpus = Corpus.from_corpus(corpus)
self.import_tracks(corpus.tracks.values())
self.import_issuers(corpus.issuers.values())
utterance_idx_mapping = self.import_utterances(corpus.utterances.values())
for subview_idx, sub... | Merge the given corpus into this corpus. All assets (tracks, utterances, issuers, ...) are copied into
this corpus. If any ids (utt-idx, track-idx, issuer-idx, subview-idx, ...) are occurring in both corpora,
the ids from the merging corpus are suffixed by a number (starting from 1 until no other is mat... |
337,324 | def time_to_next_poll(self):
if not self.config[]:
return self.time_to_next_heartbeat()
if time.time() > self.next_auto_commit_deadline:
return 0
return min(self.next_auto_commit_deadline - time.time(),
self.time_to_next_heartbeat()) | Return seconds (float) remaining until :meth:`.poll` should be called again |
337,325 | def IntegerSum(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
return Integer(context.jvm_view().IntegerSumVertex, label, cast_to_integer_vertex(input_vertex)) | Performs a sum across all dimensions
:param input_vertex: the vertex to have its values summed |
337,326 | def pad_to_multiple(self, factor):
remainder = self.pianoroll.shape[0] % factor
if remainder:
pad_width = ((0, (factor - remainder)), (0, 0))
self.pianoroll = np.pad(self.pianoroll, pad_width, ) | Pad the pianoroll with zeros at the end along the time axis with the
minimum length that makes the resulting pianoroll length a multiple of
`factor`.
Parameters
----------
factor : int
The value which the length of the resulting pianoroll will be
a multip... |
337,327 | def rollback(awsclient, function_name, alias_name=ALIAS_NAME, version=None):
if version:
log.info(.format(version))
else:
log.info()
version = _get_previous_version(awsclient, function_name, alias_name)
if version == :
log.error()
return 1
lo... | Rollback a lambda function to a given version.
:param awsclient:
:param function_name:
:param alias_name:
:param version:
:return: exit_code |
337,328 | def get_chat_id(self):
chat_id = self.json_response.get("chatid", None)
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return chat_id | Method to get chatid of group created. |
337,329 | def comunicar_certificado_icpbrasil(self, certificado):
return self.invocar__ComunicarCertificadoICPBRASIL(
self.gerar_numero_sessao(), self._codigo_ativacao, certificado) | Função ``ComunicarCertificadoICPBRASIL`` conforme ER SAT, item 6.1.2.
Envio do certificado criado pela ICP-Brasil.
:param str certificado: Conteúdo do certificado digital criado pela
autoridade certificadora ICP-Brasil.
:return: Retorna *verbatim* a resposta da função SAT.
... |
337,330 | def register_event(cls, event_name, event, method):
log.info(
.format(event_name, method.__name__))
if event_name not in cls._events:
cls._events[event_name] = {}
if event not in cls._events[event_name]:
cls._events[event_name][event] = []
... | Register an event class on it's name with a method to process it.
:param event_name: name of the event.
:param event: class of the event.
:param method: a method used to process this event. |
337,331 | def islice_extended(iterable, *args):
s = slice(*args)
start = s.start
stop = s.stop
if s.step == 0:
raise ValueError()
step = s.step or 1
it = iter(iterable)
if step > 0:
start = 0 if (start is None) else start
if (start < 0):
cache =... | An extension of :func:`itertools.islice` that supports negative values
for *stop*, *start*, and *step*.
>>> iterable = iter('abcdefgh')
>>> list(islice_extended(iterable, -4, -1))
['e', 'f', 'g']
Slices with negative values require some caching of *iterable*, but this
function take... |
337,332 | def includeme(config):
global cache_manager
settings = config.registry.settings
cache_manager = CacheManager(**parse_cache_config_options(settings)) | Configures the caching manager |
337,333 | def stats_blast(self, blast_id=None, start_date=None, end_date=None, options=None):
options = options or {}
data = options.copy()
if blast_id is not None:
data[] = blast_id
if start_date is not None:
data[] = start_date
if end_date is not None:
... | Retrieve information about a particular blast or aggregated information from all of blasts over a specified date range.
http://docs.sailthru.com/api/stat |
337,334 | def item_id(response):
dict_keys = [, , ,
, , ]
new_keys = [, , ,
, , ]
for player in response[]:
for key, new_key in zip(dict_keys, new_keys):
for item in items[]:
if item[] == player[key]:
player[new_key] = item... | Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on |
337,335 | def glsl_type(self):
if self.dtype is None:
return None
dtshape = self.dtype[0].shape
n = dtshape[0] if dtshape else 1
if n > 1:
dtype = % n
else:
dtype = if in self.dtype[0].base.kind else
return , dtype | GLSL declaration strings required for a variable to hold this data. |
337,336 | def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
self.proxy = (proxy_type, addr, port, rdns,
username.encode() if username else None,
password.encode() if password else None) | set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]])
Sets the proxy to be used.
proxy_type - The type of the proxy to be used. Three types
are supported: PROXY_TYPE_SOCKS4 (including socks4a),
PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP
... |
337,337 | def read_calibration(
detx=None, det_id=None, from_file=False, det_id_table=None
):
from km3pipe.calib import Calibration
if not (detx or det_id or from_file):
return None
if detx is not None:
return Calibration(filename=detx)
if from_file:
det_ids = np.unique(d... | Retrive calibration from file, the DB. |
337,338 | def stored_messages_archive(context, num_elements=10):
if "user" in context:
user = context["user"]
if user.is_authenticated():
qs = MessageArchive.objects.select_related("message").filter(user=user)
return {
"messages": qs[:num_elements],
... | Renders a list of archived messages for the current user |
337,339 | def _get_sqlite_columns(connection, table):
SQL_TO_PYTHON_TYPES = {
: int,
: int,
: int,
: int,
: int,
: int,
: int,
: int,
: int,
: float,
: float,
: float,
: float,
: bool,
: str,... | Returns list of tuple containg columns of the table.
Args:
connection: sqlalchemy connection to sqlite database.
table (str): name of the table
Returns:
list of (name, datatype, position): where name is column name, datatype is
python type of the column, position is ordinal... |
337,340 | def convert_cmus_output(self, cmus_output):
cmus_output = cmus_output.split()
cmus_output = [x.replace(, ) for x in cmus_output if not x in ]
cmus_output = [x.replace(, ) for x in cmus_output]
status = {}
partitioned = (item.partition() for item in cmus_output)
s... | Change the newline separated string of output data into
a dictionary which can then be used to replace the strings in the config
format.
cmus_output: A string with information about cmus that is newline
seperated. Running cmus-remote -Q in a terminal will show you what
you're de... |
337,341 | def dict_hist(item_list, weight_list=None, ordered=False, labels=None):
if labels is None:
hist_ = defaultdict(lambda: 0)
else:
hist_ = {k: 0 for k in labels}
if weight_list is None:
weight_list = it.repeat(1)
for item, weight in zip(item_list, weight_list):
his... | Builds a histogram of items, counting the number of time each item appears
in the input.
Args:
item_list (Iterable): hashable items (usually containing duplicates)
weight_list (Iterable): corresponding weights for each item
ordered (bool): if True the result is ordered by frequency
... |
337,342 | def dot_solve(self, y):
r
return np.dot(y.T, cho_solve(self._factor, y)) | r"""
Compute the inner product of a vector with the inverse of the
covariance matrix applied to itself:
.. math::
y\,K^{-1}\,y
Args:
y (ndarray[nsamples]): The vector :math:`y`. |
337,343 | def remove_image(self, image, **kwargs):
self.push_log("Removing image .".format(image))
set_raise_on_error(kwargs)
super(DockerFabricClient, self).remove_image(image, **kwargs) | Identical to :meth:`dockermap.client.base.DockerClientWrapper.remove_image` with additional logging. |
337,344 | def handle(client_message, handle_event_map_partition_lost=None, to_object=None):
message_type = client_message.get_message_type()
if message_type == EVENT_MAPPARTITIONLOST and handle_event_map_partition_lost is not None:
partition_id = client_message.read_int()
uuid = client_message.read_s... | Event handler |
337,345 | def resize(self, sizes, interpolation="cubic"):
arr_resized = ia.imresize_single_image(self.arr, sizes, interpolation=interpolation)
arr_resized = np.clip(arr_resized, 0.0, 1.0)
segmap = SegmentationMapOnImage(arr_resized, shape=self.shape)
segmap.inp... | Resize the segmentation map array to the provided size given the provided interpolation.
Parameters
----------
sizes : float or iterable of int or iterable of float
New size of the array in ``(height, width)``.
See :func:`imgaug.imgaug.imresize_single_image` for details.... |
337,346 | def _strict_date(self, lean):
return struct_time(
(
self._precise_year(lean),
self._precise_month(lean),
self._precise_day(lean),
) + tuple(TIME_EMPTY_TIME) + tuple(TIME_EMPTY_EXTRAS)
) | Return a `time.struct_time` representation of the date. |
337,347 | def parse(input_: Union[str, FileStream], default_base: Optional[str]=None) -> Optional[Schema]:
error_listener = ParseErrorListener()
if not isinstance(input_, FileStream):
input_ = InputStream(input_)
lexer = ShExDocLexer(input_)
lexer.addErrorListener(error_listener)
tokens = C... | Parse the text in infile and return the resulting schema
:param input_: text or input stream to parse
:param default_base_: base URI for relative URI's in schema
:return: ShExJ Schema object. None if error. |
337,348 | def remove_empty_files(root_directory, dry_run=False, ignore_errors=True,
enable_scandir=False):
file_list = []
for root, directories, files in _walk(root_directory,
enable_scandir=enable_scandir):
for file_name in files:
... | Remove all empty files from a path. Returns list of the empty files removed.
:param root_directory: base directory to start at
:param dry_run: just return a list of what would be removed
:param ignore_errors: Permissions are a pain, just ignore if you blocked
:param enable_scandir: on python < 3.5 enab... |
337,349 | def caps_str_to_df(caps_str):
structures = [dict([process_dict(v.groupdict())
for v in re.finditer(
r, s)])
for s in caps_str.split()]
df = pd.DataFrame(structures)
df.reset_index(drop=True, inplace=True)
def compute_multi(df):
m... | Parse caps string (as returned by `Gst.Pad.query_caps().to_string()`) into
`pandas.DataFrame` table, with one row per configuration. |
337,350 | def get_state_actions(self, state, **kwargs):
if (state.config_id.config_type == ItemType.CONTAINER and state.base_state != State.ABSENT and
not state.state_flags & StateFlags.INITIAL):
return [ItemAction(state, ContainerUtilAction.SIGNAL_STOP, extra_data=kwargs)] | Stops containers that are running. Does not check attached containers. Considers using the pre-configured
``stop_signal``.
:param state: Configuration state.
:type state: dockermap.map.state.ConfigState
:param kwargs: Additional keyword arguments.
:return: Actions on the client,... |
337,351 | def format_error(error: "GraphQLError") -> dict:
if not error:
raise ValueError("Received null or undefined error.")
formatted: Dict[str, Any] = dict(
message=error.message or "An unknown error occurred.",
locations=error.locations,
path=error.path,
)
if error.exte... | Format a GraphQL error
Given a GraphQLError, format it according to the rules described by the "Response
Format, Errors" section of the GraphQL Specification. |
337,352 | def get_muc_child(self):
if self.muc_child:
return self.muc_child
if not self.xmlnode.children:
return None
n=self.xmlnode.children
while n:
if n.name not in ("x","query"):
n=n.next
continue
ns=n.ns(... | Get the MUC specific payload element.
:return: the object describing the stanza payload in MUC namespace.
:returntype: `MucX` or `MucUserX` or `MucAdminQuery` or `MucOwnerX` |
337,353 | def is_method(method, flags=METHOD_ALL):
if isinstance(method, types.UnboundMethodType):
if flags & METHOD_CLASS and issubclass(method.im_class, type):
return True
if flags & METHOD_INSTANCE and not issubclass(method.im_class, type):
return True
if flags & METHOD... | Determines whether the passed value is a method satisfying certain conditions:
* Being instance method.
* Being class method.
* Being bound method.
* Being unbound method.
Flag check is considered or-wise. The default is to consider every option.
:param method:
:param flags:
:ret... |
337,354 | def to_api_repr(self):
resource = {}
if self.etag is not None:
resource["etag"] = self.etag
if self.version is not None:
resource["version"] = self.version
if self._bindings:
bindings = resource["bindings"] = []
for role, member... | Render a JSON policy resource.
Returns:
dict: a resource to be passed to the ``setIamPolicy`` API. |
337,355 | def write_files(self, jdoc, output_dir):
schemas = [j for j in jdoc if j.object_type == ]
schemas = [j for j in schemas if len([x for x in jdoc if x.object_type != and x.schema_name == j.object_name]) > 0]
if not os.path.exists(output_dir):
os.makedirs(output_dir)... | Writes all jdoc records into files.
One file per schema plus index file. |
337,356 | def convert_type(self, value, spec):
data_type = spec.get(, ).lower().strip()
if data_type in [, ]:
return value.lower() in BOOL_TRUISH
elif data_type in [, ]:
try:
return int(value)
except (ValueError, TypeError):
retu... | Some well-educated format guessing. |
337,357 | def blockquote(
self,
text):
m = self.reWS.match(text)
return "\n> " + ("\n> ").join(m.group(2).split("\n")) + "\n\n" | *convert plain-text to MMD blockquote*
**Key Arguments:**
- ``text`` -- the text to convert to MMD blockquote
**Return:**
- ``blockquote`` -- the MMD blockquote
**Usage:**
To convert a text to a MMD blockquote:
.. code-block:: python
... |
337,358 | def reset(self):
self.overall = {
: 0.0,
: 0.0,
: 0.0,
: 0.0,
: 0.0,
: 0.0,
}
self.tag_wise = {}
for label in self.tag_label_list:
self.tag_wise[label] = {
: 0.0,
... | Reset internal state |
337,359 | def searchExpressionLevelsInDb(
self, rnaQuantId, names=[], threshold=0.0, startIndex=0,
maxResults=0):
sql = ("SELECT * FROM Expression WHERE "
"rna_quantification_id = ? "
"AND expression > ? ")
sql_args = (rnaQuantId, threshold)
i... | :param rnaQuantId: string restrict search by quantification id
:param threshold: float minimum expression values to return
:return an array of dictionaries, representing the returned data. |
337,360 | def unregister(self, mimetype, processor):
if mimetype in self and processor in self[mimetype]:
self[mimetype].remove(processor) | Remove passed `processor` for passed `mimetype`. If processor for
this MIME type does not found in the registry, nothing happens. |
337,361 | def add_impact_layers_to_canvas(impact_function, group=None, iface=None):
layers = impact_function.outputs
name = impact_function.name
if group:
group_analysis = group
else:
root = QgsProject.instance().layerTreeRoot()
group_analysis = root.insertGroup(0, name)
... | Helper method to add impact layer to QGIS from impact function.
:param impact_function: The impact function used.
:type impact_function: ImpactFunction
:param group: An existing group as a parent, optional.
:type group: QgsLayerTreeGroup
:param iface: QGIS QgisAppInterface instance.
:type ifa... |
337,362 | def _load_settings_from_source(self, source):
if not source:
pass
elif source == :
for env_settings_uri_key in self.env_settings_uri_keys:
env_settings_uri = self._search_environ(env_settings_uri_key)
if env_settings_uri:
... | Loads the relevant settings from the specified ``source``.
:returns: a standard :func:`dict` containing the settings from the source
:rtype: dict |
337,363 | def get_transformer_encoder(config: transformer.TransformerConfig, prefix: str) -> :
encoder_seq = EncoderSequence([], dtype=config.dtype)
cls, encoder_params = _get_positional_embedding_params(config.positional_embedding_type,
config.model_size,
... | Returns a Transformer encoder, consisting of an embedding layer with
positional encodings and a TransformerEncoder instance.
:param config: Configuration for transformer encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance. |
337,364 | def _copy_number_format(other):
copy = NumberFormat(pattern=other.pattern,
format=other.format,
leading_digits_pattern=list(other.leading_digits_pattern),
national_prefix_formatting_rule=other.national_prefix_formatting_rule,
... | Return a mutable copy of the given NumberFormat object |
337,365 | def verify_state(self):
if self.state == SESSION_STATE.CONNECTING:
self.state = SESSION_STATE.OPEN
self.conn.connectionMade(self.conn_info) | Verify if session was not yet opened. If it is, open it and call
connection's C{connectionMade} |
337,366 | def get_zone():
CST6CDT,M3.2.0/2:00:00,M11.1.0/2:00:00*
if salt.utils.path.which():
ret = _timedatectl()
for line in (x.strip() for x in salt.utils.itertools.split(ret[], )):
try:
return re.match(r, line).group(1)
except AttributeError:
pa... | Get current timezone (i.e. America/Denver)
.. versionchanged:: 2016.11.4
.. note::
On AIX operating systems, Posix values can also be returned
'CST6CDT,M3.2.0/2:00:00,M11.1.0/2:00:00'
CLI Example:
.. code-block:: bash
salt '*' timezone.get_zone |
337,367 | def mutate(self, mutation, timeout=None, metadata=None, credentials=None):
return self.stub.Mutate(mutation, timeout=timeout, metadata=metadata,
credentials=credentials) | Runs mutate operation. |
337,368 | def serialize(name,
dataset=None,
dataset_pillar=None,
user=None,
group=None,
mode=None,
backup=,
makedirs=False,
show_changes=True,
create=True,
merge_if_exists=False,
... | Serializes dataset and store it into managed file. Useful for sharing
simple configuration files.
name
The location of the file to create
dataset
The dataset that will be serialized
dataset_pillar
Operates like ``dataset``, but draws from a value stored in pillar,
usin... |
337,369 | def previous(self, day_of_week=None, keep_time=False):
if day_of_week is None:
day_of_week = self.day_of_week
if day_of_week < SUNDAY or day_of_week > SATURDAY:
raise ValueError("Invalid day of week")
if keep_time:
dt = self
else:
... | Modify to the previous occurrence of a given day of the week.
If no day_of_week is provided, modify to the previous occurrence
of the current day of the week. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDAY.
:param day_of_week: The previous day of week ... |
337,370 | def get_timestamp(time=True, precice=False):
f =
if time:
f +=
if precice:
f +=
return _datetime.now().strftime(f) | What time is it?
:param time:
Append ``-%H.%M.%S`` to the final string.
:param precice:
Append ``-%f`` to the final string.
Is only recognized when `time` is set to ``True``
:returns:
A timestamp string of now in the format ``%Y.%m.%d-%H.%M.%S-%f``
.. seealso:: `strftim... |
337,371 | def get_identities(self, item):
item = item[]
user = self.get_sh_identity(item)
yield user | Return the identities from an item |
337,372 | def histogram(
data, name, bins=, datarange=(None, None), format=, suffix=, path=, rows=1,
columns=1, num=1, last=True, fontmap = None, verbose=1):
try:
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
standalone = rows == 1 and columns == 1... | Generates histogram from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the histogram.
bins: int or string
The number of bins, or a preferred binning method. Available methods include
... |
337,373 | def norm(self):
N = len(self.shape)
coef = outer(self.lmbda, self.lmbda)
for i in range(N):
coef = coef * dot(self.U[i].T, self.U[i])
return np.sqrt(coef.sum()) | Efficient computation of the Frobenius norm for ktensors
Returns
-------
norm : float
Frobenius norm of the ktensor |
337,374 | def get_cmap(self):
r = []
g = []
b = []
for p in self._colorpoint_list:
r.append((p[0], p[1][0]*1.0, p[2][0]*1.0))
g.append((p[0], p[1][1]*1.0, p[2][1]*1.0))
b.append((p[0], p[1][2]*1.0, p[2][2]*1.0))
c = {:r, :g, ... | Generates a pylab cmap object from the colorpoint data. |
337,375 | def get(self, key):
if "." in key and len(key) > 1:
return self._recursive_get(key)
return self._requirements.get(key, None) | Gets contents of requirement key.
Switches to recursive search if dots ('.') are found in the key.
:param key: key or dot separated string of keys to look for.
:return: contents of requirement key/results of search or None. |
337,376 | def factory(raw_data, request):
if ATTR_SHADE in raw_data:
raw_data = raw_data.get(ATTR_SHADE)
shade_type = raw_data.get(ATTR_TYPE)
def find_type(shade):
for tp in shade.shade_types:
if tp.shade_type == shade_type:
return shade(raw_data, tp, request)
... | Class factory to create different types of shades
depending on shade type. |
337,377 | def _skip_lines(self, n):
for i in range(n):
self.line = next(self.output)
return self.line | Skip a number of lines from the output. |
337,378 | def SetCredentials(self, password=None, username=None):
if password:
self._password = password
if username:
self._user = username | Sets the database credentials.
Args:
password (Optional[str]): password to access the database.
username (Optional[str]): username to access the database. |
337,379 | def getReferenceAnalyses(self):
ans = self.getAnalyses()
references = [an for an in ans if IReferenceAnalysis.providedBy(an)]
return references | Return the reference analyses (controls) assigned to the current
worksheet
:return: List of reference analyses
:rtype: List of IReferenceAnalysis objects |
337,380 | def export_vtkjs(self, filename, compress_arrays=False):
if not hasattr(self, ):
raise RuntimeError()
if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename):
filename = os.path.join(vtki.FIGURE_PATH, filename)
return export_plotter_vtkjs(self, filen... | Export the current rendering scene as a VTKjs scene for
rendering in a web browser |
337,381 | async def take(self, timeout=None):
args = None
if timeout is not None:
args = (timeout,)
res = await self.conn.call(self.__funcs[], args)
if len(res.body) > 0:
return self._create_task(res.body)
return None | Takes task from the queue, waiting the timeout if specified
:param timeout: Seconds to wait for ready tasks
:return: Task instance |
337,382 | def add_options(cls, parser):
parser.add_option(, action=, help=)
parser.config_options.append() | Add options to flake8.
:param parser: optparse.OptionParser from pycodestyle. |
337,383 | def getDetails(self, ip_address=None):
raw_details = self._requestDetails(ip_address)
raw_details[] = self.countries.get(raw_details.get())
raw_details[] = ipaddress.ip_address(raw_details.get())
raw_details[], raw_details[] = self._read_coords(raw_details.get())
return ... | Get details for specified IP address as a Details object. |
337,384 | def clr(M, **kwargs):
R = np.zeros(M.shape)
Id = [[0, 0] for i in range(M.shape[0])]
for i in range(M.shape[0]):
mu_i = np.mean(M[i, :])
sigma_i = np.std(M[i, :])
Id[i] = [mu_i, sigma_i]
for i in range(M.shape[0]):
for j in range(i + 1, M.shape[0]):
z_i ... | Implementation of the Context Likelihood or Relatedness Network algorithm.
Args:
mat (numpy.ndarray): matrix, if it is a square matrix, the program assumes
it is a relevance matrix where mat(i,j) represents the similarity content
between nodes i and j. Elements of matrix should be
n... |
337,385 | def get_version():
major_value = ctypes.c_int(0)
major = ctypes.pointer(major_value)
minor_value = ctypes.c_int(0)
minor = ctypes.pointer(minor_value)
rev_value = ctypes.c_int(0)
rev = ctypes.pointer(rev_value)
_glfw.glfwGetVersion(major, minor, rev)
return major_value.value, minor_... | Retrieves the version of the GLFW library.
Wrapper for:
void glfwGetVersion(int* major, int* minor, int* rev); |
337,386 | def cronbach_alpha(data=None, items=None, scores=None, subject=None,
remove_na=False, ci=.95):
assert isinstance(data, pd.DataFrame),
if all([v is not None for v in [items, scores, subject]]):
data = data.pivot(index=subject, values=scores, columns=items)
... | Cronbach's alpha reliability measure.
Parameters
----------
data : pandas dataframe
Wide or long-format dataframe.
items : str
Column in ``data`` with the items names (long-format only).
scores : str
Column in ``data`` with the scores (long-format only).
subject : str
... |
337,387 | def build_attrs(self, base_attrs, extra_attrs=None):
attrs = base_attrs.copy()
if extra_attrs is not None:
attrs.update(extra_attrs)
return attrs | Build an attribute dictionary. |
337,388 | def _simple_name(distribution):
simple_name = distribution.name
if simple_name.endswith():
simple_name = simple_name.split()[-2]
parts = simple_name.split()
if parts[-1].isdigit():
simple_name = .join(parts[:-1])
return simple_name | Infer the original name passed into a distribution constructor.
Distributions typically follow the pattern of
with.name_scope(name) as name:
super(name=name)
so we attempt to reverse the name-scope transformation to allow
addressing of RVs by the distribution's original, user-visible
name kwarg.
Args:... |
337,389 | def resolve_loader(self, meta: ResourceDescription):
meta.loader_cls = self.get_loader(meta, raise_on_error=True) | Attempts to assign a loader class to a resource description
:param meta: The resource description instance |
337,390 | def finalcallback(request, **kwargs):
default_provider.load_services()
service_name = kwargs.get()
service_object = default_provider.get_service(service_name)
lets_callback = getattr(service_object, )
return render_to_response(lets_callback(request)) | let's do the callback of the related service after
the auth request from UserServiceCreateView |
337,391 | def dump_yaml(data):
return yaml.dump(data,
indent=2,
encoding=None,
allow_unicode=True,
default_flow_style=False,
Dumper=MyDumper) | :param list | dict data:
:rtype: unicode |
337,392 | def submit_statsd_measurements(self):
for key, value in self.measurement.counters.items():
self.statsd.incr(key, value)
for key, values in self.measurement.durations.items():
for value in values:
self.statsd.add_timing(key, value)
for key, value i... | Submit a measurement for a message to statsd as individual items. |
337,393 | def eventize(self, granularity):
issue = {}
issue[BugzillaRest.ISSUE_ID] = []
issue[BugzillaRest.ISSUE_EVENT] = []
issue[BugzillaRest.ISSUE_DATE] = []
issue[BugzillaRest.ISSUE_OWNER] = []
issue[BugzillaRest.ISSUE_ADDED] = []
issue[BugzillaRest.ISSUE_REMO... | This splits the JSON information found at self.events into the
several events. For this there are three different levels of time
consuming actions: 1-soft, 2-medium and 3-hard.
Level 1 provides events about open and closed issues.
Level 2 provides events about the rest of the status upd... |
337,394 | def parse_queue(self, global_params, region, queue_url):
queue = {: queue_url}
attributes = api_clients[region].get_queue_attributes(QueueUrl = queue_url, AttributeNames = [, , ])[]
queue[] = attributes.pop()
for k in []:
queue[k] = attributes[k] if k in attributes e... | Parse a single queue and fetch additional attributes
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param queue_url: URL of the AWS queue |
337,395 | def _rest_format_section(stream, section, options, doc=None):
if section:
print("%s\n%s" % (section, "'" * len(section)), file=stream)
if doc:
print(normalize_text(doc, line_len=79, indent=""), file=stream)
print(file=stream)
for optname, optdict, value in options:
help_... | format an options section using as ReST formatted output |
337,396 | def hue(p):
min_c = min(p)
max_c = max(p)
d = float(max_c - min_c)
if d == 0:
return 0
if max_c == p[0]:
h = (p[1] - p[2]) / d
elif max_c == p[1]:
h = 2 + (p[2] - p[0]) / d
else:
h = 4 + (p[0] - p[1]) / d
h *= 60
if h < 0:
h += 360
re... | Returns the saturation of a pixel.
Gray pixels have saturation 0.
:param p: A tuple of (R,G,B) values
:return: A saturation value between 0 and 360 |
337,397 | def parse_args(args):
parser = argparse.ArgumentParser()
parser.add_argument(, nargs=,
help=, default=None)
parser.add_argument(
, ,
help=,
default=)
args_parsed = parser.parse_args(args)
if not args_parsed.config_file:
parser.error("You h... | Parse an argument string
http://stackoverflow.com/questions/18160078/
how-do-you-write-tests-for-the-argparse-portion-of-a-python-module |
337,398 | def from_function(cls, f, *args, **kwargs):
return cls.from_code(six.get_function_code(f), *args, **kwargs) | Create a new instance from a function. Gets the code object from
the function and passes it and any other specified parameters to
:meth:`from_code`.
Arguments:
f(function): The function to get the code object from.
Returns:
CodeObject: A new :class:`CodeObject` ... |
337,399 | def get_duration_h_m(start: Union[str, DateTime],
end: Union[str, DateTime],
default: str = "N/A") -> str:
start = coerce_to_pendulum(start)
end = coerce_to_pendulum(end)
if start is None or end is None:
return default
duration = end - start
min... | Calculate the time between two dates/times expressed as strings.
Args:
start: start date/time
end: end date/time
default: string value to return in case either of the inputs is
``None``
Returns:
a string that is one of
.. code-block:
'hh:mm'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.