Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
359,900 | def process_config(config, config_data):
if in config_data:
process_components_config_section(config, config_data[])
if in config_data:
process_data_config_section(config, config_data[])
if in config_data:
process_log_config_section(config, config_data[])
if in config_da... | Populates config with data from the configuration data dict. It handles
components, data, log, management and session sections from the
configuration data.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param config_data: The configura... |
359,901 | def perform_upload(self, upload_token, filename, **kwargs):
parameters = dict()
parameters[] = upload_token
parameters[] = filename
try:
create_additional_revision = kwargs[]
except KeyError:
create_additional_revision = False
if not cre... | Upload a file into a given item (or just to the public folder if the
item is not specified.
:param upload_token: The upload token (returned by
generate_upload_token)
:type upload_token: string
:param filename: The upload filename. Also used as the path to the
fil... |
359,902 | def crop_resize_image(image: np.ndarray, size) -> np.ndarray:
width, height = image.size
if width > height:
left = (width - height) / 2
right = width - left
top = 0
bottom = height
else:
top = (height - width) / 2
bottom = height - top
left = 0
... | Resize the input image.
:param image: Original image which is a PIL object.
:param size: Tuple of height and width to resize the image to.
:return: Resized image which is a PIL object |
359,903 | def run(self):
self.keep_reading = True
while self.keep_reading:
line = self._readline()
if line:
self.input_queue.appendleft(line)
Dut.process_dut(self) | Read lines while keep_reading is True. Calls process_dut for each received line.
:return: Nothing |
359,904 | def fetchref(self, ref):
log.debug(, self.name, ref)
fetch_info = self.repo.remotes.origin.fetch(ref).pop()
return fetch_info.ref | Fetch a particular git ref. |
359,905 | def update(self):
pars = self.subpars.pars
responses = pars.control.responses
fluxes = pars.model.sequences.fluxes
self(len(responses))
fluxes.qpin.shape = self.value
fluxes.qpout.shape = self.value
fluxes.qma.shape = self.value
fluxes.qar.shape =... | Determine the number of response functions.
>>> from hydpy.models.arma import *
>>> parameterstep('1d')
>>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.)))
>>> derived.nmb.update()
>>> derived.nmb
nmb(2)
Note that updating parameter `nmb` sets the shape... |
359,906 | def del_doc(self, doc):
logger.info("Removing doc from the index: %s" % doc)
doc = doc.clone()
self.docsearch.index.del_doc(doc) | Delete a document |
359,907 | def set_one_time_boot(self, value):
dic = {: value}
data = self._execute_command(
, , , dic)
return data | Configures a single boot from a specific device.
:param value: specific device to which the boot option is set |
359,908 | def __normalize_list(self, msg):
if isinstance(msg, list):
msg = "".join(msg)
return list(map(lambda x: x.strip(), msg.split(","))) | Split message to list by commas and trim whitespace. |
359,909 | def broadcast_change():
_, res = win32gui.SendMessageTimeout(
win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 0,
win32con.SMTO_ABORTIFHUNG, 5000)
return not bool(res) | Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
Usage:
.. code-block:: python
import salt.utils.win_reg
... |
359,910 | def statistics(self):
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result | Get the dictionary with the count of the check-statuses
:return: dict(str -> int) |
359,911 | def date(self, col: str, **kwargs):
try:
self.df[col] = pd.to_datetime(self.df[col], **kwargs)
except Exception as e:
self.err(e, "Can not convert to date") | Convert a column to date type
:param col: column name
:type col: str
:param \*\*kwargs: keyword arguments for ``pd.to_datetime``
:type \*\*kwargs: optional
:example: ``ds.date("mycol")`` |
359,912 | def get_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._get_free_shipping_coupon_by_id_with_http_info(free_shipping_coupon_id, **kwargs)
else:
(data) = cls._get_free_shipping_coupon_by_id_with_http_... | Find FreeShippingCoupon
Return single instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_free_shipping_coupon_by_id(free_shipping_coupon_id, async=True)
... |
359,913 | def insertPhenotypeAssociationSet(self, phenotypeAssociationSet):
datasetId = phenotypeAssociationSet.getParentContainer().getId()
attributes = json.dumps(phenotypeAssociationSet.getAttributes())
try:
models.Phenotypeassociationset.create(
id=phenotypeAssocia... | Inserts the specified phenotype annotation set into this repository. |
359,914 | def interp1d(x,Z,xout,spline=False,kind=,fill_value=np.NaN,**kwargs):
linear = not spline
nx=len(x)
if linear :
try :
f = scipy.interpolate.interp1d(x, Z, kind=kind,bounds_error=False,fill_value=fill_value,**kwargs)
Zout = f(xout)
... | INTERP1D : Interpolate values from a 1D vector at given positions
@param x: 1st dimension vector of size NX
@author: Renaud DUSSURGET, LER/PAC, Ifremer La Seyne |
359,915 | def agent(state, host, server=None, port=None):
args = []
if server:
args.append( % server)
if port:
args.append( % port)
yield % .join(args) | Run puppet agent
+ server: master server URL
+ port: puppet master port |
359,916 | def ping(self):
self.__validate_ping_param()
ping_proc = subprocrunner.SubprocessRunner(self.__get_ping_command())
ping_proc.run()
return PingResult(ping_proc.stdout, ping_proc.stderr, ping_proc.returncode) | Sending ICMP packets.
:return: ``ping`` command execution result.
:rtype: :py:class:`.PingResult`
:raises ValueError: If parameters not valid. |
359,917 | def entity_import(args):
project = args.project
workspace = args.workspace
chunk_size = args.chunk_size
with open(args.tsvfile) as tsvf:
headerline = tsvf.readline().strip()
entity_data = [l.rstrip() for l in tsvf]
return _batch_load(project, workspace, headerline, entity_data... | Upload an entity loadfile. |
359,918 | def hashes_match(self, dep_tree):
hashes = self.get_hashes()
for module, info in dep_tree.items():
md5 = self.get_hash(info[])
if md5 != hashes[info[]]:
return False
return True | Compares the app deptree file hashes with the hashes stored in the
cache. |
359,919 | def cors_allow_any(request, response):
origin = request.META.get()
if not origin:
return response
response[] = origin
patch_vary_headers(response, [])
response[] =
if request.method == :
if in request.META:
response[] \
= request.META[]
... | Add headers to permit CORS requests from any origin, with or without credentials,
with any headers. |
359,920 | def make_pdb(self):
pdb_str = write_pdb(
[self], if not self.parent else self.parent.id)
return pdb_str | Generates a PDB string for the `Monomer`. |
359,921 | def print_probabilities(state: State, ndigits: int = 4,
file: TextIO = None) -> None:
prob = bk.evaluate(state.probabilities())
for index, prob in np.ndenumerate(prob):
prob = round(prob, ndigits)
if prob == 0.0:
continue
ket = "".join([str(n) for... | Pretty print state probabilities.
Args:
state:
ndigits: Number of digits of accuracy
file: Output stream (Defaults to stdout) |
359,922 | def do_opt(self, *args, **kwargs):
args = list(args)
if not args:
largest = 0
keys = [key for key in self.conf if not key.startswith("_")]
for key in keys:
largest = max(largest, len(key))
for key in keys:
print("%s... | Get and set options |
359,923 | def estimate_tx_operational_gas(self, safe_address: str, data_bytes_length: int):
threshold = self.retrieve_threshold(safe_address)
return 15000 + data_bytes_length // 32 * 100 + 5000 * threshold | Estimates the gas for the verification of the signatures and other safe related tasks
before and after executing a transaction.
Calculation will be the sum of:
- Base cost of 15000 gas
- 100 of gas per word of `data_bytes`
- Validate the signatures 5000 * threshold (ecrecov... |
359,924 | def all(self):
identifiers = []
query = text()
for result in self.backend.library.database.connection.execute(query):
vid, type_, name = result
res = IdentifierSearchResult(
score=1, vid=vid, type=type_, name=name)
identifiers.append... | Returns list with all indexed identifiers. |
359,925 | def to_file(data, filename_or_file_object):
if isinstance(filename_or_file_object, basestring):
file_ = open(filename_or_file_object, )
we_opened = True
else:
file_ = filename_or_file_object
we_opened = False
try:
file_.write(dump(data))
finally:
if ... | Write ``data`` to a file specified by either filename of the file or an opened :class:`file` buffer.
:param data: Object to write to file
:param filename_or_file_object: filename/or opened file buffer to write to
:type filename_or_file_object: basestring|file |
359,926 | def check_data(cls, name, dims, is_unstructured):
if isinstance(name, six.string_types) or not is_iterable(name):
name = [name]
dims = [dims]
is_unstructured = [is_unstructured]
msg = (
)
if len(name) < 2:
return [None], [ms... | A validation method for the data shape
Parameters
----------
name: list of str with length 2
The variable names (one for the first, two for the second array)
dims: list with length 2 of lists with length 1
The dimension of the arrays. Only 2D-Arrays are allowed (... |
359,927 | def GetFlag(self, name):
res = self.FlagDict().get(name)
if res is None:
raise exceptions.UnrecognizedFlagError(name)
return res | Same as __getitem__, but raises a specific error. |
359,928 | def accepts_moderator_roles(func):
if inspect.isclass(func):
apply_function_to_members(func, accepts_moderator_roles)
return func
else:
@functools.wraps(func)
def decorator(*args, **kwargs):
return accepts_roles(*ROLES_MODERATOR)(func)(*args, **kwargs)
r... | Decorator that accepts only moderator roles
:param func:
:return: |
359,929 | def print_app_info(out=sys.stderr):
print("System info:", file=out)
print(configuration.App, file=out)
print("Python %(version)s on %(platform)s" %
{"version": sys.version, "platform": sys.platform}, file=out)
stime = strtime(time.time())
print("Local time:", stime, file=out... | Print system and application info (output defaults to stderr). |
359,930 | def fetch_items(self, category, **kwargs):
from_date = kwargs[]
logger.info("Looking for messages from since %s",
self.uri, str(from_date))
mailing_list = GroupsioClient(self.group_name, self.dirpath,
self.api_token, self.veri... | Fetch the messages
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items |
359,931 | def get_alias(self, index=None, name=None, params=None):
_, result = yield self.transport.perform_request(
, _make_path(index, , name), params=params)
raise gen.Return(result) | Retrieve a specified alias.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html>`_
:arg index: A comma-separated list of index names to filter aliases
:arg name: A comma-separated list of alias names to return
:arg allow_no_indices: Whether to ignore if ... |
359,932 | def attribute(*args, **kw):
return operator(kind=Operator.Type.ATTRIBUTE, *args, **kw) | Registers a new attribute only operator function in the test engine.
Arguments:
*args: variadic arguments.
**kw: variadic keyword arguments.
Returns:
function |
359,933 | def create_sync_ops(self, host_device):
sync_ops = []
host_params = self.params_device[host_device]
for device, params in (self.params_device).iteritems():
if device == host_device:
continue
for k in self.params_names:
if isinstance(params[k], tf.Variable):
sync_op... | Create an assignment operation for each weight on all devices. The
weight is assigned the value of the copy on the `host_device'. |
359,934 | def add_user(self, username, raise_on_error=False, **kwargs):
if not in kwargs:
raise ValueError("missing password")
if not in kwargs:
raise ValueError("missing email")
try:
data = {
"name": u... | Add a user to the directory
Args:
username: The account username
raise_on_error: optional (default: False)
**kwargs: key-value pairs:
password: mandatory
email: mandatory
first_name: optional
... |
359,935 | def make(directory):
if os.path.exists(directory):
if os.path.isdir(directory):
click.echo()
else:
click.echo()
sys.exit()
os.makedirs(directory)
os.mkdir(os.path.join(directory, ))
copy_default_config(os.path.join(directory, )) | Makes a RAS Machine directory |
359,936 | def on_notify_load_status(self, webkitView, *args, **kwargs):
status = webkitView.get_load_status()
if status == status.FINISHED:
if self.debug is True:
print | Callback function when the page was loaded completely
FYI, this function will be called after $(document).ready()
in jQuery |
359,937 | def cif(self):
first_chr = random.choice()
doi_body = str(random.randrange(0, 10000000)).zfill(7)
cif = first_chr + doi_body
return cif + self._calculate_control_cif(cif) | https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal
:return: a random Spanish CIF |
359,938 | def _get_coordinates_for_dataset_keys(self, dsids):
coordinates = {}
for dsid in dsids:
cids = self._get_coordinates_for_dataset_key(dsid)
coordinates.setdefault(dsid, []).extend(cids)
return coordinates | Get all coordinates. |
359,939 | def format_dimension(dimension):
result = ""
if "type" in dimension.attrib:
result += "[R" if dimension.attrib["type"] == "row" else "[C"
else:
result += "[C"
if "index" in dimension.attrib:
result += ":" + dimension.attrib["index"]
r... | Formats the specified <dimension> XML tag for string output. |
359,940 | def profile_update_schema(profile):
if profile.get() is None:
print(
.format(
c.Style.BRIGHT, c.Fore.YELLOW
)
)
profile[] = True
for validation in profile.get() or []:
if vali... | Update profile to latest schema.
Args:
profile (dict): The dictionary containting the profile settings. |
359,941 | def create_catalog(self, *args, **kwargs):
return Catalog(
self._provider_manager,
self._get_provider_session().create_catalog(*args, **kwargs),
self._runtime,
self._proxy) | Pass through to provider CatalogAdminSession.create_catalog |
359,942 | def get_connection(self, connection: str, configuration: Config) -> Any:
if connection not in self.connections:
conn = self.get_connection_parameters(connection)
self.open_connection(
connection=connection,
configuration=configuration,
... | The function of this method is twofold:
1. If an existing connection is already established for the given type return it
2. If none exists, establish a new connection of that type with default parameters
and return it
Raises:
AttributeError: if it's unknown h... |
359,943 | def outlay(self, q):
fee = self.commission(q, self._price * self.multiplier)
outlay = q * self._price * self.multiplier
return outlay + fee, outlay, fee | Determines the complete cash outlay (including commission) necessary
given a quantity q.
Second returning parameter is a commission itself.
Args:
* q (float): quantity |
359,944 | def using(self, keyspace=None, connection=None):
if connection and self._batch:
raise CQLEngineException("Cannot specify a connection on model in batch mode.")
clone = copy.deepcopy(self)
if keyspace:
from cassandra.cqlengine.models import _clone_model_class
... | Change the context on-the-fly of the Model class (keyspace, connection) |
359,945 | def add_request_log_fields(
self, log_fields: LogFields,
call_details: Union[grpc.HandlerCallDetails,
grpc.ClientCallDetails]
):
service, method = call_details.method[1:].split("/")
log_fields.add_fields({
"system": "... | Add log fields related to a request to the provided log fields
:param log_fields: log fields instance to which to add the fields
:param call_details: some information regarding the call |
359,946 | def schema_list(dbname, user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
*
ret = {}
query = (.join([
]))
rows = psql_query(query, runas=user,
host=db_host,
... | Return a dict with information about schemas in a Postgres database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_list dbname
dbname
Database name we query on
user
The system user the operation should be performed on behalf of
db_user
database user... |
359,947 | def compress(data):
if isinstance(data, bytes):
source = data
elif isinstance(data, str):
source = bytes(data, encoding=)
else:
raise RuntimeError("Compression is only supported for strings and bytes")
return base64.b64encode(gzip.compress(source)) | Compresses a string (or bytes) using Gzip and returns its Base64 representation
:param data: string or bytes
:return: Base64 (bytes) representation of compressed data |
359,948 | def try_fields(cls, *names) -> t.Optional[t.Any]:
for name in names:
if hasattr(cls, name):
return getattr(cls, name)
raise AttributeError((cls, names)) | Return first existing of given class field names. |
359,949 | def parse_map_Ns(self):
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_specular_highlight(Kd) | Specular color map |
359,950 | def put(self, message):
if self.draining is False:
self.drain()
return self._enqueue(message) | Enqueues the given message for writing to the wire.
The message must be small enough to fit in a single frame. |
359,951 | def print_recipe(recipe):
print(colors.yellow("\n{0}".format(recipe[])))
print " description: {0}".format(recipe[])
print " version: {0}".format(recipe[])
print " dependencies: {0}".format(", ".join(recipe[]))
print " attributes: {0}".format(", ".join(recipe[])) | Pretty prints the given recipe |
359,952 | def get_load(jid):
log.debug(, jid)
read_profile = __opts__.get()
client, path = _get_conn(__opts__, read_profile)
return salt.utils.json.loads(client.get(.join((path, , jid, ))).value) | Return the load data that marks a specified jid |
359,953 | def AddTransaction(self, tx):
if BC.Default() is None:
return False
if tx.Hash.ToBytes() in self.MemPool.keys():
return False
if BC.Default().ContainsTransaction(tx.Hash):
return False
if not tx.Verify(self.MemPool.values()):
lo... | Add a transaction to the memory pool.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully added. False otherwise. |
359,954 | def save_load(jid, clear_load, minions=None):
jid = _escape_jid(jid)
conn = _get_conn()
if conn is None:
return None
cur = conn.cursor()
sql = \
\
\
cur.execute(
sql, (
jid,
salt.utils.jid.jid_to_time(jid),
... | Save the load to the specified jid id |
359,955 | def ultracache(timeout, *params):
def decorator(cls):
class WrappedClass(cls):
def __init__(self, *args, **kwargs):
super(WrappedClass, self).__init__(*args, **kwargs)
@cached_get(timeout, *params)
def get(self, *args, **kwargs):
ret... | Decorator applied to a view class. The get method is decorated
implicitly. |
359,956 | def getMenuItems(self, context, request):
actions = super(WorkflowMenu, self).getMenuItems(context, request)
actions = [action for action in actions
if not action[].endswith()]
return actions | Overrides the workflow actions menu displayed top right in the
object's view. Displays the current state of the object, as well as a
list with the actions that can be performed.
The option "Advanced.." is not displayed and the list is populated with
all allowed transitions for the object... |
359,957 | def registerTopLevelWindow(self, window):
if not self._topLevelWindows:
self.setPalette(window.palette())
self.setWindowIcon(window.windowIcon())
if self.splash():
self.splash().finish(window)
self._topL... | Registers a top level window for this application.
:param window | <QtGui.QMainWindow> |
359,958 | def ParseOptions(cls, options, configuration_object):
if not isinstance(configuration_object, tools.CLITool):
raise errors.BadConfigObject(
)
storage_format = cls._ParseStringOption(options, )
if not storage_format:
raise errors.BadConfigOption()
if storage_format not in def... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type.
BadConfigOption: if the storage forma... |
359,959 | def _read1bit(d, l, offset=False):
s = l.start - 1
length = l.end - l.start + 1
ret = [0] * length
if offset:
bi = s // 8
else:
bi = 0
for i in range(0, length):
block = s % 8
i... | Read data from a 1 bit file where each byte encodes 8 bases.
Parameters
----------
d : array
byte array
l : tuple
chr, start, end
Returns
-------
list
list of 1s and 0s of length equal to the number of bases in... |
359,960 | def is_correct(self):
state = True
loop = self.no_loop_in_parents("self", "parents")
if loop:
self.add_error("Loop detected while checking hosts")
state = False
for uuid, item in list(self.items.items()):
for elem in loop:
... | Check if the hosts list configuration is correct ::
* check if any loop exists in each host dependencies
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool |
359,961 | def friendship_followings(self, user_id=None, user_name=None,
page=1, count=20):
url =
data = {
: self.client_id,
: page,
: count,
: user_id,
: user_name
}
data = remove_none_value(data)
... | doc: http://open.youku.com/docs/doc?id=26 |
359,962 | def upload(self, data, callback=None, content_type=None,
size=None):
url =
if not hasattr(data, ) and \
not (hasattr(data, ) or hasattr(data, )):
data = six.BytesIO(force_bytes(data))
e... | Upload a multi-part file for content to ingest. Returns a
temporary upload id that can be used as a datstream location.
:param data: content string, file-like object, or iterable with
content to be uploaded
:param callback: optional callback method to monitor the upload;
... |
359,963 | def get_addon_name(addonxml):
xml = parse(addonxml)
addon_node = xml.getElementsByTagName()[0]
return addon_node.getAttribute() | Parses an addon name from the given addon.xml filename. |
359,964 | def get_aggregate (config):
_urlqueue = urlqueue.UrlQueue(max_allowed_urls=config["maxnumurls"])
_robots_txt = robots_txt.RobotsTxt(config["useragent"])
plugin_manager = plugins.PluginManager(config)
result_cache = results.ResultCache()
return aggregator.Aggregate(config, _urlqueue, _robots_txt... | Get an aggregator instance with given configuration. |
359,965 | def present(name, driver=None, driver_opts=None, force=False):
s driver does not match the ``driver`` parameter (unless the
``force`` parameter is set to ``True``).
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_present** to **docker_volume.present**
name
N... | Ensure that a volume is present.
.. versionadded:: 2015.8.4
.. versionchanged:: 2015.8.6
This state no longer deletes and re-creates a volume if the existing
volume's driver does not match the ``driver`` parameter (unless the
``force`` parameter is set to ``True``).
.. versionchange... |
359,966 | def text_dict_write(fpath, dict_):
dict_text2 = util_str.repr4(dict_, strvals=False)
if VERBOSE:
print( + str(dict_text2))
util_io.write_to(fpath, dict_text2) | Very naive, but readable way of storing a dictionary on disk
FIXME: This broke on RoseMary's big dataset. Not sure why. It gave bad
syntax. And the SyntaxError did not seem to be excepted. |
359,967 | def static_filename(self, repo: str, branch: str, relative_path: Union[str, Path], *,
depth: DepthDefinitionType=1,
reference: ReferenceDefinitionType=None
) -> Path:
self.validate_repo_url(repo)
depth = self.validate_depth... | Returns an absolute path to where a file from the repo was cloned to.
:param repo: Repo URL
:param branch: Branch name
:param relative_path: Relative path to the requested file
:param depth: See :meth:`run`
:param reference: See :meth:`run`
:return: Absolute path to the... |
359,968 | def _endLineupsNode(self, name, content):
if name == :
if not self._error:
self._importer.new_mapping(self._lineupId, self._stationId,
self._channel, self._channelMinor,
self._validFrom, sel... | Process the end of a node under xtvd/lineups |
359,969 | def t_prepro_ID(self, t):
r
t.type = reserved_directives.get(t.value.lower(), )
states_ = {
: ,
: ,
: ,
: ,
:
}
if t.type in states_:
t.lexer.begin(states_[t.type])
elif t.type == and self.expect... | r'[_a-zA-Z][_a-zA-Z0-9]* |
359,970 | def write(self, string):
if ("" == string or == string or == string):
return
string = string.replace("\r", "")
if self.printData:
print >> sys.__stdout__, string
if self.logData:
self.logWrite(string) | The write method for a CalcpkgOutput object- print the string |
359,971 | def _create_minion_object(self, opts, timeout, safe,
io_loop=None, loaded_base_name=None,
jid_queue=None):
return Minion(opts,
timeout,
safe,
io_loop=io_loop,
... | Helper function to return the correct type of object |
359,972 | def get_data_table(filename):
with get_file_object(filename, "r") as rf:
return DataTable(list(csv.reader(rf))) | Returns a DataTable instance built from either the filename, or STDIN if filename is None. |
359,973 | def inject_func_as_method(self, func, method_name=None, class_=None,
allow_override=False, allow_main=False,
verbose=True, override=None, force=False):
if override is not None:
allow_override = override
if method_name is None:
met... | Injects a function into an object as a method
Wraps func as a bound method of self. Then injects func into self
It is preferable to use make_class_method_decorator and inject_instance
Args:
self (object): class instance
func : some function whos first arugment is a class instance
meth... |
359,974 | def make(id, client, cls, parent_id=None, json=None):
from .dbase import DerivedBase
if issubclass(cls, DerivedBase):
return cls(client, id, parent_id, json)
else:
return cls(client, id, json) | Makes an api object based on an id and class.
:param id: The id of the object to create
:param client: The LinodeClient to give the new object
:param cls: The class type to instantiate
:param parent_id: The parent id for derived classes
:param json: The JSON to use to populate t... |
359,975 | def run_muse_sump_perchrom(job, muse_output, univ_options, muse_options, chrom):
work_dir = os.getcwd()
input_files = {
: muse_output,
: muse_options[],
: muse_options[]}
input_files = get_files_from_filestore(job, input_files, work_dir, docker=False)
tbi = os.path.splitext(... | Run MuSE sump on the MuSE call generated vcf.
:param toil.fileStore.FileID muse_output: vcf generated by MuSE call
:param dict univ_options: Dict of universal options used by almost all tools
:param dict muse_options: Options specific to MuSE
:param str chrom: Chromosome to process
:return: fsID fo... |
359,976 | def container_file_get(name, src, dst, overwrite=False,
mode=None, uid=None, gid=None, remote_addr=None,
cert=None, key=None, verify_cert=True):
if mode is not None:
mode = six.text_type(mode)
if not mode.startswith():
mo... | Get a file from a container
name :
Name of the container
src :
The source file or directory
dst :
The destination file or directory
mode :
Set file mode to octal number
uid :
Set file uid (owner)
gid :
Set file gid (group)
remote_addr :
... |
359,977 | def get_range(self, address=None):
url = self.build_url(self._endpoints.get())
if address is not None:
url = "{}(address=)".format(url, address)
response = self.session.get(url)
if not response:
return None
return self.range_constructor(parent=sel... | Returns a Range instance from whitin this worksheet
:param str address: Optional, the range address you want
:return: a Range instance |
359,978 | def _expand_targets(self, targets, base_dir=None):
all_targets = []
for target in targets:
target_dirs = [p for p in [base_dir, os.path.dirname(target)] if p]
target_dir = target_dirs and os.path.join(*target_dirs) or
target = os.path.basename(target)
... | Expand targets by looking for '-r' in targets. |
359,979 | def get_hist(rfile, histname, get_overflow=False):
import root_numpy as rnp
rfile = open_rfile(rfile)
hist = rfile[histname]
xlims = np.array(list(hist.xedges()))
bin_values = rnp.hist2array(hist, include_overflow=get_overflow)
rfile.close()
return bin_values, xlims | Read a 1D Histogram. |
359,980 | def print_region_quota(access_token, sub_id, region):
print(region + )
quota = azurerm.get_compute_usage(access_token, sub_id, region)
if SUMMARY is False:
print(json.dumps(quota, sort_keys=False, indent=2, separators=(, )))
try:
for resource in quota[]:
if resource[][] ... | Print the Compute usage quota for a specific region |
359,981 | def _codec_can_decode_with_surrogatepass(codec, _cache={}):
try:
return _cache[codec]
except KeyError:
try:
u"\ud83d".encode(
codec, _surrogatepass).decode(codec, _surrogatepass)
except UnicodeDecodeError:
_cache[codec] = False
else:
... | Returns if a codec supports the surrogatepass error handler when
decoding. Some codecs were broken in Python <3.4 |
359,982 | def is_running(process_id: int) -> bool:
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
for line in s.stdout:
strline = line.decode(encoding)
if pstr in strline:
return True
return False | Uses the Unix ``ps`` program to see if a process is running. |
359,983 | def _connect_params_dict(self):
conn_dict = {
"hostname": self.host,
"port": self.port,
"username": self.username,
"password": self.password,
"look_for_keys": self.use_keys,
"allow_agent": self.allow_agent,
"key_filenam... | Generate dictionary of Paramiko connection parameters. |
359,984 | def _biweekly_helper(self):
self.num = 14
mycount = self.repeat_biweekly()
if mycount:
if self.event.is_chunk() and min(mycount) not in xrange(1, 8):
mycount = _chunk_fill_out_first_week(
self.year, self.month, mycount, self.event,
... | Created to take some of the load off of _handle_weekly_repeat_out |
359,985 | def check_autosign_dir(self, keyid):
autosign_dir = os.path.join(self.opts[], )
expire_minutes = self.opts.get(, 120)
if expire_minutes > 0:
min_time = time.time() - (60 * int(expire_minutes))
for root, dirs, filenames in salt.utils.path.os_walk(autosig... | Check a keyid for membership in a autosign directory. |
359,986 | def qteMakeWindowActive(self, windowObj: QtmacsWindow):
if windowObj in self._qteWindowList:
windowObj.activateWindow()
else:
self.qteLogger.warning() | Make the window ``windowObj`` active and focus the first
applet therein.
|Args|
* ``windowObj`` (**QtmacsWindow**): window to activate.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. |
359,987 | def fix_input_files_for_variadic_seq(headerDir, sourceDir, timestamp):
files = glob.glob( os.path.join( headerDir, "*.hpp" ) )
files += glob.glob( os.path.join( headerDir, "aux_", "*.hpp" ) )
files += glob.glob( os.path.join( sourceDir, "src", "*" ) )
for currentFile in sorted( files ):
... | Fixes files used as input when pre-processing MPL-containers in their variadic form. |
359,988 | def zoom_cv(x,z):
if z==0: return x
r,c,*_ = x.shape
M = cv2.getRotationMatrix2D((c/2,r/2),0,z+1.)
return cv2.warpAffine(x,M,(c,r)) | Zoom the center of image x by a factor of z+1 while retaining the original image size and proportion. |
359,989 | def geocode(query):
url_template =
url = url_template.format(query)
response = requests.get(url, timeout=60)
results = response.json()
if len(results) > 0 and in results[0] and in results[0]:
lat = float(results[0][])
lon = float(results[0][])
point = (lat... | Geocode a query string to (lat, lon) with the Nominatim geocoder.
Parameters
----------
query : string
the query string to geocode
Returns
-------
point : tuple
the (lat, lon) coordinates returned by the geocoder |
359,990 | def _parse_date_input(date_input, default_offset=0):
if date_input:
try:
return parse_date_input(date_input)
except ValueError as err:
raise CommandError(force_text(err))
else:
return get_midnight() - timedelta(days=default_offset) | Parses a date input. |
359,991 | def send_status(status: ):
global middlewares, master
if status is None:
return
s: = status
for i in middlewares:
s = i.process_status(cast(, s))
if s is None:
return
status = cast(, s)
status.verify()
status.destination_channel.send_status... | Deliver a message to the destination channel.
Args:
status (EFBStatus): The status |
359,992 | def get(self, key, side):
return getattr(self, side).ravel()[self.keys[key]] | Returns an edge given a particular key
Parmeters
----------
key : tuple
(te, be, le, re) tuple that identifies a tile
side : str
top, bottom, left, or right, which edge to return |
359,993 | def string_to_xml(text):
try:
return etree.XML(text)
except Exception:
_logger.error(
"Error parsing XML string. "
"If lxml is not available, and unicode is involved, then "
... | Convert XML string into etree.Element. |
359,994 | def list_migration_issues_groups(self, group_id, content_migration_id):
path = {}
data = {}
params = {}
path["group_id"] = group_id
path["content_migration_id"] = content_migration_id
self.logger.debug("GET /api/... | List migration issues.
Returns paginated migration issues |
359,995 | def fig_voight_painting(h, index=None, palette=,
height_factor=0.01, fig=None):
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import seaborn as sns
h = asarray_ndim(h, 2)
if index is None:
index = h.shape[0] // 2
... | Make a figure of shared haplotype prefixes for both left and right
flanks, centred on some variant of choice.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
index : int, optional
Index of the variant within the haplotype array to centre ... |
359,996 | def publish_asset_ddo(self, ddo):
try:
asset_did = ddo.did
response = self.requests_session.post(self.url, data=ddo.as_text(),
headers=self._headers)
except AttributeError:
raise AttributeError()
if re... | Register asset ddo in aquarius.
:param ddo: DDO instance
:return: API response (depends on implementation) |
359,997 | def create_modelo(self):
return Modelo(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of modelo services facade. |
359,998 | def prior_prior_model_name_dict(self):
prior_prior_model_name_dict = {prior_tuple.prior: prior_model_tuple.name
for prior_model_tuple in self.flat_prior_model_tuples
for prior_tuple in prior_model_tuple.prior_model.prior_tupl... | Returns
-------
prior_prior_model_name_dict: {Prior: str}
A dictionary mapping priors to the names of associated prior models. Each prior will only have one prior
model name; if a prior is shared by two prior models then one of those prior model's names will be in this
... |
359,999 | def get_part_filenames(num_parts=None, start_num=0):
if num_parts is None:
num_parts = get_num_part_files()
return [.format(i) for i in range(start_num+1, num_parts+1)] | Get numbered PART.html filenames. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.