Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
361,200 | async def extract_rows(self, file_or_name, **reader_kwargs):
rows = []
rows_to_read = self.sample_size
async with self.get_reader(file_or_name, **reader_kwargs) as reader:
if self.has_header:
rows_to_read += 1
for i in range(self.sample_size):
... | Extract `self.sample_size` rows from the CSV file and analyze their
data-types.
:param str file_or_name: A string filename or a file handle.
:param reader_kwargs: Arbitrary parameters to pass to the CSV reader.
:returns: A 2-tuple containing a list of headers and list of rows
... |
361,201 | def my_notes(self, start_index=0, limit=100, get_all=False, sort_by=, sort_dir=):
index = start_index
notes = {
: [],
: 0,
:
}
while True:
payload = {
: sort_by,
: sort_dir,
: index... | Return all the loan notes you've already invested in. By default it'll return 100 results at a time.
Parameters
----------
start_index : int, optional
The result index to start on. By default only 100 records will be returned at a time, so use this
to start at a later in... |
361,202 | def var_set(session, **kwargs):
if not kwargs:
for name, value in session.variables.items():
session.write_line("{0}={1}".format(name, value))
else:
for name, value in kwargs.items():
name = name.strip()
session.set(name, v... | Sets the given variables or prints the current ones. "set answer=42" |
361,203 | def _soi(self, orb):
for body in self.alt:
soi = self.SOI[body.name]
sph = orb.copy(frame=soi.frame, form=)
if sph.r < soi.radius:
active = body
break
else:
active = self.central
return active | Evaluate the need for SOI transition, by comparing the radial distance
between the considered body and the spacecraft
If therer is no body in sight, default to central body. |
361,204 | def _get_iq_handler(self, iq_type, payload):
key = (payload.__class__, payload.handler_key)
logger.debug("looking up iq {0} handler for {1!r}, key: {2!r}"
.format(iq_type, payload, key))
logger.debug("handlers: {0!r}".format(self._iq_handlers))
handle... | Get an <iq/> handler for given iq type and payload. |
361,205 | def spi_write(self, data):
data_out = array.array(, data)
data_in = array.array(, (0,) * len(data_out))
ret = api.py_aa_spi_write(self.handle, len(data_out), data_out,
len(data_in), data_in)
_raise_error_if_negative(ret)
return bytes(data_in) | Write a stream of bytes to a SPI device. |
361,206 | def recalculate(self):
scene = self.scene()
w = self.calculateSceneWidth()
scene.setSceneRect(0, 0, w, self.height())
spacing = self.spacing()
x = self.width() / 4.0
y = self.height() / 2.0
for item in self.items():
... | Recalcualtes the slider scene for this widget. |
361,207 | def stop(self):
if self.stop_event.ready():
return
self.stop_event.set()
self.transport.stop()
self.alarm.stop()
self.transport.join()
self.alarm.join()
self.blockch... | Stop the node gracefully. Raise if any stop-time error occurred on any subtask |
361,208 | def findFrequentSequentialPatterns(self, dataset):
self._transfer_params_to_java()
jdf = self._java_obj.findFrequentSequentialPatterns(dataset._jdf)
return DataFrame(jdf, dataset.sql_ctx) | .. note:: Experimental
Finds the complete set of frequent sequential patterns in the input sequences of itemsets.
:param dataset: A dataframe containing a sequence column which is
`ArrayType(ArrayType(T))` type, T is the item type for the input dataset.
:return: A `Data... |
361,209 | def t_NUMBER(self, t):
r
t.value = int(t.value)
neg = 0
if t.value < 0:
neg = 1
val = abs(t.value)
if val <= UNSIGNED32_MAX:
if neg:
t.type =
elif val <= UNSIGNED64_MAX:
if neg:
t.type =
... | r'-?[0-9]+ |
361,210 | def challenger_by_queue(self, region, queue):
url, query = LeagueApiV4Urls.challenger_by_queue(region=region, queue=queue)
return self._raw_request(self.challenger_by_queue.__name__, region, url, query) | Get the challenger league for a given queue.
:param string region: the region to execute this request on
:param string queue: the queue to get the challenger players for
:returns: LeagueListDTO |
361,211 | def invalidate(self, callback=True):
with self._lock:
if self.state != StoredInstance.VALID:
return False
self.state = StoredInstance.INVALID
self.__safe_handlers_callback("pre_invalidate")
... | Applies the component invalidation.
:param callback: If True, call back the component before the
invalidation
:return: False if the component wasn't valid |
361,212 | def call(self, action, payload):
if self.api_key:
payload[] = self.api_key
d = self.proxy.callRemote(action, payload)
d.addErrback(self._parse_errback)
return d | Make an XML-RPC call to the server. This method will automatically
authenticate the call with self.api_key, if that is set.
returns: deferred that when fired returns a dict with data from this
XML-RPC call. |
361,213 | def restart_on_change_helper(lambda_f, restart_map, stopstart=False,
restart_functions=None):
if restart_functions is None:
restart_functions = {}
checksums = {path: path_hash(path) for path in restart_map}
r = lambda_f()
restarts = [restart_map[path]
... | Helper function to perform the restart_on_change function.
This is provided for decorators to restart services if files described
in the restart_map have changed after an invocation of lambda_f().
@param lambda_f: function to call.
@param restart_map: {file: [service, ...]}
@param stopstart: wheth... |
361,214 | def assertFileTypeEqual(self, filename, extension, msg=None):
ftype = self._get_file_type(filename)
self.assertEqual(ftype, extension, msg=msg) | Fail if ``filename`` does not have the given ``extension``
as determined by the ``==`` operator.
Parameters
----------
filename : str, bytes, file-like
extension : str, bytes
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` ... |
361,215 | def read(bar, offset, size):
verify_access_range(bar, offset, size)
if bar.type == : return io_read(bar, offset, size)
if bar.type == : return mem_read(bar, offset, size)
return b | Read PCI data register.
Parameters
----------
bar : BaseAddressRegister
BAR to read.
offset : int
Address offset in BAR to read.
size : int
Data size to read.
Returns
-------
bytes
Data read from BAR
Examples
------... |
361,216 | def render_scene(self):
"render scene one time"
self.init_gl()
SDL_GL_MakeCurrent ( self.window, self.context )
self.renderer.render_scene()
glFlush() | render scene one time |
361,217 | def dispatch(self, request, *args, **kwargs):
self.wizard_name = self.get_wizard_name()
self.prefix = self.get_prefix()
self.storage = get_storage(self.storage_name, self.prefix, request,
getattr(self, , None))
self.steps = StepsHelper(self)
response... | This method gets called by the routing engine. The first argument is
`request` which contains a `HttpRequest` instance.
The request is stored in `self.request` for later use. The storage
instance is stored in `self.storage`.
After processing the request using the `dispatch` method, the
... |
361,218 | def detail(request, action_id):
return render(
request,
,
{
: get_object_or_404(models.Action, pk=action_id)
}
) | ``Action`` detail view (pretty boring, mainly used for get_absolute_url) |
361,219 | def update_or_create(cls, filter_key=None, with_status=False, **kwargs):
updated = False
defer_update = kwargs.pop(, False)
if defer_update:
with_status = True
element, created = cls.get_or_create(filter_key=filter_key, with_status=True, **... | Update or create the element. If the element exists, update it using the
kwargs provided if the provided kwargs after resolving differences from
existing values. When comparing values, strings and ints are compared
directly. If a list is provided and is a list of strings, it will be
com... |
361,220 | def create_grade(self, grade_form):
from dlkit.abstract_osid.grading.objects import GradeForm as ABCGradeForm
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
if not... | Creates a new ``Grade``.
arg: grade_form (osid.grading.GradeForm): the form for this
``Grade``
return: (osid.grading.Grade) - the new ``Grade``
raise: IllegalState - ``grade_form`` already used in a create
transaction
raise: InvalidArgument - one or ... |
361,221 | def normalize_errorlevel(error, accept_none=False):
if error is None:
if not accept_none:
raise ErrorLevelError()
return error
try:
return consts.ERROR_MAPPING[error.upper()]
except:
if error in consts.ERROR_MAPPING.values():
return error
... | \
Returns a constant for the provided error level.
This function returns ``None`` if the provided parameter is ``None`` and
`accept_none` is set to ``True`` (default: ``False``). If `error` is ``None``
and `accept_none` is ``False`` or if the provided parameter cannot be
mapped to a valid QR Code e... |
361,222 | def request_release_milestone_payment(session, milestone_id):
params_data = {
: ,
}
endpoint = .format(milestone_id)
response = make_put_request(session, endpoint, params_data=params_data)
json_data = response.json()
if response.status_code == 200:
return json_data[]
... | Release a milestone payment |
361,223 | def predict_features(self, df_features, df_target, idx=0, C=.1, **kwargs):
lsvc = LinearSVR(C=C).fit(df_features.values, df_target.values)
return np.abs(lsvc.coef_) | For one variable, predict its neighbouring nodes.
Args:
df_features (pandas.DataFrame):
df_target (pandas.Series):
idx (int): (optional) for printing purposes
kwargs (dict): additional options for algorithms
C (float): Penalty parameter of the error t... |
361,224 | def _calculate_Hfr_coal(self, T):
m_C = 0
m_H = 0
m_O = 0
m_N = 0
m_S = 0
Hfr = 0.0
for compound in self.material.compounds:
index = self.material.get_compound_index(compound)
formula = compound.split()[0]
... | Calculate the enthalpy flow rate of the stream at the specified
temperature, in the case of it being coal.
:param T: Temperature. [°C]
:returns: Enthalpy flow rate. [kWh/h] |
361,225 | def serialize(self):
res = {}
for key, item in list(self.items.items()):
res[key] = item.serialize()
return res | This function serialize items into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here is the generic function that simply serialize each item of the items object
:return: Dictionary containing item's uuid as key and item as value
:rtyp... |
361,226 | def hidden_next_pages(self):
next_pages = self.next_pages()
return len(next_pages) > 0 and next_pages[-1] < self.npages | Check if the next pages where sliced.
Example:
>>> map(lambda i: _SlicedPaginator(i, 6, 3).hidden_next_pages(), range(1, 7))
[True, True, True, True, False, False]
>>> map(lambda i: _SlicedPaginator(i, 7, 3).hidden_next_pages(), range(1, 8))
[True, True, True, True, True... |
361,227 | def postActivate_(self):
if (self.requiredGPU_MB(self.required_mb)):
self.analyzer = YoloV3TinyAnalyzer(verbose = self.verbose)
else:
self.warning_message = "WARNING: not enough GPU memory!"
self.analyzer = None | Whatever you need to do after creating the shmem client |
361,228 | def _socketpair_compat():
listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listensock.bind(("127.0.0.1", 0))
listensock.listen(1)
iface, port = listensock.getsockname()
sock1 = socket.socket(s... | TCP/IP socketpair including Windows support |
361,229 | def validate(self, document):
template = document.text
if template not in self.builtin_templates:
raise ValidationError(
message=f
+ f,
cursor_position=0
) | Check if the selected template exists. |
361,230 | def listen(d, save_dir=):
warnings.warn(
"Using report.listen is deprecated, use report.Report(d, save_dir) instead.",
ExtDeprecationWarning, stacklevel=2
)
Report(d, save_dir) | Depreciated |
361,231 | def process_columns(self, columns):
if type(columns) == list:
self.columns = columns
elif type(columns) == str:
self.columns = [c.strip() for c in columns.split()]
elif type(columns) == IntEnum:
self.columns = [str(c) for c in columns]
else:
... | Handle provided columns and if necessary, convert columns to a list for
internal strage.
:columns: A sequence of columns for the table. Can be list, comma
-delimited string, or IntEnum. |
361,232 | def schnorr_partial_combine(self, schnorr_sigs):
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
assert len(schnorr_sigs) > 0
sig64 = ffi.new()
sig64sin = []
for sig in schnorr_sigs:
if not isinstance(sig, bytes):
... | Combine multiple Schnorr partial signatures. |
361,233 | def line(self, *args):
self.lines.append(.join([%x for x in map(float,args)]))
return self | Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls |
361,234 | def fix_var_name(var_name):
name = var_name.strip()
for char in :
name = name.replace(char, )
name = name.replace(, )
name = name.replace(, )
if name.endswith():
name = name[:-1]
return name | Clean up and apply standard formatting to variable names. |
361,235 | def compare(self, other):
if self._req != other._req:
raise ArcanaUsageError(
"Canzabrczz',)
if s < o:
return -1
if s > o:
return 1
s = self._post if self._post is not None else 0
o = other._post if other._post... | Compares the version with another
Parameters
----------
other : Version
The version to compare to |
361,236 | def index_name(model, *field_names, **kwargs):
if not len(field_names):
raise ValueError("At least one field name required")
using = kwargs.pop(, DEFAULT_DB_ALIAS)
if len(kwargs):
raise ValueError("The only supported keyword argument is ")
existing_fields = {field.name: field for f... | Returns the name of the index existing on field_names, or raises KeyError
if no such index exists. |
361,237 | def list_tar (archive, compression, cmd, verbosity, interactive):
cmdlist = [cmd, ]
add_tar_opts(cmdlist, compression, verbosity)
cmdlist.extend(["--file", archive])
return cmdlist | List a TAR archive. |
361,238 | def lemmas(self):
return [lemma("%s.%s"%(self.name,variant.literal)) for variant in self._raw_synset.variants] | Returns the synset's lemmas/variants' literal represantions.
Returns
-------
list of Lemmas
List of its variations' literals as Lemma objects. |
361,239 | def run(self):
self.initialize_tracking_structures()
if self.live_monitoring:
self.logger.info("Starting up the operation policy file monitor.")
while not self.halt_trigger.is_set():
time.sleep(1)
self.scan_policies()
self.log... | Start monitoring operation policy files. |
361,240 | def prepare_kernel_string(kernel_name, kernel_string, params, grid, threads, block_size_names):
logging.debug(, kernel_name)
grid_dim_names = ["grid_size_x", "grid_size_y", "grid_size_z"]
for i, g in enumerate(grid):
kernel_string = "
for i, g in enumerate(threads):
kernel_string =... | prepare kernel string for compilation
Prepends the kernel with a series of C preprocessor defines specific
to this kernel instance:
* the thread block dimensions
* the grid dimensions
* tunable parameters
Additionally the name of kernel is replace with an instance specific name. This
i... |
361,241 | def to_ufo_propagate_font_anchors(self, ufo):
processed = set()
for glyph in ufo:
_propagate_glyph_anchors(self, ufo, glyph, processed) | Copy anchors from parent glyphs' components to the parent. |
361,242 | def store_mail(mbx, mail):
if not isinstance(mbx, mailbox.Mailbox):
logging.debug()
return False
mbx.lock()
if isinstance(mbx, mailbox.Maildir):
logging.debug()
msg = mailbox.MaildirMessage(mail)
msg.set_flags()
else:
... | stores given mail in mailbox. If mailbox is maildir, set the S-flag and
return path to newly added mail. Oherwise this will return `None`.
:param mbx: mailbox to use
:type mbx: :class:`mailbox.Mailbox`
:param mail: the mail to store
:type mail: :class:`email.message.Message` or ... |
361,243 | def delete_file_and_sync_source(self, owner, id, name, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_file_and_sync_source_with_http_info(owner, id, name, **kwargs)
else:
(data) = self.delete_file_and_sync_source_with_http_info(owner, id, name, **... | Delete a file
Delete a single file from a dataset by their name, including files added via URL.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def ca... |
361,244 | def signature(name: str) -> Optional[Tuple]:
return url_signature(name) if is_url(name) else file_signature(name) if is_file(name) else None | Return the file or URL signature for name
:param name:
:return: |
361,245 | def distance_stats_sqr(x, y, **kwargs):
if _can_use_fast_algorithm(x, y, **kwargs):
return _distance_stats_sqr_fast(x, y)
else:
return _distance_sqr_stats_naive_generic(
x, y,
matrix_centered=_distance_matrix,
product=mean_product,
**kwargs) | distance_stats_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimators for the squared distance covariance
and squared distance correlation between two random vectors, and the
individual squared distance variances.
Parameters
----------
x: array_like
First random vector. The co... |
361,246 | def exists(self, **kwargs):
if LooseVersion(self.tmos_ver) == LooseVersion():
return self._exists_11_6(**kwargs)
else:
return super(Network, self)._exists(**kwargs) | Some objects when deleted still return when called by their
direct URI, this is a known issue in 11.6.0. |
361,247 | def get_relative_path(self, domain, locale):
return self.relative_path_template.format(
domain=domain,
locale=locale,
extension=self.get_extension()
) | Gets the relative file path using the template.
@type domain: str
@param domain: The domain
@type locale: str
@param locale: The locale
@rtype: string
@return: The relative file path |
361,248 | def document_type2marc(self, key, value):
if value in DOCUMENT_TYPE_REVERSE_MAP and DOCUMENT_TYPE_REVERSE_MAP[value]:
return {: DOCUMENT_TYPE_REVERSE_MAP[value]} | Populate the ``980`` MARC field. |
361,249 | def extended_path(self):
if self.is_absolute() and not self.path.startswith("\\\\"):
return "\\\\?\\%s" % self.path
return self.path | Add prefix \\?\ to every absolute path, so that it's a "extended-length"
path, that should be longer than 259 characters (called: "MAX_PATH")
see:
https://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath |
361,250 | def sort_catalogue_chronologically(self):
dec_time = self.get_decimal_time()
idx = np.argsort(dec_time)
if np.all((idx[1:] - idx[:-1]) > 0.):
return
self.select_catalogue_events(idx) | Sorts the catalogue into chronological order |
361,251 | def _transform_col(self, x, i):
return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0) | Encode one categorical column into labels.
Args:
x (pandas.Series): a categorical column to encode
i (int): column index
Returns:
x (pandas.Series): a column with labels. |
361,252 | async def server_reflexive_candidate(protocol, stun_server):
loop = asyncio.get_event_loop()
stun_server = (
await loop.run_in_executor(None, socket.gethostbyname, stun_server[0]),
stun_server[1])
request = stun.Message(message_method=stun.Method.BINDING,
... | Query STUN server to obtain a server-reflexive candidate. |
361,253 | def DEFAULT_NULLVALUE(test):
return False if isinstance(test,bool) \
else 0 if isinstance(test,int) \
else 0.0 if isinstance(test,float) \
else | Returns a null value for each of various kinds of test values.
**Parameters**
**test** : bool, int, float or string
Value to test.
**Returns**
**null** : element in `[False, 0, 0.0, '']`
Null value corresponding to the given test value:
... |
361,254 | def combine_tensors_and_multiply(combination: str,
tensors: List[torch.Tensor],
weights: torch.nn.Parameter) -> torch.Tensor:
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combinat... | Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining.
This is a separate function from ``combine_tensors`` because we try to avoid instantiating
large intermediate tensors during the combination, which is possible because we know that we're
going to be multiplying by a w... |
361,255 | def cli():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"dataset_uri",
help="Dtool dataset URI"
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
help="Only return the http URI"
)
args = parser.parse_ar... | Command line utility to HTTP enable (publish) a dataset. |
361,256 | def getMetadata(self, objectId=None, **filters):
filters.update({"urn": objectId})
return self.getCapabilities(**filters) | Request metadata about a text or a collection
:param objectId: Filter for some object identifier
:param filters: Kwargs parameters. URN and Inv are available
:return: GetCapabilities CTS API request response |
361,257 | def _process_all_1(self, texts:Collection[str]) -> List[List[str]]:
"Process a list of `texts` in one process."
tok = self.tok_func(self.lang)
if self.special_cases: tok.add_special_cases(self.special_cases)
return [self.process_text(str(t), tok) for t in texts] | Process a list of `texts` in one process. |
361,258 | def get_instance(self, payload):
return TaskChannelInstance(self._version, payload, workspace_sid=self._solution[], ) | Build an instance of TaskChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_channel.TaskChannelInstance |
361,259 | def map_new(w: int, h: int) -> tcod.map.Map:
return tcod.map.Map(w, h) | Return a :any:`tcod.map.Map` with a width and height.
.. deprecated:: 4.5
Use the :any:`tcod.map` module for working with field-of-view,
or :any:`tcod.path` for working with path-finding. |
361,260 | def execute_order(self, order_params, private_key):
order_id = order_params[]
api_params = self.sign_execute_order_function[self.blockchain](order_params, private_key)
return self.request.post(path=.format(order_id), json_data=api_params) | This function executes the order created before it and signs the transaction to be submitted to the blockchain.
Execution of this function is as follows::
execute_order(order_params=create_order, private_key=kp)
The expected return result for this function is the same as the execute_order ... |
361,261 | def interp_S_t(S, t, z, z_new, p=None):
import numpy
isscalar = False
if not numpy.iterable(z_new):
isscalar = True
z_new = [z_new]
z_new = numpy.asarray(z_new)
inverted = False
if z[1] - z[0] < 0:
inverted = True
z = z[::-1]
S = S[.... | Linearly interpolate CTD S, t, and p (optional) from `z` to `z_new`.
Args
----
S: ndarray
CTD salinities
t: ndarray
CTD temperatures
z: ndarray
CTD Depths, must be a strictly increasing or decreasing 1-D array, and
its length must match the last dimension of `S` and ... |
361,262 | def wait(self, timeout_ms=None):
closed = timeouts.loop_until_timeout_or_true(
timeouts.PolledTimeout.from_millis(timeout_ms),
self.stream.is_closed, .1)
if closed:
if hasattr(self.stdout, ):
return self.stdout.getvalue()
return True
return None | Block until this command has completed.
Args:
timeout_ms: Timeout, in milliseconds, to wait.
Returns:
Output of the command if it complete and self.stdout is a StringIO
object or was passed in as None. Returns True if the command completed but
stdout was provided (and was not a StringIO o... |
361,263 | def create_decl_string(
return_type, arguments_types, with_defaults=True):
return free_function_type_t.NAME_TEMPLATE % {
: return_type.build_decl_string(with_defaults),
: .join(
[_f(x, with_defaults) for x in arguments_types])} | Returns free function type
:param return_type: function return type
:type return_type: :class:`type_t`
:param arguments_types: list of argument :class:`type <type_t>`
:rtype: :class:`free_function_type_t` |
361,264 | def get_value_ddist(self, attr_name, attr_value):
assert not self.tree.data.is_continuous_class, \
"Discrete distributions are only maintained for " + \
"discrete class types."
ddist = DDist()
cls_counts = self._attr_class_value_counts[attr_name][attr_value]
... | Returns the class value probability distribution of the given
attribute value. |
361,265 | def handle_join(self, params):
channel_names = params.split(, 1)[0]
for channel_name in channel_names.split():
r_channel_name = channel_name.strip()
if not re.match(, r_channel_name):
raise IRCError.from_name(
,
... | Handle the JOINing of a user to a channel. Valid channel names start
with a # and consist of a-z, A-Z, 0-9 and/or '_'. |
361,266 | def update_model(self, sentences, update_labels_bool):
n_sentences = self._add_new_labels(sentences)
n = self.model.syn0.shape[0]
self.model.syn0 = np.vstack((
self.model.syn0,
np.empty((n_sentences, self.model.layer1_size), dtype=np.float32)
)... | takes a list of sentenes and updates an existing model. Vectors will be
callable through self.model[label]
update_labels_bool: boolean that says whether to train the model (self.model.train_words = True)
or simply to get vectors for the documents (self.model.train_words = False)
s... |
361,267 | def join_path(fname:PathOrStr, path:PathOrStr=)->Path:
"Return `Path(path)/Path(fname)`, `path` defaults to current dir."
return Path(path)/Path(fname) | Return `Path(path)/Path(fname)`, `path` defaults to current dir. |
361,268 | def _xlimrev(self):
xmax,xmin=pyl.xlim()
pyl.xlim(xmin,xmax) | reverse xrange |
361,269 | def relevant_transcripts(self, var_g):
tx = self.hdp.get_tx_for_region(var_g.ac, self.alt_aln_method, var_g.posedit.pos.start.base,
var_g.posedit.pos.end.base)
return [e["tx_ac"] for e in tx] | return list of transcripts accessions (strings) for given variant,
selected by genomic overlap |
361,270 | def group_indices(groupid_list):
item_list = range(len(groupid_list))
grouped_dict = util_dict.group_items(item_list, groupid_list)
keys_ = list(grouped_dict.keys())
try:
keys = sorted(keys_)
except TypeError:
keys = util_list.sortedby2(keys_, keys_)
groupxs = ... | groups indicies of each item in ``groupid_list``
Args:
groupid_list (list): list of group ids
SeeAlso:
vt.group_indices - optimized numpy version
ut.apply_grouping
CommandLine:
python -m utool.util_alg --test-group_indices
python3 -m utool.util_alg --test-group_ind... |
361,271 | def vhosts():
*
cmd = .format(_detect_os())
ret = {}
namevhost =
out = __salt__[](cmd)
for line in out.splitlines():
if not line:
continue
comps = line.split()
if in line:
namevhost = comps[0]
ret[namevhost] = {}
else:
... | Show the settings as parsed from the config file (currently
only shows the virtualhost settings) (``apachectl -S``).
Because each additional virtual host adds to the execution
time, this command may require a long timeout be specified
by using ``-t 10``.
CLI Example:
.. code-block:: bash
... |
361,272 | def is_younger(path, age):
try:
return time.time() - os.path.getmtime(path) < age
except (OSError, TypeError):
return False | :param str|None path: Path to file
:param int|float age: How many seconds to consider the file too old
:return bool: True if file exists and is younger than 'age' seconds |
361,273 | def nrows(self):
if not self._ex._cache.nrows_valid():
self._ex._cache.flush()
self._frame(fill_cache=True)
return self._ex._cache.nrows | Number of rows in the dataframe (int). |
361,274 | def lookup(self, iterable, gather=False):
for result in self.root.lookup(iterable,
gather=gather,
edit_distance=0,
max_edit_distance=self.max_edit_distance,
... | Call the lookup on the root node with the given parameters.
Args
iterable(index or key): Used to retrive nodes from tree
gather(bool): this is passed down to the root node lookup
Notes:
max_edit_distance and match_threshold come from the init |
361,275 | def get_formatter(self, handler):
if isinstance(handler, logging.handlers.SysLogHandler):
formatter =
else:
formatter =
for p in self.prefix:
formatter += % (p)
formatter = formatter +
return logging.Formatter(formatter) | Return formatters according to handler.
All handlers are the same format, except syslog.
We omit time when syslogging. |
361,276 | def appendRecords(self, records, progressCB=None):
for record in records:
self.appendRecord(record)
if progressCB is not None:
progressCB() | Saves multiple records in the underlying storage.
:param records: array of records as in
:meth:`~.FileRecordStream.appendRecord`
:param progressCB: (function) callback to report progress |
361,277 | def _from_binary_b_ace(cls, binary_stream):
access_flags = cls._REPR.unpack(binary_stream[:cls._REPR.size])[0]
sid = SID.create_from_binary(binary_stream[cls._REPR.size:])
nw_obj = cls((ACEAccessFlags(access_flags), sid))
return nw_obj | See base class. |
361,278 | def visible_suite_paths(cls, paths=None):
suite_paths = []
if paths is None:
paths = os.getenv("PATH", "").split(os.pathsep)
for path in paths:
if path and os.path.isdir(path):
path_ = os.path.dirname(path)
filepath = os.path.join(... | Get a list of paths to suites that are visible on $PATH.
Returns:
List of str. |
361,279 | def set_initial_state(self, initial_state, initial_frames):
self.env.set_initial_state(initial_state, initial_frames)
self._initial_frames = initial_frames | Sets the state that will be used on next reset. |
361,280 | def get_proficiency_lookup_session(self):
if not self.supports_proficiency_lookup():
raise Unimplemented()
try:
from . import sessions
except ImportError:
raise OperationFailed()
try:
session = sessions.ProficiencyLookupSession(run... | Gets the OsidSession associated with the proficiency lookup
service.
return: (osid.learning.ProficiencyLookupSession) - a
ProficiencyLookupSession
raise: OperationFailed - unable to complete request
raise: Unimplemented - supports_proficiency_lookup() is false
... |
361,281 | def _merge_data_trace_events(self, event):
if isinstance(event, events.TraceDataTraceEvent):
if self._pending_data_trace is None:
self._pending_data_trace = event
else:
if event.compa... | ! @brief Look for pairs of data trace events and merge. |
361,282 | def delete_site(self, site_name, replacement_site=None):
site = self.find_by_name(site_name, self.sites)
if not site:
return False
self.sites.remove(site)
if site.location:
site.location.sites.remove(site)
samples = site.samples
for samp i... | Remove site with name site_name from self.sites.
If the site belonged to a location, remove it from the location's site list.
If the site had any samples, change sample.site to "". |
361,283 | def isobaric_to_ambient_temperature(self, data):
P = data[] / 100.0
Tiso = data[]
Td = data[] - 273.15
e = 6.11 * 10**((7.5 * Td) / (Td + 273.3))
w = 0.622 * (e / (P - e))
... | Calculates temperature from isobaric temperature.
Parameters
----------
data: DataFrame
Must contain columns pressure, temperature_iso,
temperature_dew_iso. Input temperature in K.
Returns
-------
temperature : Series
Temperature in K |
361,284 | def _in_class(self, node):
indent = self._get_indent(node)
for indent_dict in reversed(self._indent_stack):
if (indent_dict["level"] < indent) or (indent_dict["type"] == "module"):
return indent_dict["type"] == "class" | Find if callable is function or method. |
361,285 | def check_auth(username, pwd):
cfg = get_current_config()
return username == cfg["dashboard_httpauth"].split(
":")[0] and pwd == cfg["dashboard_httpauth"].split(":")[1] | This function is called to check if a username /
password combination is valid. |
361,286 | def group_indices(self):
if not self.plydata_groups:
return np.ones(len(self), dtype=int)
grouper = self.groupby()
indices = np.empty(len(self), dtype=int)
for i, (_, idx) in enumerate(sorted(grouper.indices.items())):
indices[idx] = i
r... | Return group indices |
361,287 | def get_parent_books(self, book_id):
if self._catalog_session is not None:
return self._catalog_session.get_parent_catalogs(catalog_id=book_id)
return BookLookupSession(
self._proxy,
self._runtime).get_books_by_ids(
list(self... | Gets the parent books of the given ``id``.
arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to
query
return: (osid.commenting.BookList) - the parent books of the
``id``
raise: NotFound - a ``Book`` identified by ``Id is`` not found
raise: NullAr... |
361,288 | def Rscript_cmd():
rscript = which(os.path.join(get_bcbio_bin(), "Rscript"))
if rscript:
return rscript
else:
return which("Rscript") | Retrieve path to locally installed Rscript or first in PATH.
Prefers Rscript version installed via conda to a system version. |
361,289 | def add_epoch_number(batch: Batch, epoch: int) -> Batch:
for instance in batch.instances:
instance.fields[] = MetadataField(epoch)
return batch | Add the epoch number to the batch instances as a MetadataField. |
361,290 | def syncImage(img, current, session):
def _img_str(i):
return "%s - %s" % (i.type, i.description)
for db_img in current.images:
img_info = (img.type, img.md5, img.size)
db_img_info = (db_img.type, db_img.md5, db_img.size)
if db_img_info == img_info:
img = None
... | Add or updated the Image. |
361,291 | def get_query_tables(query):
tables = []
last_keyword = None
last_token = None
table_syntax_keywords = [
, , , , , , ,
, ,
, ,
,
]
for token in get_query_tokens(query):
if token.is_keyword and tok... | :type query str
:rtype: list[str] |
361,292 | def git_clone(sub_repo, branch, commit = None, cwd = None, no_submodules = False):
s repo. So far
Travis-CI is the most limiting in the sense of only fetching partial
history of the repo.
boostorg.gitt do depth as we get merge errors.
"--quiet","--no-recurse-submodules")
... | This clone mimicks the way Travis-CI clones a project's repo. So far
Travis-CI is the most limiting in the sense of only fetching partial
history of the repo. |
361,293 | def _process_filters(filter_dictionary):
def filter_item(field):
if filter_dictionary[field] is not None:
return {
"or": [
_get_filter_field(field, filter_dictionary[field]),
{
"missing": {
... | We have a filter_dictionary - this means that if the field is included
and matches, then we can include, OR if the field is undefined, then we
assume it is safe to include |
361,294 | def create_git_ref(self, ref, sha):
assert isinstance(ref, (str, unicode)), ref
assert isinstance(sha, (str, unicode)), sha
post_parameters = {
"ref": ref,
"sha": sha,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
... | :calls: `POST /repos/:owner/:repo/git/refs <http://developer.github.com/v3/git/refs>`_
:param ref: string
:param sha: string
:rtype: :class:`github.GitRef.GitRef` |
361,295 | def run(self, x):
try:
x = np.array(x)
except:
raise ValueError()
N = len(x)
if self.outputs == 1:
y = np.zeros(N)
else:
y = np.zeros((N, self.outputs))
for k in range(N):
... | Function for batch usage of already trained and tested MLP.
**Args:**
* `x` : input array (2-dimensional array).
Every row represents one input vector (features).
**Returns:**
* `y`: output vector (n-dimensional array). Every row represents
output (out... |
361,296 | def unassign_agent_from_resource(self, agent_id, resource_id):
collection = JSONClientValidated(,
collection=,
runtime=self._runtime)
resource = collection.find_one({: ObjectId(resource_id.get_identifier())})
... | Removes an ``Agent`` from a ``Resource``.
arg: agent_id (osid.id.Id): the ``Id`` of the ``Agent``
arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource``
raise: NotFound - ``agent_id`` or ``resource_id`` not found or
``agent_id`` not assigned to ``resource_id``
... |
361,297 | def _on_mouse_moved(self, event):
if event.modifiers() & Qt.ControlModifier:
self._select_word_under_mouse_cursor()
else:
self._remove_decoration()
self.editor.set_mouse_cursor(Qt.IBeamCursor)
self._previous_cursor_start = -1
self._pre... | mouse moved callback |
361,298 | def add_users(self, category):
mapping = {: , : ,
: }
if category not in mapping:
print(.format(category))
return
func = getattr(self.sub, mapping[category])
print()
data = sys.stdin.read().strip()
for name in re.split(... | Add users to 'banned', 'contributor', or 'moderator'. |
361,299 | def transform(self):
i = self.inclination
Ω = self.longitude_of_ascending_node
ω = self.argument_of_periapsis
si = sin(i)
ci = cos(i)
sΩ = sin(Ω)
cΩ = cos(Ω)
sω = sin(ω)
cω = cos(ω)
Q = np.array([
[-sΩ*ci*sω + cΩ*cω,... | P⃗,Q⃗,W⃗ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.