Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
341,800 | def _fadn_par(vec, geom):
import numpy as np
from scipy import linalg as spla
from ..const import PRM
from ..error import InertiaError
from .vector import parallel_check as parchk
if not (len(geom.shape) == 1 and geom.shape[0] % 3 == 0):
raise ValueError("Geometry is not... | First non-zero Atomic Displacement that is Non-Parallel with Vec
Utility function to identify the first atomic displacement in a geometry
that is both (a) not the zero vector and (b) non-(anti-)parallel with a
reference vector.
Parameters
----------
vec
length-3 |npfloat_| --
R... |
341,801 | def operator(self, node, children):
operators = {: op.add, : op.sub, : op.mul, : op.div}
return operators[node.text] | operator = "+" / "-" / "*" / "/" |
341,802 | def write_documentation(self, doc_type):
for handler_name in sorted(self._documentation):
if "controller." in handler_name:
server_type = "controller"
elif "compute" in handler_name:
server_type = "compute"
else:
server... | Build all the doc page for handlers
:param doc_type: Type of doc to generate (controller, compute) |
341,803 | def handle_offchain_secretreveal(
initiator_state: InitiatorTransferState,
state_change: ReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorTransferState]:
iteration: TransitionResult[InitiatorTransferS... | Once the next hop proves it knows the secret, the initiator can unlock
the mediated transfer.
This will validate the secret, and if valid a new balance proof is sent to
the next hop with the current lock removed from the merkle tree and the
transferred amount updated. |
341,804 | def fillLayerWithColor(self, color):
layer = self.image.getActiveLayer().data
colorRGBA = color.get_0_255()
layer[:,:,0] = colorRGBA[0]
layer[:,:,1] = colorRGBA[1]
layer[:,:,2] = colorRGBA[2]
layer[:,:,3] = colorRGBA[3] | Fills the current :py:class:`Layer` with the current :py:class:`Color`.
:param color: The :py:class:`Color` to apply to the layer.
:rtype: Nothing. |
341,805 | def get_currency_symbol(self):
locale = locales.getLocale()
setup = api.get_setup()
currency = setup.getCurrency()
return locale.numbers.currencies[currency].symbol | Get the currency Symbol |
341,806 | def validate_string_list(lst):
if not isinstance(lst, list):
raise ValueError( % lst)
for x in lst:
if not isinstance(x, basestring):
raise ValueError( % x) | Validate that the input is a list of strings.
Raises ValueError if not. |
341,807 | def ising(h: List[int], J: Dict[Tuple[int, int], int],
num_steps: int = 0,
verbose: bool = True,
rand_seed: int = None,
connection: QuantumComputer = None,
samples: int = None,
initial_beta: List[float] = None,
initial_gamma: List[float] = None,
... | Ising set up method
:param h: External magnetic term of the Ising problem.
:param J: Interaction term of the Ising problem.
:param num_steps: (Optional.Default=2 * len(h)) Trotterization order for the
QAOA algorithm.
:param verbose: (Optional.Default=True) Verbosity of the code.
:... |
341,808 | def generate_api_gateway():
logger.debug("[
client = boto3.client(, region_name=PRIMARY_REGION)
matches = [x for x in client.get_rest_apis().get(, list())
if x[] == API_GATEWAY]
if len(matches) > 0:
logger.debug("[
return matches.pop()
response = client.create_re... | Create the Blockade API Gateway REST service. |
341,809 | def delete(args):
m = RiverManager(args.hosts)
m.delete(args.name) | Delete a river by name |
341,810 | def register_prefs(*args, **kwargs):
swap_settings_module = bool(kwargs.get(, True))
if __PATCHED_LOCALS_SENTINEL not in get_frame_locals(2):
raise SitePrefsException()
bind_proxy(args, **kwargs)
unpatch_locals()
swap_settings_module and proxy_settings_module() | Registers preferences that should be handled by siteprefs.
Expects preferences as *args.
Use keyword arguments to batch apply params supported by
``PrefProxy`` to all preferences not constructed by ``pref`` and ``pref_group``.
Batch kwargs:
:param str|unicode help_text: Field help text.
... |
341,811 | def send_articles(self, user_id, articles, account=None):
if isinstance(articles, (tuple, list)):
articles_data = []
for article in articles:
articles_data.append({
: article[],
: article[],
: article[],... | 发送图文消息
详情请参考
http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param articles: 一个包含至多10个图文的数组, 或者微信图文消息素材 media_id
:param account: 可选,客服账号
:return: 返回的 JSON 数据包 |
341,812 | def template_filter(self, name: Optional[str]=None) -> Callable:
def decorator(func: Callable) -> Callable:
self.add_template_filter(func, name=name)
return func
return decorator | Add a template filter.
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.template_filter('name')
def to_upper(value):
return value.upper()
Arguments:
name: The filter name (defaults to function name). |
341,813 | def next_valid_batch(self, batch_size):
start = self.index_in_valid_epoch
if self.index_in_valid_epoch + batch_size > self.num_valid_images:
batch_size = 1
self.index_in_valid_epoch += batch_size
end = self.index_in_valid_epoch
return self.valid_labels[start:... | Return the next batch of examples from validiation data set
:param batch_size: int, size of image batch returned
:return train_labels: list, of labels
:return images: list, of images |
341,814 | def _convert_string_to_native(value):
result = None
try:
result = ast.literal_eval(str(value))
except (SyntaxError, ValueError):
result = value.split()
return result | Convert a string to its native python type |
341,815 | def _get_init_args(self, skip=4):
stack = inspect.stack()
if len(stack) < skip + 1:
raise ValueError("The length of the inspection stack is shorter than the requested start position.")
args, _, _, values = inspect.getargvalues(stack[skip][0])
params = {}
... | Get all arguments of current layer for saving the graph. |
341,816 | def status(name=None):
**
name = if not name else name
return all(os.path.isfile(i) for i in _paths(name)) | Return True if there is already a frozen state.
A frozen state is merely a list of packages (including the
version) in a specific time. This information can be used to
compare with the current list of packages, and revert the
installation of some extra packages that are in the system.
name
... |
341,817 | def _add_view_menu(self):
mainMenu = self.app.mainMenu()
viewMenu = AppKit.NSMenu.alloc().init()
viewMenu.setTitle_(localization["cocoa.menu.view"])
viewMenuItem = AppKit.NSMenuItem.alloc().init()
viewMenuItem.setSubmenu_(viewMenu)
mainMenu.addItem_(vie... | Create a default View menu that shows 'Enter Full Screen'. |
341,818 | def _format_msg(self, msg, edata):
edata = edata if isinstance(edata, list) else [edata]
for fdict in edata:
if "*[{token}]*".format(token=fdict["field"]) not in msg:
raise RuntimeError(
"Field {token} not in exception message".format(
... | Substitute parameters in exception message. |
341,819 | def get_projects(self):
url = urljoin(self.keystone_endpoint, "{}/{}".format(DEFAULT_KEYSTONE_API_VERSION, "projects"))
try:
r = self._make_request(url, self.headers)
return r.get(, [])
except Exception as e:
self.logger.warning(.format(e))
... | Returns all projects in the domain |
341,820 | def exists_plain(session: Session, tablename: str, *criteria: Any) -> bool:
return exists_in_table(session, table(tablename), *criteria) | Implements an efficient way of detecting if a record or records exist;
should be faster than COUNT(*) in some circumstances.
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
tablename: name of the table
criteria: optional SQLAlchemy ... |
341,821 | def readList(self, register, length):
if length <= 0:
raise ValueError("Length must be at least 1 byte.")
self._idle()
self._transaction_start()
self._i2c_start()
self._i2c_write_bytes([self._address_byte(True), register])
self._i2c_stop()
sel... | Read a length number of bytes from the specified register. Results
will be returned as a bytearray. |
341,822 | def gene_variants(store, variants_query, page=1, per_page=50):
variant_count = variants_query.count()
skip_count = per_page * max(page - 1, 0)
more_variants = True if variant_count > (skip_count + per_page) else False
variant_res = variants_query.skip(skip_count).limit(per_page)
my_institutes ... | Pre-process list of variants. |
341,823 | def jobs(self):
if self._jobs is None:
self._jobs = JobTable(self.connection, self.database)
return self._jobs | schema.jobs provides a view of the job reservation table for the schema
:return: jobs table |
341,824 | def main():
pip_packages = {}
for package in pip.get_installed_distributions():
name = package.project_name
version = package.version
full_name = "{0}-{1}-pip".format(name.lower(), version)
pip_packages[full_name] = {: version}
data = json.dumps(pip_packages)
print(d... | Use pip to find pip installed packages in a given prefix. |
341,825 | def StartTag(self, name, attrs):
s attributes
:return: none, side effect of modifying bits of the current class
'
if name not in self.excluded:
if name in self.structure.keys():
self.handler = self.structure[name]
self.tags.append(name)
... | A method which is called by the SAX parser when a new tag is encountered
:param name: name of the tag
:param attrs: the tag's attributes
:return: none, side effect of modifying bits of the current class |
341,826 | def settings(self):
stmt = "select {fields} from pg_settings".format(fields=.join(SETTINGS_FIELDS))
settings = []
for row in self._iter_results(stmt):
row[] = self._vartype_map[row[]](row[])
settings.append(Settings(**row))
return settings | Returns settings from the server. |
341,827 | def from_defn(cls, defn):
"Return the first Repl subclass that works with this"
instances = (subcl(defn) for subcl in cls.__subclasses__())
return next(filter(None, instances)) | Return the first Repl subclass that works with this |
341,828 | def range(self, name):
range_label = % (self.title, name)
data = self.spreadsheet.values_get(range_label)
start, end = name.split()
(row_offset, column_offset) = a1_to_rowcol(start)
(last_row, last_column) = a1_to_rowcol(end)
values = data.get(, [])
... | Returns a list of :class:`Cell` objects from a specified range.
:param name: A string with range value in A1 notation, e.g. 'A1:A5'.
:type name: str
Alternatively, you may specify numeric boundaries. All values
index from 1 (one):
:param first_row: Row number
:type fir... |
341,829 | def embeddedFileUpd(self, id, buffer=None, filename=None, ufilename=None, desc=None):
return _fitz.Document_embeddedFileUpd(self, id, buffer, filename, ufilename, desc) | Change an embedded file given its entry number or name. |
341,830 | def update_group(self, group_id, **kwargs):
properties = {}
if in kwargs:
kwargs[] = kwargs.pop()
for attr, value in kwargs.items():
properties[self._underscore_to_camelcase(attr)] = value
data = {
"properties": properties
... | Updates a group.
:param group_id: The unique ID of the group.
:type group_id: ``str`` |
341,831 | def evaluate(self, epoch, iteration, summary):
batch_time = AverageMeter(False)
tot_tok_per_sec = AverageMeter(False)
iterations = AverageMeter(False)
enc_seq_len = AverageMeter(False)
dec_seq_len = AverageMeter(False)
stats = {}
output = []
for... | Runs evaluation on test dataset.
:param epoch: index of the current epoch
:param iteration: index of the current iteration
:param summary: if True prints summary |
341,832 | def check_nonbond(molecule, thresholds):
for atom1 in range(molecule.graph.num_vertices):
for atom2 in range(atom1):
if molecule.graph.distances[atom1, atom2] > 2:
distance = np.linalg.norm(molecule.coordinates[atom1] - molecule.coordinates[atom2])
if d... | Check whether all nonbonded atoms are well separated.
If a nonbond atom pair is found that has an interatomic distance below
the given thresholds. The thresholds dictionary has the following format:
{frozenset([atom_number1, atom_number2]): distance}
When random geometries are generated fo... |
341,833 | def process(thumbnail_file, size, **kwargs):
from . import conf
size_dict = conf.SIZES[size]
for processor in size_dict[]:
processor[](thumbnail_file, **processor[])
return thumbnail_file | Post processors are functions that receive file objects,
performs necessary operations and return the results as file objects. |
341,834 | def empirical_retinotopy_data(hemi, retino_type):
polar_angleeccentricityweight
dat = _empirical_retinotopy_names[retino_type.lower()]
hdat = {s.lower(): s for s in six.iterkeys(hemi.properties)}
return next((hemi.prop(hdat[s.lower()]) for s in dat if s.lower() in hdat), None) | empirical_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi
and retinotopy type t; it does this by looking at the properties in hemi and picking out any
combination that is commonly used to denote empirical retinotopy data. These common names are
stored in _empirical_ret... |
341,835 | def add_prefix(dict_like, prefix):
if not isinstance(dict_like, dict):
try:
dict_like = dict(dict_like)
except Exception as e:
raise ValueError("{0}\nCan't convert container to dict: "
"{1}".format(e, dict_like))
return {prefix + k: v for... | takes a dict (or dict-like object, e.g. etree._Attrib) and adds the
given prefix to each key. Always returns a dict (via a typecast).
Parameters
----------
dict_like : dict (or similar)
a dictionary or a container that implements .items()
prefix : str
the prefix string to be prepend... |
341,836 | def bold(s, *, escape=True):
r
if escape:
s = escape_latex(s)
return NoEscape(r + s + ) | r"""Make a string appear bold in LaTeX formatting.
bold() wraps a given string in the LaTeX command \textbf{}.
Args
----
s : str
The string to be formatted.
escape: bool
If true the bold text will be escaped
Returns
-------
NoEscape
The formatted string.
E... |
341,837 | def getMedia(self, uri):
r = self.doQuery( + uri)
if r.status_code == 200:
content_type =
if in r.headers:
content_type = r.headers[]
cache_control = None
if in r.headers:
cache_control = r.headers[]
... | Return a tuple with a media and his content-type. Don't cache anything ! |
341,838 | def generate_certificate(
ctx, slot, management_key, pin, public_key, subject, valid_days):
controller = ctx.obj[]
_ensure_authenticated(
ctx, controller, pin, management_key, require_pin_and_key=True)
data = public_key.read()
public_key = serialization.load_pem_public_key(
... | Generate a self-signed X.509 certificate.
A self-signed certificate is generated and written to one of the slots on
the YubiKey. A private key need to exist in the slot.
\b
SLOT PIV slot where private key is stored.
PUBLIC-KEY File containing a public key. Use '-' to use stdin. |
341,839 | def find_first_declaration(
declarations,
decl_type=None,
name=None,
parent=None,
recursive=True,
fullname=None):
decl_matcher = algorithm.match_declaration_t(
decl_type=decl_type,
name=name,
fullname=fullname,
parent=parent)
... | Returns first declaration that match criteria, defined by developer.
For more information about arguments see :class:`match_declaration_t`
class.
:rtype: matched declaration :class:`declaration_t` or None |
341,840 | def from_named_function(cls, function):
if not getattr(function, , ):
raise TypeError()
return cls.from_lambda(function.__name__, function) | Make a :class:`SassFunction` object from the named ``function``.
Function name and arguments are automatically inspected.
:param function: the named function to be called
:type function: :class:`types.FunctionType`
:returns: a custom function wrapper of the ``function``
:rtype: ... |
341,841 | def format_output(data, fmt=):
if isinstance(data, utils.string_types):
if fmt in (, ):
return json.dumps(data)
return data
if hasattr(data, ):
if fmt == :
return str(format_prettytable(data))
elif fmt == :
return str(format_no_tty... | Given some data, will format it for console output.
:param data: One of: String, Table, FormattedItem, List, Tuple,
SequentialOutput
:param string fmt (optional): One of: table, raw, json, python |
341,842 | def build_undercloud_on_libvirt(self, image_path,
rhsm=None, repositories=[]):
self.run()
self.fetch_image(path=image_path, dest=,
user=)
self.run("LIBGUESTFS_BACKEND=direct virt-customize -a /home/stack/gues... | Build the Undercloud by using instack-virt-setup script. |
341,843 | def _proxy(self):
if self._context is None:
self._context = AuthRegistrationsCredentialListMappingContext(
self._version,
account_sid=self._solution[],
domain_sid=self._solution[],
sid=self._solution[],
)
re... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AuthRegistrationsCredentialListMappingContext for this AuthRegistrationsCredentialListMappingInstance
:rtype: twilio.rest.api.v2010.acc... |
341,844 | def prompt_choice(prompt, possibilities, default=None, only_in_poss=True,
show_default=True, prompt_suffix=, color=None):
assert len(possibilities) >= 1
assert not only_in_poss or default is None or default in possibilities, % default
contains_spaces = any( in poss for poss in pos... | Prompt for a string in a given range of possibilities.
This also sets the history to the list of possibilities so
the user can scroll is with the arrow to find what he wants,
If only_in_poss is False, you are not guaranteed that this
will return one of the possibilities. |
341,845 | def run(*args, **kwargs):
luigi_run_result = _run(*args, **kwargs)
return luigi_run_result if kwargs.get() else luigi_run_result.scheduling_succeeded | Please dont use. Instead use `luigi` binary.
Run from cmdline using argparse.
:param use_dynamic_argparse: Deprecated and ignored |
341,846 | def get_calling_file(file_path=None, result=):
if file_path is None:
path = inspect.stack()[1][1]
else:
path = file_path
name = path.split()[-1].split()[0]
if result == :
return name
elif result == :
return path
else:
return path, name | Retrieve file_name or file_path of calling Python script |
341,847 | def config(self, config_text, plane):
NO_CONFIGURATION_CHANGE = re.compile("No configuration changes to commit")
CONFIGURATION_FAILED = re.compile("show configuration failed")
CONFIGURATION_INCONSITENCY = re.compile("No configuration commits for this SDR will be allowed until "
... | Apply config. |
341,848 | def get_assessment_taken_lookup_session_for_bank(self, bank_id):
if not self.supports_assessment_taken_lookup():
raise errors.Unimplemented()
return sessions.AssessmentTakenLookupSession(bank_id, runtime=self._runtime) | Gets the ``OsidSession`` associated with the assessment taken lookup service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the bank
return: (osid.assessment.AssessmentTakenLookupSession) - an
``AssessmentTakenLookupSession``
raise: NotFound - ``bank_id`` not f... |
341,849 | def subnet_2_json(self):
LOGGER.debug("Subnet.subnet_2_json")
json_obj = {
: self.id,
: self.name,
: self.description,
: self.ip,
: self.mask,
: self.routing_area_id,
: self.ipAddress_ids,
: self.loc... | transform ariane_clip3 subnet object to Ariane server JSON obj
:return: Ariane JSON obj |
341,850 | def write_points(self, fid):
for nr, point in enumerate(self.Points):
fid.write(
.format(
nr + 1, point[0], point[1], self.Charlengths[nr])) | Write the grid points to the GMSH-command file.
Parameters
----------
fid: file object for the command file (.geo) |
341,851 | def plot_sector_allocations(returns, sector_alloc, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
sector_alloc.plot(title=,
alpha=0.5, ax=ax, **kwargs)
box = ax.get_position()
ax.set_position([box.x0, box.y0 + box.height * 0.1,
box.width, box... | Plots the sector exposures of the portfolio over time.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
sector_alloc : pd.DataFrame
Portfolio allocation of positions. See pos.get_sect... |
341,852 | def transfer_pos_tags(self):
tagged_words = []
for word,t in self.transfer_pos_tagger.annotate(self.words):
word.pos_tag = t
tagged_words.append((word, t))
return tagged_words | Returns an list of tuples of the form (word, POS tag), using transfer POS tagger |
341,853 | def collect_summary_stats(data):
mean = np.mean(data, axis=0)
std = np.std(data, axis=0)
median = np.median(data, axis=0)
q02, q16, q84, q97 = np.percentile(data, [2.5, 16, 84, 97.5], axis=0)
o = dict(mean=mean,
std=std,
median=median,
q02=q02,
... | Collect summary statisitics from an array
This creates a dictionry of output arrays of summary
statistics, with the input array dimension reducted by one.
Parameters
----------
data : `numpy.ndarray`
Array with the collected input data
Returns
-------
output : dict
... |
341,854 | def git_checkout(branch_name, create=False):
log.info("Checking out <33>{}".format(branch_name))
shell.run(.format( if create else , branch_name)) | Checkout or create a given branch
Args:
branch_name (str):
The name of the branch to checkout or create.
create (bool):
If set to **True** it will create the branch instead of checking it
out. |
341,855 | def _remove_vm(name, datacenter, service_instance, placement=None,
power_off=None):
results = {}
if placement:
(resourcepool_object, placement_object) = \
salt.utils.vmware.get_placement(service_instance,
datacenter,
... | Helper function to remove a virtual machine
name
Name of the virtual machine
service_instance
vCenter service instance for connection and configuration
datacenter
Datacenter of the virtual machine
placement
Placement information of the virtual machine |
341,856 | def get_list_positions_obj(client, positions_obj_id):
return endpoint_helpers.get_endpoint_obj(client, client.api.Endpoints.LIST_POSITIONS, positions_obj_id) | Gets the object that defines how lists are ordered (there will always be only one of these)
See https://developer.wunderlist.com/documentation/endpoints/positions for more info
Return:
A ListPositionsObj-mapped object defining the order of list layout |
341,857 | def load_yaml(self, _yaml: YamlDocument) -> AugmentedDict:
return self.augment(self._load_plain_yaml(_yaml), document=_yaml) | Loads a partial yaml and augments it. A partial yaml in this context is a yaml that is
syntactically correct, but is not yet complete in terms of content.
The yaml will be completed by augmenting with some external resources and/or executing so
called extensions.
Args:
_yaml... |
341,858 | def setAdvancedAction(self, standardAction, advancedAction):
if advancedAction:
self._advancedMap[standardAction] = advancedAction
margins = list(self.getContentsMargins())
margins[2] = 22
self.setContentsMargins(*margins)
elif s... | Links an advanced action with the inputed standard action. This will \
create a tool button alongside the inputed standard action when the \
menu is displayed. If the user selects the advanced action, then the \
advancedAction.triggered signal will be emitted.
:param stan... |
341,859 | def _attach_objects_post_save_hook(self, cls, data, pending_relations=None):
unprocessed_pending_relations = []
if pending_relations is not None:
for post_save_relation in pending_relations:
object_id, field, id_ = post_save_relation
if self.id == id_:
target = field.model.objects.get(id=... | Gets called by this object's create and sync methods just after save.
Use this to populate fields after the model is saved.
:param cls: The target class for the instantiated object.
:param data: The data dictionary received from the Stripe API.
:type data: dict |
341,860 | def pic_loggedrequiredremoterelease_v1(self):
log = self.sequences.logs.fastaccess
rec = self.sequences.receivers.fastaccess
log.loggedrequiredremoterelease[0] = rec.d[0] | Update the receiver link sequence. |
341,861 | def prepare_response_header(origin_header, segment):
if origin_header and origin_header.sampled == :
new_header = TraceHeader(root=segment.trace_id,
sampled=segment.sampled)
else:
new_header = TraceHeader(root=segment.trace_id)
return new_header.to_head... | Prepare a trace header to be inserted into response
based on original header and the request segment. |
341,862 | def _escape(value):
if isinstance(value, (list, tuple)):
value = ",".join(value)
elif isinstance(value, (date, datetime)):
value = value.isoformat()
elif isinstance(value, bool):
value = str(value).lower()
elif isinstance(value, bytes):
return... | Escape a single value of a URL string or a query parameter. If it is a list
or tuple, turn it into a comma-separated string first. |
341,863 | async def list_batches(self, request):
paging_controls = self._get_paging_controls(request)
validator_query = client_batch_pb2.ClientBatchListRequest(
head_id=self._get_head_id(request),
batch_ids=self._get_filter_ids(request),
sorting=self._get_sorting_messa... | Fetches list of batches from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of batch ids to include in results
Response:
data: JSON array of fully expan... |
341,864 | def a_unexpected_prompt(ctx):
prompt = ctx.ctrl.match.group(0)
ctx.msg = "Received the jump host prompt: ".format(prompt)
ctx.device.connected = False
ctx.finished = True
raise ConnectionError("Unable to connect to the device.", ctx.ctrl.hostname) | Provide message when received humphost prompt. |
341,865 | def detach(self, result, sync=True):
count = 0
if sync and result.attached():
self.send()
fetch = self.fetch
while result.attached():
count += fetch()
if self._last_result is result:
self._last_result = None
i... | Detach a result from this session by fetching and buffering any
remaining records.
:param result:
:param sync:
:returns: number of records fetched |
341,866 | def mark_notifications_as_read(self, last_read_at=datetime.datetime.utcnow()):
assert isinstance(last_read_at, datetime.datetime)
put_parameters = {
"last_read_at": last_read_at.strftime()
}
headers, data = self._requester.requestJsonAndCheck(
"PUT",
... | :calls: `PUT /notifications <https://developer.github.com/v3/activity/notifications>`_
:param last_read_at: datetime |
341,867 | def _prepare_template(self, obj, needs_request=False):
if self.instance_name is None and self.template_name is None:
raise SearchFieldError("This field requires either its instance_name variable to be populated or an explicit template_name in order to load the correct template.")
i... | This is a copy of CharField.prepare_template, except that it adds a fake
request to the context, which is mainly needed to render CMS placeholders |
341,868 | def gengraphs(pth, nopyfftw):
srcmodflt =
srcqnmflt = r
dstqnmflt = r
fnmsub = (, )
grpflt = r
lnkpfx =
lnksub = (r,
lnkpfx + r)
fntsz = 9
fntfm =
kwargs = {: fntsz, : fntfm, : True}
ct = jonga.CallTracer(srcmodflt=srcmodflt, srcqnmflt=srcqnmflt,
... | Generate call graph images when necessary. Parameter pth is the path
to the directory in which images are to be created. Parameter nopyfftw
is a flag indicating whether it is necessary to avoid using pyfftw. |
341,869 | def from_dynacRepr(cls, pynacRepr):
f = float(pynacRepr[1][0][0])
p = [int(pynacRepr[1][0][1])]
return cls(f, p) | Construct a ``Steerer`` instance from the Pynac lattice element |
341,870 | def detectAllKws(self):
kwslist = []
for line in self.file_lines:
line = .join(line.strip().split())
if line.startswith("!"):
continue
if in line:
kw_name = line.split()[0]
if set(kw_n... | Detect all keyword from infile, return as a list
USAGE: kwslist = detectAllKws() |
341,871 | def dotd(A, B):
r
A = asarray(A, float)
B = asarray(B, float)
if A.ndim == 1 and B.ndim == 1:
return dot(A, B)
out = empty((A.shape[0],), float)
out[:] = sum(A * B.T, axis=1)
return out | r"""Diagonal of :math:`\mathrm A\mathrm B^\intercal`.
If ``A`` is :math:`n\times p` and ``B`` is :math:`p\times n`, it is done in
:math:`O(pn)`.
Args:
A (array_like): Left matrix.
B (array_like): Right matrix.
Returns:
:class:`numpy.ndarray`: Resulting diagonal. |
341,872 | def read(data, fmt_str):
size = struct.calcsize(fmt_str)
return struct.unpack(fmt_str, data[:size]), data[size:] | Reads input bytes and extract the given structure. Returns both the read
elements and the remaining data
:param data: Data as bytes
:param fmt_str: Struct unpack format string
:return: A tuple (results as tuple, remaining data) |
341,873 | def selectmenuitem(self, window_name, object_name):
menu_handle = self._get_menu_handle(window_name, object_name)
if not menu_handle.AXEnabled:
raise LdtpServerException(u"Object %s state disabled" % object_name)
menu_handle.Press()
return 1 | Select (click) a menu item.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob. Or menu heirarchy
... |
341,874 | def label_rigid_bodies(self, discrete_bodies=None, rigid_particles=None):
if discrete_bodies is not None:
if isinstance(discrete_bodies, string_types):
discrete_bodies = [discrete_bodies]
if rigid_particles is not None:
if isinstance(rigid_particles, stri... | Designate which Compounds should be treated as rigid bodies
If no arguments are provided, this function will treat the compound
as a single rigid body by providing all particles in `self` with the
same rigid_id. If `discrete_bodies` is not None, each instance of
a Compound with a name f... |
341,875 | def derivatives(self, x, y, theta_E, center_x=0, center_y=0):
x_shift = x - center_x
y_shift = y - center_y
R = np.sqrt(x_shift*x_shift + y_shift*y_shift)
if isinstance(R, int) or isinstance(R, float):
a = theta_E / max(0.000001, R)
else:
a=np.emp... | returns df/dx and df/dy of the function |
341,876 | def _build_wells(self) -> List[Well]:
return [
Well(
self._well_definition[well],
Location(self._calibrated_offset, self),
"{} of {}".format(well, self._display_name),
self.is_tiprack)
for well in self._ordering] | This function is used to create one instance of wells to be used by all
accessor functions. It is only called again if a new offset needs
to be applied. |
341,877 | def EmitProto(cls):
result = "message %s {\n" % cls.__name__
for _, desc in sorted(iteritems(cls.type_infos_by_field_number)):
result += desc.Definition()
result += "}\n"
return result | Emits .proto file definitions. |
341,878 | def authorize(self, login, password, scopes=None, note=, note_url=,
client_id=, client_secret=):
json = None
with self._session.temporary_basic_auth(*auth):
json = self._json(self._post(url, data=data), 201)
return Authorization(json, sel... | Obtain an authorization token from the GitHub API for the GitHub
API.
:param str login: (required)
:param str password: (required)
:param list scopes: (optional), areas you want this token to apply to,
i.e., 'gist', 'user'
:param str note: (optional), note about the ... |
341,879 | def _make_headers(config, kwargs):
headers = kwargs.get()
headers = headers.copy() if headers is not None else {}
headers[] = config.args.user_agent
kwargs = kwargs.copy()
kwargs[] = headers
return kwargs | Replace the kwargs with one where the headers include our user-agent |
341,880 | def no_new_errors(new_data, old_data, strict=False):
success = True
score = 0
message =
if new_data[] > old_data[]:
success = False
message = "Failed, More errors than prior runs!({} > {})\n" \
"Average Score: {}".format(new_data[],
... | Pylint Validator that will fail any review if there are
new Pylint errors in it (Pylint message starts with 'E:')
:param new_data:
:param old_data:
:return: |
341,881 | def run_in_thread_pool(self, pool_size=None, func=None, *args):
executor = Pool(pool_size)
return self.loop.run_in_executor(executor, func, *args) | If `kwargs` needed, try like this: func=lambda: foo(*args, **kwargs) |
341,882 | def update(self, job_binary_id, data):
if self.version >= 2:
UPDATE_FUNC = self._patch
else:
UPDATE_FUNC = self._update
return UPDATE_FUNC(
% job_binary_id, data, ) | Update Job Binary.
:param dict data: dict that contains fields that should be updated
with new values.
Fields that can be updated:
* name
* description
* url
* is_public
* is_protected
* extra - dict with the keys `user` and `passwo... |
341,883 | def replace_all_tokens(self, token):
b = self.data_buffer
for y, row in b.items():
for x, char in row.items():
b[y][x] = _CHAR_CACHE[char.char, token] | For all the characters in the screen. Set the token to the given `token`. |
341,884 | def display_as(self, name_type):
if rname_rfc6680 is None:
raise NotImplementedError("Your GSSAPI implementation does not "
"support RFC 6680 (the GSSAPI naming "
"extensions)")
return rname_rfc6680.display... | Display this name as the given name type.
This method attempts to display the current :class:`Name`
using the syntax of the given :class:`NameType`, if possible.
Warning:
In MIT krb5 versions below 1.13.3, this method can segfault if
the name was not *originally* creat... |
341,885 | def resize_image_folder(bucket, key_prefix, pil_size):
con = boto.connect_s3()
b = con.get_bucket(bucket)
for key in b.list(key_prefix):
key = b.get_key(key.name)
if not in key.content_type:
continue
size = key.get_metadata()
if size == str(pil_size):
... | This function resizes all the images in a folder |
341,886 | def parse_phone(parts, allow_multiple=False):
text_subs = misc.phone_text_subs()
Small = text_subs[]
Magnitude = text_subs[]
Others = text_subs[]
phone_pattern = r
phone_pattern_spaces = r
found_phones = []
return_parts = []
for part in parts:
body = part
body = re.sub(r, , ... | Parse the phone number from the ad's parts
parts -> The backpage ad's posting_body, separated into substrings
allow_multiple -> If false, arbitrarily chooses the most commonly occurring phone |
341,887 | def count(cls, cur, table:str, where_keys: list=None):
if where_keys:
where_clause, values = cls._get_where_clause_with_values(where_keys)
query = cls._count_query_where.format(table, where_clause)
q, t = query, values
else:
query = cls._count_qu... | gives the number of records in the table
Args:
table: a string indicating the name of the table
Returns:
an integer indicating the number of records in the table |
341,888 | def close(self):
if self.sock:
self.sock.close()
self.sock = None
if self.__response:
self.__response.close()
self.__response = None
self.__state = _CS_IDLE | Close the connection to the HTTP server. |
341,889 | def appendQKeyEvent(self, keyEvent: QtGui.QKeyEvent):
self.keylistKeyEvent.append(keyEvent)
mod = keyEvent.modifiers()
key = keyEvent.key()
self.keylistQtConstants.append((int(mod), key)) | Append another key to the key sequence represented by this object.
|Args|
* ``keyEvent`` (**QKeyEvent**): the key to add.
|Returns|
**None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. |
341,890 | def clean(self):
if self.cleaned_data.get(, None) \
and not self.cleaned_data.get(, None):
self.add_error(
,
_(),
)
super().clean() | Validates the form. |
341,891 | def __call(self, *args, **kwargs):
self.__called = True
if self.__xml:
self.__cmd.append()
if not self.__refresh and not in args:
self.__cmd.append()
if self.__root:
self.__cmd.extend([, self.__root])
self.__cmd.extend(args)
... | Call Zypper.
:param state:
:return: |
341,892 | def check_output_directory(self, path):
if not os.path.isdir(path):
self.print_error(u"Directory does not exist" % (path))
return False
test_file = os.path.join(path, u"file.test")
if not gf.file_can_be_written(test_file):
self.print_error(u"Unable t... | If the given directory cannot be written, emit an error
and return ``False``. Otherwise return ``True``.
:param path: the path of the output directory
:type path: string (path)
:rtype: bool |
341,893 | def _add_url_rule(self, app):
app.url_map.converters[] = RegexConverter
app.add_url_rule(
app.config[] + ,
app.config[],
self.handle_request
)
return app | Add url rule for get filtered images
:param app: Flask application
:return: Flask application |
341,894 | def generate_blocks(self, assume_complete_blocks=None):
_track_assume_blocks = self.assume_complete_blocks
try:
if assume_complete_blocks != None:
self.assume_complete_blocks = assume_complete_blocks
if self.processed_tables == None:
... | Identifies and extracts all blocks from the input tables. These blocks are logical
identifiers for where related information resides in the original table. Any block can be
converted into a row-titled table which can then be stitched together with other tables from
other blocks to form a fully c... |
341,895 | def write_hits_in_events(hit_table_in, hit_table_out, events, start_hit_word=0, chunk_size=5000000, condition=None):
if len(events) > 0:
min_event = np.amin(events)
max_event = np.amax(events)
logging.debug("Write hits from hit number >= %d that exists in the selected %d events with %... | Selects the hits that occurred in events and writes them to a pytable. This function reduces the in RAM operations and has to be
used if the get_hits_in_events function raises a memory error. Also a condition can be set to select hits.
Parameters
----------
hit_table_in : pytable.table
hit_table_ou... |
341,896 | def _raw_hex_id(obj):
| Return the padded hexadecimal id of ``obj``. |
341,897 | def _get_entity_pair(self, entity_id):
entity = self._entities.get(entity_id)
try:
input_entity = utils.get_input_peer(entity)
except TypeError:
try:
input_entity = self._client._entity_cache[entity_id]
except KeyError:
... | Returns ``(entity, input_entity)`` for the given entity ID. |
341,898 | def match_regex(input_str, pattern, language, context, case_insensitive=True):
if type(context) is str:
contexts = [, ]
assert context in contexts or type(context) is int, .format(contexts)
else:
context = int(context)
for match in _regex_span(pattern, input_str, case_insensitiv... | Take input string and a regex pattern, then yield generator of matches
in desired format.
TODO: Rename this `match_pattern` and incorporate the keyword expansion
code currently in search_corpus.
:param input_str:
:param pattern:
:param language:
:param context: Integer or 'sentence' 'p... |
341,899 | def get_msgs_for_lagged_nodes(self) -> List[ViewChangeDone]:
messages = []
accepted = self._accepted_view_change_done_message
if accepted:
messages.append(ViewChangeDone(self.last_completed_view_no, *accepted))
elif self.name in se... | Returns the last accepted `ViewChangeDone` message.
If no view change has happened returns ViewChangeDone
with view no 0 to a newly joined node |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.