Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
18,800 | def strel_pair(x, y):
x_center = int(np.abs(x))
y_center = int(np.abs(y))
result = np.zeros((y_center * 2 + 1, x_center * 2 + 1), bool)
result[y_center, x_center] = True
result[y_center + int(y), x_center + int(x)] = True
return result | Create a structing element composed of the origin and another pixel
x, y - x and y offsets of the other pixel
returns a structuring element |
18,801 | def MSTORE(self, address, value):
if istainted(self.pc):
for taint in get_taints(self.pc):
value = taint_with(value, taint)
self._allocate(address, 32)
self._store(address, value, 32) | Save word to memory |
18,802 | def authenticate(url, account, key, by=, expires=0, timestamp=None,
timeout=None, request_type="xml", admin_auth=False,
use_password=False, raise_on_error=False):
if timestamp is None:
timestamp = int(time.time()) * 1000
pak = ""
if not admin_auth:
p... | Authenticate to the Zimbra server
:param url: URL of Zimbra SOAP service
:param account: The account to be authenticated against
:param key: The preauth key of the domain of the account or a password (if
admin_auth or use_password is True)
:param by: If the account is specified as a name, an ID o... |
18,803 | def close(self):
endpoint = self.endpoint.replace("/api/v1/spans", "")
logger.debug("Zipkin trace may be located at this URL {}/traces/{}".format(endpoint, self.trace_id)) | End the report. |
18,804 | def lpad(col, len, pad):
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.lpad(_to_java_column(col), len, pad)) | Left-pad the string column to width `len` with `pad`.
>>> df = spark.createDataFrame([('abcd',)], ['s',])
>>> df.select(lpad(df.s, 6, '#').alias('s')).collect()
[Row(s=u'##abcd')] |
18,805 | def _get_string_match_value(self, string, string_match_type):
if string_match_type == Type(**get_type_data()):
return string
elif string_match_type == Type(**get_type_data()):
return re.compile( + string, re.I)
elif string_match_type == Type(**get_type_data()):
... | Gets the match value |
18,806 | def find_by_reference_ids(reference_ids, _connection=None, page_size=100,
page_number=0, sort_by=enums.DEFAULT_SORT_BY,
sort_order=enums.DEFAULT_SORT_ORDER):
if not isinstance(reference_ids, (list, tuple)):
err = "Video.find_by_reference_ids expects an iterable argument"
... | List all videos identified by a list of reference ids |
18,807 | def serialize_dictionary(dictionary):
string_value = {}
for k, v in list(dictionary.items()):
if isinstance(v, QUrl):
string_value[k] = v.toString()
elif isinstance(v, (QDate, QDateTime)):
string_value[k] = v.toString(Qt.ISODate)
elif isinstance(v, datetime):... | Function to stringify a dictionary recursively.
:param dictionary: The dictionary.
:type dictionary: dict
:return: The string.
:rtype: basestring |
18,808 | def clean_item_no_list(i):
itype = type(i)
if itype == dict:
return clean_dict(i, clean_item_no_list)
elif itype == list:
return clean_tuple(i, clean_item_no_list)
elif itype == tuple:
return clean_tuple(i, clean_item_no_list)
elif itype == numpy.float32:
return ... | Return a json-clean item or None. Will log info message for failure. |
18,809 | def load_features(self, features, image_type=None, from_array=False,
threshold=0.001):
if from_array:
if isinstance(features, list):
features = features[0]
self._load_features_from_array(features)
elif path.exists(features[0]):
... | Load features from current Dataset instance or a list of files.
Args:
features: List containing paths to, or names of, features to
extract. Each element in the list must be a string containing
either a path to an image, or the name of a feature (as named
... |
18,810 | def autoconfig_url_from_registry():
if not ON_WINDOWS:
raise NotWindowsError()
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
) as key:
return winreg.QueryValueEx(key, )[0]
except WindowsError:
return | Get the PAC ``AutoConfigURL`` value from the Windows Registry.
This setting is visible as the "use automatic configuration script" field in
Internet Options > Connection > LAN Settings.
:return: The value from the registry, or None if the value isn't configured or available.
Note that it may b... |
18,811 | def query_all(self):
return self.query_model(self.model, self.condition, order_by=self.order_by,
group_by=self.group_by, having=self.having) | Query all records without limit and offset. |
18,812 | def get_comments_of_delivery_note_per_page(self, delivery_note_id, per_page=1000, page=1):
return self._get_resource_per_page(
resource=DELIVERY_NOTE_COMMENTS,
per_page=per_page,
page=page,
params={: delivery_note_id},
) | Get comments of delivery note per page
:param delivery_note_id: the delivery note
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list |
18,813 | def to_config(self, k, v):
if k == "setup":
return base.to_commandline(v)
return super(DataGenerator, self).to_config(k, v) | Hook method that allows conversion of individual options.
:param k: the key of the option
:type k: str
:param v: the value
:type v: object
:return: the potentially processed value
:rtype: object |
18,814 | def annotate(args):
from jcvi.utils.grouper import Grouper
valid_resolve_choices = ["alignment", "overlap"]
p = OptionParser(annotate.__doc__)
p.add_option("--resolve", default="alignment", choices=valid_resolve_choices,
help="Resolve ID assignment based on a certain metric" \
... | %prog annotate new.bed old.bed 2> log
Annotate the `new.bed` with features from `old.bed` for the purpose of
gene numbering.
Ambiguity in ID assignment can be resolved by either of the following 2 methods:
- `alignment`: make use of global sequence alignment score (calculated by `needle`)
- `overl... |
18,815 | def raw_from_delimited(msgs: DelimitedMsg) -> RawMsgs:
delim = _rindex(msgs, b)
return tuple(msgs[:delim]), tuple(msgs[delim + 1:]) | \
From a message consisting of header frames, delimiter frame, and payload frames, return a tuple `(header, payload)`.
The payload frames may be returned as sequences of bytes (raw) or as `Message`s. |
18,816 | def fix_spelling(words, join=True, joinstring=):
return Vabamorf.instance().fix_spelling(words, join, joinstring) | Simple function for quickly correcting misspelled words.
Parameters
----------
words: list of str or str
Either a list of pretokenized words or a string. In case of a string, it will be splitted using
default behaviour of string.split() function.
join: boolean (default: True)
Sh... |
18,817 | def similarity(w1, w2, threshold=0.5):
ratio = SM(None, str(w1).lower(), str(w2).lower()).ratio()
return ratio if ratio > threshold else 0 | compare two strings 'words', and
return ratio of smiliarity, be it larger than the threshold,
or 0 otherwise.
NOTE: if the result more like junk, increase the threshold value. |
18,818 | def getKnownPlayers(reset=False):
global playerCache
if not playerCache or reset:
jsonFiles = os.path.join(c.PLAYERS_FOLDER, "*.json")
for playerFilepath in glob.glob(jsonFiles):
filename = os.path.basename(playerFilepath)
name = re.sub("^player_", "", filename)
... | identify all of the currently defined players |
18,819 | def get_disparity(self, pair):
gray = []
if pair[0].ndim == 3:
for side in pair:
gray.append(cv2.cvtColor(side, cv2.COLOR_BGR2GRAY))
else:
gray = pair
return self._block_matcher.compute(gray[0], gray[1],
... | Compute disparity from image pair (left, right).
First, convert images to grayscale if needed. Then pass to the
``_block_matcher`` for stereo matching. |
18,820 | def resume(profile_process=):
profile_process2int = {: 0, : 1}
check_call(_LIB.MXProcessProfilePause(int(0),
profile_process2int[profile_process],
profiler_kvstore_handle)) | Resume paused profiling.
Parameters
----------
profile_process : string
whether to profile kvstore `server` or `worker`.
server can only be profiled when kvstore is of type dist.
if this is not passed, defaults to `worker` |
18,821 | def choice_SlackBuild(self):
SlackBuild = ReadSBo(self.sbo_url).slackbuild(self.name, ".SlackBuild")
fill = self.fill_pager(SlackBuild)
self.pager(SlackBuild + fill) | View .SlackBuild file |
18,822 | def _insert_update(self, index: int, length: int) -> None:
ss, se = self._span
for spans in self._type_to_spans.values():
for span in spans:
if index < span[1] or span[1] == index == se:
span[1] += length
i... | Update self._type_to_spans according to the added length. |
18,823 | def get_text(self):
row_lines = []
for line in zip_longest(*[column.get_cell_lines() for column in self.columns], fillvalue=):
row_lines.append(.join(line))
return .join(row_lines) | ::returns:
a rendered string representation of the given row |
18,824 | def download_url(url, filename=None, spoof=False, iri_fallback=True,
verbose=True, new=False, chunk_size=None):
r
def reporthook_(num_blocks, block_nBytes, total_nBytes, start_time=0):
total_seconds = time.time() - start_time + 1E-9
num_kb_down = int(num_blocks * block_nBytes)... | r""" downloads a url to a filename.
Args:
url (str): url to download
filename (str): path to download to. Defaults to basename of url
spoof (bool): if True pretends to by Firefox
iri_fallback : falls back to requests get call if there is a UnicodeError
References:
http:... |
18,825 | def generate_evenly_distributed_data(dim = 2000,
num_active = 40,
num_samples = 1000,
num_negatives = 500):
sparse_data = [numpy.random.choice(dim, size = num_active, replace = False)
for i in rang... | Generates a set of data drawn from a uniform distribution. The binning
structure from Poirazi & Mel is ignored, and all (dim choose num_active)
arrangements are possible. num_negatives samples are put into a separate
negatives category for output compatibility with generate_data, but are
otherwise identical. |
18,826 | def data_find_text(data, path):
el = data_find(data, path)
if not isinstance(el, (list, tuple)):
return None
texts = [child for child in el[1:] if not isinstance(child, (tuple, list, dict))]
if not texts:
return None
return " ".join(
[
... | Return the text value of the element-as-tuple in tuple ``data`` using
simplified XPath ``path``. |
18,827 | def getPhysicalMaximum(self,chn=None):
if chn is not None:
if 0 <= chn < self.signals_in_file:
return self.physical_max(chn)
else:
return 0
else:
physMax = np.zeros(self.signals_in_file)
for i in np.arange(self.sign... | Returns the maximum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMaximum(0)==1000.0
True
>>> f... |
18,828 | def error(request, message, extra_tags=, fail_silently=False, async=False):
if ASYNC and async:
messages.debug(_get_user(request), message)
else:
add_message(request, constants.ERROR, message, extra_tags=extra_tags,
fail_silently=fail_silently) | Adds a message with the ``ERROR`` level. |
18,829 | def serialize(ty, *values, **kwargs):
try:
parsed_ty = abitypes.parse(ty)
except Exception as e:
raise EthereumError(str(e))
if parsed_ty[0] != :
if len(values) > 1:
raise ValueError()
values = values[0]
... | Serialize value using type specification in ty.
ABI.serialize('int256', 1000)
ABI.serialize('(int, int256)', 1000, 2000) |
18,830 | def getFunc(self, o: Any) -> Callable:
for cls, func in self.routes.items():
if isinstance(o, cls):
return func
logger.error("Unhandled msg {}, available handlers are:".format(o))
for cls in self.routes.keys():
logger.error(" {}".format(cls))
... | Get the next function from the list of routes that is capable of
processing o's type.
:param o: the object to process
:return: the next function |
18,831 | def removeGaps(self) :
for i in range(1, len(self.children)) :
if self.children[i].x1 > self.children[i-1].x2:
aux_moveTree(self.children[i-1].x2-self.children[i].x1, self.children[i]) | Remove all gaps between regions |
18,832 | def stopdocs():
"stop Sphinx watchdog"
for i in range(4):
pid = watchdog_pid()
if pid:
if not i:
sh(.format(pid))
sh(.format(pid))
time.sleep(.5)
else:
break | stop Sphinx watchdog |
18,833 | def updateColumnValue(self, column, value, index=None):
if index is None:
index = self.treeWidget().column(column.name())
if type(value) == datetime.date:
self.setData(index, Qt.EditRole, wrapVariant(value))
elif type(value) == datetime.time:
... | Assigns the value for the column of this record to the inputed value.
:param index | <int>
value | <variant> |
18,834 | def editpropset(self):
self.ignore(whitespace)
if not self.nextstr():
self._raiseSyntaxExpects()
relp = self.relprop()
self.ignore(whitespace)
self.nextmust()
self.ignore(whitespace)
valu = self.valu()
return s_ast.EditPropSet(ki... | :foo=10 |
18,835 | def length(self):
def ProcessContentRange(content_range):
_, _, range_spec = content_range.partition()
byte_range, _, _ = range_spec.partition()
start, _, end = byte_range.partition()
return int(end) - int(start) + 1
if in self.info and in self... | Return the length of this response.
We expose this as an attribute since using len() directly can fail
for responses larger than sys.maxint.
Returns:
Response length (as int or long) |
18,836 | def alignment_a(self):
from molmod.transformations import Rotation
new_x = self.matrix[:, 0].copy()
new_x /= np.linalg.norm(new_x)
new_z = np.cross(new_x, self.matrix[:, 1])
new_z /= np.linalg.norm(new_z)
new_y = np.cross(new_z, new_x)
new_y /= np.linalg.... | Computes the rotation matrix that aligns the unit cell with the
Cartesian axes, starting with cell vector a.
* a parallel to x
* b in xy-plane with b_y positive
* c with c_z positive |
18,837 | def RegisterArtifact(self,
artifact_rdfvalue,
source="datastore",
overwrite_if_exists=False,
overwrite_system_artifacts=False):
artifact_name = artifact_rdfvalue.name
if artifact_name in self._artifacts:
if no... | Registers a new artifact. |
18,838 | def _check_allowed_values(self, parameters):
for key, allowed_values in self.ALLOWED_VALUES:
self.log([u"Checking allowed values for parameter ", key])
if key in parameters:
value = parameters[key]
if value not in allowed_values:
... | Check whether the given parameter value is allowed.
Log messages into ``self.result``.
:param dict parameters: the given parameters |
18,839 | def _body(self, paragraphs):
body = []
for i in range(paragraphs):
paragraph = self._paragraph(random.randint(1, 10))
body.append(paragraph)
return .join(body) | Generate a body of text |
18,840 | def load_feedback():
result = {}
if os.path.exists(_feedback_file):
f = open(_feedback_file, )
cont = f.read()
f.close()
else:
cont =
try:
result = json.loads(cont) if cont else {}
except ValueError as e:
result = {"result":"crash", "text":"Feed... | Open existing feedback file |
18,841 | def initialize(self, *args):
self.n_user = 0
self.users = {}
self.n_item = 0
self.items = {} | Initialize a recommender by resetting stored users and items. |
18,842 | def dir():
dir = [
, , , , ,
, , , , , ,
, , , , , ,
, , ,
]
if IS_PY2:
dir.append()
if sys.platform != or not IS_PY2:
dir.append()
return dir | Return the list of patched function names. Used for patching
functions imported from the module. |
18,843 | def is_string_dtype(arr_or_dtype):
def condition(dtype):
return dtype.kind in (, , ) and not is_period_dtype(dtype)
return _is_dtype(arr_or_dtype, condition) | Check whether the provided array or dtype is of the string dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of the string dtype.
Examples
--------
>>> is_string_dtype(st... |
18,844 | def step(self, batch_size, ignore_stale_grad=False):
rescale_grad = self._scale / batch_size
self._check_and_rescale_grad(rescale_grad)
if not self._kv_initialized:
self._init_kvstore()
if self._params_to_init:
self._init_params()
self._allreduc... | Makes one step of parameter update. Should be called after
`autograd.backward()` and outside of `record()` scope.
For normal parameter updates, `step()` should be used, which internally calls
`allreduce_grads()` and then `update()`. However, if you need to get the reduced
gradients to p... |
18,845 | def build_paths(self, end_entity_cert):
if not isinstance(end_entity_cert, byte_cls) and not isinstance(end_entity_cert, x509.Certificate):
raise TypeError(pretty_message(
,
type_name(end_entity_cert)
))
if isinstance(end_entity_cert, by... | Builds a list of ValidationPath objects from a certificate in the
operating system trust store to the end-entity certificate
:param end_entity_cert:
A byte string of a DER or PEM-encoded X.509 certificate, or an
instance of asn1crypto.x509.Certificate
:return:
... |
18,846 | def connect(host=, port=21050, database=None, timeout=None,
use_ssl=False, ca_cert=None, auth_mechanism=, user=None,
password=None, kerberos_service_name=, use_ldap=None,
ldap_user=None, ldap_password=None, use_kerberos=None,
protocol=None, krb_host=None):
i... | Get a connection to HiveServer2 (HS2).
These options are largely compatible with the impala-shell command line
arguments. See those docs for more information.
Parameters
----------
host : str
The hostname for HS2. For Impala, this can be any of the `impalad`s.
port : int, optional
... |
18,847 | def _jar_paths():
own_jar = os.getenv("H2O_JAR_PATH", "")
if own_jar != "":
if not os.path.isfile(own_jar):
raise H2OStartupError("Environment variable H2O_JAR_PATH is set to but file does not exists, unset environment variable or provide valid path to h2o... | Produce potential paths for an h2o.jar executable. |
18,848 | def getUserInfo(self):
userJson = self.httpGet(ReaderUrl.USER_INFO_URL)
result = json.loads(userJson, strict=False)
self.userId = result[]
return result | Returns a dictionary of user info that google stores. |
18,849 | def harmonic(y, **kwargs):
stft = core.stft(y)
stft_harm = decompose.hpss(stft, **kwargs)[0]
y_harm = util.fix_length(core.istft(stft_harm, dtype=y.dtype), len(y))
return y_harm | Extract harmonic elements from an audio time-series.
Parameters
----------
y : np.ndarray [shape=(n,)]
audio time series
kwargs : additional keyword arguments.
See `librosa.decompose.hpss` for details.
Returns
-------
y_harmonic : np.ndarray [shape=(n,)]
audio time ... |
18,850 | def parse_changelog(path, **kwargs):
app, doctree = get_doctree(path, **kwargs)
first_list = None
for node in doctree[0]:
if isinstance(node, bullet_list):
first_list = node
break
releases, manager = construct_releases(first_list.children, app)
... | Load and parse changelog file from ``path``, returning data structures.
This function does not alter any files on disk; it is solely for
introspecting a Releases ``changelog.rst`` and programmatically answering
questions like "are there any unreleased bugfixes for the 2.3 line?" or
"what was included i... |
18,851 | def add_sender_info( self, sender_txhash, nulldata_vin_outpoint, sender_out_data ):
assert sender_txhash in self.sender_info.keys(), "Missing sender info for %s" % sender_txhash
assert nulldata_vin_outpoint in self.sender_info[sender_txhash], "Missing outpoint %s for sender %s" % (nulldata_vin_... | Record sender information in our block info.
@sender_txhash: txid of the sender
@nulldata_vin_outpoint: the 'vout' index from the nulldata tx input that this transaction funded |
18,852 | def distance(p_a, p_b):
return sqrt((p_a.lat - p_b.lat) ** 2 + (p_a.lon - p_b.lon) ** 2) | Euclidean distance, between two points
Args:
p_a (:obj:`Point`)
p_b (:obj:`Point`)
Returns:
float: distance, in degrees |
18,853 | def latexsnippet(code, kvs, staffsize=17, initiallines=1):
snippet =
staffsize = int(kvs[]) if in kvs \
else staffsize
initiallines = int(kvs[]) if in kvs \
else initiallines
annotationsize = .5 * staffsize
if in kvs:
snippet = (
"\\greannotation{{\\fonts... | Take in account key/values |
18,854 | def isotime(at=None, subsecond=False):
if not at:
at = utcnow()
st = at.strftime(_ISO8601_TIME_FORMAT
if not subsecond
else _ISO8601_TIME_FORMAT_SUBSECOND)
tz = at.tzinfo.tzname(None) if at.tzinfo else
st += ( if tz == else tz)
return st | Stringify time in ISO 8601 format. |
18,855 | def save_form(self, request, form, change):
name = form.cleaned_data[]
origin_url = form.cleaned_data[]
res = ClonedRepo(name=name, origin=origin_url)
LOG.info("New repo form produced %s" % str(res))
form.save(commit=False)
return res | Here we pluck out the data to create a new cloned repo.
Form is an instance of NewRepoForm. |
18,856 | def loglike(self, endog, mu, freq_weights=1., scale=1.):
if isinstance(self.link, L.Power) and self.link.power == 1:
nobs2 = endog.shape[0] / 2.
SSR = np.sum((endog-self.fitted(mu))**2, axis=0)
llf = -np.log(SSR) * nobs2
llf -= (1+np.log(np.p... | The log-likelihood in terms of the fitted mean response.
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
freq_weights : array-like
1d array of frequency weights. The default i... |
18,857 | def _create_subplots(self, fig, layout):
num_panels = len(layout)
axsarr = np.empty((self.nrow, self.ncol), dtype=object)
i = 1
for row in range(self.nrow):
for col in range(self.ncol):
axsarr[row, col] = fig.add_subplot(self.nrow, self.ncol... | Create suplots and return axs |
18,858 | def compile_template(instance, template, additionnal_context=None):
py3o_context = get_compilation_context(instance)
if additionnal_context is not None:
py3o_context.update(additionnal_context)
output_doc = StringIO()
odt_builder = Template(template, output_doc)
odt_builder.render(py... | Fill the given template with the instance's datas and return the odt file
For every instance class, common values are also inserted in the context
dict (and so can be used) :
* config values
:param obj instance: the instance of a model (like Userdatas, Company)
:param template: the template o... |
18,859 | def get_dbcollection_with_es(self, **kwargs):
es_objects = self.get_collection_es()
db_objects = self.Model.filter_objects(es_objects)
return db_objects | Get DB objects collection by first querying ES. |
18,860 | def _get_kwargs(profile=None, **connection_args):
if profile:
prefix = profile + ":keystone."
else:
prefix = "keystone."
def get(key, default=None):
return connection_args.get( + key,
__salt__[](prefix + key, default))
user = get... | get connection args |
18,861 | def get_url(cls, url, uid, **kwargs):
if uid:
url = .format(url, uid)
else:
url = url
return cls._parse_url_and_validate(url) | Construct the URL for talking to an individual resource.
http://myapi.com/api/resource/1
Args:
url: The url for this resource
uid: The unique identifier for an individual resource
kwargs: Additional keyword argueents
returns:
final_url: The URL f... |
18,862 | def wr_txt(self, fout_txt):
with open(fout_txt, ) as prt:
for line in self.ver_list:
prt.write("{LINE}\n".format(LINE=line))
self.prt_txt(prt)
print(" WROTE: {TXT}".format(TXT=fout_txt)) | Write to a file GOEA results in an ASCII text format. |
18,863 | def _find_cellid(self, code):
from difflib import SequenceMatcher
maxvalue = 0.
maxid = None
for cellid, c in self.cellids.items():
matcher = SequenceMatcher(a=c, b=code)
ratio = matcher.quick_ratio()
if ratio > maxvalue and ratio > 0... | Determines the most similar cell (if any) to the specified code. It
must have at least 50% overlap ratio and have been a loop-intercepted
cell previously.
Args:
code (str): contents of the code cell that were executed. |
18,864 | def updates(self):
updates = Updates()
found = updates.updates
for update in self._updates:
found.Add(update)
return updates | Get the contents of ``_updates`` (all updates) and puts them in an
Updates class to expose the list and summary functions.
Returns:
Updates: An instance of the Updates class with all updates for the
system.
.. code-block:: python
import salt.utils.win_updat... |
18,865 | def getDefaultItems(self):
return [
RtiRegItem(,
,
extensions=[, , , , ]),
RtiRegItem(,
,
extensions=[]),
RtiRegItem(,
,
... | Returns a list with the default plugins in the repo tree item registry. |
18,866 | def unregister_provider(self, provider):
self._unregistering_providers.add(provider)
remaining_providers = self._providers - self._unregistering_providers
if not remaining_providers:
_log.debug(, self)
self.queue_consumer.unregister_provider(self)
_lo... | Unregister a provider.
Blocks until this RpcConsumer is unregistered from its QueueConsumer,
which only happens when all providers have asked to unregister. |
18,867 | def load(dbname, dbmode=):
if dbmode == :
raise AttributeError("dbmode= not allowed for load.")
db = Database(dbname, dbmode=dbmode)
return db | Load an existing hdf5 database.
Return a Database instance.
:Parameters:
filename : string
Name of the hdf5 database to open.
mode : 'a', 'r'
File mode : 'a': append, 'r': read-only. |
18,868 | def remove_negativescores_nodes(self):
gravity_items = self.parser.css_select(self.top_node, "*[gravityScore]")
for item in gravity_items:
score = self.parser.getAttribute(item, )
score = int(score, 0)
if score < 1:
item.getparent().remove(ite... | \
if there are elements inside our top node
that have a negative gravity score,
let's give em the boot |
18,869 | def _parse_01(ofiles, individual=False):
cols = []
dats = []
for ofile in ofiles:
with open(ofile) as infile:
dat = infile.read()
lastbits = dat.split(".mcmc.txt\n\n")[1:]
results = lastbits[0].split("\n\n")[0].split()
shape = (((le... | a subfunction for summarizing results |
18,870 | def post(self, request, *args, **kwargs):
current_timestamp = "%.0f" % time.time()
user_id_str = u"{0}".format(request.user.id)
token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(current_timestamp), info="")
participant = Participant.objects.... | Returns a token identifying the user in Centrifugo. |
18,871 | def _unique_by_email(users_and_watches):
def ensure_user_has_email(user, cluster_email):
if not getattr(user, , ):
user = EmailUser(cluster_email)
return user
cluster_email =
favorite_user = None
watches = []
for u, w in users_and... | Given a sequence of (User/EmailUser, [Watch, ...]) pairs
clustered by email address (which is never ''), yield from each
cluster a single pair like this::
(User/EmailUser, [Watch, Watch, ...]).
The User/Email is that of...
(1) the first incoming pair where the User has an email and is not
... |
18,872 | def adjustMask(self):
if self.currentMode() == XPopupWidget.Mode.Dialog:
self.clearMask()
return
path = self.borderPath()
bitmap = QBitmap(self.width(), self.height())
bitmap.fill(QColor())
with XPainter(bitmap) as pain... | Updates the alpha mask for this popup widget. |
18,873 | def create_cherry_pick(self, cherry_pick_to_create, project, repository_id):
route_values = {}
if project is not None:
route_values[] = self._serialize.url(, project, )
if repository_id is not None:
route_values[] = self._serialize.url(, repository_id, )
... | CreateCherryPick.
[Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch.
:param :class:`<GitAsyncRefOperationParameters> <azure.devops.v5_0.git.models.GitAsyncRefOperationParameters>` cherry_pick_to_create:
:param str project: Project ID o... |
18,874 | def delete(self, upload_id):
return super(UploadsProxy, self).delete(upload_id, file_upload=True) | Deletes an upload by ID. |
18,875 | def read_data(self, size):
result = self.dev.bulkRead(0x81, size, timeout=1200)
if not result or len(result) < size:
raise IOError()
if not isinstance(result[0], int):
result = map(ord, result)
return list(result) | Receive data from the device.
If the read fails for any reason, an :obj:`IOError` exception
is raised.
:param size: the number of bytes to read.
:type size: int
:return: the data received.
:rtype: list(int) |
18,876 | def dereference_object(object_type, object_uuid, status):
from .models import PersistentIdentifier
pids = PersistentIdentifier.query.filter_by(
object_type=object_type, object_uuid=object_uuid
)
if status:
pids = pids.filter_by(status=status)
for found_pid in pids.all():
... | Show linked persistent identifier(s). |
18,877 | def descriptionHtml(self):
if self.cls is None:
return None
elif hasattr(self.cls, ):
return self.cls.descriptionHtml()
else:
return | HTML help describing the class. For use in the detail editor. |
18,878 | def search_process_log(self, pid, filter={}, start=0, limit=1000):
genericmy product paramtotallist
pid = self._get_pid(pid)
request_data = {: start, : limit, : filter}
return self._call_rest_api(, + pid + , data=request_data,
error=) | search_process_log(self, pid, filter={}, start=0, limit=1000)
Search in process logs
:Parameters:
* *pid* (`string`) -- Identifier of an existing process
* *start* (`int`) -- start index to retrieve from. Default is 0
* *limit* (`int`) -- maximum number of entities to retrieve.... |
18,879 | def get_player(self, *tags: crtag, **params: keys):
url = self.api.PLAYER + + .join(tags)
return self._get_model(url, FullPlayer, **params) | Get a player information
Parameters
----------
\*tags: str
Valid player tags. Minimum length: 3
Valid characters: 0289PYLQGRJCUV
\*\*keys: Optional[list] = None
Filter which keys should be included in the
response
\*\*exclude: Opti... |
18,880 | def string_chain(text, filters):
if filters is None:
return text
for filter_function in filters:
text = filter_function(text)
return text | Chain several filters after each other, applies the filter on the entire string
:param text: String to format
:param filters: Sequence of filters to apply on String
:return: The formatted String |
18,881 | def read_file(self):
file_obj = open(self.file, )
content = file_obj.read()
file_obj.close()
if content:
content = json.loads(content)
return content
else:
return {} | Open the file and assiging the permission to read/write and
return the content in json formate.
Return : json data |
18,882 | def get_default_config(self):
default_config = super(FlumeCollector, self).get_default_config()
default_config[] =
default_config[] =
default_config[] = 41414
default_config[] =
return default_config | Returns the default collector settings |
18,883 | def get_application(*args):
opts_tuple = args
def wsgi_app(environ, start_response):
root, _, conf = opts_tuple or bootstrap_app()
cherrypy.config.update({: })
cherrypy.tree.mount(root, , conf)
return cherrypy.tree(environ, start_response)
return wsgi_app | Returns a WSGI application function. If you supply the WSGI app and config
it will use that, otherwise it will try to obtain them from a local Salt
installation |
18,884 | def loop_exit_label(self, loop_type):
for i in range(len(self.LOOPS) - 1, -1, -1):
if loop_type == self.LOOPS[i][0]:
return self.LOOPS[i][1]
raise InvalidLoopError(loop_type) | Returns the label for the given loop type which
exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' |
18,885 | def process_create_ex(self, executable, arguments, environment_changes, flags, timeout_ms, priority, affinity):
if not isinstance(executable, basestring):
raise TypeError("executable can only be an instance of type basestring")
if not isinstance(arguments, list):
raise T... | Creates a new process running in the guest with the extended options
for setting the process priority and affinity.
See :py:func:`IGuestSession.process_create` for more information.
in executable of type str
Full path to the file to execute in the guest. The file has to
... |
18,886 | def search_dashboard_for_facets(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.search_dashboard_for_facets_with_http_info(**kwargs)
else:
(data) = self.search_dashboard_for_facets_with_http_info(**kwargs)
return data | Lists the values of one or more facets over the customer's non-deleted dashboards # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.search_dashboard_for_facets(async_req... |
18,887 | def agg(self, func, *fields, **name):
if name:
if len(name) > 1 or not in name:
raise TypeError("Unknown keyword args passed into `agg`: %s"
% name)
name = name.get()
if not isinstance(name, basestring):
... | Calls the aggregation function `func` on each group in the GroubyTable,
and leaves the results in a new column with the name of the aggregation
function.
Call `.agg` with `name='desired_column_name' to choose a column
name for this aggregation. |
18,888 | def write_serializable_array(self, array):
if array is None:
self.write_byte(0)
else:
self.write_var_int(len(array))
for item in array:
item.Serialize(self) | Write an array of serializable objects to the stream.
Args:
array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin |
18,889 | def _read_structure_attributes(f):
line =
variogram_info = {}
while "end structure" not in line:
line = f.readline()
if line == :
raise Exception("EOF while reading structure")
line = line.strip().lower().split()
if line[0].startswith():
continu... | function to read information from a PEST-style structure file
Parameters
----------
f : (file handle)
file handle open for reading
Returns
-------
nugget : float
the GeoStruct nugget
transform : str
the GeoStruct transformation
variogram_info : dict
dict... |
18,890 | def create_metric(metric_type, metric_id, data):
if not isinstance(data, list):
data = [data]
return { : metric_type,: metric_id, : data } | Create Hawkular-Metrics' submittable structure.
:param metric_type: MetricType to be matched (required)
:param metric_id: Exact string matching metric id
:param data: A datapoint or a list of datapoints created with create_datapoint(value, timestamp, tags) |
18,891 | def unseal(self, data, return_options=False):
data = self._remove_magic(data)
data = urlsafe_nopadding_b64decode(data)
options = self._read_header(data)
data = self._add_magic(data)
data = self._unsign_data(data, options)
data = self._remove_magic(data)
... | Unseal data |
18,892 | def open(filepath, edit_local=False):
filepath = os.fspath(filepath)
ds = np.DataSource(None)
if edit_local is False:
tf = tempfile.mkstemp(prefix="", suffix=".wt5")
with _open(tf[1], "w+b") as tff:
with ds.open(str(filepath), "rb") as f:
tff.write(f.read())
... | Open any wt5 file, returning the top-level object (data or collection).
Parameters
----------
filepath : path-like
Path to file.
Can be either a local or remote file (http/ftp).
Can be compressed with gz/bz2, decompression based on file name.
edit_local : boolean (optional)
... |
18,893 | def info_community(self,teamid):
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",: +self.domain+,"User-Agent": user_agent}
req = self.session.get(+self.domain++teamid,headers=headers).content
soup = BeautifulSoup(req)
info = []
for i... | Get comunity info using a ID |
18,894 | def validate_image_size(image):
config = get_app_config()
valid_max_image_size_in_bytes = config.valid_max_image_size * 1024
if config and not image.size <= valid_max_image_size_in_bytes:
raise ValidationError(
_("The logo image file size must be less than or equal to %s KB.") % con... | Validate that a particular image size. |
18,895 | def parse_manifest(self, manifest_xml):
manifest = dict()
try:
mdata = xmltodict.parse(manifest_xml)[][]
for module in mdata:
mod = dict()
mod[] = module[]
mod[] = module[]
mod[] = module[]
... | Parse manifest xml file
:type manifest_xml: str
:param manifest_xml: raw xml content of manifest file |
18,896 | def _initialize_plugin_system(self) -> None:
self._preloop_hooks = []
self._postloop_hooks = []
self._postparsing_hooks = []
self._precmd_hooks = []
self._postcmd_hooks = []
self._cmdfinalization_hooks = [] | Initialize the plugin system |
18,897 | def delete_ip_address(context, id):
LOG.info("delete_ip_address %s for tenant %s" % (id, context.tenant_id))
with context.session.begin():
ip_address = db_api.ip_address_find(
context, id=id, scope=db_api.ONE)
if not ip_address or ip_address.deallocated:
raise q_exc.... | Delete an ip address.
: param context: neutron api request context
: param id: UUID representing the ip address to delete. |
18,898 | def renders(self, template_content, context=None, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
kwargs = self.filter_options(kwargs, self.render_valid_options())
paths = anytemplate.utils.mk_template_paths(None, at_paths)
if context is None:
... | :param template_content: Template content
:param context: A dict or dict-like object to instantiate given
template file or None
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arguments passed to the template engine to
... |
18,899 | def p_version_def(t):
global name_dict
id = t[2]
value = t[8]
lineno = t.lineno(1)
if id_unique(id, , lineno):
name_dict[id] = const_info(id, value, lineno) | version_def : VERSION ID LBRACE procedure_def procedure_def_list RBRACE EQUALS constant SEMI |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.