Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
352,900 | def begin(self):
log.debug("handshake (version %s)" % PROTOCOL_VERSION)
version = Version()
version.services = 0
log.debug("send Version")
self.send_message(version) | This method will implement the handshake of the
Bitcoin protocol. It will send the Version message,
and block until it receives a VerAck.
Once we receive the version, we'll send the verack,
and begin downloading. |
352,901 | def __new_request_id(self):
while True:
with self.__seqnum_lock:
requestId = "%s%d" % (self.__reqpre, self.__reqnum)
self.__reqnum += 1
if requestId not in self.__requests:
break
self.__reqpre = se... | requestId follows form "pre num" where pre is some random ascii prefix EG 6 chars long
and num is an ever increasing number (self.__reqnum). MUST be called within self.__requests lock |
352,902 | def __assert_less(expected, returned):
result = "Pass"
try:
assert (expected < returned), "{0} not False".format(returned)
except AssertionError as err:
result = "Fail: " + six.text_type(err)
return result | Test if a value is less than the returned value |
352,903 | def generate_http_basic_token(username, password):
token = base64.b64encode(.format(username, password).encode()).decode()
return token | Generates a HTTP basic token from username and password
Returns a token string (not a byte) |
352,904 | def find_cc(arch, args, sp_delta):
if arch.name not in CC:
return None
possible_cc_classes = CC[arch.name]
for cc_cls in possible_cc_classes:
if cc_cls._match(arch, args, sp_delta):
return cc_cls(arch, args=args, sp_delta=sp_delta)
return ... | Pinpoint the best-fit calling convention and return the corresponding SimCC instance, or None if no fit is
found.
:param Arch arch: An ArchX instance. Can be obtained from archinfo.
:param list args: A list of arguments.
:param int sp_delta: The change of stack pointer be... |
352,905 | def register_precmd_hook(self, func: Callable[[plugin.PrecommandData], plugin.PrecommandData]) -> None:
self._validate_prepostcmd_hook(func, plugin.PrecommandData)
self._precmd_hooks.append(func) | Register a hook to be called before the command function. |
352,906 | def set_colour(self, r, g, b):
if not 0 <= r <= 255:
raise ValueError("The value for red needs to be between 0 and 255.")
if not 0 <= g <= 255:
raise ValueError("The value for green needs to be between 0 and 255.")
if not 0 <= b <= 255:
raise ValueErr... | Set colour of an rgb bulb.
Args:
r(int): Value for the colour red as int from 0-255.
g(int): Value for the colour green as int from 0-255.
b(int): Value for the colour blue as int from 0-255. |
352,907 | def skip_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_skips
api_path = "/api/v2/skips.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/ticket_skips#record-a-new-skip-for-the-current-user |
352,908 | def _stop(self):
self.running = False
self.__context.remove_service_listener(self)
with self.__instances_lock:
for svc_ref in self._handlers_refs:
self.__context.unget_service(svc_ref)
self._handlers.clear()
... | iPOPO is stopping: clean everything up |
352,909 | def _context(self):
src_stats = {
src: self._src_path_stats(src) for src in self.src_paths()
}
} | Return the context to pass to the template.
The context is a dict of the form:
{
'css_url': CSS_URL,
'report_name': REPORT_NAME,
'diff_name': DIFF_NAME,
'src_stats': {SRC_PATH: {
'percent_covered': PERCENT_COVERED,
... |
352,910 | def get_assessment_taken_lookup_session(self):
if not self.supports_assessment_taken_lookup():
raise errors.Unimplemented()
return sessions.AssessmentTakenLookupSession(runtime=self._runtime) | Gets the ``OsidSession`` associated with the assessment taken lookup service.
return: (osid.assessment.AssessmentTakenLookupSession) - an
``AssessmentTakenLookupSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_assessment_taken_loo... |
352,911 | def put_string(self, content, destination_s3_path, **kwargs):
self._check_deprecated_argument(**kwargs)
(bucket, key) = self._path_to_bucket_and_key(destination_s3_path)
self.s3.meta.client.put_object(
Key=key, Bucket=bucket, Body=content, **kwargs) | Put a string to an S3 path.
:param content: Data str
:param destination_s3_path: URL for target S3 location
:param kwargs: Keyword arguments are passed to the boto3 function `put_object` |
352,912 | def create(cls, mr_spec, shard_number, shard_attempt, _writer_state=None):
writer_spec = cls.get_params(mr_spec.mapper, allow_old=False)
seg_index = None
if writer_spec.get(cls._NO_DUPLICATE, False):
seg_index = 0
key = cls._generate_filename(writer_spec, mr_spec.name,
... | Inherit docs. |
352,913 | def create_tenant(self, name, description=None, enabled=True):
data = {"tenant": {
"name": name,
"enabled": enabled,
}}
if description:
data["tenant"]["description"] = description
resp, resp_body = self.method_post("tenants", d... | ADMIN ONLY. Creates a new tenant. |
352,914 | def _reduction_output_shape(x, output_shape, reduced_dim):
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
return x.shape - r... | Helper function to reduce_sum, etc. |
352,915 | def writer_trampoline(start):
trans = Transition(None, start)
while True:
ion_event = (yield trans.event)
if trans.event is None:
if ion_event is None:
raise TypeError()
else:
if trans.event.type is WriteEventType.HAS_PENDING and ion_event is ... | Provides the co-routine trampoline for a writer state machine.
The given co-routine is a state machine that yields :class:`Transition` and takes
a :class:`Transition` with a :class:`amazon.ion.core.IonEvent` and the co-routine itself.
Notes:
A writer delimits its logical flush points with ``WriteE... |
352,916 | def publish(self, topic, dct):
get_logger().info("Publishing message {} on routing key "
"{}...".format(dct, topic))
self._channel.basic_publish(
exchange=self.exchange,
routing_key=topic,
body=json.dumps(dct)
) | Send a dict with internal routing key to the exchange.
Args:
topic: topic to publish the message to
dct: dict object to send |
352,917 | def Field_to_xarray(field):
dom = field.domain
dims = []; dimlist = []; coords = {};
for axname in dom.axes:
dimlist.append(axname)
try:
assert field.interfaces[dom.axis_index[axname]]
bounds_name = axname +
dims.append(bounds_name)
coord... | Convert a climlab.Field object to xarray.DataArray |
352,918 | def start(self):
super(OutputExecutor, self).start()
self.poll_obj = select.poll()
self.poll_obj.register(self.output(), select.POLLIN)
try:
self.wait_for(self._wait_for_output)
self.poll_obj.unregister(self.out... | Start process.
:returns: itself
:rtype: OutputExecutor
.. note::
Process will be considered started, when defined banner will appear
in process output. |
352,919 | def attemptByKey(self, key):
return self.store.findUnique(_PasswordResetAttempt,
_PasswordResetAttempt.key == key,
default=None) | Locate the L{_PasswordResetAttempt} that corresponds to C{key} |
352,920 | def set_affinity(pid, cpuset):
_cpuset = cpu_set_t()
__CPU_ZERO(_cpuset)
for i in cpuset:
if i in range(0, sizeof(cpu_set_t) * 8):
__CPU_SET(i, _cpuset)
if libnuma.sched_setaffinity(pid, sizeof(cpu_set_t), byref(_cpuset)) < 0:
raise RuntimeError() | Sets the CPU affinity mask of the process whose ID is pid to the value specified by mask.
If pid is zero, then the calling process is used.
@param pid: process PID (0 == current process)
@type pid: C{int}
@param cpuset: set of CPU ids
@type cpuset: C{set} |
352,921 | def _parse_json(self, resources, exactly_one=True):
code = resources[].get()
if code:
exc_msg = "Error returned by What3Words: %s" % resources[][]
if code == 401:
raise exc.GeocoderAuthenticationFailure(exc_msg)
raise exc.Geoco... | Parse type, words, latitude, and longitude and language from a
JSON response. |
352,922 | def data(self, index, role = Qt.DisplayRole):
try:
if role == Qt.DisplayRole:
return to_string(self._cellValue(index), masked=self._cellMask(index),
decode_bytes=self.encoding, maskFormat=self.maskFormat,
strF... | Returns the data at an index for a certain role |
352,923 | def position_permutation(obs_stat,
context_counts,
context_to_mut,
seq_context,
gene_seq,
gene_vest=None,
num_permutations=10000,
stop_criteria=1... | Performs null-permutations for position-based mutation statistics
in a single gene.
Parameters
----------
obs_stat : tuple, (recur ct, entropy, delta entropy, mean vest)
tuple containing the observed statistics
context_counts : pd.Series
number of mutations for each context
cont... |
352,924 | def install_hook(path):
git = op.join(path, , )
hg = op.join(path, )
if op.exists(git):
install_git(git)
LOGGER.warn()
elif op.exists(hg):
install_hg(hg)
LOGGER.warn()
else:
LOGGER.error()
sys.exit(1) | Auto definition of SCM and hook installation. |
352,925 | def remove_comments(self, recursive=True):
self.text = texutils.remove_comments(self.text)
if recursive:
for path, document in self._children.iteritems():
document.remove_comments(recursive=True) | Remove latex comments from document (modifies document in place).
Parameters
----------
recursive : bool
Remove comments from all input LaTeX documents (default ``True``). |
352,926 | def add_input_data(self, datastream, data_type, options, data):
url = self.get_add_input_data_url(datastream, options)
form_data = {
: {
: (
Utils.random_string(10)+( if data_type == else ),
StringIO(data),
... | To add data to a Datastream
:param datastream: string
:param data_type: string
:param options: dict
:param data: string |
352,927 | def get_dependencies(env_yml_file):
import yaml
with open_here(env_yml_file) as f:
environment = yaml.load(f)
conda_dependencies = []
package_map = {
: ,
: ,
: ,
: ,
}
for dep in environment[]:
if isinstance(dep, s... | Read the dependencies from a Conda environment file in YAML
and return a list of such dependencies (from conda and pip list)
Be sure to match packages specification for each of:
- Conda : http://conda.pydata.org/docs/spec.html#build-version-spec
- Pip & Setuptool :
- http://pythonhosted.org/setup... |
352,928 | def find_path_package_name(thepath):
module_found = False
last_module_found = None
continue_ = True
while continue_:
module_found = is_path_python_module(thepath)
next_path = path.dirname(thepath)
if next_path == thepath:
continue_ = False
if module_found... | Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None. |
352,929 | def save(self):
LOGGER.debug("IPAddress.save")
post_payload = {}
if self.id is not None:
post_payload[] = self.id
if self.ip_address is not None:
post_payload[] = self.ip_address
if self.fqdn is not None:
post_payload[] = self.fqdn
... | :return: save this IP Address on Ariane server (create or update) |
352,930 | def path_of(self, service, node):
return "/".join([self.base_path, service.name, node.name]) | Helper method for determining the Zookeeper path for a given cluster
member node. |
352,931 | def generate_fieldvalues(self, count=1):
ar_context = self.get_ar()
copy_from = self.get_copy_from()
out = {}
fields = self.get_ar_fields()
for arnum in range(count):
source = copy_from.get(arnum)
parent = None
... | Returns a mapping of '<fieldname>-<count>' to the default value
of the field or the field value of the source AR |
352,932 | def portrait_image(model, request):
response = Response()
cfg = ugm_general(model)
response.body = model.attrs[cfg.attrs[]]
response.headers[] =
response.headers[] =
return response | XXX: needs polishing. Return configured default portrait if not set
on user. |
352,933 | def Profiler_setSamplingInterval(self, interval):
assert isinstance(interval, (int,)
), "Argument must be of type int. Received type: " % type(
interval)
subdom_funcs = self.synchronous_command(,
interval=interval)
return subdom_funcs | Function path: Profiler.setSamplingInterval
Domain: Profiler
Method name: setSamplingInterval
Parameters:
Required arguments:
'interval' (type: integer) -> New sampling interval in microseconds.
No return value.
Description: Changes CPU profiler sampling interval. Must be called before CPU... |
352,934 | def timedelta_total_minutes(td, strict=False):
minutes, seconds = divmod(td.days * 24 * 3600 + td.seconds, 60)
if seconds or td.microseconds:
if strict:
raise ValueError(
"%r is not an integral multiple of 60 seconds", td)
if seconds > 30 or (seconds == 30 and td... | Convert/round a :cls:`timedelta` to an integral number of minutes.
If ``strict`` is true than raises :exc:`ValueError` if the
:cls:`~datetime.timedelta` is not a integral multiple of 60 seconds. |
352,935 | def send_report(self, report_parts):
logger.info()
report_parts = sorted(
filter(lambda x: x.fmt in self.formats, report_parts),
key=lambda x: self.formats.index(x.fmt)
)
workdir = os.path.join(self.pubdir, self.dirname)
if not os.path.isdir(work... | Publish the report parts to local files. Each report part is a text
with a title and specific extension. For html and plaintext sending
the report part is unique, for csv send also the stats and unparsed
string are plain text and report items are csv texts. |
352,936 | def clean_abstract(abstract, remove_tags=[, , , ]):
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract | Remove unwanted tags from abstract string,
parsing it as HTML, then only keep the body paragraph contents |
352,937 | def make_stmt_from_sort_key(key, verb):
def make_agent(name):
if name == or name is None:
return None
return Agent(name)
StmtClass = get_statement_by_name(verb)
inps = list(key[1])
if verb == :
stmt = StmtClass([make_agent(name) for name in inps])
elif verb... | Make a Statement from the sort key.
Specifically, the sort key used by `group_and_sort_statements`. |
352,938 | def almost_everything(self, clean_all=False):
to_delete = self.file_to_delete()
if clean_all:
to_delete.extend(self.databases_to_delete())
for file in to_delete:
File(file).delete()
if clean_all:
Loa... | Delete almost all discovered files.
:param clean_all:
Tell the subsystem if we have to clean everything instesd
of almost everything.
:type clean_all: bool |
352,939 | def on_resize(self, event):
self.context.set_viewport(0, 0, event.size[0], event.size[1])
for visual in self.visuals:
visual.on_resize(event.size)
self.update() | Resize the OpenGL context. |
352,940 | def LoadFile(f, table_name, conn):
reader = csv.reader(f)
header = next(reader)
columns = []
for n in header:
n = n.replace(, )
n = n.replace(, )
columns.append(n)
create_columns = []
column_types = {}
for n in columns:
if n in column_types:
create_columns.append("%s %s" % (n, c... | Import lines from f as new table in db with cursor c. |
352,941 | def _convert_operator(self, node_name, op_name, attrs, inputs):
if op_name in convert_map:
op_name, new_attrs, inputs = convert_map[op_name](attrs, inputs, self)
else:
raise NotImplementedError("Operator {} not implemented.".format(op_name))
if isinstance(op_name... | Convert from onnx operator to mxnet operator.
The converter must specify conversions explicitly for incompatible name, and
apply handlers to operator attributes.
Parameters
----------
:param node_name : str
name of the node to be translated.
:param op_name : ... |
352,942 | def _handleParListMismatch(self, probStr, extra=False):
if extra:
return True
errmsg =
if self._strict:
errmsg =
errmsg = errmsg+ + \
+self.taskName+
if probStr:
errmsg += +probStr
errmsg... | Override to include ConfigObj filename and specific errors.
Note that this only handles "missing" pars and "extra" pars, not
wrong-type pars. So it isn't that big of a deal. |
352,943 | def body_content(self, election_day, body, division=None):
from electionnight.models import PageType
body_type = ContentType.objects.get_for_model(body)
page_type = PageType.objects.get(
model_type=body_type,
election_day=election_day,
body=body,
... | Return serialized content for a body page. |
352,944 | def vsub(v1, v2):
v1 = stypes.toDoubleVector(v1)
v2 = stypes.toDoubleVector(v2)
vout = stypes.emptyDoubleVector(3)
libspice.vsub_c(v1, v2, vout)
return stypes.cVectorToPython(vout) | Compute the difference between two 3-dimensional,
double precision vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsub_c.html
:param v1: First vector (minuend).
:type v1: 3-Element Array of floats
:param v2: Second vector (subtrahend).
:type v2: 3-Element Array of floats
... |
352,945 | def register_chosen_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs):
if custom_filters is None:
custom_filters = []
filters_set = self.filters_factory.resolve(self.chosen_inline_result_handlers,
... | Register handler for chosen inline query
Example:
.. code-block:: python3
dp.register_chosen_inline_handler(some_chosen_inline_handler, lambda chosen_inline_query: True)
:param callback:
:param state:
:param custom_filters:
:param run_task: run callback in... |
352,946 | def update(self, quality_score, issue=values.unset):
return self._proxy.update(quality_score, issue=issue, ) | Update the FeedbackInstance
:param unicode quality_score: The call quality expressed as an integer from 1 to 5
:param FeedbackInstance.Issues issue: Issues experienced during the call
:returns: Updated FeedbackInstance
:rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackInstanc... |
352,947 | def deserialize_subject_info(subject_info_xml_path):
try:
with open(subject_info_xml_path) as f:
return d1_common.xml.deserialize(f.read())
except ValueError as e:
raise d1_common.types.exceptions.InvalidToken(
0,
.format(
subject_info_xml... | Deserialize a SubjectInfo XML file to a PyXB object. |
352,948 | def _move_update(sourcepath, destname):
if sys.platform.startswith():
return os.system("/bin/mv -fu " % (sourcepath, destname))
else:
return os.system("rsync -ua --remove-source-files " % (sourcepath, destname)) | Move source to dest only if source is newer. |
352,949 | def within_range(df, items=None):
for k, (lower, upper) in items.items():
if (lower > df[k]).any() or (upper < df[k]).any():
raise AssertionError
return df | Assert that a DataFrame is within a range.
Parameters
==========
df : DataFame
items : dict
mapping of columns (k) to a (low, high) tuple (v)
that ``df[k]`` is expected to be between. |
352,950 | def execute(args):
is_property = in args
args = [get_vswhere_path(), ] + args
if not is_property:
args.extend([, ])
output = subprocess.check_output(args)
if is_property:
return output.decode().splitlines()
else:
return json.loads(output, encoding=) | Call vswhere with the given arguments and return an array of results.
`args` is a list of command line arguments to pass to vswhere.
If the argument list contains '-property', this returns an array with the
property value for each result. Otherwise, this returns an array of
dictionaries containing the... |
352,951 | def get_table_csv(cur, tablename, exclude_columns=[]):
import utool as ut
colnames_ = ut.get_table_columnname_list(cur, tablename)
colnames = tuple([colname for colname in colnames_ if colname not in exclude_columns])
row_list = ut.get_table_rows(cur, tablename, colnames, unpack=False)
column_l... | Conveinience: Converts a tablename to csv format
Args:
tablename (str):
exclude_columns (list):
Returns:
str: csv_table
CommandLine:
python -m ibeis.control.SQLDatabaseControl --test-get_table_csv
Example:
>>> # DISABLE_DOCTEST
>>> from ibeis.control.S... |
352,952 | def get_dword_from_data(self, data, offset):
if (offset+1)*4 > len(data):
return None
return struct.unpack(, data[offset*4:(offset+1)*4])[0] | Convert four bytes of data to a double word (little endian)
'offset' is assumed to index into a dword array. So setting it to
N will return a dword out of the data starting at offset N*4.
Returns None if the data can't be turned into a double word. |
352,953 | def generator(self, z, is_training, out_shape):
hparams = self.hparams
height, width, c_dim = out_shape
batch_size = hparams.batch_size
with tf.variable_scope(
"generator",
initializer=tf.random_normal_initializer(stddev=0.02)):
net = tf.layers.dense(z, 1024, name="g_fc1")
... | Generator outputting image in [0, 1]. |
352,954 | def cancel(self, job_id):
try:
confirmation = self.send(self.api_url + job_id, http_method="DELETE")
except CartoException as e:
if in e.args[0].args[0]:
return
else:
raise e
return confirmation[] | Cancels a job
:param job_id: The id of the job to be cancelled
:type job_id: str
:return: A status code depending on whether the cancel request was
successful
:rtype: str
:raise CartoException: |
352,955 | def pack_types(types, args, major):
if len(types) > 0:
multiple = types[-1]._multiple
else:
multiple = False
if len(types) < len(args) and not multiple:
raise ValueError("Too many arguments to pack.")
if len(args) < len(types):
retvals = map(lambda ktype, ... | Pack arguments according the the types list.
Parameters
----------
types : list of kattypes
The types of the arguments (in order).
args : list of objects
The arguments to format.
major : integer
Major version of KATCP to use when packing types |
352,956 | def _generate_instances(self):
for node in self.node_stack:
yield node
while self._data:
yield self._make_instance(self._data.pop(0)) | ListNode item generator. Will be used internally by __iter__ and __getitem__
Yields:
ListNode items (instances) |
352,957 | def stream_fastq(file_handler):
next_element =
for i, line in enumerate(file_handler):
next_element += line
if i % 4 == 3:
yield next_element
next_element = | Generator which gives all four lines if a fastq read as one string |
352,958 | def get(self, name):
self.auto_invalidate()
try:
return self._uris[name]
except KeyError:
self.refresh()
try:
return self._uris[name]
except KeyError:
raise NotFound({self._manager._name_prop: name}, self._m... | Get the resource URI for a specified resource name.
If an entry for the specified resource name does not exist in the
Name-URI cache, the cache is refreshed from the HMC with all resources
of the manager holding this cache.
If an entry for the specified resource name still does not exi... |
352,959 | def fake_index(in_bam, data):
index_file = "%s.bai" % in_bam
if not utils.file_exists(index_file):
with file_transaction(data, index_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
out_handle.write("name sorted -- no index")
return index_file | Create a fake index file for namesorted BAMs. bais require by CWL for consistency. |
352,960 | def routeevent(self, path, routinemethod, container = None, host = None, vhost = None, method = [b, b]):
regm = re.compile(path + b)
if vhost is None:
vhost = self.vhost
if container is None:
container = getattr(routinemethod, , None)
def ismatch(event):
... | Route specified path to a routine factory
:param path: path to match, can be a regular expression
:param routinemethod: factory function routinemethod(event), event is the HttpRequestEvent
:param container: routine container. If None, default to self for bound method,... |
352,961 | def add(self, value, session=None, **kwargs):
s, instance = self.session_instance(, value, session, **kwargs)
return s.add(instance) | Add ``value``, an instance of :attr:`formodel` to the
:attr:`through` model. This method can only be accessed by an instance of the
model for which this related manager is an attribute. |
352,962 | def assert_iter(**kw):
for name, value in kw.items():
if not isiter(value):
raise TypeError(
.format(name)) | Asserts if a given values implements a valid iterable interface.
Arguments:
**kw (mixed): value to check if it is an iterable.
Raises:
TypeError: if assertion fails. |
352,963 | def asJSON(self):
self._json = json.dumps(self.asDictionary)
return self._json | returns the data source as JSON |
352,964 | def delete(self, collector_id=None):
cid = self.collector_id
if collector_id:
cid = collector_id
url = .format(self.url, cid)
request = requests.delete(url, auth=self.auth)
try:
response = request.json()
except Valu... | Delete a collector from inventory.
Args:
collector_id (int): id of collector (optional) |
352,965 | def delete(self, data=None):
if not self.can_delete:
raise JSSMethodNotAllowedError(self.__class__.__name__)
if data:
self.jss.delete(self.url, data)
else:
self.jss.delete(self.url) | Delete this object from the JSS. |
352,966 | def merge_global_settings(config, cli_options):
if (not blobxfer.util.is_none_or_empty(config) and
( not in config or
config[] not in _SUPPORTED_YAML_CONFIG_VERSIONS)):
raise ValueError()
action = cli_options[]
if (action != TransferAction.Upload.name.low... | Merge "global" CLI options into main config
:param dict config: config dict
:param dict cli_options: cli options |
352,967 | def maybe_get_common_dtype(arg_list):
if all(a is None for a in arg_list):
return None
return dtype_util.common_dtype(arg_list, tf.float32) | Return common dtype of arg_list, or None.
Args:
arg_list: an iterable of items which are either `None` or have a `dtype`
property.
Returns:
dtype: The common dtype of items in `arg_list`, or `None` if the list is
empty or all items are `None`. |
352,968 | def read_file(fname, *args, **kwargs):
if not isstr(fname):
raise ValueError(
)
logger().info(.format(fname))
format_kwargs = {}
for c in [i for i in IAMC_IDX + [, , ] if i in kwargs]:
format_kwargs[c] = kwargs.pop(c)
return format_data(read_pandas(... | Read data from a file saved in the standard IAMC format
or a table with year/value columns |
352,969 | def get_application_info(self, limit=10, offset=10):
params = {}
if offset:
params[] = offset
if limit:
params[] = limit
url =
return self.get(url, params=params) | Information about applications
:param limit:
:param offset:
:return: |
352,970 | def schema_term(self):
if not self.name:
raise MetapackError("Resource for url doe not have name".format(self.url))
t = self.doc.find_first(, value=self.get_value())
frm =
if not t:
t = self.doc.find_first(, value=self.get_value())
frm = ... | Return the Table term for this resource, which is referenced either by the `table` property or the
`schema` property |
352,971 | def _parse_da(self):
if not self._text_da:
return
font = "Helv"
fsize = 0
col = (0, 0, 0)
dat = self._text_da.split()
for i, item in enumerate(dat):
if item == "Tf":
font = dat[i - 2][1:]
fsize... | Extract font name, size and color from default appearance string (/DA object). Equivalent to 'pdf_parse_default_appearance' function in MuPDF's 'pdf-annot.c'. |
352,972 | def prepare_csv_to_dataframe(data_file, config, use_target=True):
names, dtypes = [], []
model = config.get_data_model()
for feature in model:
assert feature.get_name() not in names, "Two features can't have the same name."
if not use_target and feature.is_target():
continue... | Parses the given data file following the data model of the given configuration.
@return: pandas DataFrame |
352,973 | def detect_fold_level(self, prev_block, block):
text = block.text()
prev_lvl = TextBlockHelper().get_fold_lvl(prev_block)
indent_len = 0
if (prev_lvl and prev_block is not None and
not self.editor.is_comment(prev_block)):
pre... | Detects fold level by looking at the block indentation.
:param prev_block: previous text block
:param block: current block to highlight |
352,974 | def create(model: ModelFactory, discount_factor: float, target_update_frequency: int,
max_grad_norm: float, double_dqn: bool = False):
return DistributionalDeepQLearning(
model_factory=model,
discount_factor=discount_factor,
double_dqn=double_dqn,
target_update_freque... | Vel factory function |
352,975 | def get_command_history(self, issued_command):
entry = issued_command._proto.commandQueueEntry
key = self._cache_key(entry.cmdId)
if key in self._cache:
return self._cache[key]
return None | Gets locally cached CommandHistory for the specified command.
:param .IssuedCommand issued_command: object representing a
previously issued command.
:rtype: .CommandHistory |
352,976 | def waitForURL(url, max_seconds=None):
startTime = datetime.now()
while True:
response = None
try:
response = urllib2.urlopen(HEADREQUEST(url))
except urllib2.URLError:
pass
if response is not None and isinstance(response, urllib2.addinfourl):
... | Give it a URL. Keep trying to get a HEAD request from it until it works.
If it doesn't work, wait a while and try again |
352,977 | def deserialize_dtype(d):
if isinstance(d[], six.string_types):
return np.dtype(d[])
descr = []
for col in d[]:
col_descr = []
for c in col:
if isinstance(c, six.string_types):
col_descr.append(str(c))
elif type(c) is list:
... | Deserializes a JSONified :obj:`numpy.dtype`.
Args:
d (:obj:`dict`): A dictionary representation of a :obj:`dtype` object.
Returns:
A :obj:`dtype` object. |
352,978 | def _get_or_add_definition(self):
if self._has_definition:
return self._definition
prior_headerfooter = self._prior_headerfooter
if prior_headerfooter:
return prior_headerfooter._get_or_add_definition()
return self._add... | Return HeaderPart or FooterPart object for this section.
If this header/footer inherits its content, the part for the prior header/footer
is returned; this process continue recursively until a definition is found. If
the definition cannot be inherited (because the header/footer belongs to the
... |
352,979 | def execute(filelocation, args, outdir, filters=None,
executable=):
procArgs = [executable, filelocation]
procArgs.extend(aux.toList(args))
if filters is not None:
for arg in aux.toList(filters):
procArgs.extend([, arg])
procArgs.extend([, outdir])
proc = ... | Execute the msConvert tool on Windows operating systems.
:param filelocation: input file path
:param args: str() or list(), msConvert arguments for details see the
msConvert help below.
:param outdir: path of the output directory
:param filters: str() or list(), specify additional parameters an... |
352,980 | def atomic_batch_mutate(self, mutation_map, consistency_level):
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_atomic_batch_mutate(mutation_map, consistency_level)
return d | Atomically mutate many columns or super columns for many row keys. See also: Mutation.
mutation_map maps key to column family to a list of Mutation objects to take place at that scope.
*
Parameters:
- mutation_map
- consistency_level |
352,981 | def _get_src(tree_base, source, saltenv=):
parsed = _urlparse(source)
sbase = os.path.basename(source)
dest = os.path.join(tree_base, sbase)
if parsed.scheme:
__salt__[](source, dest, saltenv=saltenv)
else:
shutil.copy(source, dest) | Get the named sources and place them into the tree_base |
352,982 | def key_type(key, host=None, port=None, db=None, password=None):
*
server = _connect(host, port, db, password)
return server.type(key) | Get redis key type
CLI Example:
.. code-block:: bash
salt '*' redis.type foo |
352,983 | def as_random_variable(distribution,
sample_shape=(),
value=None):
return _build_custom_rv(distribution=distribution,
sample_shape=sample_shape,
value=value,
name=_simple_name(distribution)) | Wrap an existing distribution as a traceable random variable.
This enables the use of custom or user-provided distributions in
Edward models. Unlike a bare `RandomVariable` object, this method
wraps the constructor so it is included in the Edward trace and its
values can be properly intercepted and overridden.... |
352,984 | def freeze(self, freeze: bool = True):
for topic in self._topics.values():
topic.freeze()
self._frozen = freeze | Freezing the hub means that each topic has to be assigned and no
new topics can be created after this point. |
352,985 | def cleanup_on_delete(self, sender, document, **kwargs):
if not self.follow or sender is not self.owner_document:
return
slug = getattr(document, self.db_field)
namespace = self.owner_document.__name__
SlugFollow.objects(namespace=namespace, new_slug=slug).delete() | Clean up slug redirections on object deletion |
352,986 | def get_ready_data_nodes(self, seed_path, gather_depth):
try:
seed_node = self.get_node(seed_path)
except MissingBranchError:
return []
all_paths = seed_node._get_all_paths(seed_path, gather_depth)
ready_data_nodes = []
for path in all_paths:
... | Returns a list [(path1,data_node1),...]
with entries only for existing nodes with DataObjects where is_ready==True.
Missing nodes or those with non-ready or non-existing data are ignored. |
352,987 | def run_select_calculation(self):
inputs = {
: self.ctx.cif,
: self.inputs.cif_select,
: self.inputs.cif_select_parameters,
: {
: self.inputs.options.get_dict(),
}
}
calculation = self.submit(CifSelectCalculati... | Run the CifSelectCalculation on the CifData output node of the CifFilterCalculation. |
352,988 | def query(transport, query):
with CommandLineClient(transport) as client:
echo_event(client.query(query)) | Query the Riemann server |
352,989 | def parse_region(self, login_response):
auth_token = login_response.cgx_content[]
auth_token_dict = self.parse_auth_token(auth_token)
auth_region = auth_token_dict.get()
return auth_region | Return region from a successful login response.
**Parameters:**
- **login_response:** requests.Response from a successful login.
**Returns:** region name. |
352,990 | def plugged_usbs(multiple=True) -> map or dict:
class FindPenDrives(object):
def __init__(self, class_):
self._class = class_
def __call__(self, device):
intf = usb.util.find_descriptor(cfg, bInterfaceClass=self._class)
if intf... | Gets the plugged-in USB Flash drives (pen-drives).
If multiple is true, it returns a map, and a dict otherwise.
If multiple is false, this method will raise a :class:`.NoUSBFound` if no USB is found. |
352,991 | def convert_value(self, v):
def stringify(value):
if self.encoding is not None:
encoder = partial(pprint_thing_encoded,
encoding=self.encoding)
else:
encoder = pprint_thing
return encoder(value)
... | convert the expression that is in the term to something that is
accepted by pytables |
352,992 | def gather(self, iterable):
for result in self.lookup(iterable, gather=True):
yield result | Calls the lookup with gather True Passing iterable and yields
the result. |
352,993 | def __get_name(self):
if self.is_new:
return _("New document")
try:
split = self.__docid.split("_")
short_docid = "_".join(split[:3])
datetime_obj = datetime.datetime.strptime(
short_docid, self.DOCNAME_FORMAT)
final = ... | Returns the localized name of the document (see l10n) |
352,994 | def schedule_ping_frequency(self):
"Send a ping message to slack every 20 seconds"
ping = crontab(, func=self.send_ping, start=False)
ping.start() | Send a ping message to slack every 20 seconds |
352,995 | def getPDT(typename):
if typename not in PrimitiveTypeMap and typename.startswith("S"):
PrimitiveTypeMap[typename] = PrimitiveType(typename)
return PrimitiveTypeMap.get(typename, None) | get(typename) -> PrimitiveType
Returns the PrimitiveType for typename or None. |
352,996 | def get_dependency_tuple_list_for_recipe(recipe, blacklist=None):
if blacklist is None:
blacklist = set()
assert(type(blacklist) == set)
if recipe.depends is None:
dependencies = []
else:
dependencies = fix_deplist(recipe.depends)
dependencies = [
... | Get the dependencies of a recipe with filtered out blacklist, and
turned into tuples with fix_deplist() |
352,997 | def add_policy(self, scaling_group, name, policy_type, cooldown,
change=None, is_percent=False, desired_capacity=None, args=None):
uri = "/%s/%s/policies" % (self.uri_base, utils.get_id(scaling_group))
body = self._create_policy_body(name, policy_type, cooldown,
chan... | Adds a policy with the given values to the specified scaling group. The
'change' parameter is treated as an absolute amount, unless
'is_percent' is True, in which case it is treated as a percentage. |
352,998 | def update_port_precommit(self, context):
vnic_type = context.current.get(bc.portbindings.VNIC_TYPE,
bc.portbindings.VNIC_NORMAL)
profile = context.current.get(bc.portbindings.PROFILE, {})
host_id = self._get_host_id(
context.current.... | Adds port profile and vlan information to the DB.
Assign a port profile to this port. To do that:
1. Get the vlan_id associated with the bound segment
2. Check if a port profile already exists for this vlan_id
3. If yes, associate that port profile with this port.
4. If no, crea... |
352,999 | def create(self):
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
db_name = self.database_id
if "-" in db_name:
db_name = "`%s`" % (db_name,)
future = api.create_database(
parent=self._instance.name,
... | Create this database within its instance
Inclues any configured schema assigned to :attr:`ddl_statements`.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase
:rtype: :class:`~google.api_core... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.