Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
342,000 | def exit():
exit_msg = None
try:
loop = asyncio.get_event_loop()
loop.stop()
except Exception as e:
logging.error(,
str(e)) | shuts down user interface without cleaning up.
Use a :class:`alot.commands.globals.ExitCommand` for a clean shutdown. |
342,001 | def build_rdn(self):
bits = []
for field in self._meta.fields:
if field.db_column and field.primary_key:
bits.append("%s=%s" % (field.db_column,
getattr(self, field.name)))
if not len(bits):
raise Exception("... | Build the Relative Distinguished Name for this entry. |
342,002 | def update_todo_list(self, list_id, name, description, milestone_id=None,
private=None, tracked=None):
path = % list_id
req = ET.Element()
list_ = ET.SubElement()
ET.SubElement(list_, ).text = str(name)
ET.SubElement(list_, ).text = str(description)
if m... | With this call you can alter the metadata for a list. |
342,003 | def update_list(self, list_id, revision, title=None, public=None):
return lists_endpoint.update_list(self, list_id, revision, title=title, public=public) | Updates the list with the given ID to have the given title and public flag |
342,004 | def section_end_distance(section):
pts = section.points
return 0 if len(pts) < 2 else mm.point_dist(pts[-1], pts[0]) | End to end distance of a section
The end to end distance of a section is defined as
the euclidian distnce between its end points.
If the section contains less than 2 points, the value 0 is returned. |
342,005 | def get_option_parser():
import optparse
prs = optparse.OptionParser(
usage=(
"$0 pyrpo [-h] [-v] [-q] [-s .] "
"[-r <report>] [--thg]"))
prs.add_option(, ,
dest=,
action=,
default=[],
help=)
... | Build an ``optparse.OptionParser`` for pyrpo commandline use |
342,006 | def get_library_path_and_name_for_os_path(self, path):
library_path = None
library_name = None
library_root_key = self._get_library_root_key_for_os_path(path)
if library_root_key is not None:
library_root_path = self._library_root_paths[library_root_key]
... | Generate valid library_path and library_name
The method checks if the given os path is in the list of loaded library root paths and use respective
library root key/mounting point to concatenate the respective library_path and separate respective library_name.
:param str path: A library os pat... |
342,007 | def accumulate(self, buf):
bytes = array.array()
if isinstance(buf, array.array):
bytes.extend(buf)
else:
bytes.fromstring(buf)
accum = self.crc
for b in bytes:
tmp = b ^ (accum & 0xff)
tmp = (tmp ^ (tmp<<4)) & 0xFF
... | add in some more bytes |
342,008 | def reconstructed_data_vector_from_blurred_mapping_matrix_and_solution_vector(blurred_mapping_matrix, solution_vector):
reconstructed_data_vector = np.zeros(blurred_mapping_matrix.shape[0])
for i in range(blurred_mapping_matrix.shape[0]):
for j in range(solution_vector.shape[0]):
recons... | Compute the reconstructed hyper vector from the blurrred mapping matrix *f* and solution vector *S*.
Parameters
-----------
blurred_mapping_matrix : ndarray
The matrix representing the blurred mappings between sub-grid pixels and pixelization pixels. |
342,009 | def deltas(predicted_values, rewards, mask, gamma=0.99):
r
d = []
_, T = rewards.shape
for t in range(T):
d.append(rewards[:, t] + (gamma * predicted_values[:, t + 1]) -
predicted_values[:, t])
return np.array(d).T * mask | r"""Computes TD-residuals from V(s) and rewards.
Where a `delta`, i.e. a td-residual is defined as:
delta_{b,t} = r_{b,t} + \gamma * v_{b,t+1} - v_{b,t}.
Args:
predicted_values: ndarray of shape (B, T+1). NOTE: Expects axis 2 was
squeezed. These represent V(s_bt) for b < B and t < T+1
rewards: nd... |
342,010 | def _sparsify(X, remove_mean=False, modify_data=False, sparse_mode=, sparse_tol=0.0):
if sparse_mode.lower() == :
min_const_col_number = 0
elif sparse_mode.lower() == :
min_const_col_number = X.shape[1] + 1
else:
if remove_mean and not modify_data:
min_const_co... | Determines the sparsity of X and returns a selected sub-matrix
Only conducts sparsification if the number of constant columns is at least
max(a N - b, min_const_col_number),
Parameters
----------
X : ndarray
data matrix
remove_mean : bool
True: remove column mean from the data,... |
342,011 | def persist(self, context):
D = self._Document
document = context.session[self.name]
D.get_collection().replace_one(D.id == document.id, document, True) | Update or insert the session document into the configured collection |
342,012 | def eauth(self, adata, load):
for sub_auth in [adata]:
if load[] not in sub_auth:
continue
try:
name = self.loadauth.load_name(load)
if not ((name in sub_auth[load[]]) |
( in sub_auth[load[]])):
... | Determine if the given eauth is valid and yield the adata |
342,013 | def _get_crop_target(target_px:Union[int,TensorImageSize], mult:int=None)->Tuple[int,int]:
"Calc crop shape of `target_px` to nearest multiple of `mult`."
target_r,target_c = tis2hw(target_px)
return _round_multiple(target_r,mult),_round_multiple(target_c,mult) | Calc crop shape of `target_px` to nearest multiple of `mult`. |
342,014 | def imresize(x, size=None, interp=, mode=None):
if size is None:
size = [100, 100]
if x.shape[-1] == 1:
x = scipy.misc.imresize(x[:, :, 0], size, interp=interp, mode=mode)
return x[:, :, np.newaxis]
else:
return scipy.misc.imresize(x, size, interp=inte... | Resize an image by given output size and method.
Warning, this function will rescale the value to [0, 255].
Parameters
-----------
x : numpy.array
An image with dimension of [row, col, channel] (default).
size : list of 2 int or None
For height and width.
interp : str
I... |
342,015 | def has_extana(self, cached=True):
if cached and self.hardware != -1:
return True if (self.hardware & EXT_HW_EXTANA) else False
result = self._check_hardware()
return True if (result & EXT_HW_EXTANA) != 0 else False | Can be used to check if an SK8-ExtAna device is currently connected.
NOTE: do not attempt to call while data streaming is active!
Args:
cached (bool): if True, use the cached value of the connected hardware
state rather than querying the device. Set to False to force a q... |
342,016 | def consistency_check(text, word_pairs, err, msg, offset=0):
errors = []
msg = " ".join(msg.split())
for w in word_pairs:
matches = [
[m for m in re.finditer(w[0], text)],
[m for m in re.finditer(w[1], text)]
]
if len(matches[0]) > 0 and len(matches[1]... | Build a consistency checker for the given word_pairs. |
342,017 | def download_as_obj(
base_url=d1_common.const.URL_DATAONE_ROOT,
timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT,
):
return decode_der(download_as_der(base_url, timeout_sec)) | Download public certificate from a TLS/SSL web server as Certificate object.
Also see download_as_der().
Args:
base_url : str
A full URL to a DataONE service endpoint or a server hostname
timeout_sec : int or float
Timeout for the SSL socket operations
Returns:
c... |
342,018 | def token_cache_pkgs(source=None, release=None):
packages = []
if enable_memcache(source=source, release=release):
packages.extend([, ])
return packages | Determine additional packages needed for token caching
@param source: source string for charm
@param release: release of OpenStack currently deployed
@returns List of package to enable token caching |
342,019 | def send_data(self, data, delay=COMMAND_DELAY):
time_since_last_send = time.time() - self._last_send
delay = max(0, delay - time_since_last_send)
time.sleep(delay)
for item in data:
data = bytes.fromhex(str(item.zfill(2)))
try:
self.so... | Send data to connected gateway |
342,020 | def get(self, li) :
i = li*4
self.__splitEntry(i)
return self.data[i] | returns the ith entry |
342,021 | def scope_deletion(sender, instance, **kwargs):
is_resource = isinstance(instance, structure_models.ResourceMixin)
if is_resource and getattr(instance, , False):
_resource_unlink(resource=instance)
elif is_resource and not getattr(instance, , False):
_resource_deletion(resource=instanc... | Run different actions on price estimate scope deletion.
If scope is a customer - delete all customer estimates and their children.
If scope is a deleted resource - redefine consumption details, recalculate
ancestors estimates and update estimate details.
... |
342,022 | def get_vnetwork_vswitches_input_name(self, **kwargs):
config = ET.Element("config")
get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
config = get_vnetwork_vswitches
input = ET.SubElement(get_vnetwork_vswitches, "input")
name = ET.SubElement(input, "name")
... | Auto Generated Code |
342,023 | def handle_ajax_request(self):
func_arg = self.traverse_subpath[0]
func_name = "ajax_{}".format(func_arg)
func = getattr(self, func_name, None)
if func is None:
return self.fail("Invalid function", status=400)
args = self.traverse... | Handle requests ajax routes |
342,024 | def move_roles(self, roles):
return move_roles(self._get_resource_root(), self.serviceRef.serviceName,
self.name, roles, self.serviceRef.clusterName) | Moves roles to this role config group.
The roles can be moved from any role config group belonging
to the same service. The role type of the destination group
must match the role type of the roles.
@param roles: The names of the roles to move.
@return: List of roles which have been moved successfu... |
342,025 | def clear_symbols(self, index):
try:
del self.table[index:]
except Exception:
self.error()
self.table_len = len(self.table) | Clears all symbols begining with the index to the end of table |
342,026 | def clan_badge_url(self):
if self.clan_tag is None:
return None
url = self.raw_data.get().get().get()
if not url:
return None
return "http://api.cr-api.com" + url | Returns clan badge url |
342,027 | def get_course_video_ids_with_youtube_profile(course_ids=None, offset=None, limit=None):
course_videos = (CourseVideo.objects.select_related()
.prefetch_related(, )
.filter(video__encoded_videos__profile__profile_name=)
.order_by()
... | Returns a list that contains all the course ids and video ids with the youtube profile
Args:
course_ids (list): valid course ids
limit (int): batch records limit
offset (int): an offset for selecting a batch
Returns:
(list): Tuples of course_id, edx_video_id and youtube vide... |
342,028 | def discard(self, element):
_check_element(element)
self._require_context()
self._removes.add(element) | Removes an element from the set.
.. note: You may remove elements from the set that are not
present, but a context from the server is required.
:param element: the element to remove
:type element: str |
342,029 | def _read_result(self, num_retries):
for i in range(num_retries):
self._assert_alive()
try:
return self._result_channel.get()
except IOError as ex:
if ex.errno == 4:
| Read an object from a channel, possibly retrying if the attempt
is interrupted by a signal from the operating system. |
342,030 | def add_acquisition_source(
self,
method,
date=None,
submission_number=None,
internal_uid=None,
email=None,
orcid=None,
source=None,
datetime=None,
):
if date is not None:
if datetime is not None:
ra... | Add acquisition source.
:type submission_number: integer
:type email: integer
:type source: string
:param date: UTC date in isoformat
.. deprecated:: 30.1.0
Use ``datetime`` instead.
:type date: string
:param method: meth... |
342,031 | def for_stmt(self, for_loc, target, in_loc, iter, for_colon_loc, body, else_opt):
stmt = ast.For(target=self._assignable(target), iter=iter, body=body, orelse=[],
keyword_loc=for_loc, in_loc=in_loc, for_colon_loc=for_colon_loc,
else_loc=None, else_colon_loc... | for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] |
342,032 | def load(self, _from):
def load_rec(inode, config):
for k in config:
if isinstance(config[k], dict) and \
k not in [, ]:
if k in inode:
load_rec(inode[k], config[k])
else:
... | Load the configuration dictionary from file. |
342,033 | def K(self, X, X2=None):
r = self._scaled_dist(X, X2)
return self.K_of_r(r) | Kernel function applied on inputs X and X2.
In the stationary case there is an inner function depending on the
distances from X to X2, called r.
K(X, X2) = K_of_r((X-X2)**2) |
342,034 | def json_loads(payload):
"Log the payload that cannot be parsed"
try:
return json.loads(payload)
except ValueError as e:
log.error("unable to json.loads(" + payload + ")")
raise e | Log the payload that cannot be parsed |
342,035 | def load_from_file(self, fp, sep=):
n = 0
body =
l = fp.readline()
while l:
if l == sep:
m = Message(self, body)
self.write(m)
n += 1
print % n
body =
else:
... | Utility function to load messages from a file-like object to a queue |
342,036 | def _read_message(self):
job = gevent.spawn(super(GConnection, self)._read_message)
job.join() | 必须启动新的greenlet,否则会有内存泄漏 |
342,037 | def download(model=None, direct=False, *pip_args):
if model is None:
model = about.__default_corpus__
if direct:
dl = download_model(.format(m=model), pip_args)
else:
shortcuts = get_json(about.__shortcuts__, "available shortcuts")
model_name = shortcuts.get(model, mode... | Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version. |
342,038 | def validate_on_submit(self):
valid = FlaskWtf.validate_on_submit(self)
if not self._schema or not self.is_submitted():
return valid
data = dict()
for field in self._fields:
data[field] = self._fields[field].data
res... | Extend validate on submit to allow validation with schema |
342,039 | def get_next_page(self):
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(
Album(
_extract(node, "artist"),
_extract(node, "name"),
... | Returns the next page of results as a sequence of Album objects. |
342,040 | def add_interface_router(self, router, subnet):
router_id = self._find_router_id(router)
subnet_id = self._find_subnet_id(subnet)
return self.network_conn.add_interface_router(
router=router_id, body={: subnet_id}) | Adds an internal network interface to the specified router |
342,041 | def get_request(self, deflate=True):
if deflate:
request = OneLogin_Saml2_Utils.deflate_and_base64_encode(self.__logout_request)
else:
request = b64encode(self.__logout_request)
return request | Returns the Logout Request deflated, base64encoded
:param deflate: It makes the deflate process optional
:type: bool
:return: Logout Request maybe deflated and base64 encoded
:rtype: str object |
342,042 | def setEncoder(self, encoder):
if not encoder:
self._encoder = json.JSONEncoder()
else:
self._encoder = encoder
self._encode = self._encoder.encode | Sets the client's encoder
``encoder`` should be an instance of a ``json.JSONEncoder`` class |
342,043 | def serialize_list(self, data):
if data is None:
return
prepped_data = data.value
else:
prepped_data = [self.prepare(item) for item in data]
final_data = self.wrap_list_response(prepped_data)
return self.serializer.seriali... | Given a collection of data (``objects`` or ``dicts``), serializes them.
:param data: The collection of items to serialize
:type data: list or iterable
:returns: The serialized body
:rtype: string |
342,044 | def _check_missing_slots(ob):
missing_slots = tuple(
filter(lambda s: not hasattr(ob, s), ob.__slots__),
)
if missing_slots:
raise TypeError(
.format(
missing_slots,
),
) | Check that all slots have been initialized when a custom __init__ method
is provided.
Parameters
----------
ob : immutable
The instance that was just initialized.
Raises
------
TypeError
Raised when the instance has not set values that are named in the
__slots__. |
342,045 | def get_box_score(game_id):
year, month, day = get_date_from_game_id(game_id)
try:
return urlopen(GAME_URL.format(year, month, day, game_id,
))
except HTTPError:
raise ValueError() | Return the box score file of a game with matching id. |
342,046 | def list_build_configurations(page_size=200, page_index=0, sort="", q=""):
data = list_build_configurations_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | List all BuildConfigurations |
342,047 | def Lombardi_Pedrocchi(m, x, rhol, rhog, sigma, D, L=1):
r
voidage_h = homogeneous(x, rhol, rhog)
rho_h = rhol*(1-voidage_h) + rhog*voidage_h
G_tp = m/(pi/4*D**2)
return 0.83*G_tp**1.4*sigma**0.4*L/(D**1.2*rho_h**0.866) | r'''Calculates two-phase pressure drop with the Lombardi-Pedrocchi (1972)
correlation from [1]_ as shown in [2]_ and [3]_.
.. math::
\Delta P_{tp} = \frac{0.83 G_{tp}^{1.4} \sigma^{0.4} L}{D^{1.2}
\rho_{h}^{0.866}}
Parameters
----------
m : float
Mass flow rate of fluid, [k... |
342,048 | def hasSystemPermission(self, login, user, perm):
self.send_hasSystemPermission(login, user, perm)
return self.recv_hasSystemPermission() | Parameters:
- login
- user
- perm |
342,049 | def generate_project_name():
adjectives = [
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
, , , , , , , ,
... | Generates a random project name. |
342,050 | def get(self):
tracking_settings = {}
if self.click_tracking is not None:
tracking_settings["click_tracking"] = self.click_tracking.get()
if self.open_tracking is not None:
tracking_settings["open_tracking"] = self.open_tracking.get()
if self.subscription... | Get a JSON-ready representation of this TrackingSettings.
:returns: This TrackingSettings, ready for use in a request body.
:rtype: dict |
342,051 | def getSimulations(self, times, **kwargs):
for t in times:
yield self.getSimulation(t, **kwargs) | A generator to quickly access many simulations.
The arguments are the same as for `getSimulation`. |
342,052 | def users_sentiments_single_most_frequent(
self,
usernames = None,
):
users_sentiments_single_most_frequent = dict()
if usernames is None:
usernames = self.usernames()
try:
for username in usernames:
sentiment = self.user_s... | This function returns the single most frequent calculated sentiment
expressed by all stored users or by a list of specified users as a
dictionary. |
342,053 | def p_case(self,t):
if len(t)==4: t[0] = CaseX(t[2],None)
elif len(t)==6: t[0] = CaseX(t[2],t[4])
else: raise NotImplementedError(,len(t)) | expression : kw_case whenlist kw_else expression kw_end
| kw_case whenlist kw_end |
342,054 | def error(self, msg):
self._execActions(, msg)
msg = self._execFilters(, msg)
self._processMsg(, msg)
self._sendMsg(, msg) | Log Error Messages |
342,055 | def docstr(self, prefix=, include_label=True):
return .join([x.docstr(prefix, include_label) for x in self]) | Returns the ``docstr`` of each parameter joined together. |
342,056 | def send_email_validation(request):
token = EmailConfirmationSerializer().create_token(
request.id, dict(email=request.sender_email)
)
pid, record = get_record(request.recid)
_send_notification(
request.sender_email,
_("Access request verification"),
"zenodo_accessr... | Receiver for request-created signal to send email notification. |
342,057 | def get_objective_query_session(self, proxy):
if not self.supports_objective_query():
raise Unimplemented()
try:
from . import sessions
except ImportError:
raise OperationFailed()
proxy = self._convert_proxy(proxy)
try:
ses... | Gets the ``OsidSession`` associated with the objective query service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ObjectiveQuerySession``
:rtype: ``osid.learning.ObjectiveQuerySession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
:raise: `... |
342,058 | def inspect_repo(self, repo_name):
req = proto.InspectRepoRequest(repo=proto.Repo(name=repo_name))
res = self.stub.InspectRepo(req, metadata=self.metadata)
return res | Returns info about a specific Repo.
Params:
* repo_name: Name of the repo. |
342,059 | def __fix_args(kwargs):
kwargs.setdefault(, kwargs.get())
kwargs.setdefault(, kwargs.get())
kwargs.setdefault(, kwargs.get())
kwargs.setdefault(, kwargs.get())
kwargs.setdefault(, kwargs.get())
kwargs.setdefault(, kwargs.get())
kwargs.setdefault(, kwargs.get())
kwargs.setdefault(, k... | Set all named arguments shortcuts and flags. |
342,060 | def monthly(self):
if self._monthly is None:
self._monthly = MonthlyList(self._version, account_sid=self._solution[], )
return self._monthly | Access the monthly
:returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList
:rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList |
342,061 | def iterator(self, includeKey=True, includeValue=True, prefix=None):
if not (includeKey or includeValue):
raise ValueError("At least one of includeKey or includeValue "
"should be true")
lines = self._lines()
if includeKey and includeValue:
... | Store iterator
:return: Iterator for data in all chunks |
342,062 | def in_placement_grid(self, pos: Union[Point2, Point3, Unit]) -> bool:
assert isinstance(pos, (Point2, Point3, Unit))
pos = pos.position.to2.rounded
return self._game_info.placement_grid[pos] != 0 | Returns True if you can place something at a position. Remember, buildings usually use 2x2, 3x3 or 5x5 of these grid points.
Caution: some x and y offset might be required, see ramp code:
https://github.com/Dentosal/python-sc2/blob/master/sc2/game_info.py#L17-L18 |
342,063 | def parse_cookies_str(cookies):
cookie_dict = {}
for record in cookies.split(";"):
key, value = record.strip().split("=", 1)
cookie_dict[key] = value
return cookie_dict | parse cookies str to dict
:param cookies: cookies str
:type cookies: str
:return: cookie dict
:rtype: dict |
342,064 | def log(x, base=None):
if base == 10:
return np.log10(x)
elif base == 2:
return np.log2(x)
elif base is None or base == np.e:
return np.log(x)
else:
return np.log(x)/np.log(base) | Calculate the log
Parameters
----------
x : float or array_like
Input values
base : int or float (Default: None)
Base of the log. If `None`, the natural logarithm
is computed (`base=np.e`).
Returns
-------
out : float or ndarray
Calculated result |
342,065 | def read_filtering_config (self):
section = "filtering"
if self.has_option(section, "ignorewarnings"):
self.config[] = [f.strip().lower() for f in \
self.get(section, ).split()]
if self.has_option(section, "ignore"):
for line in read_multiline(se... | Read configuration options in section "filtering". |
342,066 | def get_or_create(cls, mp, part_number):
obj = cls.get_or_none(mp, part_number)
if obj:
return obj
return cls.create(mp, part_number) | Get or create a part. |
342,067 | def lognoiserate(self, trigs):
alphai, ratei, thresh = self.find_fits(trigs)
newsnr = self.get_newsnr(trigs)
lognoisel = - alphai * (newsnr - thresh) + numpy.log(alphai) + \
numpy.log(ratei)
return numpy.array(lognoisel, ... | Calculate the log noise rate density over single-ifo newsnr
Read in single trigger information, make the newsnr statistic
and rescale by the fitted coefficients alpha and rate |
342,068 | def register_views(*args):
config = args[0]
settings = config.get_settings()
pages_config = settings[CONFIG_MODELS]
resources = resources_of_config(pages_config)
for resource in resources:
if hasattr(resource, )\
and not hasattr(resource, ):
continue
... | Registration view for each resource from config. |
342,069 | def run_webserver():
host = "0.0.0.0"
port = CONFIG.getint(, )
print "Serving on ", "http://" + host + ":" + str(port)
app.config[] = True
app.jinja_env.auto_reload = True
app.run(debug=True, host=host, port=port) | Run web server |
342,070 | def setKUS(self, K, U, S):
return _core.CLMM_setKUS(self, K, U, S) | setKUS(CLMM self, MatrixXd const & K, MatrixXd const & U, VectorXd const & S)
Parameters
----------
K: MatrixXd const &
U: MatrixXd const &
S: VectorXd const & |
342,071 | def get_by_signature(user_id, app_id):
try:
return TabEvaluation.get(
(TabEvaluation.user_id == user_id) & (TabEvaluation.post_id == app_id)
)
except:
return None | get by user ID, and app ID. |
342,072 | def return_values(self):
from slither.core.cfg.node import NodeType
from slither.slithir.operations import Return
from slither.slithir.variables import Constant
if self._return_values is None:
return_values = list()
returns = [n for n in self.nodes if n.... | list(Return Values): List of the return values |
342,073 | def FromNanoseconds(self, nanos):
self.seconds = nanos // _NANOS_PER_SECOND
self.nanos = nanos % _NANOS_PER_SECOND | Converts nanoseconds since epoch to Timestamp. |
342,074 | def propagate_lithology_cols(self):
cols = [, , ]
self.propagate_cols(cols, , )
cols = [, , ]
self.propagate_cols(cols, , )
if not in self.tables:
return
for col in cols:
i... | Propagate any data from lithologies, geologic_types, or geologic_classes
from the sites table to the samples and specimens table.
In the samples/specimens tables, null or "Not Specified" values
will be overwritten based on the data from their parent site. |
342,075 | def print(self, msg, *args, **kwargs):
if self.verbosity >= 1:
print(msg, *args, **kwargs) | Print formatted msg if verbosity set at 1 or above. |
342,076 | def from_dict(ddict):
d = Definition(ddict[], ddict[], ddict[],
ddict[], ddict[],
ddict[], ddict[])
for child_dict in ddict[]:
d.children.append(Definition.from_dict(child_dict))
return d | Deserializes a definition from a simple dict. |
342,077 | def _fix_tbit_dtype(self, array, colnums):
descr = array.dtype.descr
for i, colnum in enumerate(colnums):
npy_type, isvar, istbit = self._get_tbl_numpy_dtype(colnum)
if (istbit):
coldescr = list(descr[i])
coldescr[1] =
des... | If necessary, patch up the TBIT to convert to bool array
parameters
----------
array: record array
colnums: column numbers for lookup |
342,078 | def eclean_dist(destructive=False, package_names=False, size_limit=0,
time_limit=0, fetch_restricted=False,
exclude_file=):
t delete distfiles bigger than <size>.
<size> is a size specification: "10M" is "ten megabytes",
"200K" is "two hundreds kilobytes", etc. Units ... | Clean obsolete portage sources
destructive
Only keep minimum for reinstallation
package_names
Protect all versions of installed packages. Only meaningful if used
with destructive=True
size_limit <size>
Don't delete distfiles bigger than <size>.
<size> is a size spe... |
342,079 | def start(self):
if self.__framework._state not in (Bundle.STARTING, Bundle.ACTIVE):
raise BundleException(
"Framework must be started before its bundles"
)
with self._lock:
if self._state in (Bundle.ACTIVE, Bundle.STARTING):
... | Starts the bundle. Does nothing if the bundle is already starting or
active.
:raise BundleException: The framework is not yet started or the bundle
activator failed. |
342,080 | def rdd(self):
if self._lazy_rdd is None:
jrdd = self._jdf.javaToPython()
self._lazy_rdd = RDD(jrdd, self.sql_ctx._sc, BatchedSerializer(PickleSerializer()))
return self._lazy_rdd | Returns the content as an :class:`pyspark.RDD` of :class:`Row`. |
342,081 | def _create_show_definitions_action(self):
icon = resources_path(, , )
self.action_show_definitions = QAction(
QIcon(icon),
self.tr(),
self.iface.mainWindow())
self.action_show_definitions.setStatusTip(self.tr(
))
self.action_show_... | Create action for showing definitions / help. |
342,082 | def luhn(candidate):
if not isinstance(candidate, six.string_types):
candidate = str(candidate)
try:
evens = sum(int(c) for c in candidate[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(c)] for c in candidate[-2::-2])
return ((evens + odds) % 10 == 0)
except ValueError:
... | Checks a candidate number for validity according to the Luhn
algorithm (used in validation of, for example, credit cards).
Both numeric and string candidates are accepted. |
342,083 | def _sighash_final_hashing(self, copy_tx, sighash_type):
sighash = z.ZcashByteData()
sighash += copy_tx.to_bytes()
sighash += utils.i2le_padded(sighash_type, 4)
return utils.hash256(sighash.to_bytes()) | SproutTx, int -> bytes
Returns the hash that should be signed
https://en.bitcoin.it/wiki/OP_CHECKSIG#Procedure_for_Hashtype_SIGHASH_ANYONECANPAY |
342,084 | def parse_from_args(synonyms):
syns_str = .join(synonyms)
syns_str = syns_str.replace(, )
syn_set = SynonymSet()
inside_set = False
current_syn =
current_syn_set = set()
for char in syns_str:
if char == :
inside_set = True
current_syn_set =... | Parse an array of string from argparser
to SynonymSet |
342,085 | def enforce_policy(rule):
def wrapper(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
if enforcer.enforce(rule, {}, g.cred):
return func(*args, **kwargs)
return wrapped
return wrapper | Enforce a policy to a API. |
342,086 | def rollout(self, batch_info: BatchInfo, model: Model, number_of_steps: int) -> Rollout:
accumulator = TensorAccumulator()
episode_information = []
if self.hidden_state is None and model.is_recurrent:
self.hidden_state = model.zero_state(self.last_observation.size(0)).to(... | Calculate env rollout |
342,087 | def start_tree(self, tree, name):
super(FixDivisionSafe, self).start_tree(tree, name)
self.skip = "division" in tree.future_features | Skip this fixer if "__future__.division" is already imported. |
342,088 | def output(self, name: str, value: Any):
self.outputs[name] = value | Export a stack output with a given name and value. |
342,089 | def select(self, column, agg=None, _as=None, distinct=False):
if agg and not _as:
raise ValueError("Aggregate colunns require `_as` to be specified")
if column is False:
self._selects = {}
else:
self._selects.setdefault((_as or column), (column, agg, ... | What columnns to select in query.
:column should be a column name or equation to produce column **not** aggregated
:agg should be a valid aggregate method used to producte the figure
:_as should be a string used to represent the column. Required when agg present |
342,090 | def render_name(self, name, image_tag, platform):
if self.scratch or self.isolated:
name = image_tag
if platform:
platform_suffix = .format(platform)
if name.endswith(platform_suffix):
name = name[:-len(platform_s... | Sets the Build/BuildConfig object name |
342,091 | def scatter(x_fn, y_fn, *, options={}, **interact_params):
params = {
: [{
: _array_or_placeholder(x_fn),
: _array_or_placeholder(y_fn),
: _get_option(),
}]
}
fig = options.get(, False) or _create_fig(options=options)
[scat] = _create_marks(
... | Generates an interactive scatter chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with ... |
342,092 | def set_created_date(self, doc, created):
if not self.created_date_set:
self.created_date_set = True
date = utils.datetime_from_iso_format(created)
if date is not None:
doc.creation_info.created = date
return True
else:
... | Sets created date, Raises CardinalityError if
created date already set.
Raises SPDXValueError if created is not a date. |
342,093 | def set_ioloop(self, ioloop=None):
ioloop = ioloop or tornado.ioloop.IOLoop.current()
self.ioloop = ioloop
for res in dict.values(self.children):
res.set_ioloop(ioloop) | Set the tornado ioloop to use
Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if
ioloop=None. Must be called before start() |
342,094 | def get_information(self, about=):
cmd = [
(, ),
(, str(about))
]
self.send(cmd)
return self.wait_for(*cmd[1]) | Get information about given keyword. Defaults to stage. |
342,095 | def fetch_metric(self, cursor, results, tags):
t query
all of them together without having to perform some matching based on
the name afterwards so instead we query instance by instance.
We cache the list of instance so that we don
if self.sql_name not in results:
sel... | Because we need to query the metrics by matching pairs, we can't query
all of them together without having to perform some matching based on
the name afterwards so instead we query instance by instance.
We cache the list of instance so that we don't have to look it up every time |
342,096 | def p_expression_unot(self, p):
p[0] = Unot(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : NOT expression %prec UNOT |
342,097 | def convert_message_to_string(self, message):
final_message =
for submessage in message:
final_message += .format(submessage=submessage)
return final_message | Convert message from list to string for GitHub API. |
342,098 | def rename(self, **kwargs):
for old, new in kwargs.iteritems():
if old in self.groups:
self.groups[new] = self.groups[old]
del self.groups[old] | Rename series in the group. |
342,099 | def get_word_under_cursor_legacy(self):
cursor = self.textCursor()
cursor.select(QTextCursor.WordUnderCursor)
return cursor.selectedText() | Returns the document word under cursor ( Using Qt legacy "QTextCursor.WordUnderCursor" ).
:return: Word under cursor.
:rtype: QString |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.