Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
378,200 | def next(self):
loop = self.get_io_loop()
return self._framework.run_on_executor(loop, self._next) | Advance the cursor.
This method blocks until the next change document is returned or an
unrecoverable error is raised.
Raises :exc:`StopAsyncIteration` if this change stream is closed.
You can iterate the change stream by calling
``await change_stream.next()`` repeatedly, or w... |
378,201 | def modelresource_factory(model, resource_class=ModelResource):
attrs = {: model}
Meta = type(str(), (object,), attrs)
class_name = model.__name__ + str()
class_attrs = {
: Meta,
}
metaclass = ModelDeclarativeMetaclass
return metaclass(class_name, (resource_class,), class_att... | Factory for creating ``ModelResource`` class for given Django model. |
378,202 | def validateBusName(n):
try:
if not in n:
raise Exception()
if in n:
raise Exception()
if len(n) > 255:
raise Exception()
if n[0] == :
raise Exception()
if n[0].isdigit():
raise Exception()
if bus_re.s... | Verifies that the supplied name is a valid DBus Bus name. Throws
an L{error.MarshallingError} if the format is invalid
@type n: C{string}
@param n: A DBus bus name |
378,203 | def prepare_and_execute(self, connection_id, statement_id, sql, max_rows_total=None, first_frame_max_size=None):
request = requests_pb2.PrepareAndExecuteRequest()
request.connection_id = connection_id
request.statement_id = statement_id
request.sql = sql
if max_rows_tota... | Prepares and immediately executes a statement.
:param connection_id:
ID of the current connection.
:param statement_id:
ID of the statement to prepare.
:param sql:
SQL query.
:param max_rows_total:
The maximum number of rows that will b... |
378,204 | def get_electrode_node(self, electrode):
elec_node_raw = int(self.electrodes[electrode - 1][0])
if(self.header[]):
elec_node = self.nodes[][elec_node_raw]
else:
elec_node = elec_node_raw - 1
return int(elec_node) | For a given electrode (e.g. from a config.dat file), return the true
node number as in self.nodes['sorted'] |
378,205 | def optimal_variational_posterior(
kernel,
inducing_index_points,
observation_index_points,
observations,
observation_noise_variance,
mean_fn=None,
jitter=1e-6,
name=None):
with tf.name_scope(name or ):
dtype = dtype_util.common_dtype(
[inducing_... | Model selection for optimal variational hyperparameters.
Given the full training set (parameterized by `observations` and
`observation_index_points`), compute the optimal variational
location and scale for the VGP. This is based of the method suggested
in [Titsias, 2009][1].
Args:
kernel: `P... |
378,206 | def _get_handlers(self):
members = {}
for d in __conf__.ACTION_DIR_NAME:
members.update(get_members(d,
None,
lambda m: isclass(m) and issubclass(m, BaseHandler) and hasattr(m, "__urls__") and m.__urls__))
... | 获取 action.handlers
添加路径 __conf__.ACTION_DIR_NAME 列表中的 action by ABeen |
378,207 | def join(self, t2, unique=False):
x_v1 = np.concatenate((self.x, t2.x), axis=0)
y_v1 = np.concatenate((self.y, t2.y), axis=0)
if not unique:
a = np.ascontiguousarray(np.vstack((x_v1, y_v1)).T)
unique_a = np.unique(a.view([(, a.dtype)]*a.shape[1]))
... | Join this triangulation with another. If the points are known to have no duplicates, then
set unique=False to skip the testing and duplicate removal |
378,208 | def sort_func(self, key):
if key == self._KEYS.VALUE:
return
if key == self._KEYS.SOURCE:
return
return key | Sorting logic for `Quantity` objects. |
378,209 | def send_button(recipient):
page.send(recipient, Template.Buttons("hello", [
Template.ButtonWeb("Open Web URL", "https://www.oculus.com/en-us/rift/"),
Template.ButtonPostBack("trigger Postback", "DEVELOPED_DEFINED_PAYLOAD"),
Template.ButtonPhoneNumber("Call Phone Number", "+16505551234"... | Shortcuts are supported
page.send(recipient, Template.Buttons("hello", [
{'type': 'web_url', 'title': 'Open Web URL', 'value': 'https://www.oculus.com/en-us/rift/'},
{'type': 'postback', 'title': 'tigger Postback', 'value': 'DEVELOPED_DEFINED_PAYLOAD'},
{'type': 'phone_number', 'title': 'Cal... |
378,210 | def proof_req_briefs2req_creds(proof_req: dict, briefs: Union[dict, Sequence[dict]]) -> dict:
rv = {
: {},
: {},
: {}
}
attr_refts = proof_req_attr_referents(proof_req)
pred_refts = proof_req_pred_referents(proof_req)
for brief in iter_briefs(briefs):
cred_info... | Given a proof request and cred-brief(s), return a requested-creds structure.
The proof request must have cred def id restrictions on all requested attribute specifications.
:param proof_req: proof request
:param briefs: credential brief, sequence thereof (as indy-sdk wallet credential search returns),
... |
378,211 | def _put_bucket_lifecycle(self):
status =
if self.s3props[][]:
lifecycle_config = {
: self.s3props[][]
}
LOG.debug(, lifecycle_config)
_response = self.s3client.put_bucket_lifecycle_configuration(Bucket=self.bucket,
... | Adds bucket lifecycle configuration. |
378,212 | def vel_grad_avg(self):
return ((u.standard_gravity * self.HL) /
(pc.viscosity_kinematic(self.temp) * self.Gt)).to(u.s ** -1) | Calculate the average velocity gradient (G-bar) of water flowing
through the flocculator.
:returns: Average velocity gradient (G-bar)
:rtype: float * 1 / second |
378,213 | def checkValue(self,value,strict=0):
v = self._coerceValue(value,strict)
return self.checkOneValue(v,strict) | Check and convert a parameter value.
Raises an exception if the value is not permitted for this
parameter. Otherwise returns the value (converted to the
right type.) |
378,214 | def get_string(self, betas: List[float], gammas: List[float], samples: int = 100):
if samples <= 0 and not isinstance(samples, int):
raise ValueError("samples variable must be positive integer")
param_prog = self.get_parameterized_program()
stacked_params = np.hstack((betas,... | Compute the most probable string.
The method assumes you have passed init_betas and init_gammas with your
pre-computed angles or you have run the VQE loop to determine the
angles. If you have not done this you will be returning the output for
a random set of angles.
:param bet... |
378,215 | def _script_to_har_entry(cls, script, url):
entry = {
: {: url},
: {: url, : {: script}}
}
cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY)
return entry | Return entry for embed script |
378,216 | def resource_to_portal_type(resource):
if resource is None:
return None
resource_mapping = get_resource_mapping()
portal_type = resource_mapping.get(resource.lower())
if portal_type is None:
logger.warn("Could not map the resource "
"to any known portal type".... | Converts a resource to a portal type
:param resource: Resource name as it is used in the content route
:type name: string
:returns: Portal type name
:rtype: string |
378,217 | def metric_delete(self, project, metric_name):
path = "projects/%s/metrics/%s" % (project, metric_name)
self._gapic_api.delete_log_metric(path) | API call: delete a metric resource.
:type project: str
:param project: ID of the project containing the metric.
:type metric_name: str
:param metric_name: the name of the metric |
378,218 | def drawItem(self, item, painter, option):
dataset = item.dataset()
painter.save()
painter.setRenderHint(painter.Antialiasing)
center = item.buildData()
radius = item.buildData()
if int(option.state) & QStyle.State_MouseOver !... | Draws the inputed item as a bar graph.
:param item | <XChartDatasetItem>
painter | <QPainter>
option | <QStyleOptionGraphicsItem> |
378,219 | def write_jsonl_file(fname, data):
if not isinstance(data, list):
print(, fname)
return
with open(fname, ) as of:
for row in data:
if row.strip():
of.write( % row.strip()) | Writes a jsonl file.
Args:
data: list of json encoded data |
378,220 | def fetch(self, category=CATEGORY_COMMIT, from_date=DEFAULT_DATETIME, to_date=DEFAULT_LAST_DATETIME,
branches=None, latest_items=False, no_update=False):
if not from_date:
from_date = DEFAULT_DATETIME
if not to_date:
to_date = DEFAULT_LAST_DATETIME
... | Fetch commits.
The method retrieves from a Git repository or a log file
a list of commits. Commits are returned in the same order
they were obtained.
When `from_date` parameter is given it returns items commited
since the given date.
The list of `branches` is a list of... |
378,221 | def key_value(self, **kwargs):
field_name = self.name
new_df = copy_df(self)
new_df._perform_operation(op.FieldKVConfigOperation({field_name: KVConfig(**kwargs)}))
return new_df | Set fields to be key-value represented.
:rtype: Column
:Example:
>>> new_ds = df.key_value('f1 f2', kv=':', item=',') |
378,222 | def project_data_source_path(cls, project, data_source):
return google.api_core.path_template.expand(
"projects/{project}/dataSources/{data_source}",
project=project,
data_source=data_source,
) | Return a fully-qualified project_data_source string. |
378,223 | def get_time(self, idx):
qpi = self.get_qpimage_raw(idx)
if "time" in qpi.meta:
thetime = qpi.meta["time"]
else:
thetime = np.nan
return thetime | Return time of data at index `idx`
Returns nan if the time is not defined |
378,224 | def _generate_prime(bits, rng):
"primtive attempt at prime generation"
hbyte_mask = pow(2, bits % 8) - 1
while True:
x = rng.read((bits+7) // 8)
if hbyte_mask > 0:
x = chr(ord(x[0]) & hbyte_mask) + x[1:]
n = util.inflate_long(x, 1)
n |= 1
n |= (1 ... | primtive attempt at prime generation |
378,225 | def point_lm(self, context):
lm = np.empty(context.shape, context.dtype)
montblanc.log.info(context.array_schema.shape)
montblanc.log.info(context.iter_args)
(ls, us) = context.dim_extents()
lm[:,0] = 0.0008
lm[:,1] = 0.0036
lm[:,:] ... | Return a lm coordinate array to montblanc |
378,226 | def visit_tuple(self, node):
if len(node.elts) == 1:
return "(%s, )" % node.elts[0].accept(self)
return "(%s)" % ", ".join(child.accept(self) for child in node.elts) | return an astroid.Tuple node as string |
378,227 | def setup_logging(
default_level=logging.INFO,
default_path=None,
env_key=,
handler_name=,
handlers_dict=None,
log_dict=None,
config_name=None,
splunk_host=None,
splunk_port=None,
splunk_index=None,
splunk_token=None,
splunk... | setup_logging
Setup logging configuration
:param default_level: level to log
:param default_path: path to config (optional)
:param env_key: path to config in this env var
:param handler_name: handler name in the config
:param handlers_dict: handlers dict
:param log_dict: full log dictionar... |
378,228 | def create(self, name, incident_preference):
data = {
"policy": {
"name": name,
"incident_preference": incident_preference
}
}
return self._post(
url=.format(self.URL),
headers=self.headers,
da... | This API endpoint allows you to create an alert policy
:type name: str
:param name: The name of the policy
:type incident_preference: str
:param incident_preference: Can be PER_POLICY, PER_CONDITION or
PER_CONDITION_AND_TARGET
:rtype: dict
:return: The JSON... |
378,229 | def update_option_value_by_id(cls, option_value_id, option_value, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._update_option_value_by_id_with_http_info(option_value_id, option_value, **kwargs)
else:
(data) = cls._update_option_value_by_id_with_http_inf... | Update OptionValue
Update attributes of OptionValue
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_option_value_by_id(option_value_id, option_value, async=True)
>>> result = thread.get... |
378,230 | def put_connection_filename(filename, working_filename, verbose = False):
if working_filename != filename:
deferred_signals = []
def newsigterm(signum, frame):
deferred_signals.append(signum)
oldhandlers = {}
for sig in (signal.SIGTERM, signal.SIGTSTP):
oldhandlers[sig] = signal.getsignal(sig)
si... | This function reverses the effect of a previous call to
get_connection_filename(), restoring the working copy to its
original location if the two are different. This function should
always be called after calling get_connection_filename() when the
file is no longer in use.
During the move operation, this functio... |
378,231 | def _cast(self, value, format=None, **opts):
if format is not None:
return datetime.strptime(value, format)
return dateutil.parser.parse(value) | Optionally apply a format string. |
378,232 | def get_init_container(self,
init_command,
init_args,
env_vars,
context_mounts,
persistence_outputs,
persistence_data):
env_vars = to_list(en... | Pod init container for setting outputs path. |
378,233 | async def wait_read(self, message=None, *, timeout=None):
start_time = time.time()
future = self._client.loop.create_future()
target_id = self._get_message_id(message)
if self._last_read is None:
self._last_read = target_id - 1
if self._last_read >= target_... | Awaits for the sent message to be read. Note that receiving
a response doesn't imply the message was read, and this action
will also trigger even without a response. |
378,234 | def to_df(self) -> pd.DataFrame:
if issparse(self._X):
X = self._X.toarray()
else:
X = self._X
return pd.DataFrame(X, index=self.obs_names, columns=self.var_names) | Generate shallow :class:`~pandas.DataFrame`.
The data matrix :attr:`X` is returned as
:class:`~pandas.DataFrame`, where :attr:`obs_names` initializes the
index, and :attr:`var_names` the columns.
* No annotations are maintained in the returned object.
* The data matrix is densi... |
378,235 | def get_context(self, value):
context = super(RenditionAwareStructBlock, self).get_context(value)
context[] = self.rendition.\
image_rendition or
return context | Ensure `image_rendition` is added to the global context. |
378,236 | def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]:
relations_list, last_relation = [], related_model
for relation in relations:
relationship = getattr(last_relation, relation, None)
if relationship is None:
... | Transform the list of relation to list of class.
:param related_mode: The model of the query.
:type related_mode: type
:param relations: The relation list get from the `_extract_relations`.
:type relations: List[str]
:return: Tuple with the list of relations (class) and the se... |
378,237 | def nbopen(filename):
filename = osp.abspath(filename)
home_dir = get_home_dir()
server_info = find_best_server(filename)
if server_info is not None:
print("Using existing server at", server_info[])
return server_info
else:
if filename.startswith(home_dir):
... | Open a notebook using the best available server.
Returns information about the selected server. |
378,238 | def process_raw_data(self, fname, max_size):
logging.info(f)
data = []
with open(fname) as dfile:
for idx, line in enumerate(dfile):
if max_size and idx == max_size:
break
data.append(line)
return data | Loads data from the input file.
:param fname: input file name
:param max_size: loads at most 'max_size' samples from the input file,
if None loads the entire dataset |
378,239 | def flush_content(self):
LOGGER.debug("> Flushing cache content.".format(self.__class__.__name__))
self.clear()
return True | Flushes the cache content.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.flush_content()
True
>>> cache
{}
:return: Method success.
:rtype: bool |
378,240 | def from_type_name(cls, typ, name):
for k, nt in cls.defined_aliases.items():
if typ is not None and typ != nt.type: continue
if name == nt.name:
if len(k) == 1: return cls(xc=k)
if len(k) == 2: return cls(x=k[0], c=k[1])
... | Build the object from (type, name). |
378,241 | def episode_list(a):
html = get_html(ROOT + a.get())
div = html.find(, {: "list detail eplist"})
links = []
for tag in div.find_all(, {: "name"}):
links.append(tag)
return links | List of all episodes of a season |
378,242 | def shake_shake_layer(x, output_filters, num_blocks, stride, hparams):
for block_num in range(num_blocks):
curr_stride = stride if (block_num == 0) else 1
with tf.variable_scope("layer_{}".format(block_num)):
x = shake_shake_block(x, output_filters, curr_stride, hparams)
return x | Builds many sub layers into one full layer. |
378,243 | def get_flow(self, name):
config = getattr(self, "flows__{}".format(name))
if not config:
raise FlowNotFoundError("Flow not found: {}".format(name))
return FlowConfig(config) | Returns a FlowConfig |
378,244 | def message_archive(self, project_id, category_id=None):
path = % project_id
req = ET.Element()
ET.SubElement(req, ).text = str(int(project_id))
if category_id is not None:
ET.SubElement(req, ).text = str(int(category_id))
return self._request(path, req) | This will return a summary record for each message in a project. If
you specify a category_id, only messages in that category will be
returned. (Note that a summary record includes only a few bits of
information about a post, not the complete record.) |
378,245 | def make_report(self, sections_first=True, section_header_params=None):
full_story = list(self._preformat_text(self.title, style=,
fontsize=18, alignment=))
if section_header_params is None:
section_header_params = {: , : 14,
... | Create the pdf document with name `self.name + '.pdf'`.
Parameters
----------
sections_first : bool
If True (default), text and images with sections are presented first
and un-sectioned content is appended afterword. If False, sectioned
text and images will b... |
378,246 | def __replace_all(repls: dict, input: str) -> str:
return re.sub(.join(re.escape(key) for key in repls.keys()),
lambda k: repls[k.group(0)], input) | Replaces from a string **input** all the occurrences of some
symbols according to mapping **repls**.
:param dict repls: where #key is the old character and
#value is the one to substitute with;
:param str input: original string where to apply the
replacements;
:return: *(str)* the string with t... |
378,247 | def date(fmt=None,timestamp=None):
"Manejo de fechas (simil PHP)"
if fmt==:
t = datetime.datetime.now()
return int(time.mktime(t.timetuple()))
if fmt==:
d = datetime.datetime.fromtimestamp(timestamp)
return d.isoformat()
if fmt==:
d = datetime.datetime.now()
... | Manejo de fechas (simil PHP) |
378,248 | def agg_shape(self, shp, aggregate_by):
return shp + tuple(
len(getattr(self, tagname)) - 1 for tagname in aggregate_by) | :returns: a shape shp + (T, ...) depending on the tagnames |
378,249 | def set(self, align=, font=, type=, width=1, height=1):
if align.upper() == "CENTER":
self._raw(TXT_ALIGN_CT)
elif align.upper() == "RIGHT":
self._raw(TXT_ALIGN_RT)
elif align.upper() == "LEFT":
self._raw(TXT_ALIGN_LT)
if fon... | Set text properties |
378,250 | def create_queue(
self,
parent,
queue,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
if "create_queue" not in self._inner_api_calls:
self._inner_api_calls[
... | Creates a queue.
Queues created with this method allow tasks to live for a maximum of 31
days. After a task is 31 days old, the task will be deleted regardless
of whether it was dispatched or not.
WARNING: Using this method may have unintended side effects if you are
using an A... |
378,251 | def allow_buttons(self, message="", link=True, back=True):
self.info_label.set_label(message)
self.allow_close_window()
if link and self.link is not None:
self.link.set_sensitive(True)
self.link.show_all()
if back:
self.back_btn.show()
... | Function allows buttons |
378,252 | def retry(self, func, partition_id, retry_message, final_failure_message, max_retries, host_id):
loop = asyncio.new_event_loop()
loop.run_until_complete(self.retry_async(func, partition_id, retry_message,
final_failure_message, max_retries, host_... | Make attempt_renew_lease async call sync. |
378,253 | def print_packet_count():
for name in archive.list_packet_names():
packet_count = 0
for group in archive.list_packet_histogram(name):
for rec in group.records:
packet_count += rec.count
print(.format(name, packet_count)) | Print the number of packets grouped by packet name. |
378,254 | def gen_send_stdout_url(ip, port):
return .format(BASE_URL.format(ip), port, API_ROOT_URL, STDOUT_API, NNI_EXP_ID, NNI_TRIAL_JOB_ID) | Generate send stdout url |
378,255 | def install(self):
keys = self.get_keys_from_ldap()
for user, ssh_keys in keys.items():
user_dir = API.__authorized_keys_path(user)
if not os.path.isdir(user_dir):
os.makedirs(user_dir)
authorized_keys_file = os.path.join(user_dir, )
... | Install/download ssh keys from LDAP for consumption by SSH. |
378,256 | def delete_async(blob_key, **options):
if not isinstance(blob_key, (basestring, BlobKey)):
raise TypeError( % (blob_key,))
rpc = blobstore.create_rpc(**options)
yield blobstore.delete_async(blob_key, rpc=rpc) | Async version of delete(). |
378,257 | def generic_visit(self, node):
super(RangeValues, self).generic_visit(node)
return self.add(node, UNKNOWN_RANGE) | Other nodes are not known and range value neither. |
378,258 | def runSearchCallSets(self, request):
return self.runSearchRequest(
request, protocol.SearchCallSetsRequest,
protocol.SearchCallSetsResponse,
self.callSetsGenerator) | Runs the specified SearchCallSetsRequest. |
378,259 | def wait_until_not_visible(self, timeout=None):
try:
self.utils.wait_until_element_not_visible(self, timeout)
except TimeoutException as exception:
parent_msg = " and parent locator ".format(self.parent) if self.parent else
msg = "Page element of type with ... | Search element and wait until it is not visible
:param timeout: max time to wait
:returns: page element instance |
378,260 | def get_groups(self, env, token):
groups = None
memcache_client = cache_from_env(env)
if memcache_client:
memcache_key = % (self.reseller_prefix, token)
cached_auth_data = memcache_client.get(memcache_key)
if cached_auth_data:
expires... | Get groups for the given token.
:param env: The current WSGI environment dictionary.
:param token: Token to validate and return a group string for.
:returns: None if the token is invalid or a string containing a comma
separated list of groups the authenticated user is a membe... |
378,261 | def gc2gdlat(gclat):
WGS84_e2 = 0.006694379990141317
return np.rad2deg(-np.arctan(np.tan(np.deg2rad(gclat))/(WGS84_e2 - 1))) | Converts geocentric latitude to geodetic latitude using WGS84.
Parameters
==========
gclat : array_like
Geocentric latitude
Returns
=======
gdlat : ndarray or float
Geodetic latitude |
378,262 | def render(filename, obj):
template_path = abspath(filename)
env = jinja_env(template_path)
template_base = os.path.basename(template_path)
try:
parsed_content = env.parse(env
.loader
.get_source(env, template_base))
... | Render a template, maybe mixing in extra variables |
378,263 | def updateSolutionTerminal(self):
self.solution_terminal.vFunc = ValueFunc2D(self.cFunc_terminal_,self.CRRA)
self.solution_terminal.vPfunc = MargValueFunc2D(self.cFunc_terminal_,self.CRRA)
self.solution_terminal.vPPfunc = MargMargValueFunc2D(self.cFunc_terminal_,self.CRRA)
self.... | Update the terminal period solution. This method should be run when a
new AgentType is created or when CRRA changes.
Parameters
----------
None
Returns
-------
None |
378,264 | def findSynonymsArray(self, word, num):
if not isinstance(word, basestring):
word = _convert_to_vector(word)
tuples = self._java_obj.findSynonymsArray(word, num)
return list(map(lambda st: (st._1(), st._2()), list(tuples))) | Find "num" number of words closest in similarity to "word".
word can be a string or vector representation.
Returns an array with two fields word and similarity (which
gives the cosine similarity). |
378,265 | def processDatasetBlocks(self, url, conn, inputdataset, order_counter):
ordered_dict = {}
srcblks = self.getSrcBlocks(url, dataset=inputdataset)
if len(srcblks) < 0:
e = "DBSMigration: No blocks in the required dataset %s found at source %s."%(inputdataset, url)
... | Utility function, that comapares blocks of a dataset at source and dst
and returns an ordered list of blocks not already at dst for migration |
378,266 | def msg_debug(message):
if _log_lvl == logging.DEBUG:
to_stdout(" (*) {message}".format(message=message), colorf=cyan)
if _logger:
_logger.debug(message) | Log a debug message
:param message: the message to be logged |
378,267 | def list_rocs_files(url=ROCS_URL):
soup = BeautifulSoup(get(url))
if not url.endswith():
url +=
files = []
for elem in soup.findAll():
if elem[].startswith():
continue
if elem.string.lower() == :
continue
files.append(url + elem[])
return... | Gets the contents of the given url. |
378,268 | def get_subpackages(app, module):
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg] | Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError |
378,269 | def combine_or(matcher, *more_matchers):
def matcher(cause):
for sub_matcher in itertools.chain([matcher], more_matchers):
cause_cls = sub_matcher(cause)
if cause_cls is not None:
return cause_cls
return None
return matcher | Combines more than one matcher together (first that matches wins). |
378,270 | def archive_query_interval(self, _from, to):
with self.session as session:
table = self.tables.archive
try:
results = session.query(table)\
.filter(table.dateTime >= _from)\
.filter(table.dateTime < to)\
... | :param _from: Start of interval (int) (inclusive)
:param to: End of interval (int) (exclusive)
:raises: IOError |
378,271 | def _get_submodules(app, module):
if inspect.ismodule(module):
if hasattr(module, ):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
... | Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeEr... |
378,272 | def raise_server_error(self):
if self.server and self.server.error:
try:
if capybara.raise_server_errors:
raise self.server.error
finally:
self.server.reset_error() | Raise errors encountered by the server. |
378,273 | def _parse_bro_header(self, logfile):
_line = next(logfile)
while (not _line.startswith()):
_line = next(logfile)
_field_names = _line.strip().split(self.delimiter)[1:]
_line = next(logfile)
_field_types = _line.strip().split(sel... | This method tries to parse the Bro log header section.
Note: My googling is failing me on the documentation on the format,
so just making a lot of assumptions and skipping some shit.
Assumption 1: The delimeter is a tab.
Assumption 2: Types are either time, string, int or float
... |
378,274 | def parse(self, message, schema):
func = {
: self._parse_audit_log_msg,
: self._parse_event_msg,
}[schema]
return func(message) | Parse message according to schema.
`message` should already be validated against the given schema.
See :ref:`schemadef` for more information.
Args:
message (dict): message data to parse.
schema (str): valid message schema.
Returns:
(dict): parsed mes... |
378,275 | def replace_group(self, index, func_grp, strategy, bond_order=1,
graph_dict=None, strategy_params=None, reorder=True,
extend_structure=True):
self.set_node_attributes()
neighbors = self.get_connected_sites(index)
if len(neighbors) =... | Builds off of Molecule.substitute and MoleculeGraph.substitute_group
to replace a functional group in self.molecule with a functional group.
This method also amends self.graph to incorporate the new functional
group.
TODO: Figure out how to replace into a ring structure.
:param... |
378,276 | def _AddOption(self, name):
if name in [option.name for option in self.options]:
raise TextFSMTemplateError( % name)
try:
option = self._options_cls.GetOption(name)(self)
except AttributeError:
raise TextFSMTemplateError( % name)
self.options.append(option) | Add an option to this Value.
Args:
name: (str), the name of the Option to add.
Raises:
TextFSMTemplateError: If option is already present or
the option does not exist. |
378,277 | def authenticate(self, verify=True):
self.__oauth = OAuth1(self.__consumer_key,
client_secret=self.__consumer_secret,
resource_owner_key=self.__access_token,
resource_owner_secret=self.__access_token_secret)
... | Creates an authenticated and internal oauth2 handler needed for \
queries to Twitter and verifies credentials if needed. If ``verify`` \
is true, it also checks if the user credentials are valid. \
The **default** value is *True*
:param verify: boolean variable to \
directly c... |
378,278 | def get(self):
pool = current_app.config[]
with pool() as bigchain:
validators = bigchain.get_validators()
return validators | API endpoint to get validators set.
Return:
A JSON string containing the validator set of the current node. |
378,279 | def breakfast(self, message="Breakfast is ready", shout: bool = False):
return self.helper.output(message, shout) | Say something in the morning |
378,280 | def list_resources(self, session, query=):
resources = self.devices.list_resources()
resources = rname.filter(resources, query)
if resources:
return resources
raise errors.VisaIOError(errors.StatusCode.error_resource_not_found.value) | Returns a tuple of all connected devices matching query.
:param query: regular expression used to match devices. |
378,281 | def set_maxsize(self, maxsize, **kwargs):
new_cache = self._get_cache_impl(self.impl_name, maxsize, **kwargs)
self._populate_new_cache(new_cache)
self.cache = new_cache | Set maxsize. This involves creating a new cache and transferring the items. |
378,282 | def _get_combined_keywords(_keywords, split_text):
result = []
_keywords = _keywords.copy()
len_text = len(split_text)
for i in range(len_text):
word = _strip_word(split_text[i])
if word in _keywords:
combined_word = [word]
if i + 1 == len_text:
... | :param keywords:dict of keywords:scores
:param split_text: list of strings
:return: combined_keywords:list |
378,283 | def edit_form(self, obj):
form = super(OAISetModelView, self).edit_form(obj)
del form.spec
return form | Customize edit form. |
378,284 | def _get_filepaths(self):
self._printer(str(self.__len__()) + " file paths have been parsed in " + str(self.timer.end))
if self._hash_files:
return pool_hash(self.filepaths)
else:
return self.filepaths | Filters list of file paths to remove non-included, remove excluded files and concatenate full paths. |
378,285 | def get_outline(ds, t_srs=None, scale=1.0, simplify=False, convex=False):
gt = np.array(ds.GetGeoTransform())
from pygeotools.lib import iolib
a = iolib.ds_getma_sub(ds, scale=scale)
geom = ogr.Geometry(ogr.wkbPolygon)
if a.count() != 0:
if (scale != 1.0):
... | Generate outline of unmasked values in input raster
get_outline is an attempt to reproduce the PostGIS Raster ST_MinConvexHull function
Could potentially do the following: Extract random pts from unmasked elements, get indices, Run scipy convex hull, Convert hull indices to mapped coords
See this: http:/... |
378,286 | def visit_Try(self, node: ast.Try) -> Optional[ast.AST]:
new_node = self.generic_visit(node)
assert isinstance(new_node, ast.Try)
return ast.copy_location(
ast.Try(
body=_filter_dead_code(new_node.body),
handlers=new_node.handlers,
... | Eliminate dead code from except try bodies. |
378,287 | def _default_ns_prefix(nsmap):
if None in nsmap:
default_url = nsmap[None]
prefix = None
for key, val in nsmap.iteritems():
if val == default_url and key is not None:
prefix = key
break
else:
raise ValueError(
... | XML doc may have several prefix:namespace_url pairs, can also specify
a namespace_url as default, tags in that namespace don't need a prefix
NOTE:
we rely on default namespace also present in prefixed form, I'm not sure if
this is an XML certainty or a quirk of the eBay WSDLs
in our case the WSDL c... |
378,288 | def pick_kmersize(fq):
if bam.is_bam(fq):
readlength = bam.estimate_read_length(fq)
else:
readlength = fastq.estimate_read_length(fq)
halfread = int(round(readlength / 2))
if halfread >= 31:
kmersize = 31
else:
kmersize = halfread
if kmersize % 2 == 0:
... | pick an appropriate kmer size based off of https://www.biostars.org/p/201474/
tl;dr version: pick 31 unless the reads are very small, if not then guess
that readlength / 2 is about right. |
378,289 | def __write(self, thePath, theData):
fd = open(thePath, "wb")
fd.write(theData)
fd.close() | Write data to a file.
@type thePath: str
@param thePath: The file path.
@type theData: str
@param theData: The data to write. |
378,290 | def fkapply(models,pool,fn,missing_fn,(nombre,pkey,field),*args):
"wrapper for do_* funcs to call process_* with missing handler. Unpacks the FieldKey."
if (nombre,pkey) in models: return fn(pool,models[nombre,pkey],field,*args)
else: return missing_fn(pool,field,*args) if missing_fn else [] | wrapper for do_* funcs to call process_* with missing handler. Unpacks the FieldKey. |
378,291 | def mask(self, mask):
check_class(mask, (np.ndarray, bool, np.bool_))
if isinstance(mask, (bool, np.bool_)):
self._mask = bool(mask)
else:
self._mask = mask | The mask values. Must be an array or a boolean scalar. |
378,292 | def dtype_repr(dtype):
dtype = np.dtype(dtype)
if dtype == np.dtype(int):
return ""
elif dtype == np.dtype(float):
return ""
elif dtype == np.dtype(complex):
return ""
elif dtype.shape:
return "(, {})".format(dtype.base, dtype.shape)
else:
return "".f... | Stringify ``dtype`` for ``repr`` with default for int and float. |
378,293 | def inject_params(model_name: str) -> ListenerParams:
params_file = model_name +
try:
with open(params_file) as f:
pr.__dict__.update(compatibility_params, **json.load(f))
except (OSError, ValueError, TypeError):
if isfile(model_name):
print( + params_file)
... | Set the global listener params to a saved model |
378,294 | def sync_folder_to_container(self, folder_path, container, delete=False,
include_hidden=False, ignore=None, ignore_timestamps=False,
object_prefix="", verbose=False):
cont = self.get_container(container)
self._local_files = []
if verbose:
... | Compares the contents of the specified folder, and checks to make sure
that the corresponding object is present in the specified container. If
there is no remote object matching the local file, it is created. If a
matching object exists, the etag is examined to determine if the object
in... |
378,295 | def check_client_key(self, client_key):
lower, upper = self.client_key_length
return (set(client_key) <= self.safe_characters and
lower <= len(client_key) <= upper) | Check that the client key only contains safe characters
and is no shorter than lower and no longer than upper. |
378,296 | def parse_args(args):
parser = argparse.ArgumentParser(
description="Just a Hello World demonstration")
parser.add_argument(
,
,
action=,
version=.format(ver=__version__))
return parser.parse_args(args) | Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace` |
378,297 | def query(self, query_str, *query_args, **query_options):
with self.connection(**query_options) as connection:
query_options[] = connection
return self._query(query_str, query_args, **query_options) | run a raw query on the db
query_str -- string -- the query to run
*query_args -- if the query_str is a formatting string, pass the values in this
**query_options -- any query options can be passed in by using key=val syntax |
378,298 | def _yield_week_day(self, enumeration=False):
if enumeration:
for week in range(1, self.duration + 1):
for day_index, day in enumerate(self.days):
yield (week, day_index, day)
else:
for week i... | A helper function to reduce the number of nested loops.
Parameters
----------
enumeration
Whether or not to wrap the days in enumerate().
Yields
-------
tuple
A tuple with (week, day_index, day) or (week, day),
... |
378,299 | def Similarity(self, value=None):
if value is None:
value = 0.0
return Similarity(value, threshold=self.threshold) | Constructor for new default Similarities. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.