Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
338,300 | def compile(self):
params = self.column_params + self.join_params + self.params
if self.limit and self.limit >= 0:
self.sql_limit =
params += [self.limit]
return (self.sql, params, self.keys) | Compile SQL and return 3-tuple ``(sql, params, keys)``.
Example usage::
(sql, params, keys) = sc.compile()
for row in cursor.execute(sql, params):
record = dict(zip(keys, row)) |
338,301 | def init(name,
cpu,
mem,
image=None,
nic=,
interfaces=None,
hypervisor=None,
start=True,
disk=,
disks=None,
saltenv=,
seed=True,
install=True,
pub_key=None,
priv_key=None,
seed_cmd=,
... | Initialize a new vm
:param name: name of the virtual machine to create
:param cpu: Number of virtual CPUs to assign to the virtual machine
:param mem: Amount of memory to allocate to the virtual machine in MiB.
:param image: Path to a disk image to use as the first disk (Default: ``None``).
Dep... |
338,302 | def record_manifest(self):
manifest = super(TarballSatchel, self).record_manifest()
manifest[] = self.timestamp
return manifest | Called after a deployment to record any data necessary to detect changes
for a future deployment. |
338,303 | def get_relation(self, relation):
from .relations import Relation
with Relation.no_constraints(True):
rel = getattr(self.get_model(), relation)()
nested = self._nested_relations(relation)
if len(nested) > 0:
rel.get_query().with_(nested)
retur... | Get the relation instance for the given relation name.
:rtype: orator.orm.relations.Relation |
338,304 | def postprocess(self):
assert self.postscript
envmod.setup()
envmod.module(, )
cmd = .format(script=self.postscript)
cmd = shlex.split(cmd)
rc = sp.call(cmd)
assert rc == 0, | Submit a postprocessing script after collation |
338,305 | def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim):
layout_rules = convert_to_layout_rules(layout)
mesh_shape = convert_to_shape(mesh_shape)
mesh_axis = layout_rules.tensor_dimension_to_mesh_axis(tensor_dim, mesh_shape)
if mesh_axis is None:
return 1
else:
return mesh_shape.dims[mesh_a... | How many ways does a tensor dimension get split.
This is used to "cheat" when building the mtf graph and peek at how a
tensor dimension will be split. Returns 1 if the tensor dimension is not
split.
Args:
layout: an input to convert_to_layout_rules
mesh_shape: an input to convert_to_shape
tensor_... |
338,306 | def sys_transmit(self, cpu, fd, buf, count, tx_bytes):
if issymbolic(fd):
logger.info("Ask to write to a symbolic file descriptor!!")
cpu.PC = cpu.PC - cpu.instruction.size
raise SymbolicSyscallArgument(cpu, 0)
if issymbolic(buf):
logger.info("As... | Symbolic version of Decree.sys_transmit |
338,307 | def wait_until(obj, att, desired, callback=None, interval=5, attempts=0,
verbose=False, verbose_atts=None):
if callback:
waiter = _WaitThread(obj=obj, att=att, desired=desired, callback=callback,
interval=interval, attempts=attempts, verbose=verbose,
verbose_atts... | When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att` attribute until the `desired` value
is reached, or until the maximum number of attempts is reached. The updated
object... |
338,308 | def assert_equal(self, v1, v2, **kwargs):
is_success = v1 == v2
if is_success:
message = "assert equal success, %s == %s" %(v1, v2)
else:
message = % (v1, v2)
kwargs.update({
: message,
: is_success,
})
self._add_a... | Check v1 is equals v2, and take screenshot if not equals
Args:
- desc (str): some description
- safe (bool): will omit AssertionError if set to True
- screenshot: can be type <None|True|False|PIL.Image> |
338,309 | def set(self, section, option, value = None, title = None, validate = None, help = None, control = None, args = None, kwargs = None, include = None):
if self.has_option(section, option):
oldValue = self.get(section, option)
v = self.config[section][option]
self.config[section][option] = v
if val... | set(self, section, option, value = None, title = None, validate = lambda value: None, help = '', control = None, args = [], kwargs = {}, include = True)
Store the value to the configuration with all it's associated data.
* title is the friendly name for the value (will be used for textual labels etc).
* va... |
338,310 | def _ctypes_out(parameter):
if (parameter.dimension is not None and ":" in parameter.dimension
and "out" in parameter.direction and ("allocatable" in parameter.modifiers or
"pointer" in parameter.modifiers)):
if parameter.direction == "(inout)":
... | Returns a parameter variable declaration for an output variable for the specified
parameter. |
338,311 | def _osd_pct_used(self, health):
pct = re.compile(r).findall(health)
osd = re.compile(r).findall(health)
if len(pct) > 0 and len(osd) > 0:
return osd[0], int(pct[0][:-1])
else:
return None, None | Take a single health check string, return (OSD name, percentage used) |
338,312 | def next_frame_id(self):
fid = bytes(bytearray((self._frame_id,)))
self._frame_id += 1
if self._frame_id > 0xFF:
self._frame_id = 1
try:
del self._rx_frames[fid]
except KeyError:
pass
return fid | Gets a byte of the next valid frame ID (1 - 255), increments the
internal _frame_id counter and wraps it back to 1 if necessary. |
338,313 | def set_acl(self, acl, mode):
if not isinstance(acl, basestring):
raise TypeError("acl can only be an instance of type basestring")
if not isinstance(mode, baseinteger):
raise TypeError("mode can only be an instance of type baseinteger")
self._call("setACL",
... | Sets the ACL of this file.
in acl of type str
The ACL specification string. To-be-defined.
in mode of type int
UNIX-style mode mask to use if @a acl is empty. As mention in
:py:func:`IGuestSession.directory_create` this is realized on
a best effort basi... |
338,314 | def add_feature_values(self, features):
if not in self.fieldnames():
raise RuntimeError()
if not self._categories:
raise RuntimeError(
\
%(features, str(self._fields)))
for feature in features:
feat_vals = np.... | Adds feature values of feature 'feature' to all fixations in
the calling fixmat.
For fixations out of the image boundaries, NaNs are returned.
The function generates a new attribute field named with the
string in features that contains an np.array listing feature
values... |
338,315 | def safe_pow(base, exp):
if exp > MAX_EXPONENT:
raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT))
return base ** exp | safe version of pow |
338,316 | def _has_example(self, label):
if label in self._raw_examples:
return True
else:
for field in self.all_fields:
dt, _ = unwrap_nullable(field.data_type)
if not is_user_defined_type(dt) and not is_void_type(dt):
continue
... | Whether this data type has an example with the given ``label``. |
338,317 | def execute_insert_no_results(self, sock_info, run, op_id, acknowledged):
command = SON([(, self.collection.name),
(, self.ordered)])
concern = {: int(self.ordered)}
command[] = concern
if self.bypass_doc_val and sock_info.max_wire_version >= 4:
... | Execute insert, returning no results. |
338,318 | def initialize_ports(self) -> None:
if not self.params:
self.initialize_params(preload_data=False)
self.params.update_ports()
self.ports = Ports(self.params, self.request) | Load IO port parameters for device. |
338,319 | def _get_sector(self, channel, nlines, ncols):
if self._is_vis(channel):
margin = 100
sectors_ref = self.vis_sectors
else:
margin = 50
sectors_ref = self.ir_sectors
for (nlines_ref, ncols_ref), sector in sectors_ref.items():
i... | Determine which sector was scanned |
338,320 | def is_same_filename (filename1, filename2):
return os.path.realpath(filename1) == os.path.realpath(filename2) | Check if filename1 and filename2 are the same filename. |
338,321 | def get_all_records(
self,
empty2zero=False,
head=1,
default_blank="",
allow_underscores_in_numeric_literals=False,
):
idx = head - 1
data = self.get_all_values()
if len(data) <= idx:
return []
keys = data[idx]... | Returns a list of dictionaries, all of them having the contents
of the spreadsheet with the head row as keys and each of these
dictionaries holding the contents of subsequent rows of cells
as values.
Cell values are numericised (strings that can be read as ints
... |
338,322 | def set_tcp_keepalive(socket, config):
keepalive_options = {
: ,
: ,
: ,
: ,
}
for key, const in keepalive_options.items():
if key in config:
attr = getattr(zmq, const, None)
if attr:
socket.setsockopt(attr, confi... | Set a series of TCP keepalive options on the socket if
and only if
1) they are specified explicitly in the config and
2) the version of pyzmq has been compiled with support
We ran into a problem in FedoraInfrastructure where long-standing
connections between some hosts would suddenly drop off t... |
338,323 | def sync_heater_control(self, device_id, fan_status=None,
power_status=None):
loop = asyncio.get_event_loop()
task = loop.create_task(self.heater_control(device_id,
fan_status,
... | Set heater temps. |
338,324 | def enable_hostgroup_host_notifications(self, hostgroup):
for host_id in hostgroup.get_hosts():
if host_id in self.daemon.hosts:
self.enable_host_notifications(self.daemon.hosts[host_id]) | Enable host notifications for a hostgroup
Format of the line that triggers function call::
ENABLE_HOSTGROUP_HOST_NOTIFICATIONS;<hostgroup_name>
:param hostgroup: hostgroup to enable
:type hostgroup: alignak.objects.hostgroup.Hostgroup
:return: None |
338,325 | def masked_array(self, geometry=None):
if geometry is None:
return self._masked_array()
geom = transform(geometry, self.sref)
env = Envelope.from_geom(geom).intersect(self.envelope)
arr = self._masked_array(env)
if geom.GetGeometryType() != ogr.wkbPoint:
... | Returns a MaskedArray using nodata values.
Keyword args:
geometry -- any geometry, envelope, or coordinate extent tuple |
338,326 | def emitDataChanged(self, treeItem):
indexLeft, indexRight = self.indexTupleFromItem(treeItem)
checkItem = self.getItem(indexLeft)
assert checkItem is treeItem, "{} != {}".format(checkItem, treeItem)
self.dataChanged.emit(indexLeft, indexRight) | Emits the data changed for the model indices (all columns) for this treeItem |
338,327 | def perform_query(self, query, **params):
try:
return self.engine.execute(query, params)
except:
print("Error with query: {}".format(query))
raise | Perform a query, where query is a string. |
338,328 | def _prepare_files(self, encoding):
content_type =
if self.__op.consumes and content_type not in self.__op.consumes:
raise errs.SchemaError(.format(content_type, self.__op.consumes))
boundary = uuid4().hex
content_type +=
content_type = content_type.format... | private function to prepare content for paramType=form with File |
338,329 | def record_leaving(self, time, code, frame_key, parent_stats):
try:
stats = parent_stats.get_child(code)
time_entered = self._times_entered.pop((code, frame_key))
except KeyError:
return
time_elapsed = time - time_entered
stats.deep_time += ma... | Left from a function call. |
338,330 | def _custom_dtype_getter(self, getter, name, shape=None, dtype=DEFAULT_DTYPE,
*args, **kwargs):
if dtype in CASTABLE_TYPES:
var = getter(name, shape, tf.float32, *args, **kwargs)
return tf.cast(var, dtype=dtype, name=name + )
else:
return getter(name, shape, dt... | Creates variables in fp32, then casts to fp16 if necessary.
This function is a custom getter. A custom getter is a function with the
same signature as tf.get_variable, except it has an additional getter
parameter. Custom getters can be passed as the `custom_getter` parameter of
tf.variable_scope. Then,... |
338,331 | def limit_replace(self, accountID, orderID, **kwargs):
return self.replace(
accountID,
orderID,
order=LimitOrderRequest(**kwargs)
) | Shortcut to replace a pending Limit Order in an Account
Args:
accountID : The ID of the Account
orderID : The ID of the Limit Order to replace
kwargs : The arguments to create a LimitOrderRequest
Returns:
v20.response.Response containing the results from... |
338,332 | def is_all_field_none(self):
if self._id_ is not None:
return False
if self._created is not None:
return False
if self._updated is not None:
return False
if self._billing_account_id is not None:
return False
if self._i... | :rtype: bool |
338,333 | def expect_equal(first, second, msg=None, extras=None):
try:
asserts.assert_equal(first, second, msg, extras)
except signals.TestSignal as e:
logging.exception(, first,
second)
recorder.add_error(e) | Expects the equality of objects, otherwise fail the test.
If the expectation is not met, the test is marked as fail after its
execution finishes.
Error message is "first != second" by default. Additional explanation can
be supplied in the message.
Args:
first: The first object to compare.... |
338,334 | def MOVE(classical_reg1, classical_reg2):
left, right = unpack_reg_val_pair(classical_reg1, classical_reg2)
return ClassicalMove(left, right) | Produce a MOVE instruction.
:param classical_reg1: The first classical register, which gets modified.
:param classical_reg2: The second classical register or immediate value.
:return: A ClassicalMove instance. |
338,335 | def advance(self):
self.cursor += 1
if self.cursor >= len(self.raw):
self.char = None
else:
self.char = self.raw[self.cursor] | Increments the cursor position. |
338,336 | def query(
name,
rdtype,
method=None,
servers=None,
timeout=None,
walk=False,
walk_tld=False,
secure=None
):
s results
:param name: name to lookup
:param rdtype: DNS record type
:param method: gai (getaddrinfo()), pydns, dig, drill, host, nslookup or auto (default)
:... | Query DNS for information.
Where `lookup()` returns record data, `query()` tries to interpret the data and return it's results
:param name: name to lookup
:param rdtype: DNS record type
:param method: gai (getaddrinfo()), pydns, dig, drill, host, nslookup or auto (default)
:param servers: (list of)... |
338,337 | def transposable_node(self, parent=None, tag=, attrib=None, **extras):
if self.graph.horizontal:
for key1, key2 in ((, ), (, ), (, )):
attr1 = extras.get(key1, None)
attr2 = extras.get(key2, None)
if attr2:
extras[key1] = a... | Make a new svg node which can be transposed if horizontal |
338,338 | def get_segment_token_offsets(segment_token_list, token_map):
token_indices = [token_map[token_id] for token_id in segment_token_list]
return min(token_indices), max(token_indices) | given a list of token node IDs, returns the index of its first and last
elements. this actually calculates the int indices, as there are weird
formats like RS3, which use unordered / wrongly ordered IDs.
Parameters
----------
segment_token_list : list of str
sorted list of token IDs (i.e. t... |
338,339 | def close(self):
if self.connection:
self.connection.close()
self.connection = None
logging.debug("Connection closed.") | Close the connection. |
338,340 | def _is_excluded(obj, properties, regexes, include_only_marked):
if isinstance(obj, vim.HostSystem):
if regexes and regexes.get() is not None:
match = re.search(regexes[], properties.get("name", ""), re.IGNORECASE)
if not match:
... | Return `True` if the given host or virtual machine is excluded by the user configuration,
i.e. violates any of the following rules:
* Do not match the corresponding `*_include_only` regular expressions
* Is "non-labeled" while `include_only_marked` is enabled (virtual machine only) |
338,341 | def _get_catalog_hierarchy_id(self, catalog_id, proxy, runtime):
seed_str = convert_catalog_id_to_object_id_string(catalog_id)
ident = Id(authority=self._authority,
namespace=,
identifier=seed_str)
return HierarchyLookupSession(proxy, runtime).get_h... | Gets the catalog hierarchy |
338,342 | def fcoe_get_login_output_fcoe_login_list_fcoe_login_session_mac(self, **kwargs):
config = ET.Element("config")
fcoe_get_login = ET.Element("fcoe_get_login")
config = fcoe_get_login
output = ET.SubElement(fcoe_get_login, "output")
fcoe_login_list = ET.SubElement(output, ... | Auto Generated Code |
338,343 | def export_to_fta(self, sample_rate, filename: str, include_amplitude=False):
spectrogram = self.__calculate_spectrogram(self.samples)
spectrogram = np.flipud(spectrogram.T)
if include_amplitude:
result = np.empty((spectrogram.shape[0], spectrogram.shape[1], 3),
... | Export to Frequency, Time, Amplitude file.
Frequency is double, Time (nanosecond) is uint32, Amplitude is float32
:return: |
338,344 | def upgrade(self, dependencies=False, prerelease=False, force=False):
pip_args = [, self.pkg]
found = self._get_current() != (-1)
if found:
pip_args.append("--upgrade")
if force:
pip_args.append(
"--force-reinstall" if found else "--igno... | Upgrade the package unconditionaly
Args:
dependencies: update package dependencies if True (see pip --no-deps)
prerelease: update to pre-release and development versions
force: reinstall all packages even if they are already up-to-date
Returns True if pip was sucessfu... |
338,345 | def setup_logging():
logging_configs = DEFAULT_LOGGING_CONFIG
new_logging_configs = bigchaindb.config[]
if in new_logging_configs:
filename = new_logging_configs[]
logging_configs[][][] = filename
if in new_logging_configs:
error_filename = new_logging_configs[]
... | Function to configure log hadlers.
.. important::
Configuration, if needed, should be applied before invoking this
decorator, as starting the subscriber process for logging will
configure the root logger for the child process based on the
state of :obj:`bigchaindb.config` at the mo... |
338,346 | def add_variable(self, name, expression, overwrite=True, unique=True):
if unique or overwrite or name not in self.variables:
existing_names = self.get_column_names(virtual=False) + list(self.variables.keys())
name = vaex.utils.find_valid_name(name, used=[] if not unique else exi... | Add a variable to to a DataFrame.
A variable may refer to other variables, and virtual columns and expression may refer to variables.
Example
>>> df.add_variable('center', 0)
>>> df.add_virtual_column('x_prime', 'x-center')
>>> df.select('x_prime < 0')
:param: str nam... |
338,347 | def start(name):
hotfix_branch = + common.to_branch_name(name)
master = conf.get(, )
common.assert_on_branch(master)
common.git_checkout(hotfix_branch, create=True) | Start working on a new hotfix.
This will create a new branch off master called hotfix/<name>.
Args:
name (str):
The name of the new feature. |
338,348 | def save(self, filename):
with open(filename, "wb") as fd:
fd.write(self.__buff) | Save the current buffer to `filename`
Exisiting files with the same name will be overwritten.
:param str filename: the name of the file to save to |
338,349 | def _to_png(self, delay=3):
if self._png_image is None:
from selenium import webdriver
options = webdriver.firefox.options.Options()
options.add_argument()
driver = webdriver.Firefox(options=options)
html = self.get_root().render()
... | Export the HTML to byte representation of a PNG image.
Uses selenium to render the HTML and record a PNG. You may need to
adjust the `delay` time keyword argument if maps render without data or tiles.
Examples
--------
>>> m._to_png()
>>> m._to_png(time=10) # Wait 10 s... |
338,350 | def create_custom_views(auth, url,name=None, upperview=None):
create_custom_views_url =
f_url = url + create_custom_views_url
if upperview is None:
payload = + name +
print (payload)
else:
parentviewid = get_custom_views(auth, url, upperview)[0][]
payload = +name+... | function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input
will return only the specified view.
:param name: string containg the name of the desired custom view
:return: list of dictionaries containing attributes of the custom views. |
338,351 | def summarise(self, base_list, trusted_placements, reverse_pipe, times,
hit_read_count_list, max_samples_for_krona):
placements_list = []
for base in base_list:
placements = trusted_placements[base]
self.... | summarise - write summary information to file, including otu table, biom
file, krona plot, and timing information
Parameters
----------
base_list : array
list of each of the files processed by graftm, with the path and
and suffixed removed
tru... |
338,352 | def cached(func):
@wraps(func)
def wrapper(*args, **kwargs):
global cache
key = json.dumps((func, args, kwargs), sort_keys=True, default=str)
try:
return cache[key]
except KeyError:
pass
res = func(*args, **kwargs)
cache[key] = res
... | Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls. |
338,353 | def surfaceBrightness(abs_mag, r_physical, distance):
r_angle = np.degrees(np.arctan(r_physical / distance))
c_v = 19.78
return abs_mag + dist2mod(distance) + c_v + 2.5 * np.log10(r_angle**2) | Compute the average surface brightness [mag arcsec^-2] within the half-light radius
abs_mag = absolute magnitude [mag]
r_physical = half-light radius [kpc]
distance = [kpc]
The factor 2 in the c_v equation below account for half the luminosity
within the half-light radius. The 3600.**2 is conver... |
338,354 | def normalize(self, method=, window=None, perc=20, offset=0.1):
check_options(method, [, , , ])
from warnings import warn
if not (method == or method == ) and window is not None:
warn()
if method == :
baseFunc = mean
if method == :
... | Normalize by subtracting and dividing by a baseline.
Baseline can be derived from a global mean or percentile,
or a smoothed percentile estimated within a rolling window.
Windowed baselines may only be well-defined for
temporal series data.
Parameters
----------
... |
338,355 | def patch_namespaced_endpoints(self, name, namespace, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.patch_namespaced_endpoints_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_endpoints_with_http_info(name, name... | partially update the specified Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_endpoints(name, namespace, body, async_req=True)
>>> result = thread.get()
:param ... |
338,356 | def connected_components(image, connectivity=2, background=None):
if background is None:
image[np.where(image == 0)] = np.max(image) + 1
ar = skimage.measure.label(image, connectivity=connectivity,
background=background)
if backgrou... | Return :class:`jicbioimage.core.image.SegmentedImage`.
:param image: input :class:`jicbioimage.core.image.Image`
:param connectivity: maximum number of orthagonal hops to consider a
pixel/voxel as a neighbor
:param background: consider all pixels with this value (int) as background... |
338,357 | def get_web_session(self, language=):
if self._web_session:
return self._web_session
cookies = self.get_web_session_cookies()
if cookies is None:
return None
self._web_session = session = make_requests_session()
session_id = generate_session_id(... | Get a :class:`requests.Session` that is ready for use
See :meth:`get_web_session_cookies`
.. note::
Auth cookies will only be send to ``(help|store).steampowered.com`` and ``steamcommunity.com`` domains
.. note::
The session is valid only while :class:`.SteamClient` in... |
338,358 | def _collapse_ranges(ranges, ja):
arow0, _, acol0, acol1 = ranges[ja]
jb = 0
while jb < len(ranges):
if jb == ja:
jb += 1
continue
brow0, brow1, bcol0, bcol1 = ranges[jb]
if bcol0 <= acol1 and brow1 >= arow0 and \
not(bcol0 == acol1 and br... | Within the `ranges` list find those 2d-ranges that overlap with `ranges[ja]`
and merge them into `ranges[ja]`. Finally, return the new index of the
ja-th range within the `ranges` list. |
338,359 | def _createDatabase( self ):
command =
self._connection.execute(command.format(tn = self.EXPERIMENT_METADATA_TABLE,
k = self.EXPERIMENT_ID))
self.commit() | Private method to create the SQLite database file. |
338,360 | def computePhase2(self, doLearn=False):
self.confidence[][c,i] = maxConfidence | This is the phase 2 of learning, inference and multistep prediction. During
this phase, all the cell with lateral support have their predictedState
turned on and the firing segments are queued up for updates.
Parameters:
--------------------------------------------
doLearn: Boolean flag to que... |
338,361 | def get_vasp_kpoint_file_sym(structure):
output = run_aconvasp_command(["aconvasp", "--kpath"], structure)
if "ERROR" in output[1]:
raise AconvaspError(output[1])
started = False
kpoints_string = ""
for line in output[0].split("\n"):
if started or line.find("END") != -1... | get a kpoint file ready to be ran in VASP along the symmetry lines of the
Brillouin Zone |
338,362 | def encode_contents(self):
header = struct.pack("<LL", self.offset, len(self.raw_data))
return bytearray(header) + self.raw_data | Encode the contents of this update record without including a record header.
Returns:
bytearary: The encoded contents. |
338,363 | def set_position(self, position):
self._player_interface.SetPosition(ObjectPath("/not/used"), Int64(position * 1000.0 * 1000))
self.positionEvent(self, position) | Set the video to playback position to `position` seconds from the start of the video
Args:
position (float): The position in seconds. |
338,364 | def timeago_template(locale, index, ago_in):
try:
LOCALE = __import__( + locale)
LOCALE = locale_module(LOCALE, locale)
except:
locale = setting.DEFAULT_LOCALE
LOCALE = __import__( + locale)
LOCALE = locale_module(LOCALE, locale)
if isinstance(LOCALE, list):
... | simple locale implement |
338,365 | def short_form_one_format(jupytext_format):
if not isinstance(jupytext_format, dict):
return jupytext_format
fmt = jupytext_format[]
if in jupytext_format:
fmt = jupytext_format[] + fmt
elif fmt.startswith():
fmt = fmt[1:]
if in jupytext_format:
fmt = jupytext... | Represent one jupytext format as a string |
338,366 | def unacknowledge_problem_if_not_sticky(self):
if hasattr(self, ) and self.acknowledgement is not None:
if not self.acknowledgement.sticky:
self.unacknowledge_problem() | Remove the acknowledge if it is not sticky
:return: None |
338,367 | def feature_names(self, names):
"Stores the text labels for features"
if len(names) != self.num_features:
raise ValueError("Number of names do not match the number of features!")
if not isinstance(names, (Sequence, np.ndarray, np.generic)):
raise ValueError("Input is not... | Stores the text labels for features |
338,368 | def reverse_complement(self):
copy = self.copy()
copy.top = self.top.reverse_complement()
copy.bottom = self.bottom.reverse_complement()
copy.features = []
return copy | Reverse complement the DNA.
:returns: A reverse-complemented instance of the current sequence.
:rtype: coral.DNA |
338,369 | def NewFromYiq(y, i, q, alpha=1.0, wref=_DEFAULT_WREF):
(0.999902, 0.499955, -6.6905e-05, 1)(0.999902, 0.499955, -6.6905e-05, 0.5)
return Color(Color.YiqToRgb(y, i, q), , alpha, wref) | Create a new instance based on the specifed YIQ values.
Parameters:
:y:
The Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
The whitep... |
338,370 | def get_object_cache_keys(instance):
if instance.pk is None or instance._state.adding:
return []
keys = []
tr_models = instance._parler_meta.get_all_models()
for language in instance.get_available_languages():
for tr_model in tr_models:
keys.append(get_translation... | Return the cache keys associated with an object. |
338,371 | def get_except_handler_name(self, node):
name = node.name
if not name:
return None
if version_info < (3,):
return name.id
return name | Helper to get the exception name from an ExceptHandler node in both py2 and py3. |
338,372 | def reverse_format(format_string, resolved_string):
from string import Formatter
from datetime import datetime
fmt = Formatter()
args = {}
format_string = make_path_posix(format_string)
literal_texts, field_names, format_specs, conversions = zip(*fmt.parse(format_string))
i... | Reverse the string method format.
Given format_string and resolved_string, find arguments that would
give ``format_string.format(**arguments) == resolved_string``
Parameters
----------
format_string : str
Format template string as used with str.format method
resolved_string : str
... |
338,373 | def _local_call(self, call_conf):
try:
ret = self._get_caller(call_conf).call()
except SystemExit:
ret =
self.out.error(ret)
except Exception as ex:
ret = .format(ex)
log.debug(ex, exc_info=True)
self.out.error(ret... | Execute local call |
338,374 | def get_memory_size(self):
n = sys.getsizeof(self)
n += sys.getsizeof(self.padding)
n += total_size(self.start_addr)
n += total_size(self._buf)
n += sys.getsizeof(self._offset)
return n | Returns the approximate memory footprint for data. |
338,375 | def wait_for_task(service, task, timeout_sec=120):
return time_wait(lambda: task_predicate(service, task), timeout_seconds=timeout_sec) | Waits for a task which was launched to be launched |
338,376 | def jsonify(obj, pretty=False):
if pretty:
params = dict(sort_keys=True, indent=2, allow_nan=False,
separators=(",", ": "), ensure_ascii=False)
else:
params = dict(sort_keys=False, indent=None, allow_nan=False,
separators=(",", ":"), ensure_ascii=... | Turn a nested object into a (compressed) JSON string.
Parameters
----------
obj : dict
Any kind of dictionary structure.
pretty : bool, optional
Whether to format the resulting JSON in a more legible way (
default False). |
338,377 | def hook_get_queryset(self, changelist, request):
changelist.check_field_exists(self.pid_field)
self.pid = self.get_pid_from_request(changelist, request)
changelist.params[self.pid_field] = self.pid | Triggered by `ChangeList.get_queryset()`. |
338,378 | def gunzip(content):
gzip_magic_numbers = [ 0x1f, 0x8b ]
first_two_bytes = [ byte for byte in bytearray(content)[:2] ]
if first_two_bytes != gzip_magic_numbers:
raise DecompressionError(.format(
hex(first_two_bytes[0]), hex(first_two_bytes[1])), hex(gzip_magic_numbers[0]), hex(gzip_magic_numbers[1]))... | Decompression is applied if the first to bytes matches with
the gzip magic numbers.
There is once chance in 65536 that a file that is not gzipped will
be ungzipped. |
338,379 | def set_label(self, label, lineno, local=False):
ex_label, namespace = Memory.id_name(label)
if ex_label in self.local_labels[-1].keys():
result = self.local_labels[-1][ex_label]
result.lineno = lineno
else:
result = self.local_labels[-1][ex_label] =... | Sets a label, lineno and local flag in the current scope
(even if it exist in previous scopes). If the label exist in
the current scope, changes it flags.
The resulting label is returned. |
338,380 | def cleanup_storage(*args):
ShardedClusters().cleanup()
ReplicaSets().cleanup()
Servers().cleanup()
sys.exit(0) | Clean up processes after SIGTERM or SIGINT is received. |
338,381 | def aggregate_history(self, ip, days_limit=None):
first_date = None
last_date = None
prec_asn = None
prec_block = None
for entry in self.history(ip, days_limit):
if entry is None:
continue
date, asn, block = entry
if fi... | Get the full history of an IP, aggregate the result instead of
returning one line per day.
:param ip: IP address to search for
:param days_limit: Max amount of days to query. (None means no limit)
:rtype: list. For each change: FirstDay, LastDay, ASN, Block |
338,382 | def register_extensions(self):
try:
for extension, config in self.config[].items():
extension_bstr =
extension_pieces = extension.split()
if len(extension_pieces) > 1:
extension_bstr = ... | Function registers extensions given extensions list
Args
----
extensions (list) : the extensions dict on app.config.<env>
Raises
------
Exception: Raises exception when extension can't be loaded
properly. |
338,383 | def _onMenuItemSelected(self, evt):
current = self._menu.IsChecked(evt.GetId())
if current:
new = False
else:
new = True
self._menu.Check(evt.GetId(), new)
self._toolbar.set_active(self.getActiveAxes())
evt.Skip() | Called whenever one of the specific axis menu items is selected |
338,384 | def copy_file(src, dst):
try:
fin = os.open(src, READ_FLAGS)
stat = os.fstat(fin)
fout = os.open(dst, WRITE_FLAGS, stat.st_mode)
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
os.write(fout, x)
finally:
try:
os.close(fin)
excep... | Copy a single file.
:param src: Source name
:param dst: Destination name |
338,385 | def getModelData(self,name):
if name in self.modelcache:
return self.modelcache[name]
return self.loadModelData(name) | Gets the model data associated with the given name.
If it was loaded, a cached copy will be returned.
It it was not loaded, it will be loaded and cached. |
338,386 | def fill_rawq(self):
if self.irawq >= len(self.rawq):
self.rawq = b
self.irawq = 0
buf = yield from self._reader.read(50)
self.eof = (not buf)
self.rawq = self.rawq + buf | Fill raw queue from exactly one recv() system call.
Set self.eof when connection is closed. |
338,387 | def as_set(self, preserve_casing=False):
if preserve_casing:
return set(self._headers)
return set(self._set) | Return the set as real python set type. When calling this, all
the items are converted to lowercase and the ordering is lost.
:param preserve_casing: if set to `True` the items in the set returned
will have the original case like in the
:... |
338,388 | def update(self, frame_to, frame_from=None, **kwargs):
self._updated = np.random.random()
if frame_from is None:
frame_from = self.base_frame
matrix = kwargs_to_matrix(**kwargs)
attr = {: matrix, : time.time()}
i... | Update a transform in the tree.
Parameters
---------
frame_from : hashable object
Usually a string (eg 'world').
If left as None it will be set to self.base_frame
frame_to : hashable object
Usually a string (eg 'mesh_0')
matrix : (4,4) float
... |
338,389 | def validate_ssl_certificate(self, client):
response = client.request(, )
if response.status_code < 200 or response.status_code >= 300:
raise TwilioRestException(response.status_code, , ) | Validate that a request to the new SSL certificate is successful
:return: null on success, raise TwilioRestException if the request fails |
338,390 | def loadGrammar(self, grammar, searchpaths=None):
self.grammar = self._load(grammar, searchpaths=searchpaths)
self.refs = {}
for ref in self.grammar.getElementsByTagName("ref"):
self.refs[ref.attributes["id"].value] = ref | load context-free grammar |
338,391 | def compile(self, limit=None, params=None):
from ibis.client import compile
return compile(self, limit=limit, params=params) | Compile expression to whatever execution target, to verify
Returns
-------
compiled : value or list
query representation or list thereof |
338,392 | def reset(self):
self._components = OrderedDict()
self.clear_selections()
self._logger.info("<block: %s> reset component list" % (self.name)) | Removes all the components of the block |
338,393 | def _repair_column(self):
check_for_title = True
for column_index in range(self.start[1], self.end[1]):
table_column = TableTranspose(self.table)[column_index]
column_start = table_column[self.start[0]]
if check_for_title and is_empty_c... | Same as _repair_row but for columns. |
338,394 | def reset(vm_):
*
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, , vm_)
if vm_uuid is False:
return False
try:
xapi.VM.hard_reboot(vm_uuid)
return True
except Exception:
return False | Reset a VM by emulating the reset button on a physical machine
CLI Example:
.. code-block:: bash
salt '*' virt.reset <vm name> |
338,395 | def get_score(student_item):
try:
student_item_model = StudentItem.objects.get(**student_item)
score = ScoreSummary.objects.get(student_item=student_item_model).latest
except (ScoreSummary.DoesNotExist, StudentItem.DoesNotExist):
return None
if score.is_hidden():
... | Get the score for a particular student item
Each student item should have a unique score. This function will return the
score if it is available. A score is only calculated for a student item if
it has completed the workflow for a particular assessment module.
Args:
student_item (dict): The di... |
338,396 | def _validate(self, val):
if self.allow_None and val is None:
return
if not isinstance(val, dt_types) and not (self.allow_None and val is None):
raise ValueError("Date only takes datetime types."%self.name)
if self.step is not None and not isinstance(self.step... | Checks that the value is numeric and that it is within the hard
bounds; if not, an exception is raised. |
338,397 | def from_range(cls, range_list, register_flag=True):
s = dict_from_range(range_list)
obj = cls.from_serializable(s, register_flag)
return obj | core class method to create visible objects from a range (nested list) |
338,398 | def consumer_process_task(processor, log_groups, check_point_tracker):
try:
check_point = processor.process(log_groups, check_point_tracker)
check_point_tracker.flush_check()
except Exception as e:
return TaskResult(e)
return ProcessTaskResult(check_point) | return TaskResult if failed,
return ProcessTaskResult if succeed
:param processor:
:param log_groups:
:param check_point_tracker:
:return: |
338,399 | def show_frontpage(self):
if self.content.name != :
target =
self.toggled_subreddit = self.content.name
else:
target = self.toggled_subreddit
| If on a subreddit, remember it and head back to the front page.
If this was pressed on the front page, go back to the last subreddit. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.