code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def generate_new_cid(upstream_cid=None):
if upstream_cid is None:
return str(uuid.uuid4()) if getattr(settings, 'CID_GENERATE', False) else None
if (
getattr(settings, 'CID_CONCATENATE_IDS', False)
and getattr(settings, 'CID_GENERATE', False)
):
return '%s, %s' % (ups... | Generate a new correlation id, possibly based on the given one. |
def _setup_master(self):
self.broker = mitogen.master.Broker(install_watcher=False)
self.router = mitogen.master.Router(
broker=self.broker,
max_message_size=4096 * 1048576,
)
self._setup_responder(self.router.responder)
mitogen.core.listen(self.broker, 's... | Construct a Router, Broker, and mitogen.unix listener |
def address_info(self):
return {
"node_ip_address": self._node_ip_address,
"redis_address": self._redis_address,
"object_store_address": self._plasma_store_socket_name,
"raylet_socket_name": self._raylet_socket_name,
"webui_url": self._webui_url,
... | Get a dictionary of addresses. |
def dependents_of_addresses(self, addresses):
seen = OrderedSet(addresses)
for address in addresses:
seen.update(self._dependent_address_map[address])
seen.update(self._implicit_dependent_address_map[address])
return seen | Given an iterable of addresses, yield all of those addresses dependents. |
def display(self):
for pkg in self.binary:
name = GetFromInstalled(pkg).name()
ver = GetFromInstalled(pkg).version()
find = find_package("{0}{1}{2}".format(name, ver, self.meta.sp),
self.meta.pkg_path)
if find:
packa... | Print the Slackware packages contents |
def sync_fetch(self, task):
if not self._running:
return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))
wait_result = threading.Condition()
_result = {}
def callback(type, task, result):
wait_result.acquire()
_res... | Synchronization fetch, usually used in xmlrpc thread |
def _bed_to_bed6(orig_file, out_dir):
bed6_file = os.path.join(out_dir, "%s-bed6%s" % os.path.splitext(os.path.basename(orig_file)))
if not utils.file_exists(bed6_file):
with open(bed6_file, "w") as out_handle:
for i, region in enumerate(list(x) for x in pybedtools.BedTool(orig_file)):
... | Convert bed to required bed6 inputs. |
def site_info(request):
site = get_current_site(request)
context = {
'WAFER_CONFERENCE_NAME': site.name,
'WAFER_CONFERENCE_DOMAIN': site.domain,
}
return context | Expose the site's info to templates |
def _validate_xor_args(self, p):
if len(p[1]) != 2:
raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p)) | Raises ValueError if 2 arguments are not passed to an XOR |
def _HandleLegacy(self, args, token=None):
hunt_obj = aff4.FACTORY.Open(
args.hunt_id.ToURN(), aff4_type=implementation.GRRHunt, token=token)
stats = hunt_obj.GetRunner().context.usage_stats
return ApiGetHuntStatsResult(stats=stats) | Retrieves the stats for a hunt. |
def _announce_theta(theta):
c = 299792.458
is_a_redshift = lambda p: p == "z" or p[:2] == "z_"
for parameter, value in theta.items():
try:
value[0]
except (IndexError, TypeError):
message = "\t{0}: {1:.3f}".format(parameter, value)
if is_a_redshift(paramet... | Announce theta values to the log. |
def load_bookmark(self, slot_num):
bookmarks = CONF.get('editor', 'bookmarks')
if slot_num in bookmarks:
filename, line_num, column = bookmarks[slot_num]
else:
return
if not osp.isfile(filename):
self.last_edit_cursor_pos = None
ret... | Set cursor to bookmarked file and position. |
def toggleLongTouchPoint(self):
if not self.isLongTouchingPoint:
msg = 'Long touching point'
self.toast(msg, background=Color.GREEN)
self.statusBar.set(msg)
self.isLongTouchingPoint = True
self.coordinatesUnit = Unit.PX
else:
self.t... | Toggles the long touch point operation. |
def master_event(type, master=None):
event_map = {'connected': '__master_connected',
'disconnected': '__master_disconnected',
'failback': '__master_failback',
'alive': '__master_alive'}
if type == 'alive' and master is not None:
return '{0}_{1}'.format(... | Centralized master event function which will return event type based on event_map |
def innerHTML(self) -> str:
if self._inner_element:
return self._inner_element.innerHTML
return super().innerHTML | Get innerHTML of the inner node. |
def full_name(self):
if self._tree.parent is None:
return self._intern.name
return self._tree.parent.full_name() + '.' + self._intern.name | returns name all the way up the tree |
def cookie_length(self, domain):
cookies = self.cookie_jar._cookies
if domain not in cookies:
return 0
length = 0
for path in cookies[domain]:
for name in cookies[domain][path]:
cookie = cookies[domain][path][name]
length += len(pat... | Return approximate length of all cookie key-values for a domain. |
def refresh_committed_offsets_if_needed(self):
if self._subscription.needs_fetch_committed_offsets:
offsets = self.fetch_committed_offsets(self._subscription.assigned_partitions())
for partition, offset in six.iteritems(offsets):
if self._subscription.is_assigned(partitio... | Fetch committed offsets for assigned partitions. |
def lock(self):
if self.cache.get(self.lock_name):
return False
else:
self.cache.set(self.lock_name, timezone.now(), self.timeout)
return True | This method sets a cache variable to mark current job as "already running". |
def build_filtered_queryset(self, query, **kwargs):
qs = self.get_queryset()
qs = qs.filter(self.get_queryset_filters(query))
return self.build_extra_filtered_queryset(qs, **kwargs) | Build and return the fully-filtered queryset |
def _execute_commands(self, commands, fails=False):
if self._prep_statements:
prepared_commands = [prepare_sql(c) for c in tqdm(commands, total=len(commands),
desc='Prepping SQL Commands')]
print('\tCommands prepared', len(pre... | Execute commands and get list of failed commands and count of successful commands |
def _load_schemas(self):
for filename in os.listdir(self.settings['SCHEMA_DIR']):
if filename[-4:] == 'json':
name = filename[:-5]
with open(self.settings['SCHEMA_DIR'] + filename) as the_file:
self.schemas[name] = json.load(the_file)
... | Loads any schemas for JSON validation |
def interface_type(self):
return self.visalib.parse_resource(self._resource_manager.session,
self.resource_name)[0].interface_type | The interface type of the resource as a number. |
def send_post_command(self, command, body):
res = requests.post("http://{host}:{port}{command}".format(
host=self._host, port=self._receiver_port, command=command),
data=body, timeout=self.timeout)
if res.status_code == 200:
return res.text
els... | Send command via HTTP post to receiver. |
def main():
if check_import():
sys.exit(1)
from aeneas.diagnostics import Diagnostics
errors, warnings, c_ext_warnings = Diagnostics.check_all()
if errors:
sys.exit(1)
if c_ext_warnings:
print_warning(u"All required dependencies are met but at least one Python C extension is ... | The entry point for this module |
def configure_logging(conf):
root_logger = logging.getLogger()
root_logger.setLevel(getattr(logging, conf.loglevel.upper()))
if conf.logtostderr:
add_stream_handler(root_logger, sys.stderr)
if conf.logtostdout:
add_stream_handler(root_logger, sys.stdout) | Initialize and configure logging. |
def merge(revision, branch_label, message, list_revisions=''):
alembic_command.merge(
config=get_config(),
revisions=list_revisions,
message=message,
branch_label=branch_label,
rev_id=revision
) | Merge two revision together, create new revision file |
def _get_fout_go(self):
assert self.goids, "NO VALID GO IDs WERE PROVIDED AS STARTING POINTS FOR HIERARCHY REPORT"
base = next(iter(self.goids)).replace(':', '')
upstr = '_up' if 'up' in self.kws else ''
return "hier_{BASE}{UP}.{EXT}".format(BASE=base, UP=upstr, EXT='txt') | Get the name of an output file based on the top GO term. |
def merge(l1, l2):
x1, y1, x2, y2 = l1
xx1, yy1, xx2, yy2 = l2
comb = ((x1, y1, xx1, yy1),
(x1, y1, xx2, yy2),
(x2, y2, xx1, yy1),
(x2, y2, xx2, yy2))
d = [length(c) for c in comb]
i = argmax(d)
dist = d[i]
mid = middle(comb[i])
a = (angle(l1) + angle(... | merge 2 lines together |
def output(self):
return luigi.LocalTarget(path=self.path(digest=True, ext='html')) | Use the digest version, since URL can be ugly. |
def host_domains(self, ip=None, limit=None, **kwargs):
return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs) | Pass in an IP address. |
def from_config(cls, pyvlx, item):
name = item['name']
ident = item['id']
subtype = item['subtype']
typeid = item['typeId']
return cls(pyvlx, ident, name, subtype, typeid) | Read roller shutter from config. |
def _initStormCmds(self):
self.addStormCmd(s_storm.MaxCmd)
self.addStormCmd(s_storm.MinCmd)
self.addStormCmd(s_storm.HelpCmd)
self.addStormCmd(s_storm.IdenCmd)
self.addStormCmd(s_storm.SpinCmd)
self.addStormCmd(s_storm.SudoCmd)
self.addStormCmd(s_storm.UniqCmd)
... | Registration for built-in Storm commands. |
def send(self, data):
_LOGGER.debug("send: " + data)
self.socket.send(data.encode('ascii'))
sleep(.01) | Send data to socket. |
def main():
from spyder.utils.qthelpers import qapplication
app = qapplication()
if os.name == 'nt':
dialog = WinUserEnvDialog()
else:
dialog = EnvDialog()
dialog.show()
app.exec_() | Run Windows environment variable editor |
def save_token(self, user, token):
self.config.set('auth', 'user', user)
self.config.set('auth', 'token', token)
new_config = ConfigParser(allow_no_value=True)
new_config.read(self.config_file)
self.check_sections(new_config)
new_config.set('auth', 'user', user)
n... | Save the token on the config file. |
def size_to_content(self):
new_sizing = self.copy_sizing()
new_sizing.minimum_height = 0
new_sizing.maximum_height = 0
axes = self.__axes
if axes and axes.is_valid:
if axes.x_calibration and axes.x_calibration.units:
new_sizing.minimum_height = self.fo... | Size the canvas item to the proper height. |
def require_editable(f):
def wrapper(self, *args, **kwargs):
if not self._edit:
raise RegistryKeyNotEditable("The key is not set as editable.")
return f(self, *args, **kwargs)
return wrapper | Makes sure the registry key is editable before trying to edit it. |
def symbol_search(self, search_terms):
self.log.debug('symbol_search: in')
if not search_terms:
self.editor.message('symbol_search_symbol_required')
return
req = {
"typehint": "PublicSymbolSearchReq",
"keywords": search_terms,
"maxResul... | Search for symbols matching a set of keywords |
def cluster_count_key_in_slots(self, slot):
if not isinstance(slot, int):
raise TypeError("Expected slot to be of type int, got {}"
.format(type(slot)))
return self.execute(b'CLUSTER', b'COUNTKEYSINSLOT', slot) | Return the number of local keys in the specified hash slot. |
def read_bytes(self, start_position: int, size: int) -> bytes:
return bytes(self._bytes[start_position:start_position + size]) | Read a value from memory and return a fresh bytes instance |
def convert_compound_entry(self, compound):
d = OrderedDict()
d['id'] = compound.id
order = {
key: i for i, key in enumerate(
['name', 'formula', 'formula_neutral', 'charge', 'kegg',
'cas'])}
prop_keys = (
set(compound.properties) ... | Convert compound entry to YAML dict. |
def _compute_mean(self, C, mag, rjb):
ffc = self._compute_finite_fault_correction(mag)
d = np.sqrt(rjb ** 2 + (C['c7'] ** 2) * (ffc ** 2))
mean = (
C['c1'] + C['c2'] * (mag - 6.) +
C['c3'] * ((mag - 6.) ** 2) -
C['c4'] * np.log(d) - C['c6'] * d
)
... | Compute ground motion mean value. |
def find_user_emails(self, user):
user_emails = self.db_adapter.find_objects(self.UserEmailClass, user_id=user.id)
return user_emails | Find all the UserEmail object belonging to a user. |
def translator(self):
if self._translator is None:
languages = self.lang
if not languages:
return gettext.NullTranslations()
if not isinstance(languages, list):
languages = [languages]
translator = gettext.NullTranslations()
... | Get a valid translator object from one or several languages names. |
def option_parser():
usage =
version = "2.0.0"
parser = optparse.OptionParser(usage=usage, version=version)
parser.add_option("-l", "--links", action="store_true",
default=False, dest="links", help="links for target url")
parser.add_option("-d", "--depth", action="store", type=... | Option Parser to give various options. |
def compare(self, range_comparison, range_objs):
range_values = [obj.value for obj in range_objs]
comparison_func = get_comparison_func(range_comparison)
return comparison_func(self.value, *range_values) | Compares this type against comparison filters |
def interp(self):
if self.ndim == 0:
return 'nearest'
elif all(interp == self.interp_byaxis[0]
for interp in self.interp_byaxis):
return self.interp_byaxis[0]
else:
return self.interp_byaxis | Interpolation type of this discretization. |
def template_string(context, template):
'Return the rendered template content with the current context'
if not isinstance(context, Context):
context = Context(context)
return Template(template).render(context) | Return the rendered template content with the current context |
def _validate_dataset_names(dataset):
def check_name(name):
if isinstance(name, str):
if not name:
raise ValueError('Invalid name for DataArray or Dataset key: '
'string must be length 1 or greater for '
'serializa... | DataArray.name and Dataset keys must be a string or None |
def list_subnets(self, retrieve_all=True, **_params):
return self.list('subnets', self.subnets_path, retrieve_all,
**_params) | Fetches a list of all subnets for a project. |
def VSTools(self):
paths = [r'Common7\IDE', r'Common7\Tools']
if self.vc_ver >= 14.0:
arch_subdir = self.pi.current_dir(hidex86=True, x64=True)
paths += [r'Common7\IDE\CommonExtensions\Microsoft\TestWindow']
paths += [r'Team Tools\Performance Tools']
paths... | Microsoft Visual Studio Tools |
def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads):
if isinstance(pads, str):
pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = 'Wrong number of explicit pads for conv: expected {}, got {}.'
raise TypeError(msg.format(le... | Compute the shape of a conv given input shapes in canonical order. |
def paste_buffer(pymux, variables):
pane = pymux.arrangement.get_active_pane()
pane.process.write_input(get_app().clipboard.get_data().text, paste=True) | Paste clipboard content into buffer. |
def collapse_all(self):
if implementsCollapseAPI(self._tree):
self._tree.collapse_all()
self.set_focus(self._tree.root)
self._walker.clear_cache()
self.refresh() | Collapse all positions; works only if the underlying tree allows it. |
def copy(self, parent=None):
new = Structure(None, parent=parent)
new.key = self.key
new.type_ = self.type_
new.val_guaranteed = self.val_guaranteed
new.key_guaranteed = self.key_guaranteed
for child in self.children:
new.children.append(child.copy(new))
... | Copies an existing structure and all of it's children |
def delete_records(keep=20):
sql = "SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}".format(keep)
assert isinstance(g.db, sqlite3.Connection)
c = g.db.cursor()
c.execute(sql)
rows = c.fetchall()
for row in rows:
name = row[1]
xmind = join(app.config[... | Clean up files on server and mark the record as deleted |
def last_datetime(self):
from datetime import datetime
try:
return datetime.fromtimestamp(self.state.lasttime)
except TypeError:
return None | Return the time of the last operation on the bundle as a datetime object |
def _get_gatk_opts(config, names, tmp_dir=None, memscale=None, include_gatk=True, parallel_gc=False):
if include_gatk and "gatk4" in dd.get_tools_off({"config": config}):
opts = ["-U", "LENIENT_VCF_PROCESSING", "--read_filter",
"BadCigar", "--read_filter", "NotPrimaryAlignment"]
else:
... | Retrieve GATK memory specifications, moving down a list of potential specifications. |
def delete(self, *args, **kwargs):
hosted_zone = route53_backend.get_hosted_zone_by_name(
self.hosted_zone_name)
if not hosted_zone:
hosted_zone = route53_backend.get_hosted_zone(self.hosted_zone_id)
hosted_zone.delete_rrset_by_name(self.name) | Not exposed as part of the Route 53 API - used for CloudFormation. args are ignored |
def remove_arg(self, arg):
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()]
for arg_ in list(self.args):
if arg_.lower() == arg.lower():
self.args.remove(arg_) | Remove an arg to the arg list |
def go_to_py_cookie(go_cookie):
expires = None
if go_cookie.get('Expires') is not None:
t = pyrfc3339.parse(go_cookie['Expires'])
expires = t.timestamp()
return cookiejar.Cookie(
version=0,
name=go_cookie['Name'],
value=go_cookie['Value'],
port=None,
p... | Convert a Go-style JSON-unmarshaled cookie into a Python cookie |
def export_envars(self, env):
for k, v in env.items():
self.export_envar(k, v) | Export the environment variables contained in the dict env. |
def build_idx_set(branch_id, start_date):
code_set = branch_id.split("/")
code_set.insert(3, "Rates")
idx_set = {
"sec": "/".join([code_set[0], code_set[1], "Sections"]),
"mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])}
idx_set["rate"] = "/".join(code_set)
idx_s... | Builds a dictionary of keys based on the branch code |
def use_plenary_bank_view(self):
self._bank_view = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_bank_view()
except AttributeError:
pass | Pass through to provider ItemBankSession.use_plenary_bank_view |
def reset(self):
old_value = self._value
old_raw_str_value = self.raw_str_value
self._value = not_set
self.raw_str_value = not_set
new_value = self._value
if old_value is not_set:
return
if self.section:
self.section.dispatch_event(
... | Resets the value of config item to its default value. |
def _float_feature(value):
if not isinstance(value, list):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value)) | Wrapper for inserting float features into Example proto. |
def neural_gpu_body(inputs, hparams, name=None):
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp):
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers.conv_gru(
x, (hparams.kernel_height, hparams.kernel_wi... | The core Neural GPU. |
def register_animation(self, animation_class):
self.state.animationClasses.append(animation_class)
return len(self.state.animationClasses) - 1 | Add a new animation |
def nodePush(ctxt, value):
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if value is None: value__o = None
else: value__o = value._o
ret = libxml2mod.nodePush(ctxt__o, value__o)
return ret | Pushes a new element node on top of the node stack |
def copy_file(aws_access_key_id, aws_secret_access_key, bucket_name, file, s3_folder):
bucket = s3_bucket(aws_access_key_id, aws_secret_access_key, bucket_name)
key = boto.s3.key.Key(bucket)
if s3_folder:
target_name = '%s/%s' % (s3_folder, os.path.basename(file))
else:
target_name = os.... | copies file to bucket s3_folder |
def isRunActive(g):
if g.cpars['hcam_server_on']:
url = g.cpars['hipercam_server'] + 'summary'
response = urllib.request.urlopen(url, timeout=2)
rs = ReadServer(response.read(), status_msg=True)
if not rs.ok:
raise DriverError('isRunActive error: ' + str(rs.err))
... | Polls the data server to see if a run is active |
def str_to_bitstring(data):
assert isinstance(data, bytes), "Data must be an instance of bytes"
byte_list = data_to_byte_list(data)
bit_list = [bit for data_byte in byte_list for bit in byte_to_bitstring(data_byte)]
return bit_list | Convert a string to a list of bits |
def _get_location_list(interval_bed):
import pybedtools
regions = collections.OrderedDict()
for region in pybedtools.BedTool(interval_bed):
regions[str(region.chrom)] = None
return regions.keys() | Retrieve list of locations to analyze from input BED file. |
def deploy_lambda(collector):
amazon = collector.configuration['amazon']
aws_syncr = collector.configuration['aws_syncr']
find_lambda_function(aws_syncr, collector.configuration).deploy(aws_syncr, amazon) | Deploy a lambda function |
def do_DELETE(self):
self.do_initial_operations()
coap_response = self.client.delete(self.coap_uri.path)
self.client.stop()
logger.debug("Server response: %s", coap_response.pretty_print())
self.set_http_response(coap_response) | Perform a DELETE request |
def remove_group_role(request, role, group, domain=None, project=None):
manager = keystoneclient(request, admin=True).roles
return manager.revoke(role=role, group=group, project=project,
domain=domain) | Removes a given single role for a group from a domain or project. |
def options(self, parser, env=os.environ):
super(PerfDumpPlugin, self).options(parser, env=env)
parser.add_option("", "--perfdump-html", dest="perfdump_html_file",
help="Set destination for HTML report output") | Handle parsing additional command-line options |
def do_it(self, dbg):
try:
var_objects = []
for variable in self.vars:
variable = variable.strip()
if len(variable) > 0:
if '\t' in variable:
scope, attrs = variable.split('\t', 1)
name = ... | Starts a thread that will load values asynchronously |
def _create_subplots(self, fig, layout):
num_panels = len(layout)
axsarr = np.empty((self.nrow, self.ncol), dtype=object)
i = 1
for row in range(self.nrow):
for col in range(self.ncol):
axsarr[row, col] = fig.add_subplot(self.nrow, self.ncol, i)
... | Create suplots and return axs |
def _is_download(ending):
list = [
'PDF',
'DOC',
'TXT',
'PPT',
'XLSX',
'MP3',
'SVG',
'7Z',
'HTML',
'TEX',
'MPP',
'ODT',
'RAR',
'ZIP',
'T... | Check if file ending is considered as download. |
def deserialize_email_messages(messages: List[str]):
return [
pickle.loads(zlib.decompress(base64.b64decode(m)))
for m in messages
] | Deserialize EmailMessages passed as task argument. |
def _get_variable(vid, variables):
if isinstance(vid, six.string_types):
vid = get_base_id(vid)
else:
vid = _get_string_vid(vid)
for v in variables:
if vid == get_base_id(v["id"]):
return copy.deepcopy(v)
raise ValueError("Did not find variable %s in \n%s" % (vid, ppr... | Retrieve an input variable from our existing pool of options. |
def _split_classes_by_kind(self, class_name_to_definition):
for class_name in class_name_to_definition:
inheritance_set = self._inheritance_sets[class_name]
is_vertex = ORIENTDB_BASE_VERTEX_CLASS_NAME in inheritance_set
is_edge = ORIENTDB_BASE_EDGE_CLASS_NAME in inheritance_s... | Assign each class to the vertex, edge or non-graph type sets based on its kind. |
def stats(path, fmt, nocolor, timezones, utc, noprogress, most_common, resolve, length):
with colorize_output(nocolor):
try:
chat_history = _process_history(
path=path, thread='', timezones=timezones,
utc=utc, noprogress=noprogress, resolve=resolve)
except... | Analysis of Facebook chat history. |
def _Ep(self):
return np.logspace(
np.log10(self.Epmin.to("GeV").value),
np.log10(self.Epmax.to("GeV").value),
int(self.nEpd * (np.log10(self.Epmax / self.Epmin))),
) | Proton energy array in GeV |
def _get_arrays(self, wavelengths, **kwargs):
x = self._validate_wavelengths(wavelengths)
y = self(x, **kwargs)
if isinstance(wavelengths, u.Quantity):
w = x.to(wavelengths.unit, u.spectral())
else:
w = x
return w, y | Get sampled spectrum or bandpass in user units. |
def section_end_distances(neurites, neurite_type=NeuriteType.all):
return map_sections(sectionfunc.section_end_distance, neurites, neurite_type=neurite_type) | section end to end distances in a collection of neurites |
def upload_napp(self, metadata, package):
endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')
metadata['token'] = self._config.get('auth', 'token')
request = self.make_request(endpoint, json=metadata, package=package,
method="POST")
... | Upload the napp from the current directory to the napps server. |
def intuition_module(location):
path = location.split('.')
obj = path.pop(-1)
return dna.utils.dynamic_import('.'.join(path), obj) | Build the module path and import it |
def Validate(self):
self.pathspec.Validate()
if (self.HasField("start_time") and self.HasField("end_time") and
self.start_time > self.end_time):
raise ValueError("Start time must be before end time.")
if not self.path_regex and not self.data_regex and not self.path_glob:
raise ValueError... | Ensure the pathspec is valid. |
def validate_maildirs(ctx, param, value):
for path in value:
for subdir in MD_SUBDIRS:
if not os.path.isdir(os.path.join(path, subdir)):
raise click.BadParameter(
'{} is not a maildir (missing {!r} sub-directory).'.format(
path, subdir)... | Check that folders are maildirs. |
def zoomTo(self, bbox):
'set visible area to bbox, maintaining aspectRatio if applicable'
self.fixPoint(self.plotviewBox.xymin, bbox.xymin)
self.zoomlevel=max(bbox.w/self.canvasBox.w, bbox.h/self.canvasBox.h) | set visible area to bbox, maintaining aspectRatio if applicable |
def _build_fluent_table(self):
self.fluent_table = collections.OrderedDict()
for name, size in zip(self.domain.non_fluent_ordering, self.non_fluent_size):
non_fluent = self.domain.non_fluents[name]
self.fluent_table[name] = (non_fluent, size)
for name, size in zip(self.do... | Builds the fluent table for each RDDL pvariable. |
def build_estimator(model_dir, model_type, model_column_fn, inter_op, intra_op, ctx):
wide_columns, deep_columns = model_column_fn()
hidden_units = [100, 75, 50, 25]
run_config = tf.estimator.RunConfig().replace(
session_config=tf.ConfigProto(device_count={'GPU': 0},
devi... | Build an estimator appropriate for the given model type. |
def parse_file(self, sourcepath):
with open(sourcepath, 'r') as logfile:
jsonstr = logfile.read()
data = {}
data['entries'] = json.loads(jsonstr)
if self.tzone:
for e in data['entries']:
e['tzone'] = self.tzone
return data | Parse single JSON object into a LogData object |
def load_file(path, encoding, encoding_errors):
abs_path = abspath(path)
if exists(abs_path):
return read_unicode(abs_path, encoding, encoding_errors)
raise IOError('File %s does not exist' % (abs_path)) | Given an existing path, attempt to load it as a unicode string. |
def fetch_fieldnames(self, sql: str, *args) -> List[str]:
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description]
except:
log.exception("fetch_fieldnames: SQL was: " + sql)... | Executes SQL; returns just the output fieldnames. |
def _set_id_variable_by_entity_key(self) -> Dict[str, str]:
if self.id_variable_by_entity_key is None:
self.id_variable_by_entity_key = dict(
(entity.key, entity.key + '_id') for entity in self.tax_benefit_system.entities)
log.debug("Use default id_variable names:\n {}".... | Identify and set the good ids for the different entities |
def process_result_value(
self,
value,
dialect
):
if self.__use_json(dialect) or value is None:
return value
return self.__json_codec.loads(value) | Decode data, if required. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.