Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
1,600 | def datetime_to_timestamp(dt):
epoch = datetime.utcfromtimestamp(0).replace(tzinfo=UTC)
return (dt - epoch).total_seconds() | Convert timezone-aware `datetime` to POSIX timestamp and
return seconds since UNIX epoch.
Note: similar to `datetime.timestamp()` in Python 3.3+. |
1,601 | def intersects(self, geometry, crs=None):
if crs:
geometry = dict(geometry)
geometry[] = {: , : {: crs}}
return Filter({self._name: {: {: geometry}}}) | Select geometries that intersect with a GeoJSON geometry.
Geospatial operator: {$geoIntersects: {...}}
Documentation: https://docs.mongodb.com/manual/reference/operator/query/geoIntersects/#op._S_geoIntersects
{
$geoIntersects: { $geometry: <geometry; a GeoJSON object> }
} |
1,602 | def one_of(inners, arg):
for inner in inners:
with suppress(com.IbisTypeError, ValueError):
return inner(arg)
rules_formatted = .join(map(repr, inners))
raise com.IbisTypeError(
.format(rules_formatted)
) | At least one of the inner validators must pass |
1,603 | def _param_grad_helper(self,dL_dK,X,X2,target):
AX = np.dot(X,self.transform)
if X2 is None:
X2 = X
ZX2 = AX
else:
AX2 = np.dot(X2, self.transform)
self.k._param_grad_helper(dL_dK,X,X2,target)
self.k._param_grad_helper(dL_dK,AX,X2,targ... | derivative of the covariance matrix with respect to the parameters. |
1,604 | def clean_up_dangling_images(self):
cargoes = Image.all(client=self._client_session, filters={: True})
for id, cargo in six.iteritems(cargoes):
logger.info("Removing dangling image: {0}".format(id))
cargo.delete() | Clean up all dangling images. |
1,605 | def addBiosample(self):
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
biosample = bio_metadata.Biosample(
dataset, self._args.biosampleName)
biosample.populateFromJson(self._args.biosample)
self._updateRepo(self._repo.insertBi... | Adds a new biosample into this repo |
1,606 | def dict_match(d, key, default=None):
if key in d and "[" not in key:
return d[key]
else:
for pattern, value in iteritems(d):
if fnmatchcase(key, pattern):
return value
return default | Like __getitem__ but works as if the keys() are all filename patterns.
Returns the value of any dict key that matches the passed key.
Args:
d (dict): A dict with filename patterns as keys
key (str): A key potentially matching any of the keys
default (object): The object to return if no ... |
1,607 | def commented_out_code_lines(source):
line_numbers = []
try:
for t in generate_tokens(source):
token_type = t[0]
token_string = t[1]
start_row = t[2][0]
line = t[4]
if not line.lstrip().startswith():
continue
... | Return line numbers of comments that are likely code.
Commented-out code is bad practice, but modifying it just adds even
more clutter. |
1,608 | def _items_to_rela_paths(self, items):
paths = []
for item in items:
if isinstance(item, (BaseIndexEntry, (Blob, Submodule))):
paths.append(self._to_relative_path(item.path))
elif isinstance(item, string_types):
paths.append(self._to_relat... | Returns a list of repo-relative paths from the given items which
may be absolute or relative paths, entries or blobs |
1,609 | def autoscan():
for port in serial.tools.list_ports.comports():
if is_micropython_usb_device(port):
connect_serial(port[0]) | autoscan will check all of the serial ports to see if they have
a matching VID:PID for a MicroPython board. |
1,610 | def handle(cls, value, provider=None, **kwargs):
if provider is None:
raise ValueError()
d = deconstruct(value)
stack_fqn = d.stack_name
output = provider.get_output(stack_fqn, d.output_name)
return output | Fetch an output from the designated stack.
Args:
value (str): string with the following format:
<stack_name>::<output_name>, ie. some-stack::SomeOutput
provider (:class:`stacker.provider.base.BaseProvider`): subclass of
the base provider
Returns:... |
1,611 | def pipe(self, target):
if callable(target):
sender, recver = self.hub.pipe()
self.downstream = sender
sender.upstream = self
@self.hub.spawn
def _():
try:
target(sel... | Pipes this Recver to *target*. *target* can either be `Sender`_ (or
`Pair`_) or a callable.
If *target* is a Sender, the two pairs are rewired so that sending on
this Recver's Sender will now be directed to the target's Recver::
sender1, recver1 = h.pipe()
sender2, recv... |
1,612 | def leaky_twice_relu6(x, alpha_low=0.2, alpha_high=0.2, name="leaky_relu6"):
if not isinstance(alpha_high, tf.Tensor) and not (0 < alpha_high <= 1):
raise ValueError("`alpha_high` value must be in [0, 1]`")
if not isinstance(alpha_low, tf.Tensor) and not (0 < alpha_low <= 1):
raise ValueEr... | :func:`leaky_twice_relu6` can be used through its shortcut: :func:`:func:`tl.act.ltrelu6`.
This activation function is a modified version :func:`leaky_relu` introduced by the following paper:
`Rectifier Nonlinearities Improve Neural Network Acoustic Models [A. L. Maas et al., 2013] <https://ai.stanford.edu/~am... |
1,613 | def approx_min_num_components(nodes, negative_edges):
import utool as ut
num = 0
g_neg = nx.Graph()
g_neg.add_nodes_from(nodes)
g_neg.add_edges_from(negative_edges)
if nx.__version__.startswith():
deg0_nodes = [n for n, d in g_neg.degree() if d == 0]
else:
deg0_nod... | Find approximate minimum number of connected components possible
Each edge represents that two nodes must be separated
This code doesn't solve the problem. The problem is NP-complete and
reduces to minimum clique cover (MCC). This is only an approximate
solution. Not sure what the approximation ratio i... |
1,614 | def _sync_last_sale_prices(self, dt=None):
if dt is None:
dt = self.datetime
if dt != self._last_sync_time:
self.metrics_tracker.sync_last_sale_prices(
dt,
self.data_portal,
)
self._last_sync_time = dt | Sync the last sale prices on the metrics tracker to a given
datetime.
Parameters
----------
dt : datetime
The time to sync the prices to.
Notes
-----
This call is cached by the datetime. Repeated calls in the same bar
are cheap. |
1,615 | def translate_features_to_letter_annotations(protein, more_sites=None):
from ssbio.databases.uniprot import longname_sites
from collections import defaultdict
sites = longname_sites
sites.append()
sites.append()
sites.append()
sites.append("transmembra... | Store select uniprot features (sites) as letter annotations with the key as the
type of site and the values as a list of booleans |
1,616 | def check_file_encoding(self, input_file_path):
self.log([u"Checking encoding of file ", input_file_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_file_encoding"):
return self.result
if not gf.file_can_be_read(input_file_path):
... | Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult` |
1,617 | def abs(cls, x: ) -> :
return cls._unary_op(x, tf.abs, tf.float32) | Returns a TensorFluent for the abs function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the abs function. |
1,618 | def clear(self):
self.tags = []
self.chars = {}
self.attribs = {}
self.handler = None
self.piece = PieceTree.PieceTree()
self.isDynamic = False
self.data["note"] = None
self.data["direct... | Method which resets any variables held by this class, so that the parser can be used again
:return: Nothing |
1,619 | def instantiate_by_name(self, object_name):
if object_name not in self.instances:
instance = self.instantiate_from_data(self.environment[object_name])
self.instances[object_name] = instance
return instance
else:
return self.instances[object_name] | Instantiate object from the environment, possibly giving some extra arguments |
1,620 | def serialize(self, pid, record, links_factory=None):
return self.schema.tostring(
self.transform_record(pid, record, links_factory)) | Serialize a single record and persistent identifier.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links. |
1,621 | def total_surface_energy(self):
tot_surface_energy = 0
for hkl in self.miller_energy_dict.keys():
tot_surface_energy += self.miller_energy_dict[hkl] * \
self.miller_area_dict[hkl]
return tot_surface_energy | Total surface energy of the Wulff shape.
Returns:
(float) sum(surface_energy_hkl * area_hkl) |
1,622 | def inflate_bbox(self):
left, top, right, bottom = self.bounding_box
self.bounding_box = (
left & 0xFFFC,
top,
right if right % 4 == 0 else (right & 0xFFFC) + 0x04,
bottom)
return self.bounding_box | Realign the left and right edges of the bounding box such that they are
inflated to align modulo 4.
This method is optional, and used mainly to accommodate devices with
COM/SEG GDDRAM structures that store pixels in 4-bit nibbles. |
1,623 | def reload(name=DEFAULT, all_names=False):
for namespace in get_namespaces_from_names(name, all_names):
for value_proxy in namespace.get_value_proxies():
value_proxy.reset() | Reload one or all :class:`ConfigNamespace`. Reload clears the cache of
:mod:`staticconf.schema` and :mod:`staticconf.getters`, allowing them to
pickup the latest values in the namespace.
Defaults to reloading just the DEFAULT namespace.
:param name: the name of the :class:`ConfigNamespace` to reload
... |
1,624 | def tune(runner, kernel_options, device_options, tuning_options):
results = []
cache = {}
tuning_options["scaling"] = True
bounds, _, _ = get_bounds_x0_eps(tuning_options)
args = (kernel_options, tuning_options, runner, results, cache)
num_particles = 20
maxiter = 100
... | Find the best performing kernel configuration in the parameter space
:params runner: A runner from kernel_tuner.runners
:type runner: kernel_tuner.runner
:param kernel_options: A dictionary with all options for the kernel.
:type kernel_options: dict
:param device_options: A dictionary with all op... |
1,625 | def add_transcript(self, transcript):
logger.debug("Adding transcript {0} to variant {1}".format(
transcript, self[]))
self[].append(transcript) | Add the information transcript
This adds a transcript dict to variant['transcripts']
Args:
transcript (dict): A transcript dictionary |
1,626 | def stops(self):
serves = set()
for trip in self.trips():
for stop_time in trip.stop_times():
serves |= stop_time.stops()
return serves | Return stops served by this route. |
1,627 | def chunker(f, n):
f = iter(f)
x = []
while 1:
if len(x) < n:
try:
x.append(f.next())
except StopIteration:
if len(x) > 0:
yield tuple(x)
break
else:
yield tuple(x)
x = [] | Utility function to split iterable `f` into `n` chunks |
1,628 | async def write_register(self, address, value, skip_encode=False):
await self._request(, address, value, skip_encode=skip_encode) | Write a modbus register. |
1,629 | def getViews(self, path, year=None, month=None, day=None, hour=None):
if path is None:
raise TelegraphAPIException("Error while executing getViews: "
"PAGE_NOT_FOUND")
r = requests.post(BASE_URL + "getViews/" + path, data={
"... | Use this method to get the number of views for a Telegraph article.
:param path: Required. Path to the Telegraph page
(in the format Title-12-31, where 12 is the month and 31 the day the article was first published).
:type path: str
:param year: Required if month is passed.
... |
1,630 | def wait_until_element_visible(self, element, timeout=None):
return self._wait_until(self._expected_condition_find_element_visible, element, timeout) | Search element and wait until it is visible
:param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
:param timeout: max time to wait
:returns: the web element if it is visible
:rtype: selenium.webdriver.remote.webelement.WebElement or appium.w... |
1,631 | async def _into_id_set(client, chats):
if chats is None:
return None
if not utils.is_list_like(chats):
chats = (chats,)
result = set()
for chat in chats:
if isinstance(chat, int):
if chat < 0:
result.add(chat)
else:
... | Helper util to turn the input chat or chats into a set of IDs. |
1,632 | def guess_headers(self):
name = self.name.replace("*", "")
headers = []
if name in KNOWN_TYPES:
headers.append(KNOWN_TYPES[name])
elif name in STL:
headers.append(.format(name))
elif hasattr(ROOT, name) and name.startswith("T"):
header... | Attempt to guess what headers may be required in order to use this
type. Returns `guess_headers` of all children recursively.
* If the typename is in the :const:`KNOWN_TYPES` dictionary, use the
header specified there
* If it's an STL type, include <{type}>
* If it exists in... |
1,633 | def stream_sample(self, md5, kwargs=None):
max_rows = kwargs.get(, None) if kwargs else None
| Stream the sample by giving back a generator, typically used on 'logs'.
Args:
md5: the md5 of the sample
kwargs: a way of specifying subsets of samples (None for all)
max_rows: the maximum number of rows to return
Returns:
A gen... |
1,634 | def _encode_char(char, charmap, defaultchar):
if ord(char) < 128:
return ord(char)
if char in charmap:
return charmap[char]
return ord(defaultchar) | Encode a single character with the given encoding map
:param char: char to encode
:param charmap: dictionary for mapping characters in this code page |
1,635 | def get_printable(iterable):
if iterable:
return .join(i for i in iterable if i in string.printable)
return | Get printable characters from the specified string.
Note that str.isprintable() is not available in Python 2. |
1,636 | def _replace_bm(self):
self._block_matcher = cv2.StereoBM(preset=self._bm_preset,
ndisparities=self._search_range,
SADWindowSize=self._window_size) | Replace ``_block_matcher`` with current values. |
1,637 | def print_licences(params, metadata):
if hasattr(params, ):
if params.licenses:
_pp(metadata.licenses_desc())
sys.exit(0) | Print licenses.
:param argparse.Namespace params: parameter
:param bootstrap_py.classifier.Classifiers metadata: package metadata |
1,638 | def _RawGlobPathSpecWithNumericSchema(
file_system, parent_path_spec, segment_format, location, segment_number):
segment_files = []
while True:
segment_location = segment_format.format(location, segment_number)
segment_path_spec = path_spec_factory.Factory.NewPathSpec(
parent_path_spe... | Globs for path specifications according to a numeric naming schema.
Args:
file_system (FileSystem): file system.
parent_path_spec (PathSpec): parent path specification.
segment_format (str): naming schema of the segment file location.
location (str): the base segment file location string.
segment... |
1,639 | def socket_recv(self):
try:
data = self.sock.recv(2048)
except socket.error, ex:
print ("?? socket.recv() error from %s" %
(ex[0], ex[1], self.addrport()))
raise BogConnectionLost()
size = len(data)
if size == 0:
... | Called by TelnetServer when recv data is ready. |
1,640 | def get_hdrgos_g_usrgos(self, usrgos):
hdrgos_for_usrgos = set()
hdrgos_all = self.get_hdrgos()
usrgo2hdrgo = self.get_usrgo2hdrgo()
for usrgo in usrgos:
if usrgo in hdrgos_all:
hdrgos_for_usrgos.add(usrgo)
continue
hdrgo_c... | Return hdrgos which contain the usrgos. |
1,641 | def point_in_polygon(points, x, y):
odd = False
n = len(points)
for i in range(n):
j = i < n - 1 and i + 1 or 0
x0, y0 = points[i][0], points[i][1]
x1, y1 = points[j][0], points[j][1]
if (y0 < y and y1 >= y) or (y1 < y and y0 >= y):
if x0 + (y - y0) ... | Ray casting algorithm.
Determines how many times a horizontal ray starting from the point
intersects with the sides of the polygon.
If it is an even number of times, the point is outside, if odd, inside.
The algorithm does not always report correctly when the point is very close to t... |
1,642 | def get_supported_file_loaders_2(force=False):
if force or (2, 7) <= sys.version_info < (3, 4):
import imp
loaders = []
for suffix, mode, type in imp.get_suffixes():
if type == imp.PY_SOURCE:
loaders.append((SourceFileLoader2, [suffix]))
else... | Returns a list of file-based module loaders.
Each item is a tuple (loader, suffixes). |
1,643 | def get_service(self):
http_authorized = self._authorize()
return build(
, , http=http_authorized, cache_discovery=False) | Returns a BigQuery service object. |
1,644 | def pad(self, pad_length):
self.pianoroll = np.pad(
self.pianoroll, ((0, pad_length), (0, 0)), ) | Pad the pianoroll with zeros at the end along the time axis.
Parameters
----------
pad_length : int
The length to pad with zeros along the time axis. |
1,645 | def post_create_app(cls, app, **settings):
register_errorhandler = settings.pop(, True)
if register_errorhandler:
AppException.register_errorhandler(app)
return app | Register the errorhandler for the AppException to the passed in
App.
Args:
app (fleaker.base.BaseApplication): A Flask application that
extends the Fleaker Base Application, such that the hooks are
implemented.
Kwargs:
register_errorhandl... |
1,646 | def probe_plugins():
plugins = UwsgiRunner().get_plugins()
for plugin in sorted(plugins.generic):
click.secho(plugin)
click.secho()
for plugin in sorted(plugins.request):
click.secho(plugin) | Runs uWSGI to determine what plugins are available and prints them out.
Generic plugins come first then after blank line follow request plugins. |
1,647 | def service_upsert(path, service_name, definition):
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result[][]
if service_name in services:
msg = .format(service_name)
return __standardize_result(Fal... | Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to cr... |
1,648 | def LOO(self, kern, X, Y, likelihood, posterior, Y_metadata=None, K=None):
g = posterior.woodbury_vector
c = posterior.woodbury_inv
c_diag = np.diag(c)[:, None]
neg_log_marginal_LOO = 0.5*np.log(2*np.pi) - 0.5*np.log(c_diag) + 0.5*(g**2)/c_diag
return -... | Leave one out error as found in
"Bayesian leave-one-out cross-validation approximations for Gaussian latent variable models"
Vehtari et al. 2014. |
1,649 | def new_driver(self, testname=None):
resuebrowser
channel = self.__get_channel()
driver = self.__get_driver_for_channel(channel)
if self.__config.get(WebDriverManager.REUSE_BROWSER, True):
if driver is None:
driver = self._webdriver_factory.create_... | Used at a start of a test to get a new instance of WebDriver. If the
'resuebrowser' setting is true, it will use a recycled WebDriver instance
with delete_all_cookies() called.
Kwargs:
testname (str) - Optional test name to pass to Selenium Grid. Helpful for
... |
1,650 | def images(self):
api_version = self._get_api_version()
if api_version == :
from .v2016_04_30_preview.operations import ImagesOperations as OperationClass
elif api_version == :
from .v2017_03_30.operations import ImagesOperations as OperationClass
elif ap... | Instance depends on the API version:
* 2016-04-30-preview: :class:`ImagesOperations<azure.mgmt.compute.v2016_04_30_preview.operations.ImagesOperations>`
* 2017-03-30: :class:`ImagesOperations<azure.mgmt.compute.v2017_03_30.operations.ImagesOperations>`
* 2017-12-01: :class:`ImagesOpera... |
1,651 | def get_default_config(self):
config = super(UsersCollector, self).get_default_config()
config.update({
: ,
: None,
})
return config | Returns the default collector settings |
1,652 | def get_metric_by_name(name: str) -> Callable[..., Any]:
if name not in _REGISTRY:
raise ConfigError(f)
return fn_from_str(_REGISTRY[name]) | Returns a metric callable with a corresponding name. |
1,653 | def name(self):
name = self._element.name_val
if name is None:
return None
return BabelFish.internal2ui(name) | The UI name of this style. |
1,654 | def _load_key(key_object):
if key_object.algorithm == :
curve_type, details = key_object.curve
if curve_type != :
raise AsymmetricKeyError()
if details not in set([, , ]):
raise AsymmetricKeyError(pretty_message(
))
elif key_obj... | Common code to load public and private keys into PublicKey and PrivateKey
objects
:param key_object:
An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo
object
:raises:
ValueError - when any of the parameters contain an invalid value
TypeError - when any of t... |
1,655 | def highshelf(self, gain=-20.0, frequency=3000, slope=0.5):
self.command.append()
self.command.append(gain)
self.command.append(frequency)
self.command.append(slope)
return self | highshelf takes 3 parameters: a signed number for gain or
attenuation in dB, filter frequency in Hz and slope (default=0.5).
Beware of clipping when using positive gain. |
1,656 | def is_condition_met(self, hand, *args):
pon_sets = [x for x in hand if is_pon(x)]
if len(pon_sets) != 4:
return False
count_wind_sets = 0
winds = [EAST, SOUTH, WEST, NORTH]
for item in pon_sets:
if is_pon(item) and item[0] in winds:
... | The hand contains four sets of winds
:param hand: list of hand's sets
:return: boolean |
1,657 | def auth_request_url(self, client_id=None, redirect_uris="urn:ietf:wg:oauth:2.0:oob",
scopes=__DEFAULT_SCOPES, force_login=False):
if client_id is None:
client_id = self.client_id
else:
if os.path.isfile(client_id):
with open(clie... | Returns the url that a client needs to request an oauth grant from the server.
To log in with oauth, send your user to this URL. The user will then log in and
get a code which you can pass to log_in.
scopes are as in `log_in()`_, redirect_uris is where the user should be redire... |
1,658 | def collect_analysis(self):
analysis = {}
for field in self.fields.values():
for analyzer_name in (, , ):
if not hasattr(field, analyzer_name):
continue
analyzer = getattr(field, analyzer_name)
if not isinstance(a... | :return: a dictionary which is used to get the serialized analyzer definition from the analyzer class. |
1,659 | def database_list_folder(object_id, input_params={}, always_retry=True, **kwargs):
return DXHTTPRequest( % object_id, input_params, always_retry=always_retry, **kwargs) | Invokes the /database-xxxx/listFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Databases#API-method%3A-%2Fdatabase-xxxx%2FlistFolder |
1,660 | def kl_divergence(self, logits_q, logits_p):
return (torch.exp(logits_q) * (logits_q - logits_p)).sum(1, keepdim=True) | Categorical distribution KL divergence calculation
KL(Q || P) = sum Q_i log (Q_i / P_i)
When talking about logits this is:
sum exp(Q_i) * (Q_i - P_i) |
1,661 | def assign_types_to_resources(resource_types,**kwargs):
type_ids = list(set([rt.type_id for rt in resource_types]))
db_types = db.DBSession.query(TemplateType).filter(TemplateType.id.in_(type_ids)).options(joinedload_all()).all()
types = {}
for db_type in db_types:
if types.get(db_ty... | Assign new types to list of resources.
This function checks if the necessary
attributes are present and adds them if needed. Non existing attributes
are also added when the type is already assigned. This means that this
function can also be used to update resources, when a resource type ... |
1,662 | def run(self, cell, is_full_fc=False, parse_fc=True):
with open(self._filename) as f:
fc_dct = self._parse_q2r(f)
self.dimension = fc_dct[]
self.epsilon = fc_dct[]
self.borns = fc_dct[]
if parse_fc:
(self.fc,
... | Make supercell force constants readable for phonopy
Note
----
Born effective charges and dielectric constant tensor are read
from QE output file if they exist. But this means
dipole-dipole contributions are removed from force constants
and this force constants matrix is ... |
1,663 | def wait_turns(self, turns, cb=None):
self.disable_input()
self.app.wait_turns(turns, cb=partial(self.enable_input, cb)) | Call ``self.app.engine.next_turn()`` ``n`` times, waiting ``self.app.turn_length`` in between
Disables input for the duration.
:param turns: number of turns to wait
:param cb: function to call when done waiting, optional
:return: ``None`` |
1,664 | def _get_notmuch_message(self, mid):
mode = Database.MODE.READ_ONLY
db = Database(path=self.path, mode=mode)
try:
return db.find_message(mid)
except:
errmsg = % mid
raise NonexistantObjectError(errmsg) | returns :class:`notmuch.database.Message` with given id |
1,665 | def delete_table_records(self, table, query_column, ids_to_delete):
table = table.get_soap_object(self.client)
result = self.call(, table, query_column, ids_to_delete)
if hasattr(result, ):
return [DeleteResult(delete_result) for delete_result in result]
return [Dele... | Responsys.deleteTableRecords call
Accepts:
InteractObject table
string query_column
possible values: 'RIID'|'EMAIL_ADDRESS'|'CUSTOMER_ID'|'MOBILE_NUMBER'
list ids_to_delete
Returns a list of DeleteResult instances |
1,666 | def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA,
bits=2048, years=5, alt_names=None, serial=0,
overwrite=False):
key = self.create_key_pair(cert_type, bits)
req = self.create_request(key, CN=name)
extensions = ... | Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name - The name of the CA to sign this cert
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An arra... |
1,667 | def transform_literals(rdf, literalmap):
affected_types = (SKOS.Concept, SKOS.Collection,
SKOSEXT.DeprecatedConcept)
props = set()
for t in affected_types:
for conc in rdf.subjects(RDF.type, t):
for p, o in rdf.predicate_objects(conc):
if isin... | Transform literal properties of Concepts, as defined by config file. |
1,668 | def netdevs():
with open() as f:
net_dump = f.readlines()
device_data={}
data = namedtuple(,[,])
for line in net_dump[2:]:
line = line.split()
if line[0].strip() != :
device_data[line[0].strip()] = data(float(line[1].split()[0])/(1024.0*1024.0),
... | RX and TX bytes for each of the network devices |
1,669 | def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS,
stop_words=None):
fox foxword wordfox foxword word wordalice bobBob alicea doga dog catbob alicea dog catonebar bahOnea doga dog catA DOGoneonea doga dog
_raise_error_if_not_sarray(text, "text")
sf = _turic... | Remove words that occur below a certain number of times in an SArray.
This is a common method of cleaning text before it is used, and can increase the
quality and explainability of the models learned on the transformed data.
RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed
... |
1,670 | def filter_geoquiet(sat, maxKp=None, filterTime=None, kpData=None, kp_inst=None):
if kp_inst is not None:
kp_inst.load(date=sat.date, verifyPad=True)
kpData = kp_inst
elif kpData is None:
kp = pysat.Instrument(, , pad=pds.DateOffset(days=1))
kp.load(date=sat.date, verifyPad=... | Filters pysat.Instrument data for given time after Kp drops below gate.
Loads Kp data for the same timeframe covered by sat and sets sat.data to
NaN for times when Kp > maxKp and for filterTime after Kp drops below maxKp.
Parameters
----------
sat : pysat.Instrument
Instrument to b... |
1,671 | def creationTime(item):
forThisItem = _CreationTime.createdItem == item
return item.store.findUnique(_CreationTime, forThisItem).timestamp | Returns the creation time of the given item. |
1,672 | def apply_all_rules(self, *args, **kwargs):
for x in self.rules:
self._quit_check()
if self.config.chatty_rules:
self.config.logger.debug(
,
to_str(x.__class__)
)
predicate_result, action_result ... | cycle through all rules and apply them all without regard to
success or failure
returns:
True - since success or failure is ignored |
1,673 | def completion():
shell = env.get("SHELL", None)
if env.get("SHELL", None):
echo(
click_completion.get_code(
shell=shell.split(os.sep)[-1], prog_name="doitlive"
)
)
else:
echo(
"Please ensure that the {SHELL} environment "
... | Output completion (to be eval'd).
For bash or zsh, add the following to your .bashrc or .zshrc:
eval "$(doitlive completion)"
For fish, add the following to ~/.config/fish/completions/doitlive.fish:
eval (doitlive completion) |
1,674 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.feedback_id is not None:
_dict[] = self.feedback_id
if hasattr(self, ) and self.user_id is not None:
_dict[] = self.user_id
if hasattr(self, ) and self.comment is not None:
_dict[] = s... | Return a json dictionary representing this model. |
1,675 | def GetTemplateID(alias,location,name):
if alias is None: alias = clc.v1.Account.GetAlias()
if location is None: location = clc.v1.Account.GetLocation()
r = Server.GetTemplates(alias,location)
for row in r:
if row[].lower() == name.lower(): return(row[])
else:
if clc.args: clc.v1.output.Status("... | Given a template name return the unique OperatingSystem ID.
:param alias: short code for a particular account. If none will use account's default alias
:param location: datacenter where group resides
:param name: template name |
1,676 | def subbrick(dset,label,coef=False,tstat=False,fstat=False,rstat=False,number_only=False):
if coef is not False:
if coef is True:
coef = 0
label += "
elif tstat != False:
if tstat==True:
tstat = 0
label += "
elif fstat:
label += "_Fstat"
... | returns a string referencing the given subbrick within a dset
This method reads the header of the dataset ``dset``, finds the subbrick whose
label matches ``label`` and returns a string of type ``dataset[X]``, which can
be used by most AFNI programs to refer to a subbrick within a file
The options coe... |
1,677 | def _translate_dst_register_oprnd(self, operand):
reg_info = self._arch_alias_mapper.get(operand.name, None)
parent_reg_constrs = []
if reg_info:
var_base_name, offset = reg_info
var_name_old = self._get_var_name(var_base_name, fresh=False)
var_nam... | Translate destination register operand to SMT expr. |
1,678 | def p_ident_parts(self, p):
if not isinstance(p[1], list):
p[1] = [p[1]]
p[0] = p[1] | ident_parts : ident_part
| selector
| filter_group |
1,679 | def dropEvent(self, event: QDropEvent):
items = [item for item in self.items(event.scenePos()) if isinstance(item, GraphicsItem) and item.acceptDrops()]
item = None if len(items) == 0 else items[0]
if len(event.mimeData().urls()) > 0:
self.files_dropped.emit(event.mimeData().urls())
... | :type: list of ProtocolTreeItem |
1,680 | def upload_resumable(self, fd, filesize, filehash, unit_hash, unit_id,
unit_size, quick_key=None, action_on_duplicate=None,
mtime=None, version_control=None, folder_key=None,
filedrop_key=None, path=None, previous_hash=None):
ac... | upload/resumable
http://www.mediafire.com/developers/core_api/1.3/upload/#resumable |
1,681 | def attend_fight(self, mappings, node_ip, predictions, ntp):
mappings = self.add_listen_sock(mappings)
log.debug(mappings)
self.simultaneous_cons = []
predictions = predictions.split(" ")
self.simultaneous_fight(mappings, node_ip, predictions,... | This function is for starting and managing a fight
once the details are known. It also handles the
task of returning any valid connections (if any) that
may be returned from threads in the simultaneous_fight function. |
1,682 | def analyze(self, mode=None, timesteps=None):
if timesteps is None:
timesteps = self.network.timeseries.timeindex
if not hasattr(timesteps, "__len__"):
timesteps = [timesteps]
if self.network.pypsa is None:
self.network.pypsa = ... | Analyzes the grid by power flow analysis
Analyze the grid for violations of hosting capacity. Means, perform a
power flow analysis and obtain voltages at nodes (load, generator,
stations/transformers and branch tees) and active/reactive power at
lines.
The power flow analysis c... |
1,683 | def reload(self, **kwargs):
frame = self.one({: self._id}, **kwargs)
self._document = frame._document | Reload the document |
1,684 | def _decrypt_data_key(self, encrypted_data_key, algorithm, encryption_context=None):
kms_params = {"CiphertextBlob": encrypted_data_key.encrypted_data_key}
if encryption_context:
kms_params["EncryptionContext"] = encryption_context
if self.config.grant_tokens:
km... | Decrypts an encrypted data key and returns the plaintext.
:param data_key: Encrypted data key
:type data_key: aws_encryption_sdk.structures.EncryptedDataKey
:type algorithm: `aws_encryption_sdk.identifiers.Algorithm` (not used for KMS)
:param dict encryption_context: Encryption context ... |
1,685 | def saveNetworkToFile(self, filename, makeWrapper = 1, mode = "pickle", counter = None):
if "?" in filename:
import re
char = "?"
match = re.search(re.escape(char) + "+", filename)
if match:
num = self.epoch
if counter != ... | Deprecated. |
1,686 | def StyleFactory(style_elm):
style_cls = {
WD_STYLE_TYPE.PARAGRAPH: _ParagraphStyle,
WD_STYLE_TYPE.CHARACTER: _CharacterStyle,
WD_STYLE_TYPE.TABLE: _TableStyle,
WD_STYLE_TYPE.LIST: _NumberingStyle
}[style_elm.type]
return style_cls(style_elm) | Return a style object of the appropriate |BaseStyle| subclass, according
to the type of *style_elm*. |
1,687 | def __QueryFeed(self,
path,
type,
id,
result_fn,
create_fn,
query,
options=None,
partition_key_range_id=None):
if options is None:
... | Query for more than one Azure Cosmos resources.
:param str path:
:param str type:
:param str id:
:param function result_fn:
:param function create_fn:
:param (str or dict) query:
:param dict options:
The request options for the request.
:param... |
1,688 | def toxml(self):
return +\
(.format(self.name) if self.name else ) +\
(.format(self.symbol) if self.symbol else ) +\
(.format(self.value) if self.value else ) +\
(.format(self.dimension) if self.dimension else ) +\
(.format(self.description) if self.d... | Exports this object into a LEMS XML object |
1,689 | def authenticate_direct_credentials(self, username, password):
bind_user = .format(
self.config.get(),
username,
self.config.get()
)
connection = self._make_connection(
bind_user=bind_user,
bind_password=password,
)
... | Performs a direct bind, however using direct credentials. Can be used
if interfacing with an Active Directory domain controller which
authenticates using username@domain.com directly.
Performing this kind of lookup limits the information we can get from
ldap. Instead we can only deduce ... |
1,690 | def describe_instance_health(self, load_balancer_name, instances=None):
params = { : load_balancer_name}
if instances:
self.build_list_params(params, instances,
)
return self.get_list(, params,
[(, InstanceState... | Get current state of all Instances registered to an Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type instances: List of strings
:param instances: The instance ID's of the EC2 instances
to return sta... |
1,691 | def decr(name, value=1, rate=1, tags=None):
client().decr(name, value, rate, tags) | Decrement a metric by value.
>>> import statsdecor
>>> statsdecor.decr('my.metric') |
1,692 | def available(name):
*
path = .format(name)
return os.path.isfile(path) and os.access(path, os.X_OK) | .. versionadded:: 2014.7.0
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd |
1,693 | def start_capture(self, port_number, output_file, data_link_type="DLT_EN10MB"):
if port_number not in self._mappings:
raise DynamipsError("Port {} is not allocated".format(port_number))
nio = self._mappings[port_number]
data_link_type = data_link_type.lower()
if d... | Starts a packet capture.
:param port_number: allocated port number
:param output_file: PCAP destination file for the capture
:param data_link_type: PCAP data link type (DLT_*), default is DLT_EN10MB |
1,694 | def _Execute(self, options):
whitelist = dict(
name=options["name"],
description=options.get("description", "<empty>"))
return self._agent.client.compute.security_groups.create(**whitelist) | Handles security groups operations. |
1,695 | def union(self, other):
if not isinstance(other, self.__class__):
m = "You can only union striplogs with each other."
raise StriplogError(m)
result = []
for iv in deepcopy(self):
for jv in other:
if iv.any_overlaps(jv):
... | Makes a striplog of all unions.
Args:
Striplog. The striplog instance to union with.
Returns:
Striplog. The result of the union. |
1,696 | def createSystem(self, topology, nonbondedMethod=NoCutoff,
nonbondedCutoff=1.0 * u.nanometer, constraints=None,
rigidWater=True, removeCMMotion=True, hydrogenMass=None,
**args):
self._SystemData = app.ForceField._SystemData()
... | Construct an OpenMM System representing a Topology with this force field.
Parameters
----------
topology : Topology
The Topology for which to create a System
nonbondedMethod : object=NoCutoff
The method to use for nonbonded interactions. Allowed values are
... |
1,697 | def select_key(self, key, bucket_name=None,
expression=,
expression_type=,
input_serialization=None,
output_serialization=None):
if input_serialization is None:
input_serialization = {: {}}
if output_seriali... | Reads a key with S3 Select.
:param key: S3 key that will point to the file
:type key: str
:param bucket_name: Name of the bucket in which the file is stored
:type bucket_name: str
:param expression: S3 Select expression
:type expression: str
:param expression_typ... |
1,698 | def paste_to_current_cell(self, tl_key, data, freq=None):
self.pasting = True
grid_rows, grid_cols, __ = self.grid.code_array.shape
self.need_abort = False
tl_row, tl_col, tl_tab = self._get_full_key(tl_key)
row_overflow = False
col_overflow = False
... | Pastes data into grid from top left cell tl_key
Parameters
----------
ul_key: Tuple
\key of top left cell of paste area
data: iterable of iterables where inner iterable returns string
\tThe outer iterable represents rows
freq: Integer, defaults to None
\... |
1,699 | def cli(env, sortby, columns, datacenter, username, storage_type):
file_manager = SoftLayer.FileStorageManager(env.client)
file_volumes = file_manager.list_file_volumes(datacenter=datacenter,
username=username,
... | List file storage. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.