Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
384,800 | def filter_by_analysis_period(self, analysis_period):
_filtered_data = self.filter_by_months(analysis_period.months_int)
_filtered_data.header._analysis_period = analysis_period
return _filtered_data | Filter the Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data |
384,801 | def runDeferred(self, deferred):
for handler, scope, offset in deferred:
self.scopeStack = scope
self.offset = offset
handler() | Run the callables in C{deferred} using their associated scope stack. |
384,802 | def initialize_weights(self):
n = self._outputSize
m = self._inputSize
self._Q = self._random.sample((n,m))
for i in range(n):
self._Q[i] /= np.sqrt( np.dot(self._Q[i], self._Q[i]) ) | Randomly initializes the visible-to-hidden connections. |
384,803 | def discard(self, value):
hash(value)
self.redis.srem(self.key, self._pickle(value)) | Remove element *value* from the set if it is present. |
384,804 | def _check_d1_characters(name):
bytename = bytearray(name)
for char in bytename:
if char not in _allowed_d1_characters:
raise pycdlibexception.PyCdlibInvalidInput() | A function to check that a name only uses d1 characters as defined by ISO9660.
Parameters:
name - The name to check.
Returns:
Nothing. |
384,805 | def controller(self):
if hasattr(self, ):
if len(self.controller_info[]) > 1:
raise TypeError(
)
return self.controller_id
raise AttributeError() | Check if multiple controllers are connected.
:returns: Return the controller_id of the active controller.
:rtype: string |
384,806 | def _get_bucket(self, bucket_name):
t exist, create it.
Parameters
==========
bucket_name: the name of the bucket to get (or create). It should
not contain google, and should be all lowercase with -
or underscores.
Cannot ... | get a bucket based on a bucket name. If it doesn't exist, create it.
Parameters
==========
bucket_name: the name of the bucket to get (or create). It should
not contain google, and should be all lowercase with -
or underscores. |
384,807 | def listen(self, event):
if event in self.registered:
return
def handler(client, *args):
return self.process_event(event, client, args)
self.client.add_handler(event, handler)
self.registered.add(event)
_log.debug("Controller is now l... | Request that the Controller listen for and dispatch an event.
Note: Even if the module that requested the listening is later
unloaded, the Controller will continue to dispatch the event, there
just might not be anything that cares about it. That's okay. |
384,808 | def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
observed=False, mutated=False, validate=True):
group_axis = obj._get_axis(axis)
if level is not None:
if isinstance(group_axis, MultiInd... | create and return a BaseGrouper, which is an internal
mapping of how to create the grouper indexers.
This may be composed of multiple Grouping objects, indicating
multiple groupers
Groupers are ultimately index mappings. They can originate as:
index mappings, keys to columns, functions, or Groupers... |
384,809 | def _prodterm_prime(lexer):
tok = next(lexer)
else:
lexer.unpop_token(tok)
return None | Return a product term' expression, eliminates left recursion. |
384,810 | def get_wcs(self, data_x, data_y):
img = self.fitsimage.get_image()
ra, dec = img.pixtoradec(data_x, data_y)
return ra, dec | Return (re_deg, dec_deg) for the (data_x, data_y) position
based on any WCS associated with the loaded image. |
384,811 | def set_table_cb(self, viewer, table):
self.clear()
tree_dict = OrderedDict()
a_tab = table.get_data()
try:
a_tab = a_tab.filled()
except Exception:
pass
i_fmt = .format(len(str(len(a_tab))))
... | Display the given table object. |
384,812 | def disable_svc_notifications(self, service):
if service.notifications_enabled:
service.modified_attributes |= \
DICT_MODATTR["MODATTR_NOTIFICATIONS_ENABLED"].value
service.notifications_enabled = False
self.send_an_element(service.get_update_status_b... | Disable notifications for a service
Format of the line that triggers function call::
DISABLE_SVC_NOTIFICATIONS;<host_name>;<service_description>
:param service: service to edit
:type service: alignak.objects.service.Service
:return: None |
384,813 | def list_resources(self, device_id):
api = self._get_api(mds.EndpointsApi)
return [Resource(r) for r in api.get_endpoint_resources(device_id)] | List all resources registered to a connected device.
.. code-block:: python
>>> for r in api.list_resources(device_id):
print(r.name, r.observable, r.uri)
None,True,/3/0/1
Update,False,/5/0/3
...
:param str device_id: The ID of the d... |
384,814 | def run_model(self, model_run, run_url):
try:
credentials = pika.PlainCredentials(self.user, self.password)
con = pika.BlockingConnection(pika.ConnectionParameters(
host=self.host,
port=self.port,
virtual... | Run model by sending message to RabbitMQ queue containing the
run end experiment identifier. Messages are persistent to ensure that
a worker will process process the run request at some point.
Throws a EngineException if communication with the server fails.
Parameters
---------... |
384,815 | def warning(self, *msg):
label = colors.yellow("WARNING")
self._msg(label, *msg) | Prints a warning |
384,816 | def endpoints(self):
if not self.__endpoints:
self.__endpoints = Endpoints(self.__connection)
return self.__endpoints | Gets the Endpoints API client.
Returns:
Endpoints: |
384,817 | def lithospheric_stress(step, trench, ridge, time):
timestep = step.isnap
base_lith = step.geom.rcmb + 1 - 0.105
stressfld = step.fields[][0, :, :, 0]
stressfld = np.ma.masked_where(step.geom.r_mesh[0] < base_lith, stressfld)
dzm = (step.geom.r_coord[1:] - step.geom.r_coord[:-1])
str... | calculate stress in the lithosphere |
384,818 | def collect(self):
def traverse(d, metric_name=):
for key, value in d.iteritems():
if isinstance(value, dict):
if metric_name == :
metric_name_next = key
else:
metric_name_ne... | Publish all mdstat metrics. |
384,819 | def aggregationToMonthsSeconds(interval):
seconds = interval.get(, 0) * 0.000001
seconds += interval.get(, 0) * 0.001
seconds += interval.get(, 0)
seconds += interval.get(, 0) * 60
seconds += interval.get(, 0) * 60 * 60
seconds += interval.get(, 0) * 24 * 60 * 60
seconds += interval.get(, 0) * 7 * 24 ... | Return the number of months and seconds from an aggregation dict that
represents a date and time.
Interval is a dict that contain one or more of the following keys: 'years',
'months', 'weeks', 'days', 'hours', 'minutes', seconds', 'milliseconds',
'microseconds'.
For example:
::
aggregationMicrosecon... |
384,820 | def address_checksum_and_decode(addr: str) -> Address:
if not is_0x_prefixed(addr):
raise InvalidAddress()
if not is_checksum_address(addr):
raise InvalidAddress()
addr_bytes = decode_hex(addr)
assert len(addr_bytes) in (20, 0)
return Address(addr_bytes) | Accepts a string address and turns it into binary.
Makes sure that the string address provided starts is 0x prefixed and
checksummed according to EIP55 specification |
384,821 | def contour(z, x=None, y=None, v=5, xlbl=None, ylbl=None, title=None,
cfntsz=10, lfntsz=None, intrp=, alpha=0.5, cmap=None,
vmin=None, vmax=None, fgsz=None, fgnm=None, fig=None, ax=None):
figp = fig
if fig is None:
fig = plt.figure(num=fgnm, figsize=fgsz)
fig.clf()
... | Contour plot of a 2D surface. If a figure object is specified then the
plot is drawn in that figure, and ``fig.show()`` is not called. The
figure is closed on key entry 'q'.
Parameters
----------
z : array_like
2d array of data to plot
x : array_like, optional (default None)
Val... |
384,822 | def check_honeypot(func=None, field_name=None):
if isinstance(func, six.string_types):
func, field_name = field_name, func
def decorated(func):
def inner(request, *args, **kwargs):
response = verify_honeypot_value(request, field_name)
if response:
... | Check request.POST for valid honeypot field.
Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if
not specified. |
384,823 | def _gen_delta_per_sec(self, path, value_delta, time_delta, multiplier,
prettyname, device):
if time_delta < 0:
return
value = (value_delta / time_delta) * multiplier
if value > 0.0:
self._replace_and_publish(path, pre... | Calulates the difference between to point, and scales is to per second. |
384,824 | def azimuth(lons1, lats1, lons2, lats2):
lons1, lats1, lons2, lats2 = _prepare_coords(lons1, lats1, lons2, lats2)
cos_lat2 = numpy.cos(lats2)
true_course = numpy.degrees(numpy.arctan2(
numpy.sin(lons1 - lons2) * cos_lat2,
numpy.cos(lats1) * numpy.sin(lats2)
- numpy.sin(lats1) * ... | Calculate the azimuth between two points or two collections of points.
Parameters are the same as for :func:`geodetic_distance`.
Implements an "alternative formula" from
http://williams.best.vwh.net/avform.htm#Crs
:returns:
Azimuth as an angle between direction to north from first point and
... |
384,825 | def __locate_scubainit(self):
pkg_path = os.path.dirname(__file__)
self.scubainit_path = os.path.join(pkg_path, )
if not os.path.isfile(self.scubainit_path):
raise ScubaError(.format(self.scubainit_path)) | Determine path to scubainit binary |
384,826 | def GetStartTime(self, problems=problems_module.default_problem_reporter):
cursor = self._schedule._connection.cursor()
cursor.execute(
, (self.trip_id,))
(arrival_secs, departure_secs) = cursor.fetchone()
if arrival_secs != None:
return arrival_secs
elif departure_secs !... | Return the first time of the trip. TODO: For trips defined by frequency
return the first time of the first trip. |
384,827 | def sample(self, N=1):
if not self.filt:
self.forward()
paths = np.empty((len(self.filt), N), np.int)
paths[-1, :] = rs.multinomial(self.filt[-1], M=N)
log_trans = np.log(self.hmm.trans_mat)
for t, f in reversed(list(enumerate(self.filt[:-1]))):
f... | Sample N trajectories from the posterior.
Note
----
Performs the forward step in case it has not been performed. |
384,828 | def StrIndexOf(input_string, substring, startIndex, bitlength):
try:
s = input_string.value
t = substring.value
i = startIndex.value
return BVV(i + s[i:].index(t), bitlength)
except ValueError:
return BVV(-1, bitlength) | Return True if the concrete value of the input_string ends with suffix
otherwise false.
:param input_string: the string we want to check
:param substring: the substring we want to find the index
:param startIndex: the index to start searching at
:param bitlength: bitlength of the bitvector represen... |
384,829 | def add_fluctuations(hdf5_file, N_columns, N_processes):
random_state = np.random.RandomState(0)
slice_queue = multiprocessing.JoinableQueue()
pid_list = []
for i in range(N_processes):
worker = Fluctuations_worker(hdf5_file,
, random_state,
... | This procedure organizes the addition of small fluctuations on top of
a matrix of similarities at 'hdf5_file' across 'N_processes'
different processes. Each of those processes is an instance of the
class 'Fluctuations_Worker' defined elsewhere in this module. |
384,830 | def accuracy_helper(egg, match=, distance=,
features=None):
def acc(lst):
return len([i for i in np.unique(lst) if i>=0])/(egg.list_length)
opts = dict(match=match, distance=distance, features=features)
if match is :
opts.update({ : })
recmat = recall_matrix(eg... | Computes proportion of words recalled
Parameters
----------
egg : quail.Egg
Data to analyze
match : str (exact, best or smooth)
Matching approach to compute recall matrix. If exact, the presented and
recalled items must be identical (default). If best, the recalled item
... |
384,831 | def align_bam(in_bam, ref_file, names, align_dir, data):
config = data["config"]
out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"]))
samtools = config_utils.get_program("samtools", config)
bedtools = config_utils.get_program("bedtools", config)
resources = config_utils.get_... | Perform direct alignment of an input BAM file with BWA using pipes.
This avoids disk IO by piping between processes:
- samtools sort of input BAM to queryname
- bedtools conversion to interleaved FASTQ
- bwa-mem alignment
- samtools conversion to BAM
- samtools sort to coordinate |
384,832 | def _CallWindowsNetCommand(parameters):
import subprocess
popen = subprocess.Popen(["net"] + parameters, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdoutdata, stderrdata = popen.communicate()
if stderrdata:
raise OSError("Failed on call net.exe: %s" % stderrdata)
return stdoutda... | Call Windows NET command, used to acquire/configure network services settings.
:param parameters: list of command line parameters
:return: command output |
384,833 | def register(self, token, regexp):
self._tokens.append((token, re.compile(regexp))) | Register a token.
Args:
token (Token): the token class to register
regexp (str): the regexp for that token |
384,834 | def turn_right(self, angle_degrees, rate=RATE):
flight_time = angle_degrees / rate
self.start_turn_right(rate)
time.sleep(flight_time)
self.stop() | Turn to the right, staying on the spot
:param angle_degrees: How far to turn (degrees)
:param rate: The trurning speed (degrees/second)
:return: |
384,835 | def walk_dependencies(root, visitor):
def visit(parent, visitor):
for d in get_dependencies(parent):
visitor(d, parent)
visit(d, visitor)
visitor(root, None)
visit(root, visitor) | Call visitor on root and all dependencies reachable from it in breadth
first order.
Args:
root (component): component function or class
visitor (function): signature is `func(component, parent)`. The
call on root is `visitor(root, None)`. |
384,836 | def activities(self, *args, **kwargs):
if self._client.match_app_version(label=, version=, default=True):
return self._client.activities(*args, scope=self.id, **kwargs)
else:
return self._client.activities(*args, scope_id=self.id, **kwargs) | Retrieve activities belonging to this scope.
See :class:`pykechain.Client.activities` for available parameters. |
384,837 | def delete(self, ids):
url = build_uri_with_ids(, ids)
return super(ApiVlan, self).delete(url) | Method to delete vlan's by their ids
:param ids: Identifiers of vlan's
:return: None |
384,838 | def execute(self):
python_tgts = self.context.targets(
lambda tgt: isinstance(tgt, (PythonTarget))
)
if not python_tgts:
return 0
interpreter_cache = PythonInterpreterCache.global_instance()
with self.invalidated(self.get_targets(self._is_checked)) as invalidation_check:
failu... | Run Checkstyle on all found non-synthetic source files. |
384,839 | def add_details(file_name, title, artist, album, lyrics=""):
tags = EasyMP3(file_name)
tags["title"] = title
tags["artist"] = artist
tags["album"] = album
tags.save()
tags = ID3(file_name)
uslt_output = USLT(encoding=3, lang=u, desc=u, text=lyrics)
tags["USLT::"] = uslt_output
... | Adds the details to song |
384,840 | def lower_camel(string, prefix=, suffix=):
return require_valid(append_underscore_if_keyword(.join(
word.lower() if index == 0 else upper_case_first_char(word)
for index, word in enumerate(en.words(.join([prefix, string, suffix]))))
)) | Generate a camel-case identifier.
Useful for unit test methods.
Takes a string, prefix, and optional suffix.
`prefix` can be set to `''`, though be careful - without a prefix, the
function will throw `InvalidIdentifier` when your string starts with a
number.
Example:
>>> lower_camel("... |
384,841 | def __send_command(
self, name, args=None, withcontent=False, extralines=None,
nblines=-1):
tosend = name.encode("utf-8")
if args:
tosend += b" " + b" ".join(self.__prepare_args(args))
self.__dprint(b"Command: " + tosend)
self.sock.sendall(tos... | Send a command to the server.
If args is not empty, we concatenate the given command with
the content of this list. If extralines is not empty, they are
sent one by one to the server. (CLRF are automatically
appended to them)
We wait for a response just after the command has be... |
384,842 | def avail_sizes(call=None):
if call == :
raise SaltCloudSystemExit(
)
conn = get_conn()
sizes = conn.fixed_server_flavors()
return sizes | Return a dict of all available VM sizes on the cloud provider with
relevant data. |
384,843 | def log_likelihood_pairwise(data, params):
loglik = 0
for winner, loser in data:
loglik -= np.logaddexp(0, -(params[winner] - params[loser]))
return loglik | Compute the log-likelihood of model parameters. |
384,844 | def read(self, size=None):
if not self.fd:
raise ValueError()
if not size:
size = self.remaining
size = min([self.remaining, size])
if not size:
return
data = self.fd.read(size)
self.remaining -= size
return data | Read a specified number of bytes from the file descriptor
This method emulates the normal file descriptor's ``read()`` method and
restricts the total number of bytes readable.
If file descriptor is not present (e.g., ``close()`` method had been
called), ``ValueError`` is raised.
... |
384,845 | def file_root_name(name):
base = os.path.basename(name)
root = os.path.splitext(base)[0]
if not root:
warning =
log.warning(warning.format(name))
return root | Returns the root name of a file from a full file path.
It will not raise an error if the result is empty, but an warning will be
issued. |
384,846 | def synthesize_software_module_info(modules, module_types):
res = {}
for mod_id, mod_info in modules.items():
mod_info = dict(mod_info)
mod_type = module_types[mod_info["type"]]
mod_info["package"] = mod_type["package"]
mod_info["executable"] = mod_type["executable... | This function takes as input a dictionary of `modules` (mapping module IDs
to :class:`~openag.models.SoftwareModule` objects) and a dictionary of
`module_types` (mapping module type IDs to
:class:`~openag.models.FirmwareModuleType` objects). For each module, it
synthesizes the information in that module... |
384,847 | def setupArgparse():
parser = argparse.ArgumentParser()
parser.add_argument("callsign", help="Callsign of radio")
parser.add_argument("id", type=int, help="ID number radio")
parser.add_argument("-l", "--loopback", action="store_true",
help="Use software loopback ... | Sets up argparse module to create command line options and parse them.
Uses the argparse module to add arguments to the command line for
faradayio-cli. Once the arguments are added and parsed the arguments are
returned
Returns:
argparse.Namespace: Populated namespace of arguments |
384,848 | def update_wish_list_by_id(cls, wish_list_id, wish_list, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._update_wish_list_by_id_with_http_info(wish_list_id, wish_list, **kwargs)
else:
(data) = cls._update_wish_list_by_id_with_http_info(wish_list_id, wish_... | Update WishList
Update attributes of WishList
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_wish_list_by_id(wish_list_id, wish_list, async=True)
>>> result = thread.get()
:pa... |
384,849 | def is_job_config(config):
try:
if config[][][] is not None:
return True
except KeyError:
return False
except TypeError:
return False
except IndexError:
return False
return False | Check whether given dict of config is job config |
384,850 | def update(self, iterable={}, **kwargs):
def _merge(a, *args):
for key, value in itertools.chain(*args):
if key in a and isinstance(value, (dict, Conf)):
value = _merge(a[key], value.items())
a[key] = value
return a
... | Updates recursively a self with a given iterable.
TODO: rewrite this ugly stuff |
384,851 | def _load_enums(root):
out = collections.OrderedDict()
for elem in root.findall():
name = elem.attrib[]
value = elem.attrib[]
comment = elem.get()
out[name] = Enum(name, value, comment)
return out | Returns {name: Enum} |
384,852 | def alter_edge(self, from_index, to_index,
new_weight=None, new_edge_properties=None):
existing_edge = self.graph.get_edge_data(from_index, to_index)
if not existing_edge:
raise ValueError("Edge between {} and {} cannot be altered;\
... | Alters either the weight or the edge_properties of
an edge in the MoleculeGraph.
:param from_index: int
:param to_index: int
:param new_weight: alter_edge does not require
that weight be altered. As such, by default, this
is None. If weight is to be changed, it should be... |
384,853 | def cmd(send, msg, args):
if msg and not check_exists(msg):
send("Non-existant subreddit.")
return
subreddit = msg if msg else None
send(random_post(subreddit, args[][][])) | Gets a random Reddit post.
Syntax: {command} [subreddit] |
384,854 | def query(self, coords, return_sigma=False):
n_coords_ret = coords.shape[0]
has_dist = hasattr(coords.distance, )
d = coords.distance.kpc if has_dist else None
pix_idx = self._coords2idx(coords)
mask_idx = (pix_idx == self._n_pix)
if... | Returns r-band extinction, A_r, at the given coordinates. Can also
return uncertainties.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
return_sigma (Optional[:obj:`bool`]): If ``True``, returns the uncertainty in
extinction as well... |
384,855 | def makepipecomponent(idf, pname):
apipe = idf.newidfobject("Pipe:Adiabatic".upper(), Name=pname)
apipe.Inlet_Node_Name = "%s_inlet" % (pname,)
apipe.Outlet_Node_Name = "%s_outlet" % (pname,)
return apipe | make a pipe component
generate inlet outlet names |
384,856 | def _match_files_flat_hierarchy(self, text_files, audio_files):
self.log(u"Matching files in flat hierarchy")
self.log([u"Text files: ", text_files])
self.log([u"Audio files: ", audio_files])
d_text = {}
d_audio = {}
for text_file in text_files:
text_... | Match audio and text files in flat hierarchies.
Two files match if their names,
once removed the file extension,
are the same.
Examples: ::
foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"]
foo/text/a.txt foo/audio/b.mp3 => no ... |
384,857 | def parse_requested_expands(query_key, request):
requested_expands = []
for key, val in request.params.items():
if key == query_key:
requested_expands += val.split()
return requested_expands | Extracts the value of the expand query string parameter from a request.
Supports comma separated lists.
:param query_key: The name query string parameter.
:param request: Request instance.
:return: List of strings representing the values of the expand query string value. |
384,858 | def _scalar_power(self, f, p, out):
f_copy = f.copy()
def pow_posint(x, n):
if isinstance(x, np.ndarray):
y = x.copy()
return ipow_posint(y, n)
else:
return x ** n
def ipow_posint(x, n):
... | Compute ``p``-th power of ``f`` for ``p`` scalar. |
384,859 | def find_pulls(self, testpulls=None):
result = {}
for lname, repo in self.repositories.items():
if lname not in self.archive:
raise ValueError("Trying to find pull requests for a repository "
"that hasnt eve... | Finds a list of new pull requests that need to be processed.
:arg testpulls: a list of tserver.FakePull instances so we can test the code
functionality without making live requests to github. |
384,860 | def toggle_buttons(self):
all_time_on = self.all_time.get_value()
all_chan_on = self.all_chan.get_value()
self.times[].setEnabled(not all_time_on)
self.times[].setEnabled(not all_time_on)
self.idx_chan.setEnabled(not all_chan_on) | Turn buttons on and off. |
384,861 | def get_selinux_status():
getenforce_command_exists()
o = run_cmd(["getenforce"], return_output=True).strip()
logger.debug("SELinux is %r", o)
return o | get SELinux status of host
:return: string, one of Enforced, Permissive, Disabled |
384,862 | def update(self, *args, **kwargs):
for next_dict in chain(args, (kwargs, )):
for k, v in next_dict.items():
self[k] = v | Equivalent to the python dict update method.
Update the dictionary with the key/value pairs from other, overwriting
existing keys.
Args:
other (dict): The source of key value pairs to add to headers
Keyword Args:
All keyword arguments are stored in header direct... |
384,863 | def to_designspace_instances(self):
for instance in self.font.instances:
if self.minimize_glyphs_diffs or (
is_instance_active(instance)
and _is_instance_included_in_family(self, instance)
):
_to_designspace_instance(self, instance) | Write instance data from self.font to self.designspace. |
384,864 | def insured_losses(losses, deductible, insured_limit):
return numpy.piecewise(
losses,
[losses < deductible, losses > insured_limit],
[0, insured_limit - deductible, lambda x: x - deductible]) | :param losses: an array of ground-up loss ratios
:param float deductible: the deductible limit in fraction form
:param float insured_limit: the insured limit in fraction form
Compute insured losses for the given asset and losses, from the point
of view of the insurance company. For instance:
>>> i... |
384,865 | def on_data(self, raw_data):
data = json.loads(raw_data)
message_type = data[].get()
prepare_method = % (message_type)
args = getattr(self, prepare_method, self.prepare_fallback)(data.get())
method_name = % (message_type,)
func = getattr(self, method_name, se... | Called when raw data is received from connection.
Override this method if you wish to manually handle
the stream data. Return False to stop stream and close connection. |
384,866 | def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s"):
if dest_path == os.devnull:
yield dest_path
else:
tmp_path = ("%s" + suffix) % (dest_path, new_uid())
if make_parents:
make_parent_dirs(tmp_path)
yield tmp_path
if backup_suffix:... | A context manager for convenience in writing a file or directory in an atomic way. Set up
a temporary name, then rename it after the operation is done, optionally making a backup of
the previous file or directory, if present. |
384,867 | def stupid_hack(most=10, wait=None):
if wait is not None:
time.sleep(wait)
else:
time.sleep(random.randrange(1, most)) | Return a random time between 1 - 10 Seconds. |
384,868 | def read_pl_dataset(infile):
m, n = [int(i) for i in infile.readline().split()]
gamma = np.array([float(f) for f in infile.readline().split()])
if len(gamma) != m:
infile.close()
raise ValueError("malformed file: len(gamma) != m")
votes = []
i = 0
for line in infi... | Description:
Read from disk a Plackett-Luce dataset.
Parameters:
infile: open file object from which to read the dataset |
384,869 | def get_livestate(self):
livestate = 0
if self.active:
if not self.reachable:
livestate = 1
elif not self.alive:
livestate = 2
else:
livestate = 3
livestate_output = "%s/%s is %s" % (self.type, self.name, [
... | Get the SatelliteLink live state.
The live state is a tuple information containing a state identifier and a message, where:
state is:
- 0 for an up and running satellite
- 1 if the satellite is not reachale
- 2 if the satellite is dead
- 3 else (not a... |
384,870 | def validate(self, validator=None, skip_relations=False):
validator = validation.make_validator(validator)
self.log()
self.preload()
required = [
,
,
,
,
,
]
for f in required:
self.log("Validating required file: %s"%f)
data = self.read(... | Validate a GTFS
:param validator: a ValidationReport
:param (bool) skip_relations: skip validation of relations between entities (e.g. stop_times to stops)
:return: |
384,871 | def delete_feed(self, pid):
logger.info("delete_feed(pid=\"%s\") [lid=%s]", pid, self.__lid)
return self.__delete_point(R_FEED, pid) | Delete a feed, identified by its local id.
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a... |
384,872 | def save(self) -> None:
path = str(self.save_path.absolute())
log.info(.format(path))
self._net.save(path) | Saves model to the save_path, provided in config. The directory is
already created by super().__init__, which is called in __init__ of this class |
384,873 | def from_url(cls, url, **kwargs):
url = urllib3.util.parse_url(url)
if url.host:
kwargs.setdefault(, url.host)
if url.port:
kwargs.setdefault(, url.port)
if url.scheme == :
kwargs.setdefault(, urllib3.HTTPSConnectionPool)
return cls... | Create a client from a url. |
384,874 | def LockRetryWrapper(self,
subject,
retrywrap_timeout=1,
retrywrap_max_timeout=10,
blocking=True,
lease_time=None):
timeout = 0
while timeout < retrywrap_max_timeout:
try:
return... | Retry a DBSubjectLock until it succeeds.
Args:
subject: The subject which the lock applies to.
retrywrap_timeout: How long to wait before retrying the lock.
retrywrap_max_timeout: The maximum time to wait for a retry until we
raise.
blocking: If False, raise on first lock failure.
... |
384,875 | def parse_uci(self, uci: str) -> Move:
move = Move.from_uci(uci)
if not move:
return move
move = self._to_chess960(move)
move = self._from_chess960(self.chess960, move.from_square, move.to_square, move.promotion, move.drop)
if not self.is_legal(move):
... | Parses the given move in UCI notation.
Supports both Chess960 and standard UCI notation.
The returned move is guaranteed to be either legal or a null move.
:raises: :exc:`ValueError` if the move is invalid or illegal in the
current position (but not a null move). |
384,876 | def add_prefix_from_pool(arg, opts):
args = {}
if in opts:
res = Pool.list({ : opts[] })
if len(res) == 0:
print("No pool named found." % opts[], file=sys.stderr)
sys.exit(1)
args[] = res[0]
if not in opts:
print("ERROR: You have to sp... | Add prefix using from-pool to NIPAP |
384,877 | def _parse_vars_tbl(self, var_tbl):
T = self._check_forward_mode_input_dict(var_tbl)
shape = (T, 1)
X = np.zeros(shape)
X[:,0] = var_tbl[self.var_name]
return X | Parse a table of variable bindings (dictionary with key = variable name) |
384,878 | def _find_proj_root():
proj_files = frozenset((, ))
curr = os.getcwd()
while curr.startswith() and len(curr) > 1:
if proj_files & frozenset(os.listdir(curr)):
return curr
else:
curr = os.path.dirname(curr)
return None | Find the project path by going up the file tree.
This will look in the current directory and upwards for the pelconf file
(.yaml or .py) |
384,879 | def enclosing_frame(frame=None, level=2):
frame = frame or sys._getframe(level)
while frame.f_globals.get() == __name__: frame = frame.f_back
return frame | Get an enclosing frame that skips decorator code |
384,880 | def save_file(self, obj):
try:
import StringIO as pystringIO
raise pickle.PicklingError(
"Cannot pickle file %s as it does not appear to map to a physical, real file" % name)
else:
try:
tmpfile = file(name)
contents = tmpfile.read()
tmpfile.close()
... | Save a file |
384,881 | def checkpoint(self, message, header=None, delay=0, **kwargs):
if not self.transport:
raise ValueError(
"This RecipeWrapper object does not contain "
"a reference to a transport object."
)
if not self.recipe_step:
raise ValueE... | Send a message to the current recipe destination. This can be used to
keep a state for longer processing tasks.
:param delay: Delay transport of message by this many seconds |
384,882 | def do_struct(self, subcmd, opts, message):
client = MdClient(self.maildir, filesystem=self.filesystem)
as_json = getattr(opts, "json", False)
client.getstruct(message, as_json=as_json, stream=self.stdout) | ${cmd_name}: get the structure of the specified message
${cmd_usage}
${cmd_option_list} |
384,883 | def feature_enabled(self, feature_name):
feature_list = self.prop(, None)
if feature_list is None:
raise ValueError("Firmware features are not supported on CPC %s" %
self.manager.cpc.name)
for feature in feature_list:
if feature[] == ... | Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:... |
384,884 | def file_loc():
import sys
import inspect
try:
raise Exception
except:
file_ = + .join((inspect.currentframe().f_code.co_filename.split())[-3:])
line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno
return "{}:{}".format(file_, line_) | Return file and line number |
384,885 | def setup_panel_params(self, coord):
if not self.panel_scales_x:
raise PlotnineError()
if not self.panel_scales_y:
raise PlotnineError()
self.panel_params = []
cols = [, ]
for i, j in self.layout[cols].itertuples(index=False):
i, j =... | Calculate the x & y range & breaks information for each panel
Parameters
----------
coord : coord
Coordinate |
384,886 | def as_error(self) :
"fills in and returns an Error object that reports the specified error name and message."
result = dbus.Error.init()
result.set(self.args[0], self.args[1])
return \
result | fills in and returns an Error object that reports the specified error name and message. |
384,887 | def get_for_model(self, obj):
qs = Tag.objects.language(get_language())
qs = qs.filter(
tagged_items__content_type=ctype_models.ContentType.objects.get_for_model(obj))
return qs.distinct() | Returns the tags for a specific model/content type. |
384,888 | def delete_pool(name):
try:
pool = pool_api.delete_pool(name=name)
except AirflowException as err:
_log.error(err)
response = jsonify(error="{}".format(err))
response.status_code = err.status_code
return response
else:
return jsonify(pool.to_json()) | Delete pool. |
384,889 | def serialize(script_string):
string_tokens = script_string.split()
serialized_script = bytearray()
for token in string_tokens:
if token == or token == :
raise NotImplementedError(.format(token))
if token in riemann.network.CODE_TO_INT_OVERWRITE:
serialized_sc... | str -> bytearray |
384,890 | def get_substrates(self, material_id, number=50, orient=None):
req = "/materials/{}/substrates?n={}".format(material_id, number)
if orient:
req += "&orient={}".format(" ".join(map(str, orient)))
return self._make_request(req) | Get a substrate list for a material id. The list is in order of
increasing elastic energy if a elastic tensor is available for
the material_id. Otherwise the list is in order of increasing
matching area.
Args:
material_id (str): Materials Project material_id, e.g. 'mp-123'.
... |
384,891 | def main():
arguments = docopt(__doc__)
cfg_filename = pkg_resources.resource_filename(
,
)
kb = KnowledgeBase(cfg_filename)
if arguments["find"]:
search_string = arguments["<search_string>"]
try:
urn = CTS_URN(search_string)
match ... | Define the CLI inteface/commands. |
384,892 | def one(self, command, params=None):
dr = self.query(command, params)
if dr[]:
return dr[][0]
else:
return None | Возвращает первую строку ответа, полученного через query
> db.query('SELECT * FORM users WHERE id=:id', {"id":MY_USER_ID})
:param command: SQL запрос
:param params: Параметры для prepared statements
:rtype: dict |
384,893 | def create_actor_delaunay(pts, color, **kwargs):
array_name = kwargs.get(, "")
array_index = kwargs.get(, 0)
use_delaunay3d = kwargs.get("d3d", False)
points = vtk.vtkPoints()
points.SetData(pts)
polydata = vtk.vtkPolyData()
polydata.SetPoints(points)
triangul... | Creates a VTK actor for rendering triangulated plots using Delaunay triangulation.
Keyword Arguments:
* ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False*
:param pts: points
:type pts: vtkFloatArray
:param color: actor color
:type color: list... |
384,894 | def subdevicenames(self) -> Tuple[str, ...]:
stats: List[str] = collections.deque()
for devicename, seq in self.sequences.items():
if seq.NDIM:
temp = devicename +
for prod in self._product(seq.shape):
stats.append(temp + .join(st... | A |tuple| containing the (sub)device names.
Property |NetCDFVariableFlat.subdevicenames| clarifies which
row of |NetCDFVariableAgg.array| contains which time series.
For 0-dimensional series like |lland_inputs.Nied|, the plain
device names are returned
>>> from hydpy.core.examp... |
384,895 | def get_array_for_fit(observables: dict, track_pt_bin: int, jet_pt_bin: int) -> histogram.Histogram1D:
for name, observable in observables.items():
if observable.track_pt_bin == track_pt_bin and observable.jet_pt_bin == jet_pt_bin:
return histogram.Histogram1D.from_existing_hist(observable.... | Get a Histogram1D associated with the selected jet and track pt bins.
This is often used to retrieve data for fitting.
Args:
observables (dict): The observables from which the hist should be retrieved.
track_pt_bin (int): Track pt bin of the desired hist.
jet_ptbin (int): Jet pt bin of... |
384,896 | def get(self, *args, **kwargs):
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
objects_count, objects = self.get_collection(qs, kwargs)
schema_kwargs = getattr(self, , dict())
schema_kwargs.update({: True})
self.before_marshmallow(arg... | Retrieve a collection of objects |
384,897 | def upload_image(vol, img, offset, parallel=1,
manual_shared_memory_id=None, manual_shared_memory_bbox=None, manual_shared_memory_order=):
global NON_ALIGNED_WRITE
if not np.issubdtype(img.dtype, np.dtype(vol.dtype).type):
raise ValueError(.format(vol.dtype, img.dtype))
(is_aligned, bounds, expanded) ... | Upload img to vol with offset. This is the primary entry point for uploads. |
384,898 | def tuning_config(tuner, inputs, job_name=None):
train_config = training_base_config(tuner.estimator, inputs)
hyperparameters = train_config.pop(, None)
s3_operations = train_config.pop(, None)
if hyperparameters and len(hyperparameters) > 0:
tuner.static_hyperparameters = \
{u... | Export Airflow tuning config from an estimator
Args:
tuner (sagemaker.tuner.HyperparameterTuner): The tuner to export tuning config from.
inputs: Information about the training data. Please refer to the ``fit()`` method of
the associated estimator in the tuner, as this can take any ... |
384,899 | def _add_trits(left, right):
res = left + right
return res if -2 < res < 2 else (res < 0) - (res > 0) | Adds two individual trits together.
The result is always a single trit. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.