code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def update(self, key, item):
return lib.zhash_update(self._as_parameter_, key, item) | Update item into hash table with specified key and item.
If key is already present, destroys old item and inserts new one.
Use free_fn method to ensure deallocator is properly called on item. |
def array(self, size, type, name, *parameters):
self._new_list(size, name)
BuiltIn().run_keyword(type, '', *parameters)
self._end_list() | Define a new array of given `size` and containing fields of type `type`.
`name` if the name of this array element. The `type` is the name of keyword that is executed as the contents of
the array and optional extra parameters are passed as arguments to this keyword.
Examples:
| Array | ... |
def get_psd(self, omega):
w = np.asarray(omega)
(alpha_real, beta_real, alpha_complex_real, alpha_complex_imag,
beta_complex_real, beta_complex_imag) = self.coefficients
p = get_psd_value(
alpha_real, beta_real,
alpha_complex_real, alpha_complex_imag,
... | Compute the PSD of the term for an array of angular frequencies
Args:
omega (array[...]): An array of frequencies where the PSD should
be evaluated.
Returns:
The value of the PSD for each ``omega``. This will have the same
shape as ``omega``. |
def read(self, cnt=None):
if cnt is None or cnt < 0:
cnt = self._remain
elif cnt > self._remain:
cnt = self._remain
if cnt == 0:
return EMPTY
data = self._read(cnt)
if data:
self._md_context.update(data)
self._remain -= ... | Read all or specified amount of data from archive entry. |
def draw(self):
self.context.set_line_cap(cairo.LINE_CAP_SQUARE)
self.context.save()
self.context.rectangle(*self.rect)
self.context.clip()
cell_borders = CellBorders(self.cell_attributes, self.key, self.rect)
borders = list(cell_borders.gen_all())
borders.sort(ke... | Draws cell border to context |
def select(self, columns=(), by=(), where=(), **kwds):
return self._seu('select', columns, by, where, kwds) | select from self
>>> t = q('([]a:1 2 3; b:10 20 30)')
>>> t.select('a', where='b > 20').show()
a
-
3 |
def unesc(line, language):
comment = _COMMENT[language]
if line.startswith(comment + ' '):
return line[len(comment) + 1:]
if line.startswith(comment):
return line[len(comment):]
return line | Uncomment once a commented line |
def _prune_all_if_small(self, small_size, a_or_u):
"Return True and delete children if small enough."
if self._nodes is None:
return True
total_size = (self.app_size() if a_or_u else self.use_size())
if total_size < small_size:
if a_or_u:
self._set... | Return True and delete children if small enough. |
def score(self, X, y=None, train=False, **kwargs):
score = self.estimator.score(X, y, **kwargs)
if train:
self.train_score_ = score
else:
self.test_score_ = score
y_pred = self.predict(X)
scores = y_pred - y
self.draw(y_pred, scores, train=train)
... | Generates predicted target values using the Scikit-Learn
estimator.
Parameters
----------
X : array-like
X (also X_test) are the dependent variables of test set to predict
y : array-like
y (also y_test) is the independent actual variables to score agains... |
def roc(y_true, y_score, ax=None):
if any((val is None for val in (y_true, y_score))):
raise ValueError("y_true and y_score are needed to plot ROC")
if ax is None:
ax = plt.gca()
y_score_is_vector = is_column_vector(y_score) or is_row_vector(y_score)
if y_score_is_vector:
n_class... | Plot ROC curve.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples] or [n_samples, 2] for binary
classification or [n_samples, n_classes] for multiclass
Target scores (estimator pre... |
def yank_last_arg(event):
n = (event.arg if event.arg_present else None)
event.current_buffer.yank_last_arg(n) | Like `yank_nth_arg`, but if no argument has been given, yank the last word
of each line. |
def _replace_missing_values_column(values, mv):
for idx, v in enumerate(values):
try:
if v in EMPTY or v == mv:
values[idx] = "nan"
elif math.isnan(float(v)):
values[idx] = "nan"
else:
values[idx] = v
except (TypeErr... | Replace missing values in the values list where applicable
:param list values: Metadata (column values)
:return list values: Metadata (column values) |
def get_content_type(self, content_type):
qs = self.get_queryset()
return qs.filter(content_type__name=content_type) | Get all the items of the given content type related to this item. |
def data_import(self, json_response):
if 'data' not in json_response:
raise PyVLXException('no element data found: {0}'.format(
json.dumps(json_response)))
data = json_response['data']
for item in data:
if 'category' not in item:
raise PyVL... | Import data from json response. |
def file_needs_update(target_file, source_file):
if not os.path.isfile(target_file) or get_md5_file_hash(target_file) != get_md5_file_hash(source_file):
return True
return False | Checks if target_file is not existing or differing from source_file
:param target_file: File target for a copy action
:param source_file: File to be copied
:return: True, if target_file not existing or differing from source_file, else False
:rtype: False |
def update(self, url, doc):
if self.pid.is_deleted():
logger.info("Reactivate in DataCite",
extra=dict(pid=self.pid))
try:
self.api.metadata_post(doc)
self.api.doi_post(self.pid.pid_value, url)
except (DataCiteError, HttpError):
... | Update metadata associated with a DOI.
This can be called before/after a DOI is registered.
:param doc: Set metadata for DOI.
:returns: `True` if is updated successfully. |
def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False):
if self._dimension != 2:
raise NotImplementedError(
"2D is the only supported dimension",
"Current dimension",
self._dimension,
)
if ax is None:
ax = _... | Plot the current surface.
Args:
pts_per_edge (int): Number of points to plot per edge.
color (Optional[Tuple[float, float, float]]): Color as RGB profile.
ax (Optional[matplotlib.artist.Artist]): matplotlib axis object
to add plot to.
with_nodes (... |
def get_functions_and_classes(package):
classes, functions = [], []
for name, member in inspect.getmembers(package):
if not name.startswith('_'):
if inspect.isclass(member):
classes.append([name, member])
elif inspect.isfunction(member):
functions.... | Retun lists of functions and classes from a package.
Parameters
----------
package : python package object
Returns
--------
list, list : list of classes and functions
Each sublist consists of [name, member] sublists. |
def cleanup_dataset(dataset, data_home=None, ext=".zip"):
removed = 0
data_home = get_data_home(data_home)
datadir = os.path.join(data_home, dataset)
archive = os.path.join(data_home, dataset+ext)
if os.path.exists(datadir):
shutil.rmtree(datadir)
removed += 1
if os.path.exists(a... | Removes the dataset directory and archive file from the data home directory.
Parameters
----------
dataset : str
The name of the dataset; should either be a folder in data home or
specified in the yellowbrick.datasets.DATASETS variable.
data_home : str, optional
The path on dis... |
def parse(version):
match = _REGEX.match(version)
if match is None:
raise ValueError('%s is not valid SemVer string' % version)
version_parts = match.groupdict()
version_parts['major'] = int(version_parts['major'])
version_parts['minor'] = int(version_parts['minor'])
version_parts['patch... | Parse version to major, minor, patch, pre-release, build parts.
:param version: version string
:return: dictionary with the keys 'build', 'major', 'minor', 'patch',
and 'prerelease'. The prerelease or build keys can be None
if not provided
:rtype: dict
>>> import semver
>... |
def offset_limit(func):
def func_wrapper(self, start, stop):
offset = start
limit = stop - start
return func(self, offset, limit)
return func_wrapper | Decorator that converts python slicing to offset and limit |
def hex2term(hexval: str, allow_short: bool = False) -> str:
return rgb2term(*hex2rgb(hexval, allow_short=allow_short)) | Convert a hex value into the nearest terminal code number. |
def shutdown(self):
task = asyncio.ensure_future(self.core.shutdown())
self.loop.run_until_complete(task) | Shutdown the application and exit
:returns: No return value |
def start(self, zone_id, duration):
path = 'zone/start'
payload = {'id': zone_id, 'duration': duration}
return self.rachio.put(path, payload) | Start a zone. |
def add(self, item):
if not item.startswith(self.prefix):
item = os.path.join(self.base, item)
self.files.add(os.path.normpath(item)) | Add a file to the manifest.
:param item: The pathname to add. This can be relative to the base. |
def create_object(self, name, image_sets):
identifier = str(uuid.uuid4()).replace('-','')
properties = {datastore.PROPERTY_NAME: name}
obj = PredictionImageSetHandle(identifier, properties, image_sets)
self.insert_object(obj)
return obj | Create a prediction image set list.
Parameters
----------
name : string
User-provided name for the image group.
image_sets : list(PredictionImageSet)
List of prediction image sets
Returns
-------
PredictionImageSetHandle
Objec... |
def _backup_file(path):
backup_base = '/var/local/woven-backup'
backup_path = ''.join([backup_base,path])
if not exists(backup_path):
directory = ''.join([backup_base,os.path.split(path)[0]])
sudo('mkdir -p %s'% directory)
sudo('cp %s %s'% (path,backup_path)) | Backup a file but never overwrite an existing backup file |
def get_setting(key, *default):
if default:
return get_settings().get(key, default[0])
else:
return get_settings()[key] | Return specific search setting from Django conf. |
def get_widget(name):
for widget in registry:
if widget.__name__ == name:
return widget
raise WidgetNotFound(
_('The widget %s has not been registered.') % name) | Give back a widget class according to his name. |
def config_required(f):
def new_func(obj, *args, **kwargs):
if 'config' not in obj:
click.echo(_style(obj.get('show_color', False),
'Could not find a valid configuration file!',
fg='red', bold=True))
raise click.Abort()
... | Decorator that checks whether a configuration file was set. |
def copyNamespaceList(self):
ret = libxml2mod.xmlCopyNamespaceList(self._o)
if ret is None:raise treeError('xmlCopyNamespaceList() failed')
__tmp = xmlNs(_obj=ret)
return __tmp | Do a copy of an namespace list. |
def __import_vars(self, env_file):
with open(env_file, "r") as f:
for line in f:
try:
line = line.lstrip()
if line.startswith('export'):
line = line.replace('export', '', 1)
key, val = line.strip().sp... | Actual importing function. |
def text(self, data):
data = data
middle = data.lstrip(spaceCharacters)
left = data[:len(data) - len(middle)]
if left:
yield {"type": "SpaceCharacters", "data": left}
data = middle
middle = data.rstrip(spaceCharacters)
right = data[len(middle):]
... | Generates SpaceCharacters and Characters tokens
Depending on what's in the data, this generates one or more
``SpaceCharacters`` and ``Characters`` tokens.
For example:
>>> from html5lib.treewalkers.base import TreeWalker
>>> # Give it an empty tree just so it instantia... |
def inject_coordinates(self,
x_coords,
y_coords,
rescale_x=None,
rescale_y=None,
original_x=None,
original_y=None):
self._verify_coordinates(x_coords,... | Inject custom x and y coordinates for each term into chart.
Parameters
----------
x_coords: array-like
positions on x-axis \in [0,1]
y_coords: array-like
positions on y-axis \in [0,1]
rescale_x: lambda list[0,1]: list[0,1], default identity
Re... |
def delete_thumbnails(self, image_file):
thumbnail_keys = self._get(image_file.key, identity='thumbnails')
if thumbnail_keys:
for key in thumbnail_keys:
thumbnail = self._get(key)
if thumbnail:
self.delete(thumbnail, False)
... | Deletes references to thumbnails as well as thumbnail ``image_files``. |
def __set_whitelist(self, whitelist=None):
self.whitelist = {}
self.sanitizelist = ['script', 'style']
if isinstance(whitelist, dict) and '*' in whitelist.keys():
self.isNotPurify = True
self.whitelist_keys = []
return
else:
self.isNotPurif... | Update default white list by customer white list |
def _check_module_is_image_embedding(module_spec):
issues = []
input_info_dict = module_spec.get_input_info_dict()
if (list(input_info_dict.keys()) != ["images"] or
input_info_dict["images"].dtype != tf.float32):
issues.append("Module 'default' signature must require a single input, "
... | Raises ValueError if `module_spec` is not usable as image embedding.
Args:
module_spec: A `_ModuleSpec` to test.
Raises:
ValueError: if `module_spec` default signature is not compatible with
mappingan "images" input to a Tensor(float32, shape=(_,K)). |
def t_php_OBJECT_OPERATOR(t):
r'->'
if re.match(r'[A-Za-z_]', peek(t.lexer)):
t.lexer.push_state('property')
return t | r'-> |
def dump(self):
out = []
out.append(self.filetype)
out.append("Format: {}".format(self.version))
out.append("Type: ASCII")
out.append("")
for cmd in self.commands:
out.append(self.encode(cmd))
return "\n".join(out) + "\n" | Dump all commands in this object to a string.
Returns:
str: An encoded list of commands separated by
\n characters suitable for saving to a file. |
def concatenate_and_rewrite(self, paths, output_filename, variant=None):
stylesheets = []
for path in paths:
def reconstruct(match):
quote = match.group(1) or ''
asset_path = match.group(2)
if NON_REWRITABLE_URL.match(asset_path):
... | Concatenate together files and rewrite urls |
def find_clique_embedding(k, m, n=None, t=None, target_edges=None):
import random
_, nodes = k
m, n, t, target_edges = _chimera_input(m, n, t, target_edges)
if len(nodes) == 1:
qubits = set().union(*target_edges)
qubit = random.choice(tuple(qubits))
embedding = [[qubit]]
elif... | Find an embedding for a clique in a Chimera graph.
Given a target :term:`Chimera` graph size, and a clique (fully connect graph),
attempts to find an embedding.
Args:
k (int/iterable):
Clique to embed. If k is an integer, generates an embedding for a clique of size k
labell... |
def lists(self, value, key=None):
results = map(lambda x: x[value], self._items)
return list(results) | Get a list with the values of a given key
:rtype: list |
def remove(self, objs):
if self.readonly:
raise NotImplementedError(
'{} links can\'t be modified'.format(self._slug)
)
if not self._parent.id:
raise ObjectNotSavedException(
"Links can not be modified before the object has been saved."... | Removes the given `objs` from this `LinkCollection`.
- **objs** can be a list of :py:class:`.PanoptesObject` instances, a
list of object IDs, a single :py:class:`.PanoptesObject` instance, or
a single object ID.
Examples::
organization.links.projects.remove(1234)
... |
def command_line():
from docopt import docopt
doc = docopt( __doc__, version=VERSION )
args = pd.Series({k.replace('--', ''): v for k, v in doc.items()})
if args.all:
graph = Graph2Pandas(args.file, _type='all')
elif args.type:
graph = Graph2Pandas(args.file, _type=args.type)
els... | If you want to use the command line |
def get_by(self, field, value):
if field == 'userName' or field == 'name':
return self._client.get(self.URI + '/' + value)
elif field == 'role':
value = value.replace(" ", "%20")
return self._client.get(self.URI + '/roles/users/' + value)['members']
else:
... | Gets all Users that match the filter.
The search is case-insensitive.
Args:
field: Field name to filter. Accepted values: 'name', 'userName', 'role'
value: Value to filter.
Returns:
list: A list of Users. |
def process_tick(self, tick_tup):
self._tick_counter += 1
self.ack(tick_tup)
if self._tick_counter > self.ticks_between_batches and self._batches:
self.process_batches()
self._tick_counter = 0 | Increment tick counter, and call ``process_batch`` for all current
batches if tick counter exceeds ``ticks_between_batches``.
See :class:`pystorm.component.Bolt` for more information.
.. warning::
This method should **not** be overriden. If you want to tweak
how Tuples... |
def solve_each(expr, vars):
lhs_values, _ = __solve_for_repeated(expr.lhs, vars)
for lhs_value in repeated.getvalues(lhs_values):
result = solve(expr.rhs, __nest_scope(expr.lhs, vars, lhs_value))
if not result.value:
return result._replace(value=False)
return Result(True, ()) | Return True if RHS evaluates to a true value with each state of LHS.
If LHS evaluates to a normal IAssociative object then this is the same as
a regular let-form, except the return value is always a boolean. If LHS
evaluates to a repeared var (see efilter.protocols.repeated) of
IAssociative objects the... |
def setParentAnalysisRequest(self, value):
self.Schema().getField("ParentAnalysisRequest").set(self, value)
if not value:
noLongerProvides(self, IAnalysisRequestPartition)
else:
alsoProvides(self, IAnalysisRequestPartition) | Sets a parent analysis request, making the current a partition |
def error(self, line_number, offset, text, check):
code = super(_PycodestyleReport, self).error(
line_number, offset, text, check)
if code:
self.errors.append(dict(
text=text,
type=code.replace('E', 'C'),
col=offset + 1,
... | Save errors. |
def set_walltime(self, walltime):
if not isinstance(walltime, timedelta):
raise TypeError(
'walltime must be an instance of datetime.timedelta. %s given' %
type(walltime)
)
self._options['walltime'] = walltime
return self | Setting a walltime for the job
>>> job.set_walltime(datetime.timedelta(hours=2, minutes=30))
:param walltime: Walltime of the job (an instance of timedelta)
:returns: self
:rtype: self |
def recv_rpc(self, context, payload):
logger.debug("Adding RPC payload to ControlBuffer queue: %s", payload)
self.buf.put(('rpc', (context, payload)))
with self.cv:
self.cv.notifyAll() | Call from any thread |
def _process_pod_rate(self, metric_name, metric, scraper_config):
if metric.type not in METRIC_TYPES:
self.log.error("Metric type %s unsupported for metric %s" % (metric.type, metric.name))
return
samples = self._sum_values_by_context(metric, self._get_pod_uid_if_pod_metric)
... | Takes a simple metric about a pod, reports it as a rate.
If several series are found for a given pod, values are summed before submission. |
def index_resources(self):
if not self.__index_resources:
self.__index_resources = IndexResources(self.__connection)
return self.__index_resources | Gets the Index Resources API client.
Returns:
IndexResources: |
def rebase(self, text, char='X'):
regexp = re.compile(r'\b(%s)\b' % '|'.join(self.collection),
re.IGNORECASE | re.UNICODE)
def replace(m):
word = m.group(1)
return char * len(word)
return regexp.sub(replace, text) | Rebases text with stop words removed. |
def fill_subparser(subparser):
urls = ([None] * len(ALL_FILES))
filenames = list(ALL_FILES)
subparser.set_defaults(urls=urls, filenames=filenames)
subparser.add_argument('-P', '--url-prefix', type=str, default=None,
help="URL prefix to prepend to the filenames of "
... | Sets up a subparser to download the ILSVRC2012 dataset files.
Note that you will need to use `--url-prefix` to download the
non-public files (namely, the TARs of images). This is a single
prefix that is common to all distributed files, which you can
obtain by registering at the ImageNet website [DOWNLO... |
def build_query(self, sql, lookup):
for key, val in six.iteritems(lookup):
sql = sql.replace("$" + key, val)
return sql | Modify table and field name variables in a sql string with a dict.
This seems to be discouraged by psycopg2 docs but it makes small
adjustments to large sql strings much easier, making prepped queries
much more versatile.
USAGE
sql = 'SELECT $myInputField FROM $myInputTable'
... |
def distros_for_filename(filename, metadata=None):
return distros_for_location(
normalize_path(filename), os.path.basename(filename), metadata
) | Yield possible egg or source distribution objects based on a filename |
def get_report_rst(self):
res = ''
res += '-----------------------------------\n'
res += self.nme + '\n'
res += '-----------------------------------\n\n'
res += self.desc + '\n'
res += self.fldr + '\n\n'
res += '.. contents:: \n\n\n'
res += 'Overview\n' ... | formats the project into a report in RST format |
def parse_address(text: str) -> Tuple[str, int]:
match = re.search(
r'\('
r'(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*,'
r'\s*(\d{1,3})\s*'
r'\)',
text)
if match:
return (
... | Parse PASV address. |
def check_and_consume(self):
if self._count < 1.0:
self._fill()
consumable = self._count >= 1.0
if consumable:
self._count -= 1.0
self.throttle_count = 0
else:
self.throttle_count += 1
return consumable | Returns True if there is currently at least one token, and reduces
it by one. |
def removeSubscriber(self, email):
headers, raw_data = self._perform_subscribe()
missing_flag, raw_data = self._remove_subscriber(email, raw_data)
if missing_flag:
return
self._update_subscribe(headers, raw_data)
self.log.info("Successfully remove a subscriber: %s for... | Remove a subscriber from this workitem
If the subscriber has not been added, no more actions will be
performed.
:param email: the subscriber's email |
def _make_request(self, opener, request, timeout=None):
timeout = timeout or self.timeout
try:
return opener.open(request, timeout=timeout)
except HTTPError as err:
exc = handle_error(err)
exc.__cause__ = None
raise exc | Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
:param opener:
:type opener:
:param request: url payload to request
:type request: urllib.Request object
:param timeout: timeout value or None
... |
def generate_certificate(self, common_name, public_key_algorithm='rsa',
signature_algorithm='rsa_sha_512', key_length=2048,
signing_ca=None):
return GatewayCertificate._create(self, common_name, public_key_algorithm,
signature_algorithm, key_length, signing_ca) | Generate an internal gateway certificate used for VPN on this engine.
Certificate request should be an instance of VPNCertificate.
:param: str common_name: common name for certificate
:param str public_key_algorithm: public key type to use. Valid values
rsa, dsa, ecdsa.
:par... |
def variant_to_list(obj):
if isinstance(obj, list):
return obj
elif is_unicode_string(obj):
return [s for s in obj.split() if len(s) > 0]
elif isinstance(obj, set) or isinstance(obj, frozenset):
return list(obj)
raise TypeError("The given value must be a list or a set of descript... | Return a list containing the descriptors in the given object.
The ``obj`` can be a list or a set of descriptor strings, or a Unicode string.
If ``obj`` is a Unicode string, it will be split using spaces as delimiters.
:param variant obj: the object to be parsed
:rtype: list
:raise TypeError:... |
def _create_word_graph_file(name, file_storage, word_set):
word_graph_file = file_storage.create_file(name)
spelling.wordlist_to_graph_file(sorted(list(word_set)),
word_graph_file)
return copy_to_ram(file_storage).open_file(name) | Create a word graph file and open it in memory. |
def redirect_to_lang(*args, **kwargs):
endpoint = request.endpoint.replace('_redirect', '')
kwargs = multi_to_dict(request.args)
kwargs.update(request.view_args)
kwargs['lang_code'] = default_lang
return redirect(url_for(endpoint, **kwargs)) | Redirect non lang-prefixed urls to default language. |
def _control_line(self, line):
if line > float(self.LINE_LAST_PIXEL):
return int(self.LINE_LAST_PIXEL)
elif line < float(self.LINE_FIRST_PIXEL):
return int(self.LINE_FIRST_PIXEL)
else:
return line | Control the asked line is ok |
def message_interactions(self):
if self._message_interactions is None:
self._message_interactions = MessageInteractionList(
self._version,
service_sid=self._solution['service_sid'],
session_sid=self._solution['session_sid'],
participant... | Access the message_interactions
:returns: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList
:rtype: twilio.rest.proxy.v1.service.session.participant.message_interaction.MessageInteractionList |
def list_users(self):
url = self.bucket_url + '/_user/'
response = requests.get(url)
response = response.json()
return response | a method to list all the user ids of all users in the bucket |
def from_string(species_string: str):
m = re.search(r"([A-Z][a-z]*)([0-9.]*)([+\-])(.*)", species_string)
if m:
sym = m.group(1)
oxi = 1 if m.group(2) == "" else float(m.group(2))
oxi = -oxi if m.group(3) == "-" else oxi
properties = None
if m.... | Returns a Specie from a string representation.
Args:
species_string (str): A typical string representation of a
species, e.g., "Mn2+", "Fe3+", "O2-".
Returns:
A Specie object.
Raises:
ValueError if species_string cannot be intepreted. |
def copy_node_info(src, dest):
for attr in ['lineno', 'fromlineno', 'tolineno',
'col_offset', 'parent']:
if hasattr(src, attr):
setattr(dest, attr, getattr(src, attr)) | Copy information from src to dest
Every node in the AST has to have line number information. Get
the information from the old stmt. |
def _get_callargs(self, *args, **kwargs):
callargs = getcallargs(self.func, *args, **kwargs)
return callargs | Retrieve all arguments that `self.func` needs and
return a dictionary with call arguments. |
def setup_actions(self):
self.actionOpen.triggered.connect(self.on_open)
self.actionNew.triggered.connect(self.on_new)
self.actionSave.triggered.connect(self.on_save)
self.actionSave_as.triggered.connect(self.on_save_as)
self.actionQuit.triggered.connect(QtWidgets.QApplication.in... | Connects slots to signals |
def t_newline(self, t):
r'\n'
t.lexer.lineno += 1
t.lexer.latest_newline = t.lexpos | r'\n |
def import_keypair(kwargs=None, call=None):
with salt.utils.files.fopen(kwargs['file'], 'r') as public_key_filename:
public_key_content = salt.utils.stringutils.to_unicode(public_key_filename.read())
digitalocean_kwargs = {
'name': kwargs['keyname'],
'public_key': public_key_content
... | Upload public key to cloud provider.
Similar to EC2 import_keypair.
.. versionadded:: 2016.11.0
kwargs
file(mandatory): public key file-name
keyname(mandatory): public key name in the provider |
def config(self, config):
for section, data in config.items():
for variable, value in data.items():
self.set_value(section, variable, value) | Set config values from config dictionary. |
def delete_proficiency(self, proficiency_id):
collection = JSONClientValidated('learning',
collection='Proficiency',
runtime=self._runtime)
if not isinstance(proficiency_id, ABCId):
raise errors.InvalidArgument... | Deletes a ``Proficiency``.
arg: proficiency_id (osid.id.Id): the ``Id`` of the
``Proficiency`` to remove
raise: NotFound - ``proficiency_id`` not found
raise: NullArgument - ``proficiency_id`` is ``null``
raise: OperationFailed - unable to complete request
... |
def make_random(cls):
self = object.__new__(cls)
self.rank = Rank.make_random()
self.suit = Suit.make_random()
return self | Returns a random Card instance. |
def _read_addr_resolve(self, length, htype):
if htype == 1:
_byte = self._read_fileng(6)
_addr = '-'.join(textwrap.wrap(_byte.hex(), 2))
else:
_addr = self._read_fileng(length)
return _addr | Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address |
def index():
identity = g.identity
actions = {}
for action in access.actions.values():
actions[action.value] = DynamicPermission(action).allows(identity)
if current_user.is_anonymous:
return render_template("invenio_access/open.html",
actions=actions,
... | Basic test view. |
def autodiscover_media_extensions():
import copy
from django.conf import settings
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
import_module('%s.media_extension' % app)
except:
... | Auto-discover INSTALLED_APPS media_extensions.py modules and fail silently when
not present. This forces an import on them to register any media extension bits
they may want.
Rip of django.contrib.admin.autodiscover() |
def check_honeypot(func=None, field_name=None):
if isinstance(func, six.string_types):
func, field_name = field_name, func
def decorated(func):
def inner(request, *args, **kwargs):
response = verify_honeypot_value(request, field_name)
if response:
return r... | Check request.POST for valid honeypot field.
Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if
not specified. |
def _apply_line_rules(lines, commit, rules, line_nr_start):
all_violations = []
line_nr = line_nr_start
for line in lines:
for rule in rules:
violations = rule.validate(line, commit)
if violations:
for violation in violations:
... | Iterates over the lines in a given list of lines and validates a given list of rules against each line |
def set_all_curriculums_to_lesson_num(self, lesson_num):
for _, curriculum in self.brains_to_curriculums.items():
curriculum.lesson_num = lesson_num | Sets all the curriculums in this meta curriculum to a specified
lesson number.
Args:
lesson_num (int): The lesson number which all the curriculums will
be set to. |
async def set(self, *args, **kwargs):
return await _maybe_await(self.event.set(*args, **kwargs)) | Sets the value of the event. |
def welcome(self, user):
self.send_message(create_message('RoomServer', 'Please welcome {name} to the server!\nThere are currently {i} users online -\n {r}\n'.format(name=user.id,
i=self.amount_of_users_connected,
r=' '.join(self.user_names))))
loggi... | welcomes a user to the roomserver |
def run(self):
def receive():
if self.with_communicate:
self.stdout, self.stderr = self.process.communicate(input=self.stdin)
elif self.wait:
self.process.wait()
if not self.timeout:
receive()
else:
rt = threading.Th... | wait for subprocess to terminate and return subprocess' return code.
If timeout is reached, throw TimedProcTimeoutError |
def remove(self, spec_or_id, multi=True, *args, **kwargs):
if multi:
return self.delete_many(spec_or_id)
return self.delete_one(spec_or_id) | Backwards compatibility with remove |
def archive(self):
for path, dirs, files in os.walk(self.work_path, topdown=False):
for f_name in files:
f_path = os.path.join(path, f_name)
if os.path.islink(f_path) or os.path.getsize(f_path) == 0:
os.remove(f_path)
if len(os.listdir(... | Store model output to laboratory archive. |
def keys_info(cls, fqdn, key):
return cls.json_get('%s/domains/%s/keys/%s' %
(cls.api_url, fqdn, key)) | Retrieve key information. |
def update(sc, filename, asset_id):
addresses = []
with open(filename) as hostfile:
for line in hostfile.readlines():
addresses.append(line.strip('\n'))
sc.asset_update(asset_id, dns=addresses) | Updates a DNS Asset List with the contents of the filename. The assumed
format of the file is 1 entry per line. This function will convert the
file contents into an array of entries and then upload that array into
SecurityCenter. |
def clean_source_index(self):
cleanup_timer = Timer()
cleanup_counter = 0
for entry in os.listdir(self.config.source_index):
pathname = os.path.join(self.config.source_index, entry)
if os.path.islink(pathname) and not os.path.exists(pathname):
logger.warn(... | Cleanup broken symbolic links in the local source distribution index.
The purpose of this method requires some context to understand. Let me
preface this by stating that I realize I'm probably overcomplicating
things, but I like to preserve forward / backward compatibility when
possible... |
def _bnd(self, xloc, dist, length, cache):
lower, upper = evaluation.evaluate_bound(
dist, xloc.reshape(1, -1))
lower = lower.reshape(length, -1)
upper = upper.reshape(length, -1)
assert lower.shape == xloc.shape, (lower.shape, xloc.shape)
assert upper.shape == xloc.s... | boundary function.
Example:
>>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).range(
... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]]))
[[[0. 0. 0.]
[0. 0. 0.]]
<BLANKLINE>
[[2. 2. 2.]
[2. 2. 2.]]] |
def _gen_back(self):
back = set()
if self.backends:
for backend in self.backends:
fun = '{0}.targets'.format(backend)
if fun in self.rosters:
back.add(backend)
return back
return sorted(back) | Return a list of loaded roster backends |
def data_from_dict(self, data):
nvars = []
for key, val in data.items():
self.__dict__[key].extend(val)
if len(nvars) > 1 and len(val) != nvars[-1]:
raise IndexError(
'Model <{}> parameter <{}> must have the same length'.
fo... | Populate model parameters from a dictionary of parameters
Parameters
----------
data : dict
List of parameter dictionaries
Returns
-------
None |
def makeDirectory(self, full_path, dummy = 40841):
if full_path[-1] is not '/':
full_path += '/'
data = {'dstresource': full_path,
'userid': self.user_id,
'useridx': self.useridx,
'dummy': dummy,
}
s, metadata = self.POS... | Make a directory
>>> nd.makeDirectory('/test')
:param full_path: The full path to get the directory property. Should be end with '/'.
:return: ``True`` when success to make a directory or ``False`` |
def split_list(
list_object = None,
granularity = None
):
if granularity < 0:
raise Exception("negative granularity")
mean_length = len(list_object) / float(granularity)
split_list_object = []
last_length = float(0)
if len(list_object) > granularity:
while last_length < l... | This function splits a list into a specified number of lists. It returns a
list of lists that correspond to these parts. Negative numbers of parts are
not accepted and numbers of parts greater than the number of elements in the
list result in the maximum possible number of lists being returned. |
def __GetRequestField(self, method_description, body_type):
body_field_name = self.__BodyFieldName(body_type)
if body_field_name in method_description.get('parameters', {}):
body_field_name = self.__names.FieldName(
'%s_resource' % body_field_name)
while body_field_na... | Determine the request field for this method. |
def reply(self, ticket_id, text='', cc='', bcc='', content_type='text/plain', files=[]):
return self.__correspond(ticket_id, text, 'correspond', cc, bcc, content_type, files) | Sends email message to the contacts in ``Requestors`` field of
given ticket with subject as is set in ``Subject`` field.
Form of message according to documentation::
id: <ticket-id>
Action: correspond
Text: the text comment
second line starts with ... |
def create_session_engine(uri=None, cfg=None):
if uri is not None:
eng = sa.create_engine(uri)
elif cfg is not None:
eng = sa.create_engine(cfg.get('db', 'SA_ENGINE_URI'))
else:
raise IOError("unable to connect to SQL database")
ses = orm.sessionmaker(bind=eng)()
return ses, ... | Create an sqlalchemy session and engine.
:param str uri: The database URI to connect to
:param cfg: The configuration object with database URI info.
:return: The session and the engine as a list (in that order) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.