Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
360,400 | def is_instance_or_subclass(val, class_):
try:
return issubclass(val, class_)
except TypeError:
return isinstance(val, class_) | Return True if ``val`` is either a subclass or instance of ``class_``. |
360,401 | def dict_from_hdf5(dict_like, h5group):
for name, value in h5group.attrs.items():
dict_like[name] = value | Load a dictionnary-like object from a h5 file group |
360,402 | def _get_data(filenames):
if filenames:
data = ""
for filename in filenames:
with open(filename, "rb") as f:
data += f.read()
else:
data = sys.stdin.read()
return data | Read data from file(s) or STDIN.
Args:
filenames (list): List of files to read to get data. If empty or
None, read from STDIN. |
360,403 | def convert_dict(d, cls=AttrDict):
s values to a specified type
(defaults to AttrDict)
'
for k, v in d.items():
if isinstance(v, Mapping):
d[k] = convert_dict(v)
elif isinstance(v, list):
for i, e in enumerate(v):
if isinstance(e, Mapping):
... | recursively convert a normal Mapping `d` and it's values to a specified type
(defaults to AttrDict) |
360,404 | def get_transformer_choices():
from luma.emulator.render import transformer
return [fn for fn in dir(transformer) if fn[0:2] != "__"] | :rtype: list |
360,405 | def JECXZ(cpu, target):
cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.ECX == 0, target.read(), cpu.PC) | Jumps short if ECX register is 0.
:param cpu: current CPU.
:param target: destination operand. |
360,406 | def _set_secondary_path(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("secpath_name",secondary_path.secondary_path, yang_name="secondary-path", rest_name="secondary-path", parent=self, is_container=, user_ordered=False, path_helper=self... | Setter method for secondary_path, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_secondary_path is considered as a private
method. Backends looking to populate this variable should... |
360,407 | def _AddToSingleColumnTable(self, tableName, columnHeading, newValue):
match = None
currentTable = self._GetFromSingleColumnTable(tableName)
if currentTable is not None:
for currentValue in currentTable:
if currentValue == newValue:
match = True
if match is None:
goo... | Add an entry to a table containing a single column. Checks existing
table entries to avoid duplicate entries if the given value already
exists in the table.
Parameters
----------
tableName : string
Name of table to add entry to.
columnHeading : string
Name of column heading... |
360,408 | def get_opcodes(self, script, verify_minimal_data=False, pc=0):
while pc < len(script):
opcode, data, new_pc, is_ok = self.scriptStreamer.get_opcode(
script, pc, verify_minimal_data=verify_minimal_data)
yield opcode, data, pc, new_pc
pc = new_pc | Iterator. Return opcode, data, pc, new_pc at each step |
360,409 | def set_options(
self, time_duration: int = 1, time_reset: int = 2, peak: int = -30
) -> None:
self._time_duration = time_duration
self._time_reset = time_reset
self._peak = peak | Set option parameter for noise sensor. |
360,410 | def to_pngs(pdf_path):
pdf_list = split_pdf(pdf_path)
pngs = []
for pdf in pdf_list:
pngs.append(to_png(pdf))
os.remove(pdf)
return pngs | Converts a multi-page pdfs to a list of pngs via the `sips` command
:returns: A list of converted pngs |
360,411 | def from_bool(value):
if value in [, ]:
value = True
elif value in [, ]:
value = False
elif value == :
value = None
return value | Convert zfs bool to python bool |
360,412 | def _verify_password(self, raw_password, hashed_password):
PraetorianError.require_condition(
self.pwd_ctx is not None,
"Praetorian must be initialized before this method is available",
)
return self.pwd_ctx.verify(raw_password, hashed_password) | Verifies that a plaintext password matches the hashed version of that
password using the stored passlib password context |
360,413 | def evaluate_recurrence_coefficients(
distribution,
k_data,
parameters=None,
cache=None,
):
assert len(k_data) == len(distribution), (
"distribution %s is not of length %d" % (distribution, len(k_data)))
assert len(k_data.shape) == 1
def cache_key(distribution):... | Evaluate three terms recurrence coefficients (TTR).
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate recurrence coefficients for.
parameters (:py:data:typing.Any):
Collection of parameters to overri... |
360,414 | def _create_authenticator(a_service):
if not isinstance(a_service, sm_messages.Service):
raise ValueError(u"service is None or not an instance of Service")
authentication = a_service.authentication
if not authentication:
_logger.info(u"authentication is not configured in service, "
... | Create an instance of :class:`google.auth.tokens.Authenticator`.
Args:
a_service (:class:`endpoints_management.gen.servicemanagement_v1_messages.Service`): a
service instance |
360,415 | def set_metadata(self, fp):
base_url = self._client.get_url(, , , {: self.id})
self._manager._metadata.set(base_url, fp)
r = self._client.request(, base_url)
return self._deserialize(r.json(), self._manager) | Set the XML metadata on a set.
:param file fp: file-like object to read the XML metadata from. |
360,416 | def has_netmask(interface_name):
for interface in interfaces():
if interface["name"] == interface_name:
if interface["netmask"] and len(interface["netmask"]) > 0:
return True
return False
return False | Checks if an interface has a netmask.
:param interface: interface name
:returns: boolean |
360,417 | def bayesianUpperLimit(self, alpha, steps=1.e5, plot=False):
x_dense, y_dense = self.densify()
y_dense -= np.max(y_dense)
f = scipy.interpolate.interp1d(x_dense, y_dense, kind=)
x = np.linspace(0., np.max(x_dense), steps)
pdf = np.exp(f(x) / 2.)
cut = (pdf / np.... | Compute one-sided upper limit using Bayesian Method of Helene.
Several methods of increasing numerical stability have been implemented. |
360,418 | def run(self):
self._logger.debug("Starting Dummy Model: modelID=%s;" % (self._modelID))
periodic = self._initPeriodicActivities()
self._optimizedMetricLabel = self._optimizeKeyPattern
self._reportMetricLabels = [self._optimizeKeyPattern]
if self._iterations >=... | Runs the given OPF task against the given Model instance |
360,419 | def Disconnect(self, reason=None, isDead=True):
self.disconnecting = True
self.expect_verack_next = False
if reason:
logger.debug(f"Disconnecting with reason: {reason}")
self.stop_block_loop()
self.stop_header_loop()
self.stop_peerinfo_loop()
... | Close the connection with the remote node client. |
360,420 | def start_tasks(self):
while self.tasks_at_once > len(self.pending_results) and self._has_more_tasks():
task, parent_result = self.tasks.popleft()
self.execute_task(task, parent_result) | Start however many tasks we can based on our limits and what we have left to finish. |
360,421 | def iter_regions(self):
for x,z in self.regionfiles.keys():
close_after_use = False
if (x,z) in self.regions:
regionfile = self.regions[(x,z)]
else:
regionfile = region.RegionFile(sel... | Return an iterable list of all region files. Use this function if you only
want to loop through each region files once, and do not want to cache the results. |
360,422 | def check_ip(self, ip):
self._last_result = None
if is_valid_ipv4(ip):
key = None
if self._use_cache:
key = self._make_cache_key(ip)
self._last_result = self._cache.get(key, version=self._cache_version)
if self._last_result ... | Check IP trough the httpBL API
:param ip: ipv4 ip address
:return: httpBL results or None if any error is occurred |
360,423 | def DOM_discardSearchResults(self, searchId):
assert isinstance(searchId, (str,)
), "Argument must be of type str. Received type: " % type(
searchId)
subdom_funcs = self.synchronous_command(,
searchId=searchId)
return subdom_funcs | Function path: DOM.discardSearchResults
Domain: DOM
Method name: discardSearchResults
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'searchId' (type: string) -> Unique search session identifier.
No return value.
Description: Discards search results ... |
360,424 | def json_post_required(*decorator_args):
def decorator(method):
@wraps(method)
def wrapper(*args, **kwargs):
field = decorator_args[0]
if len(decorator_args) == 2:
request_name = decorator_args[1]
else:
request_name = field
... | View decorator that enforces that the method was called using POST and
contains a field containing a JSON dictionary. This method should
only be used to wrap views and assumes the first argument of the method
being wrapped is a ``request`` object.
.. code-block:: python
@json_post_required('da... |
360,425 | def getTarget(self):
return self.getCenter().offset(self._target.x, self._target.y) | Returns the location of the match click target (center by default, but may be offset) |
360,426 | def unlock(self, session=None):
cmd = SON([("fsyncUnlock", 1)])
with self._socket_for_writes(session) as sock_info:
if sock_info.max_wire_version >= 4:
try:
with self._tmp_session(session) as s:
sock_info.command(
... | Unlock a previously locked server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.6
Added ``session`` parameter. |
360,427 | def thermostat_state(self, name):
self._validate_thermostat_state_name(name)
id_ = next((key for key in STATES.keys()
if STATES[key].lower() == name.lower()), None)
data = copy.copy(self._parameters)
data.update({: 2,
: id_})
resp... | Changes the thermostat state to the one passed as an argument as name
:param name: The name of the thermostat state to change to. |
360,428 | def stats_keyboard(events, table):
if len(events) < 2: return [], []
deltas, prev_dt = [], None
sessions, session = [], None
UNBROKEN_DELTA = datetime.timedelta(seconds=conf.KeyboardSessionMaxDelta)
blank = collections.defaultdict(lambda: collections.defaultdict(int))
collated = [bla... | Return statistics and collated events for keyboard events. |
360,429 | async def handler(self):
self.ws = await websockets.connect(self.url, ssl=self.ssl)
while self.ws:
message = await self.ws.recv()
for handle in self.on_message:
if asyncio.iscoroutinefunction(handle):
await handle(self, message)
else:
handle(self, message) | Handle loop, get and process messages |
360,430 | def create(self, from_=None, **kwargs):
if "dummy" in kwargs and kwargs["dummy"]:
response, instance = self.request("POST", self.uri, data=kwargs)
return instance
if from_:
kwargs["from"] = from_
return self.create_instance(kwargs) | Create and send a new outbound message.
Returns :class:`Message` object contains next attributes: 'id', 'href', 'type',
'sessionId', 'bulkId', 'messageId', 'scheduledId'.
:Example:
message = client.messages.create(from_="447624800500", phones="999000001", text="Hello!", lists="1909100"... |
360,431 | def signal(signal=None):
t ship with an init script so one must be created.
signal : str (None)
The command to pass to the apache solr init valid values are ,
, and
CLI Example:
.. code-block:: bash
salt solr.signal restart
startstoprestartor {0}{0} is an invalid signal... | Signals Apache Solr to start, stop, or restart. Obviously this is only
going to work if the minion resides on the solr host. Additionally Solr
doesn't ship with an init script so one must be created.
signal : str (None)
The command to pass to the apache solr init valid values are 'start',
'... |
360,432 | def _set_output_arguments(self):
group = self.parser.add_argument_group()
group.add_argument(, , type=argparse.FileType(),
dest=, default=sys.stdout,
help="output file")
group.add_argument(, dest=, action=,
... | Activate output arguments parsing |
360,433 | def find_vext_files(self):
packages = self.depends_on("vext")
vext_files = []
for location in [package.get("location") for package in packages]:
if not location:
continue
vext_files.extend(glob(join(location, "*.vext")))
return vext_files | :return: Absolute paths to any provided vext files |
360,434 | def push(self, channel_id, data):
channel_path = self.channel_path(channel_id)
response = requests.post(channel_path, data)
return response.json() | Push message with POST ``data`` for ``channel_id`` |
360,435 | def fontFamilyIndex(qFont, families):
try:
return families.index(qFont.family())
except ValueError:
if False and DEBUGGING:
raise
else:
logger.warn("{} not found in font families, using default.".format(qFont.family()))
return families.index(qFont... | Searches the index of qFont.family in the families list.
If qFont.family() is not in the list, the index of qFont.defaultFamily() is returned.
If that is also not present an error is raised. |
360,436 | def _xml_convert(self, element):
children = list(element)
if len(children) == 0:
return self._type_convert(element.text)
else:
if children[0].tag == "list-item":
data = []
for child in children:
d... | convert the xml `element` into the corresponding python object |
360,437 | def document(info=None, input=None, output=None):
def wrapper(func):
if info is not None:
setattr(func, "_swg_info", info)
if input is not None:
setattr(func, "_swg_input", input)
if output is not None:
setattr(func, "_swg_output", output)
ret... | Add extra information about request handler and its params |
360,438 | def _process_consensus_mhcii(mhc_file, normal=False):
core_col = None
results = pandas.DataFrame(columns=[, , , ])
with open(mhc_file, ) as mf:
peptides = set()
for line in mf:
if not line.startswith():
continue
line = line.strip().... | Process the results from running IEDB MHCII binding predictions using the consensus method into
a pandas dataframe.
:param str mhc_file: Output file containing consensus mhcii:peptide binding predictions
:param bool normal: Is this processing the results of a normal?
:return: Results in a tabular forma... |
360,439 | def _request(self, path, method, body=None):
"Base request function"
h = httplib2.Http()
resp, content = h.request(
self.base_url + path,
method,
body = json.dumps(body),
)
if resp[] == "200":
return json.loads(content)
else... | Base request function |
360,440 | def read_inifile (self, noexistok=False, typed=False):
if typed:
from .tinifile import read_stream
else:
from .inifile import read_stream
try:
with self.open () as f:
for item in read_stream (f):
yield item
... | Open assuming an “ini-file” format and return a generator yielding data
records using either :func:`pwkit.inifile.read_stream` (if *typed* is
false) or :func:`pwkit.tinifile.read_stream` (if it’s true). The
latter version is designed to work with numerical data using the
:mod:`pwkit.msmt... |
360,441 | def add_device(self, device: Union[DeviceType, str]) -> None:
try:
if self.mutable:
_device = self.get_contentclass()(device)
self._name2device[_device.name] = _device
_id2devices[_device][id(self)] = self
else:
rai... | Add the given |Node| or |Element| object to the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Nodes
>>> nodes = Nodes()
>>> nodes.add_device('old_node')
>>> nodes
Nodes("old_node")
>>> nodes.add_devi... |
360,442 | def planner(self, *, resource=):
if not isinstance(self.protocol, MSGraphProtocol):
raise RuntimeError(
)
return Planner(parent=self, main_resource=resource) | Get an instance to read information from Microsoft planner |
360,443 | def from_Track(track):
if not hasattr(track, ):
return False
lastkey = Key()
lasttime = (4, 4)
result =
for bar in track.bars:
if lastkey != bar.key:
showkey = True
else:
showkey = False
if lasttime != bar.meter:
sh... | Process a Track object and return the LilyPond equivalent in a string. |
360,444 | def folder_shared_message(self, request, user, folder):
messages.success(request, _("Folder {} is now shared with {}".format(folder, user))) | Send messages.success message after successful share. |
360,445 | def forward(self, inputs, label, begin_state, sampled_values):
encoded = self.embedding(inputs)
length = inputs.shape[0]
batch_size = inputs.shape[1]
encoded, out_states = self.encoder.unroll(length, encoded, begin_state,
layout... | Defines the forward computation.
Parameters
-----------
inputs : NDArray
input tensor with shape `(sequence_length, batch_size)`
when `layout` is "TNC".
begin_state : list
initial recurrent state tensor with length equals to num_layers*2.
... |
360,446 | def exec_rabbitmqctl_list(self, resources, args=[],
rabbitmq_opts=[, ]):
command = .format(resources)
return self.exec_rabbitmqctl(command, args, rabbitmq_opts) | Execute a ``rabbitmqctl`` command to list the given resources.
:param resources: the resources to list, e.g. ``'vhosts'``
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to pass to ``rabbitmqctl``
:returns: a tuple of the command ... |
360,447 | def display(table, limit=0, vrepr=None, index_header=None, caption=None,
tr_style=None, td_styles=None, encoding=None, truncate=None,
epilogue=None):
from IPython.core.display import display_html
html = _display_html(table, limit=limit, vrepr=vrepr,
index_h... | Display a table inline within an IPython notebook. |
360,448 | def is_causal(self):
return all(filt.is_causal() for filt in self.callables
if hasattr(filt, "is_causal")) | Tests whether all filters in the list are causal (i.e., no future-data
delay in positive ``z`` exponents). Non-linear filters are seem as causal
by default. CascadeFilter and ParallelFilter are causal if all the
filters they group are causal. |
360,449 | def item_straat_adapter(obj, request):
return {
: obj.id,
: obj.label,
: obj.namen,
: {
: obj.status.id,
: obj.status.naam,
: obj.status.definitie
},
: {
: obj.taal.id,
: obj.taal.naam,
: obj... | Adapter for rendering an object of
:class:`crabpy.gateway.crab.Straat` to json. |
360,450 | def get_help(command):
assert isinstance(command, click.Command)
def help_(self):
extra = {}
for key, value in command.context_settings.items():
if key not in extra:
extra[key] = value
return help_ | Get the Cmd help function from the click command
:param command: The click Command object
:return: the help_* method for Cmd
:rtype: function |
360,451 | def extract_element_internationalized_comment(element):
element_entry_comment = get_element_attribute_or_empty(element, )
if element_entry_comment == "":
try:
element_entry_comment = element.getElementsByTagName()[0].firstChild.nodeValue
except Exception:
element_ent... | Extracts the xib element's comment, if the element has been internationalized.
Args:
element (element): The element from which to extract the comment.
Returns:
The element's internationalized comment, None if it does not exist, or hasn't been internationalized (according
to the JTLocal... |
360,452 | def get_value(self, default=None):
if default is None:
default =
try:
text = self.currentText()
except ValueError:
lg.debug( + str(text) + +
+ str(default))
text = default
self.set_value(text)
... | Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox |
360,453 | def from_week(cls, year, iso_week):
first_day = date_from_iso_week(year, iso_week)
return cls.from_date(first_day, period="week") | Create ``daterange`` based on a year and an ISO week
:param year: Year as an integer
:param iso_week: ISO week number
:return: A new ``daterange`` for the given week
.. versionadded:: 0.4.0 |
360,454 | def parse_color(color):
return col | Return the RGB 0-255 representation of the current string
passed.
It first tries to match the string with DVI color names. |
360,455 | def setup_arrow_buttons(self):
vsb = self.scrollarea.verticalScrollBar()
style = vsb.style()
opt = QStyleOptionSlider()
vsb.initStyleOption(opt)
vsb_up_arrow = style.subControlRect(
QStyle.CC_ScrollBar, opt, QStyle.SC_ScrollBarAddLine, s... | Setup the up and down arrow buttons that are placed at the top and
bottom of the scrollarea. |
360,456 | def unwrap(self, message, signature):
plain_text = _Ntlm2Session.decrypt(self, message)
_Ntlm2Session.verify(self, plain_text, signature)
return plain_text | NTLM GSSUnwrap()
:param message: The message to be decrypted
:return: The decrypted message |
360,457 | def base_url(self, url):
parts = list(self.parse_url(url))
parts[4:] = [ for i in parts[4:]]
return urlunparse(parts) | Return url without querystring or fragment |
360,458 | def delete(self, port, qos_policy=None):
LOG.info("Deleting QoS policy %(qos_policy)s on port %(port)s",
dict(qos_policy=qos_policy, port=port))
self._utils.remove_port_qos_rule(port["port_id"]) | Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port. |
360,459 | def has_parent_books(self, book_id):
if self._catalog_session is not None:
return self._catalog_session.has_parent_catalogs(catalog_id=book_id)
return self._hierarchy_session.has_parents(id_=book_id) | Tests if the ``Book`` has any parents.
arg: book_id (osid.id.Id): a book ``Id``
return: (boolean) - ``true`` if the book has parents, f ``alse``
otherwise
raise: NotFound - ``book_id`` is not found
raise: NullArgument - ``book_id`` is ``null``
raise: Operat... |
360,460 | def get_response(response: Dict[str, Any]) -> JSONRPCResponse:
if "error" in response:
return ErrorResponse(**response)
return SuccessResponse(**response) | Converts a deserialized response into a JSONRPCResponse object.
The dictionary be either an error or success response, never a notification.
Args:
response: Deserialized response dictionary. We can assume the response is valid
JSON-RPC here, since it passed the jsonschema validation. |
360,461 | def _convert_num(self, sign):
| Converts number registered in get_number_from_sign.
input = ["a2", "☉", "be3"]
output = ["a₂", "☉", "be₃"]
:param sign: string
:return sign: string |
360,462 | def _start(self, my_task, force=False):
if not hasattr(my_task, ) and \
my_task._get_internal_data() is not None:
task_id = my_task._get_internal_data()
my_task.async_call = default_app.AsyncResult(task_id)
my_task.deserialized = True
... | Returns False when successfully fired, True otherwise |
360,463 | def Parse(self, stat, file_object, knowledge_base):
_, _ = stat, knowledge_base
lines = [
l.strip()
for l in utils.ReadFileBytesAsUnicode(file_object).splitlines()
]
return self.ParseLines(lines) | Parse the netgroup file and return User objects.
Lines are of the form:
group1 (-,user1,) (-,user2,) (-,user3,)
Groups are ignored, we return users in lines that match the filter regexes,
or all users in the file if no filters are specified.
We assume usernames are in the default regex format s... |
360,464 | def get_shared_files_from_shake(self,
shake_id=None,
before=None,
after=None):
if before and after:
raise Exception("You cannot specify both before and after keys")
endpoint ... | Returns a list of SharedFile objects from a particular shake.
Args:
shake_id (int): Shake from which to get a list of SharedFiles
before (str): get 10 SharedFile objects before (but not including)
the SharedFile given by `before` for the given Shake.
after (s... |
360,465 | def assign_force_field(ampal_obj, ff):
if hasattr(ampal_obj, ):
atoms = ampal_obj.get_atoms(ligands=True, inc_alt_states=True)
else:
atoms = ampal_obj.get_atoms(inc_alt_states=True)
for atom in atoms:
w_str = None
a_ff_id = None
if atom.element == :
c... | Assigns force field parameters to Atoms in the AMPAL object.
Parameters
----------
ampal_obj : AMPAL Object
Any AMPAL object with a `get_atoms` method.
ff: BuffForceField
The force field to be used for scoring. |
360,466 | def show_content(self, with_content=False):
if isinstance(self.model, LibraryStateModel) and self.model.show_content():
return not with_content or isinstance(self.model.state_copy, ContainerStateModel)
return False | Checks if the state is a library with the `show_content` flag set
:param with_content: If this parameter is `True`, the method return only True if the library represents a
ContainerState
:return: Whether the content of a library state is shown |
360,467 | def setup_cmd_parser(cls):
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
from_date=True,
token_auth=True,
archive=True)
group = pa... | Returns the GitLab argument parser. |
360,468 | def smoother(self):
if not self.filt:
self.filter()
self.smth = [self.filt[-1]]
for t, f in reversed(list(enumerate(self.filt[:-1]))):
self.smth += [smoother_step(self.ssm.F, f, self.pred[t + 1],
self.smth[t + 1])]
... | Backward recursion: compute mean/variance of marginal smoother.
Performs the filter step in a preliminary step if needed. |
360,469 | def memoize(f):
memory = {}
@wraps(f)
def new_f(*args):
try:
return memory[args]
except KeyError:
r = f(*args)
memory[args] = r
return r
return new_f | A decorator that memoizes a function result based on its parameters. For example, this can be
used in place of lazy initialization. If the decorating function is invoked by multiple
threads, the decorated function may be called more than once with the same arguments. |
360,470 | def construct_from(cls, values, **kwargs):
instance = cls(values.get(cls.ID_ATTR), **kwargs)
instance.refresh_from(values)
return instance | Used to create a new object from an HTTP response |
360,471 | def tokens(self):
spans = self.word_tokenizer.span_tokenize(self.text)
toks = [Token(
text=self.text[span[0]:span[1]],
start=span[0] + self.start,
end=span[1] + self.start,
lexicon=self.lexicon
) for span in spans]
return toks | Return a list of token Spans for this sentence. |
360,472 | def patch_docs(subclass, superclass):
funcs0 = inspect.getmembers(subclass, predicate=inspect.ismethod)
funcs1 = inspect.getmembers(superclass, predicate=inspect.ismethod)
funcs1 = [f[0] for f in funcs1]
for name, func in funcs0:
if name.startswith():
continue
if name... | Apply the documentation from ``superclass`` to ``subclass`` by filling
in all overridden member function docstrings with those from the
parent class |
360,473 | def setupModule(
self):
import pymysql as ms
logging.config.dictConfig(yaml.load(self.loggerConfig))
log = logging.getLogger(__name__)
connDict = yaml.load(self.dbConfig)
dbConn = ms.connect(
host=connDict[],
user=connDict[],
... | *The setupModule method*
**Return:**
- ``log`` -- a logger
- ``dbConn`` -- a database connection to a test database (details from yaml settings file)
- ``pathToInputDir`` -- path to modules own test input directory
- ``pathToOutputDir`` -- path to modules own tes... |
360,474 | def find_domain(session, name):
domain = session.query(Domain). \
filter(Domain.domain == name).first()
return domain | Find a domain.
Find a domain by its domain name using the given `session`.
When the domain does not exist the function will
return `None`.
:param session: database session
:param name: name of the domain to find
:returns: a domain object; `None` when the domain
does not exist |
360,475 | def matches_ordering(self, other):
a = CollinearMagneticStructureAnalyzer(
self.structure, overwrite_magmom_mode="normalize"
).get_structure_with_spin()
b_positive = CollinearMagneticStructureAnalyzer(
other, overwrite_magmom... | Compares the magnetic orderings of one structure with another.
:param other: Structure
:return (bool): |
360,476 | def run(self):
salt.utils.process.appendproctitle(self.__class__.__name__)
self.io_loop = tornado.ioloop.IOLoop()
with salt.utils.asynchronous.current_ioloop(self.io_loop):
if self.opts[] == :
epub_uri = int(self.opts[])
epull_uri = int(self.o... | Bind the pub and pull sockets for events |
360,477 | def _find_calls(self, ast_tree, called_module, called_func):
pout.vvvoompoom.v
s = set()
s.add("{}.{}".format(called_module, called_func))
if hasattr(ast_tree, ):
if ast_tree.name == called_func:
s.add(called_func)
if hasa... | scan the abstract source tree looking for possible ways to call the called_module
and called_func
since -- 7-2-12 -- Jay
example --
# import the module a couple ways:
import pout
from pout import v
from pout import v as voom
import p... |
360,478 | def _set_ieee_bpdu(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=ieee_bpdu.ieee_bpdu, is_container=, presence=False, yang_name="ieee-bpdu", rest_name="ieee-bpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_path... | Setter method for ieee_bpdu, mapped from YANG variable /rbridge_id/spanning_tree/ieee_bpdu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ieee_bpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... |
360,479 | def load_path(obj, file_type=None, **kwargs):
if isinstance(obj, Path):
return obj
elif util.is_file(obj):
loaded = path_loaders[file_type](obj,
file_type=file_type)
obj.close()
elif util.is_string(obj):
... | Load a file to a Path object.
Parameters
-----------
obj : One of the following:
- Path, Path2D, or Path3D objects
- open file object (dxf or svg)
- file name (dxf or svg)
- shapely.geometry.Polygon
- shapely.geometry.MultiLineString
- dict with kwargs ... |
360,480 | def create_key(key_type=,
key_length=1024,
name_real=,
name_comment=,
name_email=None,
subkey_type=None,
subkey_length=None,
expire_date=None,
use_passphrase=False,
user=None,
... | Create a key in the GPG keychain
.. note::
GPG key generation requires *a lot* of entropy and randomness.
Difficult to do over a remote connection, consider having
another process available which is generating randomness for
the machine. Also especially difficult on virtual machin... |
360,481 | def compose_mbox(projects):
mbox_archives =
mailing_lists_projects = [project for project in projects if in projects[project]]
for mailing_lists in mailing_lists_projects:
projects[mailing_lists][] = []
for mailing_list in projects[mailing_lists][]:
if in mailing_list:
... | Compose projects.json only for mbox, but using the mailing_lists lists
change: 'https://dev.eclipse.org/mailman/listinfo/emft-dev'
to: 'emfg-dev /home/bitergia/mboxes/emft-dev.mbox/emft-dev.mbox
:param projects: projects.json
:return: projects.json with mbox |
360,482 | def ma_bias_ratio(self, day1, day2):
data1 = self.moving_average(self.price, day1)
data2 = self.moving_average(self.price, day2)
result = [data1[-i] - data2[-i] for i in range(1, min(len(data1), len(data2)) + 1)]
return result[::-1] | Calculate moving average bias ratio |
360,483 | def recover(y):
p = (y*y - 1) * inverse(D*y*y + 1)
x = powmod(p, (PRIME+3) // 8, PRIME)
if (x*x - p) % PRIME != 0:
i = powmod(2, (PRIME-1) // 4, PRIME)
x = (x*i) % PRIME
if x % 2 != 0:
x = PRIME - x
return x | given a value y, recover the preimage x |
360,484 | def update_wsnum_in_files(self, vernum):
self.version_num = vernum
for f in self.files:
url = self.files[f].get()
url = re.sub(r, self.version_num, url)
self.files[f][] = url
LOG.debug(
"Replacing WSNUMBER in %s with %s", ... | With the given version number ```vernum```,
update the source's version number, and replace in the file hashmap.
the version number is in the CHECKSUMS file.
:param vernum:
:return: |
360,485 | def integrate(self, fluxunits=):
u = self.fluxunits
self.convert(fluxunits)
wave, flux = self.getArrays()
self.convert(u)
return self.trapezoidIntegration(wave, flux) | Integrate the flux in given unit.
Integration is done using :meth:`~Integrator.trapezoidIntegration`
with ``x=wave`` and ``y=flux``, where flux has been
convert to given unit first.
.. math::
\\textnormal{result} = \\int F_{\\lambda} d\\lambda
Parameters
-... |
360,486 | def assign_bins(x, breaks, weight=None, pad=False, closed=):
right = closed ==
if weight is None:
weight = np.ones(len(x))
else:
weight = np.asarray(weight)
weight[np.isnan(weight)] = 0
bin_idx = pd.cut(x, bins=breaks, labels=False,
right=right, i... | Assign value in x to bins demacated by the break points
Parameters
----------
x : array_like
Values to be binned.
breaks : array_like
Sequence of break points.
weight : array_like
Weight of each value in `x`. Used in creating the frequency
table. If `None`, then each... |
360,487 | def nodes(self):
description = self._topology.description
return frozenset(s.address for s in description.known_servers) | Set of all currently connected servers.
.. warning:: When connected to a replica set the value of :attr:`nodes`
can change over time as :class:`MongoClient`'s view of the replica
set changes. :attr:`nodes` can also be an empty set when
:class:`MongoClient` is first instantiated an... |
360,488 | def run(self, *args):
if self.running:
return self
self._mut_finished(False)
self._mut_running(True)
stream = self.target(*args)
def subr():
self._mut_running(True)
try:
for each in stream:
... | You can choose whether to use lock method when running threads. |
360,489 | def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):
print()
if len(params[]) > 1:
raise AssertionError()
def target_layer(x, axis=int(params[][0])):
import tensorflow as tf
return tf.squeeze(x, axis=axis)
lambda_layer = keras.layers.Lambda(tar... | Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for... |
360,490 | def symlinks(self):
if not self._P.Block.Symlinks:
return []
return [decode_ay(path) for path in self._P.Block.Symlinks] | Known symlinks of the block device. |
360,491 | def remote(self):
from ambry.exc import NotFoundError
ds = self.dataset
if not in ds.data:
raise NotFoundError(.format(self.identity.fqname))
return self._bundle.library.remote(ds.data[]) | Return the remote for this partition
:return: |
360,492 | def run(self):
self._scheduler_thread.start()
self.irc_bot.create_connection()
self.irc_bot.add_signal_handlers()
event_loop = asyncio.get_event_loop()
event_loop.run_forever()
event_loop.close() | handle_close = _handle_close(messaging,
event_loop)
signal.signal(signal.SIGINT, handle_close)
signal.signal(signal.SIGTERM, handle_close) |
360,493 | def close(self):
if self._local.conn:
self._local.conn.transport.close()
self._local.conn = None | If a connection is open, close its transport. |
360,494 | def list_dvportgroups(dvs=None, portgroup_names=None, service_instance=None):
****
ret_dict = []
proxy_type = get_proxy_type()
if proxy_type == :
datacenter = __salt__[]()[]
dc_ref = _get_proxy_target(service_instance)
elif proxy_type == :
datacenter = __salt__[]()[]
... | Returns a list of distributed virtual switch portgroups.
The list can be filtered by the portgroup names or by the DVS.
dvs
Name of the DVS containing the portgroups.
Default value is None.
portgroup_names
List of portgroup names to look for. If None, all portgroups are
ret... |
360,495 | def output_aliases(aliases):
for alias in aliases:
cmd = + alias
click.echo(columns([colored.yellow( + alias), 20], [cmd, None])) | Display git aliases |
360,496 | def add_cluster(self, info):
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is not None:
cluster = Cluster()
retval = cluster.edit_traits(parent = info.ui.control,
kind... | Handles adding a Cluster to the main graph. |
360,497 | def decode(image, timeout=None, gap_size=None, shrink=1, shape=None,
deviation=None, threshold=None, min_edge=None, max_edge=None,
corrections=None, max_count=None):
dmtx_timeout = None
if timeout:
now = dmtxTimeNow()
dmtx_timeout = dmtxTimeAdd(now, timeout)
if ma... | Decodes datamatrix barcodes in `image`.
Args:
image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, height)
timeout (int): milliseconds
gap_size (int):
shrink (int):
shape (int):
deviation (int):
threshold (int):
min_edge (int):
max_edg... |
360,498 | def filter_search(self, search):
builder = QueryBuilder(
self.filtering_fields,
self.filtering_map,
self
)
search, unmatched = builder.build(search, self.get_query_params())
for argument in self.get_always_allowed_arguments():
... | Filter given search by the filter parameter given in request.
:param search: ElasticSearch query object |
360,499 | def copy_neg(self):
result = mpfr.Mpfr_t.__new__(BigFloat)
mpfr.mpfr_init2(result, self.precision)
new_sign = not self._sign()
mpfr.mpfr_setsign(result, self, new_sign, ROUND_TIES_TO_EVEN)
return result | Return a copy of self with the opposite sign bit.
Unlike -self, this does not make use of the context: the result
has the same precision as the original. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.