Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
339,800 | def assign_candidate(self, verse: Verse, candidate: str) -> Verse:
verse.scansion = candidate
verse.valid = True
verse.accented = self.formatter.merge_line_scansion(
verse.original, verse.scansion)
return verse | Helper method; make sure that the verse object is properly packaged.
:param verse:
:param candidate:
:return: |
339,801 | def GetDecoder(cls, encoding_method):
encoding_method = encoding_method.lower()
decoder = cls._decoders.get(encoding_method, None)
if not decoder:
return None
return decoder() | Retrieves the decoder object for a specific encoding method.
Args:
encoding_method (str): encoding method identifier.
Returns:
Decoder: decoder or None if the encoding method does not exists. |
339,802 | def argv_to_cmdline(argv):
cmdline = list()
for token in argv:
if not token:
token =
else:
if in token:
token = token.replace(, )
if in token or \
in token or \
... | Convert a list of arguments to a single command line string.
@type argv: list( str )
@param argv: List of argument strings.
The first element is the program to execute.
@rtype: str
@return: Command line string. |
339,803 | def get_suffix_tree(self, suffix_tree_id):
suffix_tree = self.suffix_tree_repo[suffix_tree_id]
assert isinstance(suffix_tree, GeneralizedSuffixTree)
suffix_tree._node_repo = self.node_repo
suffix_tree._node_child_collection_repo = self.node_child_collection_repo
suffix_t... | Returns a suffix tree entity, equipped with node and edge repos it (at least at the moment) needs. |
339,804 | def is_opened(cls, dc_code, type_):
options = {: dc_code, % type_: True}
datacenters = cls.safe_call(, options)
if not datacenters:
options = {: dc_code, % type_: True}
datacenters = cls.safe_call(, options)
if not datacenters:
... | List opened datacenters for given type. |
339,805 | def hotp_truncate(hmac_result, length=6):
if len(hmac_result) != 20:
raise yubico_exception.YubicoError("HMAC-SHA-1 not 20 bytes long")
offset = ord_byte(hmac_result[19]) & 0xf
bin_code = (ord_byte(hmac_result[offset]) & 0x7f) << 24 \
| (ord_byte(hmac_result[offset+1]) & 0xff) << 16 ... | Perform the HOTP Algorithm truncating.
Input is a bytestring. |
339,806 | def format_rpc(self, address, rpc_id, payload):
addr_word = (rpc_id | (address << 16) | ((1 << 1) << 24))
send_length = len(payload)
if len(payload) < 20:
payload = payload + b*(20 - len(payload))
payload_words = struct.unpack("<5L", payload)
return self.... | Create a formated word list that encodes this rpc. |
339,807 | def tail(self, n=5):
self._reset_group_selection()
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask] | Return last n rows of each group.
Essentially equivalent to ``.apply(lambda x: x.tail(n))``,
except ignores as_index flag.
%(see_also)s
Examples
--------
>>> df = pd.DataFrame([['a', 1], ['a', 2], ['b', 1], ['b', 2]],
columns=['A', 'B'])
... |
339,808 | def show_version_info(self, version):
if version in self.versions:
stdout = self.repo.show(version, ).stdout
logger.info(stdout)
else:
logger.info(.format(version)) | Summarizes info of a particular version (a la "git show version") |
339,809 | def build(cls, the_dict):
assert isinstance(the_dict, dict),
geom_type = the_dict.get(, None)
if geom_type == :
return Point.from_dict(the_dict)
elif geom_type == :
return MultiPoint.from_dict(the_dict)
elif geom_type == :
return Poly... | Builds a `pyowm.utils.geo.Geometry` subtype based on the geoJSON geometry type specified on the input dictionary
:param the_dict: a geoJSON compliant dict
:return: a `pyowm.utils.geo.Geometry` subtype instance
:raises `ValueError` if unable to the geometry type cannot be recognized |
339,810 | def get_next_char_level_in_j_str(curr_lv,curr_seq,j_str,block_op_pairs_dict=get_block_op_pairs("{}[]()")):
curr_ch = j_str[curr_seq]
next_ch = j_str[curr_seq + 1]
cond = 0
for i in range(1,block_op_pairs_dict.__len__()+1):
if(curr_ch == block_op_pairs_dict[i][0]):
if(next_ch == ... | the first-char is level-1
when current is non-op, next-char-level = curr-level
when current is lop, non-paired-rop-next-char-level = lop-level+1;
when current is lop, paired-rop-next-char-level = lop-level
when current is rop, next-char-level = rop-level - 1
# {"key_4_UF0a... |
339,811 | def range_by_score(self, min, max):
data = self.items()
keys = [r[1] for r in data]
start = bisect.bisect_left(keys, min)
end = bisect.bisect_right(keys, max, start)
return self._as_set()[start:end] | Return all the elements with score >= min and score <= max
(a range query) from the sorted set. |
339,812 | def search(self, CorpNum, DType, SDate, EDate, State, TradeType, TradeUsage, TaxationType, Page, PerPage, Order,
UserID=None, QString=None, TradeOpt=None):
if DType == None or DType == :
raise PopbillException(-99999999, "일자유형이 입력되지 않았습니다.")
if SDate == None ... | 목록 조회
args
CorpNum : 팝빌회원 사업자번호
DType : 일자유형, R-등록일자, T-거래일자, I-발행일자 중 택 1
SDate : 시작일자, 표시형식(yyyyMMdd)
EDate : 종료일자, 표시형식(yyyyMMdd)
State : 상태코드 배열, 2,3번째 자리에 와일드카드(*) 사용가능
TradeType : 문서형태 배열, N-일반현금영수증,... |
339,813 | def patched_fax_init(self, twilio):
super(TwilioFax, self).__init__(twilio)
self.base_url =
self.account_sid = twilio.account_sid
self._v1 = None | Initialize the Fax Domain
:returns: Domain for Fax
:rtype: twilio.rest.fax.Fax |
339,814 | def save_to_data(self, in_place=False):
if in_place:
return [
list(self._index.items()),
list(self._undefined_keys.keys())
]
return (
[(key, values[:]) for key, values in self._index.items()],
list(self._undefined_k... | Save index to data structure.
:param in_place: Do not copy index value to a new list object
:type in_place: bool
:return: Index data structure
:rtype: list |
339,815 | def act(self, *args, **kwargs):
if self.predicate(*args, **kwargs):
bool_result = self.action(*args, **kwargs)
return (True, bool_result)
else:
return (False, None) | gather a rules parameters together and run the predicate. If that
returns True, then go on and run the action function
returns:
a tuple indicating the results of applying the predicate and the
action function:
(False, None) - the predicate failed, action function ... |
339,816 | def postprocessor(prediction):
prediction = prediction.data.numpy()[0]
top_predictions = prediction.argsort()[-3:][::-1]
return [labels[prediction] for prediction in top_predictions] | Map prediction tensor to labels. |
339,817 | def scaffold_coords(rings):
rs = deque(sorted(rings, key=len, reverse=True))
base = rs.popleft()
first = base[0]
coords = {first: [0, 0, 0, 1]}
attach_spiro(coords, base, first)
while rs:
r = rs.popleft()
isec = list(set(coords) & set(r))
if not isec:
... | assign scaffold coordinate and angle
{node: (coords, angle)} |
339,818 | def validate_values(self, definition):
if not self._strict_type_checks:
return
scalar_kind = definition.get()
if scalar_kind not in SCALAR_TYPES_MAP.keys():
raise ParserError(self._name + + scalar_kind +
.format(BASE_DOC_... | This function checks that the fields have the correct values.
:param definition: the dictionary containing the scalar properties.
:raises ParserError: if a scalar definition field contains an unexpected value. |
339,819 | def randdict(self):
return {
self.randstr: self._map_type(int)
for x in range(self.random.randint(3, 10))} | -> a #dict of |{random_string: random_int}| |
339,820 | def snmp_server_community_community(self, **kwargs):
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
community = ET.SubElement(snmp_server, "community")
community = ET.SubElement(community, "community")
... | Auto Generated Code |
339,821 | def poke_64(library, session, address, data):
return library.viPoke64(session, address, data) | Write an 64-bit value from the specified address.
Corresponds to viPoke64 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to read the value.
:param data: value to be written to ... |
339,822 | def get_page_numbers(current_page, num_pages):
if current_page <= 2:
start_page = 1
else:
start_page = current_page - 2
if num_pages <= 4:
end_page = num_pages
else:
end_page = start_page + 4
if end_page > num_pages:
end_page = num_pages
pa... | Default callable for page listing.
Produce a Digg-style pagination. |
339,823 | def type(self) -> EntityType:
if self.data is None:
guessed_type = self.client.guess_entity_type(self.id)
if guessed_type is not None:
return guessed_type
return EntityType(self.attributes[]) | (:class:`EntityType`) The type of entity, :attr:`~EntityType.item`
or :attr:`~EntityType.property`.
.. versionadded:: 0.2.0 |
339,824 | def define_symbol(name, open_brace, comma, i, j,
close_brace, variables, **kwds):
r
if variables is None:
return Symbol(name+open_brace+str(i+1)+comma+str(j+1) +
close_brace, **kwds)
else:
return Function(name+open_brace+str(i+1)+comma+str(j+1) +
... | r"""Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace = ""
>>> comma = ""
>>> close_brace = ""
>>> i = 0
>>> j = 1
>>> f = define_symbol(name,... |
339,825 | def keep_indels(mut_df,
indel_len_col=True,
indel_type_col=True):
mut_df = mut_df[is_indel_annotation(mut_df)]
if indel_len_col:
mut_df.loc[:, ] = compute_indel_length(mut_df)
if indel_type_col:
is_ins = mut_df[]==
is_del = mut_df[... | Filters out all mutations that are not indels.
Requires that one of the alleles have '-' indicating either an insertion
or deletion depending if found in reference allele or somatic allele
columns, respectively.
Parameters
----------
mut_df : pd.DataFrame
mutation input file as a dataf... |
339,826 | def evaluate_all(ctx, model):
click.echo()
click.echo( % model)
ctx.invoke(evaluate, model= % model, corpus=, clusters=False)
ctx.invoke(evaluate, model= % model, corpus=, clusters=False)
ctx.invoke(evaluate, model= % model, corpus=, clusters=True)
ctx.invoke(evaluate, model= % model, corpu... | Evaluate POS taggers on WSJ and GENIA. |
339,827 | def from_array_list(cls, result, list_level):
return from_array_list(cls, result, list_level, is_builtin=False) | Tries to parse the `result` as type given in `required_type`, while traversing into lists as often as specified in `list_level`.
:param cls: Type as what it should be parsed as. Can be any class extending :class:`TgBotApiObject`.
E.g. If you call `Class.from_array_list`, it will automatical... |
339,828 | def delete_resourcegroupitems(scenario_id, item_ids, **kwargs):
user_id = int(kwargs.get())
_get_scenario(scenario_id, user_id)
for item_id in item_ids:
rgi = db.DBSession.query(ResourceGroupItem).\
filter(ResourceGroupItem.id==item_id).one()
db.DBSession.delete(rgi... | Delete specified items in a group, in a scenario. |
339,829 | def name_session(self, name):
with self.db:
self.db.execute("UPDATE sessions SET remark=? WHERE session==?",
(name, self.session_number)) | Give the current session a name in the history database. |
339,830 | def train_cb(self, param):
if param.nbatch % self.frequent == 0:
self._process_batch(param, ) | Callback funtion for training. |
339,831 | def plot_diagram(ax, x, y, label="S", title="syntenic", gradient=True):
trackgap = .06
tracklen = .12
xa, xb = x - tracklen, x + tracklen
ya, yb = y + trackgap, y - trackgap
hsps = (((60, 150), (50, 130)),
((190, 225), (200, 240)),
((330, 280), (360, 310)))
for yy in ... | Part of the diagrams that are re-used. (x, y) marks the center of the
diagram. Label determines the modification to the "S" graph. |
339,832 | def get(keys):
_config = GlobalConfigManager.get_config_or_default()
if not keys:
return
print_values = {}
for key in keys:
if hasattr(_config, key):
print_values[key] = getattr(_config, key)
else:
click.echo(.format(key))
dict_tabulate(print_v... | Get the global config values by keys.
Example:
\b
```bash
$ polyaxon config get host http_port
``` |
339,833 | def _add_custom_values_to_token_info(self, token_info):
t directly provided by a Web API
response.
expires_atexpires_inscope'] = self.scope
return token_info | Store some values that aren't directly provided by a Web API
response. |
339,834 | def get_ticket_for_exception(exc_type=None, exc_value=None, exc_traceback=None, title=None):
if exc_type and exc_value and exc_traceback:
mini_uuid = exception_uuid(exc_type, exc_value, exc_traceback)
else:
mini_uuid = None
shotgun = get_shotgun()
if mini_uui... | Get (or create) a ticket for the given exception.
Uses :func:`exception_uuid` to identify existing tickets by looking for the
tag in square brackets in the title. E.g. ``Something happened. [deadbeef]``.
:param str title: Title to use if creating a new ticket. Defaults to the
exception typ... |
339,835 | def cmd(self, cmd_name):
return "{0}.tube.{1}:{2}".format(self.queue.lua_queue_name, self.name, cmd_name) | Returns tarantool queue command name for current tube. |
339,836 | def from_path(cls, path: pathlib.Path) -> :
if not path.is_dir():
raise ValueError()
return Directory(path.name, {entity.name: Entity.from_path(entity)
for entity in path.iterdir()}) | Create a directory entity from a directory path.
:param path: The path of the directory.
:return: A directory entity instance representing the directory.
:raises ValueError: If the path does not point to a directory. |
339,837 | def _cgc_package_list_identifier(self, data_addr, data_size):
if data_size < 100:
return None, None
data = self.fast_memory_load(data_addr, data_size, str)
if data[:10] != :
return None, None
if not all(i in string.printable for i in data):
... | Identifies the CGC package list associated with the CGC binary.
:param int data_addr: Address of the data in memory.
:param int data_size: Maximum size possible.
:return: A 2-tuple of data type and size.
:rtype: tuple |
339,838 | def parse(cls, buff, offset):
primitive_struct = struct.Struct("!" + cls.fmt)
value = primitive_struct.unpack_from(buff, offset)[0]
offset += primitive_struct.size
return value, offset | Given a buffer and offset, returns the parsed value and new offset.
Uses the ``format`` class attribute to unpack the data from the buffer
and determine the used up number of bytes. |
339,839 | def create_file(self, path, fp, force=False, update=False):
if not in fp.mode:
raise ValueError("File has to be opened in binary mode.")
path = norm_remote_path(path)
directory, fname = os.path.split(path)
directories = directory.split(os.path.sep)
... | Store a new file at `path` in this storage.
The contents of the file descriptor `fp` (opened in 'rb' mode)
will be uploaded to `path` which is the full path at
which to store the file.
To force overwrite of an existing file, set `force=True`.
To overwrite an existing file only ... |
339,840 | def _permute_two_sample_iscs(iscs, group_parameters, i, pairwise=False,
summary_statistic=,
exact_permutations=None, prng=None):
if exact_permutations:
group_shuffler = np.array(exact_permutations[i])
elif not exact_permutations and p... | Applies two-sample permutations to ISC data
Input ISCs should be n_subjects (leave-one-out approach) or
n_pairs (pairwise approach) by n_voxels or n_ROIs array.
This function is only intended to be used internally by the
permutation_isc function in this module.
Parameters
----------
iscs :... |
339,841 | def _calc_T_var(self,X) -> int:
shape = X.shape
tensor_rank: int = len(shape)
if tensor_rank == 0:
return 1
if tensor_rank == 1:
return shape[0]
if tensor_rank == 2:
if shape[1] > 1:
raise ValueError()
retur... | Calculate the number of samples, T, from the shape of X |
339,842 | def get_assessment_part_item_session(self, proxy):
if not self.supports_assessment_part_lookup():
raise errors.Unimplemented()
return sessions.AssessmentPartItemSession(proxy=proxy, runtime=self._runtime) | Gets the ``OsidSession`` associated with the assessment part item service.
return: (osid.assessment.authoring.AssessmentPartItemSession)
- an ``AssessmentPartItemSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_assessment_part_ite... |
339,843 | def add_record(self, msg_id, rec):
if self._records.has_key(msg_id):
raise KeyError("Already have msg_id %r"%(msg_id))
self._records[msg_id] = rec | Add a new Task Record, by msg_id. |
339,844 | def parse_workflow_call_body_declarations(self, i):
declaration_array = []
if isinstance(i, wdl_parser.Terminal):
declaration_array = [i.source_string]
elif isinstance(i, wdl_parser.Ast):
raise NotImplementedError
elif isinstance(i, wdl_parser.AstList):
... | Have not seen this used, so expects to return "[]".
:param i:
:return: |
339,845 | def print_tree(current_node, childattr=, nameattr=, indent=, last=):
if hasattr(current_node, nameattr):
name = lambda node: getattr(node, nameattr)
else:
name = lambda node: str(node)
children = lambda node: getattr(node, childattr)
nb_children = lambda node: sum(nb_children(c... | Creation of balanced lists for "up" branch and "down" branch. |
339,846 | def getroot(self):
if in self.root.attrib:
attrib = {: self.root.attrib[]}
else:
attrib = None
return GroupElement(self.root.getchildren(), attrib=attrib) | Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag. |
339,847 | def get(self, worker_id):
code = 200
if worker_id == :
report = {: [{
: job,
: self._inspect_worker(job)}
for job in self.jobs]
}
elif worker_id in self.jobs:
report = {
: worker_id,
... | Return status report |
339,848 | def get_interfaces_ip(self):
def extract_ip_info(parsed_intf_dict):
<ip>N/As are in . If no secondaries, this field is not returned by
the xmltodict.parse() method.
IPv6:
- All addresses are returned in . If no v6 configured, this is not returned
... | Return IP interface data. |
339,849 | def _convert_radec(self, val):
try:
ans = val.to()
except Exception as e:
self.logger.error()
ans = val.data
else:
ans = ans.value
return ans | Convert RA or DEC table column to degrees and extract data.
Assume already in degrees if cannot convert. |
339,850 | def insert(self, cert_p):
return lib.zcertstore_insert(self._as_parameter_, byref(zcert_p.from_param(cert_p))) | Insert certificate into certificate store in memory. Note that this
does not save the certificate to disk. To do that, use zcert_save()
directly on the certificate. Takes ownership of zcert_t object. |
339,851 | def _find_agent(cls):
if not psutil:
return False
this_process = psutil.Process(os.getpid())
ownership_match = False
if _util._running_windows:
identity = this_process.username()
else:
identity = this_process.uids
for proc i... | Discover if a gpg-agent process for the current euid is running.
If there is a matching gpg-agent process, set a :class:`psutil.Process`
instance containing the gpg-agent process' information to
``cls._agent_proc``.
For Unix systems, we check that the effective UID of this
``py... |
339,852 | def patch_addPadding(self, patches):
paddingLength = self.Patch_Margin
nullPadding = ""
for x in range(1, paddingLength + 1):
nullPadding += chr(x)
for patch in patches:
patch.start1 += paddingLength
patch.start2 += paddingLength
patch = patches[0]
diffs = patc... | Add some padding on text start and end so that edges can match
something. Intended to be called only from within patch_apply.
Args:
patches: Array of Patch objects.
Returns:
The padding string added to each side. |
339,853 | def del_files(self, source):
src_files = []
for obj in self.s3walk(source):
if not obj[]:
src_files.append(obj[])
pool = ThreadPool(ThreadUtil, self.opt)
pool.batch_delete(src_files)
pool.join() | Delete files on S3 |
339,854 | def read(self, line, f, data):
f.readline()
f.readline()
N = len(data["symbols"])
numbers = data.get("numbers")
if numbers is None:
numbers = np.zeros(N, int)
data["numbers"] = numbers
coordinates = data.get("coordinates")
... | See :meth:`PunchParser.read` |
339,855 | def duel_command(f):
@functools.wraps(f)
def func_wrapper(self, *argv, **kwargs):
commands = _get_commands(f, self, *argv, **kwargs)
return self.execute_dual(commands)
return func_wrapper | indicate it's a command need to be called on both SP
:param f: function that returns the command in list
:return: command execution result on both sps (tuple of 2) |
339,856 | def _syllabify_simplex(word):
word, rules = apply_T1(word)
if re.search(r, word):
word, T2 = apply_T2(word)
word, T8 = apply_T8(word)
word, T9 = apply_T9(word)
rules += T2 + T8 + T9
syllabifications = list(apply_T4(word))
else:
syllabification... | Syllabify the given word. |
339,857 | def get_common_PDB_IDs(pdb_id, cache_dir = None, exception_on_failure = True):
m = pdb_to_uniparc([pdb_id], cache_dir = cache_dir)
UniProtACs = []
if pdb_id in m:
for entry in m[pdb_id]:
if entry.UniProtACs:
UniProtACs.extend(entry.UniProtACs)
elif except... | This function takes a PDB ID, maps it to UniProt ACCs, then returns the common set of PDB IDs related to those ACCs.
The purpose is to find any PDB files related to pdb_id, particularly for complexes, such that the other PDB files
contain identical sequences or mutant complexes. |
339,858 | def get_obj(source, extract=None, child_transform=None, transform=None):
if extract is None:
obj = source
else:
obj = extract(source)
if child_transform is None:
data = obj
else:
data = dict()
for k, v in child_transform.items():
try:
data[k] = v(obj)
except Exception... | Maps an object based on a key->extractor child_transform dict. |
339,859 | def remove_watcher(self, fd):
if not isinstance(fd, int):
fd = fd.fileno()
if fd not in self.callbacks:
return
self.callbacks.pop(fd, None)
self.epoll.unregister(fd) | Stops watching a fd. |
339,860 | def write(self, data):
if (len(data) > 65536):
print()
print()
exit(1)
command = 0x10 | (self.lsbfirst << 3) | self.write_clock_ve
logger.debug(.format(command))
data1 = data[:len(data)/2]
data2 = data[... | Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line. |
339,861 | def normality(*args, alpha=.05):
from scipy.stats import shapiro
k = len(args)
p = np.zeros(k)
normal = np.zeros(k, )
for j in range(k):
_, p[j] = shapiro(args[j])
normal[j] = True if p[j] > alpha else False
if k == 1:
normal = bool(normal)
p = float(p)
... | Shapiro-Wilk univariate normality test.
Parameters
----------
sample1, sample2,... : array_like
Array of sample data. May be of different lengths.
Returns
-------
normal : boolean
True if x comes from a normal distribution.
p : float
P-value.
See Also
-----... |
339,862 | def _siftup_max(heap, pos):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
childpos = 2*pos + 1
while childpos < endpos:
rightpos = childpos + 1
if rightpos < endpos and not heap[rightpos] < heap[childpos]:
childpos = rightpos
... | Maxheap variant of _siftup |
339,863 | def set_categories(self,
category_name,
not_category_names=[],
neutral_category_names=[]):
tdf = self.term_ranker_.get_ranks()
d = {: tdf[category_name + ]}
if not_category_names == []:
not_category_names =... | Specify the category to score. Optionally, score against a specific set of categories. |
339,864 | def simxClearStringSignal(clientID, signalName, operationMode):
if (sys.version_info[0] == 3) and (type(signalName) is str):
signalName=signalName.encode()
return c_ClearStringSignal(clientID, signalName, operationMode) | Please have a look at the function description/documentation in the V-REP user manual |
339,865 | def collection(self, *collection_path):
if len(collection_path) == 1:
path = collection_path[0].split(_helpers.DOCUMENT_PATH_DELIMITER)
else:
path = collection_path
return CollectionReference(*path, client=self) | Get a reference to a collection.
For a top-level collection:
.. code-block:: python
>>> client.collection('top')
For a sub-collection:
.. code-block:: python
>>> client.collection('mydocs/doc/subcol')
>>> # is the same as
>>> client.c... |
339,866 | def cleanup_tail(options):
if options.kwargs[] == "csv":
options.kwargs[].write("\n")
elif options.kwargs[] == "xml":
options.kwargs[].write("\n</results>\n")
else:
options.kwargs[].write("\n]\n") | cleanup the tail of a recovery |
339,867 | def venn2(subsets, set_labels=(, ), set_colors=(, ), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None):
100111100111100111ABdashed1010white10UnknownASet AABdashed
if isinstance(subsets, dict):
subsets = [subsets.get(t, 0) for t in [, , ]]
elif len(subsets) == 2:
subsets = co... | Plots a 2-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple) containing two set objects.
- A dict, providing sizes of three diagram regions.
The regions are identified via two-letter binary codes ('10', '01', and '11'), hence a valid set could l... |
339,868 | def run(self, start_date=None, end_date=None, **kwargs):
start_date = self.extract_date(start_date) if start_date else None
end_date = self.extract_date(end_date) if end_date else None
self.validate_arguments(start_date, end_date, **kwargs)
agg_query = self.build_query(start_da... | Run the query. |
339,869 | def _resize(self, ratio_x, ratio_y, resampling):
new_width = int(np.ceil(self.width * ratio_x))
new_height = int(np.ceil(self.height * ratio_y))
dest_affine = self.affine * Affine.scale(1 / ratio_x, 1 / ratio_y)
if self.not_loaded():
window = rasterio.windows.Window... | Return raster resized by ratio. |
339,870 | def calacs(input_file, exec_path=None, time_stamps=False, temp_files=False,
verbose=False, debug=False, quiet=False, single_core=False,
exe_args=None):
if exec_path:
if not os.path.exists(exec_path):
raise OSError( + exec_path)
call_list = [exec_path]
else... | Run the calacs.e executable as from the shell.
By default this will run the calacs given by 'calacs.e'.
Parameters
----------
input_file : str
Name of input file.
exec_path : str, optional
The complete path to a calacs executable.
time_stamps : bool, optional
Set to T... |
339,871 | def exists(self):
path = self.path
if in path or in path or in path or in path:
logger.warning("Using wildcards in path %s might lead to processing of an incomplete dataset; "
"override exists() to suppress the warning.", path)
return self.fs.e... | Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise.
This method is implemented by using :py:attr:`fs`. |
339,872 | def getProjectionMatrix(self, eEye, fNearZ, fFarZ):
fn = self.function_table.getProjectionMatrix
result = fn(eEye, fNearZ, fFarZ)
return result | The projection matrix for the specified eye |
339,873 | def filldb(self):
from app import World, Fortune, odm, MAXINT
mapper = odm.Mapper(self.cfg.postgresql)
mapper.register(World)
mapper.register(Fortune)
mapper.table_create()
with mapper.begin() as session:
query = session.query(mapper.world)
... | Fill database |
339,874 | def post_vars(self):
if self.method() != :
raise RuntimeError()
content_type = self.content_type()
if content_type is None or content_type.lower() != :
raise RuntimeError()
request_data = self.request_data()
request_data = request_data.decode() if request_data is not None else
re_search = WWebRe... | Parse request payload and return POST-vars
:return: None or dictionary of names and tuples of values |
339,875 | def clear_stats(self):
self._start_time = None
self._run_time = 0
self.stats = {
: False,
: lambda s: repr(self.bind_addr),
: lambda s: (not s[]) and -1 or self.runtime(),
: 0,
: lambda s: s[] / self.runtime(),
: la... | Reset server stat counters.. |
339,876 | def Where(self, field):
where_builder = _WhereBuilder(self, field)
self.where_builders.append(where_builder)
return where_builder | Creates a WHERE builder using a provided field.
Args:
field: the field to be added as an argument in the WHERE clause.
Returns:
The created WHERE builder. |
339,877 | def get_tags(self, view_object=None):
tags = [force_unicode(self.bundle.get_title())]
back_bundle = self.get_back_bundle()
if back_bundle and back_bundle != self.bundle:
tags.append(force_unicode(back_bundle.get_title()))
if view_object:
tags.append(force... | This method return a list of tags to use in the template
:return: list of tags |
339,878 | def timestamp(self, name, value):
counter = self.get(name, CounterType.Timestamp)
counter.time = value if value != None else datetime.datetime.utcnow()
self._update() | Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record. |
339,879 | def update(self, n, t):
if self.avg_n and self.avg_t:
self.avg_n = (self.avg_n * self.weight) + n
self.avg_t = (self.avg_t * self.weight) + t
else:
self.avg_n = n
self.avg_t = t
new_n = int(self.avg_rate * self.target_t)
return ne... | Update weighted average rate. Param n is generic; it's how many of
whatever the caller is doing (rows, checksums, etc.). Param s is how
long this n took, in seconds (hi-res or not).
Parameters:
n - Number of operations (rows, etc.)
t - Amount of time in seconds that n ... |
339,880 | def get_child_folders(path):
path = FileHelper.abspath(path)
return [dirname for dirname in os.listdir(path) if os.path.isdir(os.path.join(path, dirname))] | Get all child folders of a folder |
339,881 | def _get_ctx(self, subctx=None):
"Return or or or depending on this and constructor arguments"
l = []
if self.ctx is not None: l.append(self.ctx)
if subctx is not None: l.append(subctx)
return if len(l) == 0 else f" ({.join(l)})" | Return ' (ctx: subctx)' or ' (ctx)' or ' (subctx)' or '' depending on this and constructor arguments |
339,882 | def get_ams_access_token(accountname, accountkey):
accountkey_encoded = urllib.parse.quote(accountkey, safe=)
body = "grant_type=client_credentials&client_id=" + accountname + \
"&client_secret=" + accountkey_encoded + " &scope=urn%3aWindowsAzureMediaServices"
return do_ams_auth(ams_auth_endpoint, bod... | Get Media Services Authentication Token.
Args:
accountname (str): Azure Media Services account name.
accountkey (str): Azure Media Services Key.
Returns:
HTTP response. JSON body. |
339,883 | def get_lambdas(awsclient, config, add_arn=False):
if in config:
client_lambda = awsclient.get_client()
lambda_entries = config[].get(, [])
lmbdas = []
for lambda_entry in lambda_entries:
lmbda = {
: lambda_entry.get(, None),
: lambda... | Get the list of lambda functions.
:param config:
:param add_arn:
:return: list containing lambda entries |
339,884 | def compute(self, t, yerr=1.123e-12, check_sorted=True,
A=None, U=None, V=None):
t = np.atleast_1d(t)
if check_sorted and np.any(np.diff(t) < 0.0):
raise ValueError("the input coordinates must be sorted")
if check_sorted and len(t.shape) > 1:
rais... | Compute the extended form of the covariance matrix and factorize
Args:
x (array[n]): The independent coordinates of the data points.
This array must be _sorted_ in ascending order.
yerr (Optional[float or array[n]]): The measurement uncertainties
for the ... |
339,885 | def get_info(self):
info = {}
info["top_row"] = self.top_row_text_ctrl.GetValue()
info["bottom_row"] = self.bottom_row_text_ctrl.GetValue()
info["left_col"] = self.left_col_text_ctrl.GetValue()
info["right_col"] = self.right_col_text_ctrl.GetValue()
info["first... | Returns a dict with the dialog PDF info
Dict keys are:
top_row, bottom_row, left_col, right_col, first_tab, last_tab,
paper_width, paper_height |
339,886 | def get_chembl_id(nlm_mesh):
mesh_id = get_mesh_id(nlm_mesh)
pcid = get_pcid(mesh_id)
url_mesh2pcid = + \
% pcid
r = requests.get(url_mesh2pcid)
res = r.json()
synonyms = res[][][0][]
chembl_id = [syn for syn in synonyms
if in syn and not in syn]... | Get ChEMBL ID from NLM MESH
Parameters
----------
nlm_mesh : str
Returns
-------
chembl_id : str |
339,887 | def create_table_from_fits(fitsfile, hduname, colnames=None):
if colnames is None:
return Table.read(fitsfile, hduname)
cols = []
with fits.open(fitsfile, memmap=True) as h:
for k in colnames:
data = h[hduname].data.field(k)
cols += [Column(name=k, data=data)]
... | Memory efficient function for loading a table from a FITS
file. |
339,888 | def set_label(self, value,callb=None):
if len(value) > 32:
value = value[:32]
mypartial=partial(self.resp_set_label,label=value)
if callb:
self.req_with_ack(SetLabel, {"label": value},lambda x,y:(mypartial(y),callb(x,y)) )
else:
self.req_with_... | Convenience method to set the label of the device
This method will send a SetLabel message to the device, and request callb be executed
when an ACK is received. The default callback will simply cache the value.
:param value: The new label
:type value: str
:param cal... |
339,889 | def unitpicker(a, llim=0.1, denominator=None, focus_stage=None):
if not isinstance(a, (int, float)):
a = nominal_values(a)
a = np.percentile(a[~np.isnan(a)], 25)
if denominator is not None:
pd = pretty_element(denominator)
else:
pd =
if focus_stage == :
u... | Determines the most appropriate plotting unit for data.
Parameters
----------
a : float or array-like
number to optimise. If array like, the 25% quantile is optimised.
llim : float
minimum allowable value in scaled data.
Returns
-------
(float, str)
(multiplier, uni... |
339,890 | def crop(self, box):
xmin, ymin, xmax, ymax = self._split_into_xyxy()
w, h = box[2] - box[0], box[3] - box[1]
cropped_xmin = (xmin - box[0]).clamp(min=0, max=w)
cropped_ymin = (ymin - box[1]).clamp(min=0, max=h)
cropped_xmax = (xmax - box[0]).clamp(min=0, max=w)
... | Cropss a rectangular region from this bounding box. The box is a
4-tuple defining the left, upper, right, and lower pixel
coordinate. |
339,891 | def get_filename_by_suffixes(dir_src, suffixes):
list_files = os.listdir(dir_src)
re_files = list()
if is_string(suffixes):
suffixes = [suffixes]
if not isinstance(suffixes, list):
return None
for i, suf in enumerate(suffixes):
... | get file names with the given suffixes in the given directory
Args:
dir_src: directory path
suffixes: wanted suffixes list, the suffix in suffixes can with or without '.'
Returns:
file names with the given suffixes as list |
339,892 | def rest_get_stream(self, url, auth=None, verify=True, cert=None):
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert)
return res.raw, res.status_code | Perform a chunked GET request to url with optional authentication
This is specifically to download files. |
339,893 | def to_naf(self):
if self.type == :
for node_coref in self.__get_corefs_nodes():
node_coref.set(,node_coref.get())
del node_coref.attrib[] | Converts the coreference layer to NAF |
339,894 | def get_location(bucket, retry_params=None, _account_id=None):
return _get_bucket_attribute(bucket,
,
,
retry_params=retry_params,
_account_id=_account_id) | Returns the location for the given bucket.
https://cloud.google.com/storage/docs/bucket-locations
Args:
bucket: A Google Cloud Storage bucket of form '/bucket'.
retry_params: An api_utils.RetryParams for this call to GCS. If None,
the default one is used.
_account_id: Internal-use only.
Retur... |
339,895 | def quatInv(q):
qConj = -q
qConj[0] = -qConj[0]
normSqr = multiplyQuats(q, qConj)[0]
return qConj/normSqr | Returns QBar such that Q*QBar = 1 |
339,896 | def insert(cls, index, interceptor):
cls._check(interceptor)
cls._interceptors.insert(index, interceptor) | Add interceptor to the given index in the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor`` |
339,897 | def locked_put(self, credentials):
self._create_file_if_needed()
_helpers.validate_file(self._filename)
f = open(self._filename, )
f.write(credentials.to_json())
f.close() | Write Credentials to file.
Args:
credentials: Credentials, the credentials to store.
Raises:
IOError if the file is a symbolic link. |
339,898 | def on_authenticated(self, authorization):
self.is_authenticating.acquire()
self.authorization = authorization
print( % self.authorization)
self.is_authenticating.notify_all()
self.is_authenticating.release() | Device authenticated.
:param authorization: Authentication token details
:type authorization: dict |
339,899 | def unique(seq, key=None, return_as=None):
seen = set()
add = seen.add
if key:
generator = (x for x in seq if key(x) not in seen and not add(key(x)))
else:
generator = (x for x in seq if x not in seen and not add(x))
if return_as:
if return_as == str:
return ... | Unique the seq and keep the order.
Instead of the slow way:
`lambda seq: (x for index, x in enumerate(seq) if seq.index(x)==index)`
:param seq: raw sequence.
:param return_as: generator for default, or list / set / str...
>>> from torequests.utils import unique
>>> a = [1,2,3,4,2,3,4]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.