code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def _no_spelling_errors(relative_path, contents, linter_options):
block_regexps = linter_options.get("block_regexps", None)
chunks, shadow = spellcheckable_and_shadow_contents(contents,
block_regexps)
cache = linter_options.get("spellcheck_cache", None... | No spelling errors in strings, comments or anything of the like. |
def clear(self, *resource_types):
resource_types = resource_types or tuple(self.__caches.keys())
for cls in resource_types:
self.__caches[cls].clear()
del self.__caches[cls] | Clear cache for each provided APIResource class, or all resources if no classes are provided |
def _load_from_geo_ref(self, dsid):
file_handlers = self._get_file_handlers(dsid)
if not file_handlers:
return None
fns = []
for fh in file_handlers:
base_dir = os.path.dirname(fh.filename)
try:
fn = fh['/attr/N_GEO_Ref'][:46] + '*.h5'
... | Load filenames from the N_GEO_Ref attribute of a dataset's file. |
def input(self, request, tag):
subform = self.parameter.form.asSubForm(self.parameter.name)
subform.setFragmentParent(self)
return tag[subform] | Add the wrapped form, as a subform, as a child of the given tag. |
def surface2image(surface):
global g_lock
with g_lock:
img_io = io.BytesIO()
surface.write_to_png(img_io)
img_io.seek(0)
img = PIL.Image.open(img_io)
img.load()
if "A" not in img.getbands():
return img
img_no_alpha = PIL.Image.new("RGB", img.si... | Convert a cairo surface into a PIL image |
def print_runs(query):
if query is None:
return
for tup in query:
print(("{0} @ {1} - {2} id: {3} group: {4}".format(
tup.end, tup.experiment_name, tup.project_name,
tup.experiment_group, tup.run_group))) | Print all rows in this result query. |
def ports(self) -> dict:
return {
param: self[param].raw
for param in self
if param.startswith(IOPORT)
} | Create a smaller dictionary containing all ports. |
def component_div(vec1, vec2):
new_vec = Vector2()
new_vec.X = vec1.X / vec2.X
new_vec.Y = vec1.Y / vec2.Y
return new_vec | Divide the components of the vectors and return the result. |
def _update_feature_log_prob(self, alpha):
smoothed_fc = self.feature_count_ + alpha
smoothed_cc = self.class_count_ + alpha * 2
self.feature_log_prob_ = (np.log(smoothed_fc) -
np.log(smoothed_cc.reshape(-1, 1))) | Apply smoothing to raw counts and recompute log probabilities |
def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None):
if not any([subnet_name, tags, cidr]):
raise SaltInvocationError('At least one of the following must be '
'specified: subnet_name, cidr or tags.')
filter_parameters = {'filters': {}}
... | Given subnet properties, find and return matching subnet ids |
def globalsfilter(input_dict, check_all=False, filters=None,
exclude_private=None, exclude_capitalized=None,
exclude_uppercase=None, exclude_unsupported=None,
excluded_names=None):
output_dict = {}
for key, value in list(input_dict.items()):
excluded... | Keep only objects that can be pickled |
def read_values(target_usage):
all_devices = hid.HidDeviceFilter().get_devices()
if not all_devices:
print("Can't find any non system HID device connected")
else:
usage_found = False
for device in all_devices:
try:
device.open()
fo... | read feature report values |
def add_hbar_widget(self, ref, x=1, y=1, length=10):
if ref not in self.widgets:
widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length)
self.widgets[ref] = widget
return self.widgets[ref] | Add Horizontal Bar Widget |
def logged_delete(self, user):
self.delete()
entry = ChangeLogEntry({
'type': 'DELETED',
'documents': [self],
'user': user
})
entry.insert()
return entry | Delete the document and log the event in the change log |
def pad_block(block, block_size):
unique_vals, unique_counts = np.unique(block, return_counts=True)
most_frequent_value = unique_vals[np.argmax(unique_counts)]
return np.pad(block,
tuple((0, desired_size - actual_size)
for desired_size, actual_size
... | Pad a block to block_size with its most frequent value |
def omerc2cf(area):
proj_dict = area.proj_dict
args = dict(azimuth_of_central_line=proj_dict.get('alpha'),
latitude_of_projection_origin=proj_dict.get('lat_0'),
longitude_of_projection_origin=proj_dict.get('lonc'),
grid_mapping_name='oblique_mercator',
... | Return the cf grid mapping for the omerc projection. |
def update_project_template(push):
import ballet.update
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.update.update_project_template(push=push) | Update an existing ballet project from the upstream template |
def write_to(output, txt):
if (isinstance(txt, six.binary_type) or six.PY3 and isinstance(output, StringIO)) or isinstance(output, TextIOWrapper):
output.write(txt)
else:
output.write(txt.encode("utf-8", "replace")) | Write some text to some output |
def _get_variant_regions(items):
return list(filter(lambda x: x is not None,
[tz.get_in(("config", "algorithm", "variant_regions"), data)
for data in items
if tz.get_in(["config", "algorithm", "coverage_interval"], data) != "genome"])) | Retrieve variant regions defined in any of the input items. |
def _eq(field, value, document):
try:
return document.get(field, None) == value
except TypeError:
return False | Returns True if the value of a document field is equal to a given value |
def list_security_groups(self, retrieve_all=True, **_params):
return self.list('security_groups', self.security_groups_path,
retrieve_all, **_params) | Fetches a list of all security groups for a project. |
def fetch(bank, key, cachedir):
inkey = False
key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key))
if not os.path.isfile(key_file):
key_file = os.path.join(cachedir, os.path.normpath(bank) + '.p')
inkey = True
if not os.path.isfile(key_file):
log.debug('... | Fetch information from a file. |
def bind(self, container):
def clone(prototype):
if prototype.is_bound():
raise RuntimeError('Cannot `bind` a bound extension.')
cls = type(prototype)
args, kwargs = prototype.__params
instance = cls(*args, **kwargs)
instance.container ... | Get an instance of this Extension to bind to `container`. |
def _create_default_tiles(self):
for value, background, text in self.DEFAULT_TILES:
self.tiles[value] = self._make_tile(value, background, text) | Create all default tiles, as defined above. |
def tech_requirement(self) -> Optional[UnitTypeId]:
if self._proto.tech_requirement == 0:
return None
if self._proto.tech_requirement not in self._game_data.units:
return None
return UnitTypeId(self._proto.tech_requirement) | Tech-building requirement of buildings - may work for units but unreliably |
def _init_idxs_float(self, usr_hdrs):
self.idxs_float = [
Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in self.float_hdrs] | List of indexes whose values will be floats. |
def _jws_header(keyid, algorithm):
data = {
'typ': 'JWT',
'alg': algorithm.name,
'kid': keyid
}
datajson = json.dumps(data, sort_keys=True).encode('utf8')
return base64url_encode(datajson) | Produce a base64-encoded JWS header. |
def bdd(*keywords):
settings = _personal_settings().data
_storybook().with_params(
**{"python version": settings["params"]["python version"]}
).only_uninherited().shortcut(*keywords).play() | Run tests matching keywords. |
def proxy_it(request, port):
websocket_proxy = request.registry.settings.get("pyramid_notebook.websocket_proxy", "")
if websocket_proxy.strip():
r = DottedNameResolver()
websocket_proxy = r.maybe_resolve(websocket_proxy)
if "upgrade" in request.headers.get("connection", "").lower():
... | Proxy HTTP request to upstream IPython Notebook Tornado server. |
def startLoop():
def _ipython_loop_asyncio(kernel):
loop = asyncio.get_event_loop()
def kernel_handler():
kernel.do_one_iteration()
loop.call_later(kernel._poll_interval, kernel_handler)
loop.call_soon(kernel_handler)
try:
if not loop.is_running():... | Use nested asyncio event loop for Jupyter notebooks. |
def remove_object(self, key):
state = self.state
for layer in state.layers:
state.layers[layer].pop(key, None)
state.need_redraw = True | remove an object by key from all layers |
def text(self, string, x, y, color, *,
font_name="font5x8.bin"):
if not self._font or self._font.font_name != font_name:
self._font = BitmapFont()
w = self._font.font_width
for i, char in enumerate(string):
self._font.draw_char(char,
... | text is not yet implemented |
def center(self):
bounds = self.bounds
x = (bounds[1] + bounds[0])/2
y = (bounds[3] + bounds[2])/2
z = (bounds[5] + bounds[4])/2
return [x, y, z] | Center of the bounding box around all data present in the scene |
def update(self, automation):
self._automation.update(
{k: automation[k] for k in automation if self._automation.get(k)}) | Update the internal automation json. |
def best(self):
return pd.Series(
{
"name": self.best_dist.name,
"params": self.best_param,
"sse": self.best_sse,
}
) | The resulting best-fit distribution, its parameters, and SSE. |
def _get_at_from_session(self):
try:
return self.request.session['oauth_%s_access_token'
% get_token_prefix(
self.request_token_url)]
except KeyError:
raise OAuthError(
_('No acces... | Get the saved access token for private resources from the session. |
async def destroy(self, container = None):
if container is None:
container = RoutineContainer(self.scheduler)
if self.queue is not None:
await container.syscall_noreturn(syscall_removequeue(self.scheduler.queue, self.queue))
self.queue = None | Destroy the created subqueue to change the behavior back to Lock |
def timedelta_seconds(timedelta):
return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds")
else timedelta.days * 24 * 3600 + timedelta.seconds +
timedelta.microseconds / 1000000.) | Returns the total timedelta duration in seconds. |
def scorable_block_completion(sender, **kwargs):
if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING):
return
course_key = CourseKey.from_string(kwargs['course_id'])
block_key = UsageKey.from_string(kwargs['usage_id'])
block_cls = XBlock.load_class(block_key.block_type)
if XB... | When a problem is scored, submit a new BlockCompletion for that block. |
def create_logger(self):
name = "bors"
if hasattr(self, "name"):
name = self.name
self.log = logging.getLogger(name)
try:
lvl = self.conf.get_log_level()
except AttributeError:
lvl = self.context.get("log_level", None)
self.log.setLevel... | Generates a logger instance from the singleton |
def events_list(self):
evt = []
evt.extend(events.NEPALI_EVENTS[self.month, self.day])
evt.extend(events.ENGLISH_EVENTS[self.en_date.month, self.en_date.day])
return evt | Returns the events today |
def handle_m2m_user(self, sender, instance, **kwargs):
self.handle_save(instance.user.__class__, instance.user) | Handle many to many relationships for user field |
def quit(self):
response = self.run() == Gtk.ResponseType.YES
self.destroy()
return response | Run the "are you sure" dialog for quitting Guake |
def pass_verbosity(f):
def new_func(*args, **kwargs):
kwargs['verbosity'] = click.get_current_context().verbosity
return f(*args, **kwargs)
return update_wrapper(new_func, f) | Marks a callback as wanting to receive the verbosity as a keyword argument. |
def _populateComboBoxes(self, row):
logger.debug("_populateComboBoxes")
for comboBox in self._comboBoxes:
comboBox.clear()
if not self.rtiIsSliceable:
for comboBoxNr, comboBox in enumerate(self._comboBoxes):
comboBox.addItem('', userData=None)
... | Populates the combo boxes with values of the repo tree item |
def _get_localized_field_checks(self):
localized_fields_checks = []
for localized_field in self.instance.localized_fields:
if self.cleaned_data.get(localized_field) is None:
continue
f = getattr(self.instance.__class__, localized_field, None)
if f and ... | Get the checks we must perform for the localized fields. |
def problem_serializing(value, e=None):
from mo_logs import Log
try:
typename = type(value).__name__
except Exception:
typename = "<error getting name>"
try:
rep = text_type(repr(value))
except Exception as _:
rep = None
if rep == None:
Log.error(
... | THROW ERROR ABOUT SERIALIZING |
def _deserialize(cls, key, value, fields):
converter = cls._get_converter_for_field(key, None, fields)
return converter.deserialize(value) | Marshal incoming data into Python objects. |
def _transform_i(self, x, i):
x = self._shift_or_mirror_into_invertible_i(x, i)
lb = self._lb[self._index(i)]
ub = self._ub[self._index(i)]
al = self._al[self._index(i)]
au = self._au[self._index(i)]
if x < lb + al:
return lb + (x - (lb - al))**2 / 4 / al
... | return transform of x in component i |
def atlas_peer_set_zonefile_inventory( peer_hostport, peer_inv, peer_table=None ):
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return None
ptbl[peer_hostport]['zonefile_inv'] = peer_inv
return peer_inv | Set this peer's zonefile inventory |
def reportTime(t, options, field=None):
if options.pretty:
return prettyTime(t, field=field)
else:
if field is not None:
return "%*.2f" % (field, t)
else:
return "%.2f" % t | Given t seconds, report back the correct format as string. |
def nodes_aws(c_obj):
aws_nodes = []
try:
aws_nodes = c_obj.list_nodes()
except BaseHTTPError as e:
abort_err("\r HTTP Error with AWS: {}".format(e))
aws_nodes = adj_nodes_aws(aws_nodes)
return aws_nodes | Get node objects from AWS. |
def select_observations(self, name):
return [n for n in self.get_obs_nodes() if n.obsname==name] | Returns nodes whose instrument-band matches 'name' |
def unhandled(self, key):
self.key = key
self.size = self.tui.get_cols_rows()
if self.search is True:
if self.enter is False and self.no_matches is False:
if len(key) == 1 and key.isprintable():
self.search_string += key
self._searc... | Handle other keyboard actions not handled by the ListBox widget. |
def exponential_backoff(fn, sleeptime_s_max=30 * 60):
sleeptime_ms = 500
while True:
if fn():
return True
else:
print('Sleeping {} ms'.format(sleeptime_ms))
time.sleep(sleeptime_ms / 1000.0)
sleeptime_ms *= 2
if sleeptime_ms / 1000.0 > slee... | Calls `fn` until it returns True, with an exponentially increasing wait time between calls |
def create_turtle(self, id, shape, model_init, color_init):
assert id not in self.id_to_shape
data = self._create_turtle(id, shape, model_init, color_init)
self.id_to_shape[id] = shape
return data | Create a slice of memory for turtle data storage |
def _filter_disabled_regions(contents):
contents = list(contents)
in_backticks = False
contents_len = len(contents)
index = 0
while index < contents_len:
character = contents[index]
if character == "`":
if ((index + 2) < contents_len and
"".join(conten... | Filter regions that are contained in back-ticks. |
def collect(self):
if redis is None:
self.log.error('Unable to import module redis')
return {}
for nick in self.instances.keys():
(host, port, unix_socket, auth) = self.instances[nick]
self.collect_instance(nick, host, int(port), unix_socket, auth) | Collect the stats from the redis instance and publish them. |
def numericise_all(input, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False):
return [numericise(s, empty2zero, default_blank, allow_underscores_in_numeric_literals) for s in input] | Returns a list of numericised values from strings |
def make_patch(self):
path = [self.arcs[0].start_point()]
for a in self.arcs:
if a.direction:
vertices = Path.arc(a.from_angle, a.to_angle).vertices
else:
vertices = Path.arc(a.to_angle, a.from_angle).vertices
vertices = vertices[np... | Retuns a matplotlib PathPatch representing the current region. |
def parse_stations(html):
html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '')
html = json.loads(html)
return html['suggestions'] | Strips JS code, loads JSON |
def setPriority(self, queue, priority):
q = self.queueindex[queue]
self.queues[q[0]].removeSubQueue(q[1])
newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(self, priority))
q[0] = priority
newPriority.addSubQueue(q[1]) | Set priority of a sub-queue |
def _render(item: ConfigItem, indent: str = "") -> str:
optional = item.default_value != _NO_DEFAULT
if is_configurable(item.annotation):
rendered_annotation = f"{item.annotation} (configurable)"
else:
rendered_annotation = str(item.annotation)
rendered_item = "".join([
inden... | Render a single config item, with the provided indent |
def sorted_filetype_items(self):
processed_types = []
file_type_items = deque(self.config['file_types'].items())
while len(file_type_items):
filetype, filetype_info = file_type_items.popleft()
requirements = filetype_info.get('requires')
if requirements is not... | Sort the instance's filetypes in using order. |
def init(cls, *args, **kwargs):
instance = cls()
instance._values.update(dict(*args, **kwargs))
return instance | Initialize the config like as you would a regular dict. |
def copy(self):
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | Creates a copy of the TT-matrix |
def calculate_grid(self):
if self.grid is None:
self.grid = self.get_wellseries(self.get_grid())
if self.grid_transposed is None:
self.grid_transposed = self.get_wellseries(
self.transpose(
self.get_grid())) | Calculates and stores grid structure |
def compute(self, write_to_tar=True):
data = self._get_all_data(self.start_date, self.end_date)
logging.info('Computing timeseries for {0} -- '
'{1}.'.format(self.start_date, self.end_date))
full, full_dt = self._compute_full_ts(data)
full_out = self._full_to_yearly_... | Perform all desired calculations on the data and save externally. |
def unsubscribe(self, topic):
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.logger.info("UNSUBSCRIBE: %s", topic)
return self.send_unsubscribe(False, [utf8encode(topic)]) | Unsubscribe to some topic. |
def run_after_async(seconds, func, *args, **kwargs):
t = Timer(seconds, func, args, kwargs)
t.daemon = True
t.start()
return t | Run the function after seconds asynchronously. |
async def log_source(self, **params):
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return {"error":400, "reason":"Missed required fields"}
database = client[settings.DBNAME]
source_collection = database[settings.SOURCE]
await source_collection.update({"public... | Logging users request sources |
def primal_name(func, wrt):
if not isinstance(func, types.FunctionType):
raise TypeError(func)
varnames = six.get_function_code(func).co_varnames
return PRIMAL_NAME.format(func.__name__, ''.join(varnames[i] for i in wrt)) | Name for the primal of a function. |
def _clean_args(sys_argv, args):
base = [x for x in sys_argv if
x.startswith("-") or not args.datadir == os.path.abspath(os.path.expanduser(x))]
base = [x for x in base if x not in set(["--minimize-disk"])]
if "--nodata" in base:
base.remove("--nodata")
else:
base.append("--d... | Remove data directory from arguments to pass to upgrade function. |
def rmrf(items, verbose=True):
"Silently remove a list of directories or files"
if isinstance(items, str):
items = [items]
for item in items:
if verbose:
print("Removing {}".format(item))
shutil.rmtree(item, ignore_errors=True)
try:
os.remove(item)
... | Silently remove a list of directories or files |
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 ls(obj=None):
if obj is None:
import builtins
all = builtins.__dict__.copy()
all.update(globals())
objlst = sorted(conf.layers, key=lambda x:x.__name__)
for o in objlst:
print("%-10s : %s" %(o.__name__,o.name))
else:
if isinstance(obj, type) and is... | List available layers, or infos on a given layer |
def generate_sample_json():
check = EpubCheck(samples.EPUB3_VALID)
with open(samples.RESULT_VALID, 'wb') as jsonfile:
jsonfile.write(check._stdout)
check = EpubCheck(samples.EPUB3_INVALID)
with open(samples.RESULT_INVALID, 'wb') as jsonfile:
jsonfile.write(check._stdout) | Generate sample json data for testing |
def plot_cable_length(stats, plotpath):
f, axarr = plt.subplots(2, 2, sharex=True)
stats.hist(column=['Length of MV overhead lines'], bins=5, alpha=0.5, ax=axarr[0, 0])
stats.hist(column=['Length of MV underground cables'], bins=5, alpha=0.5, ax=axarr[0, 1])
stats.hist(column=['Length of LV overhead lin... | Cable length per MV grid district |
def _structure_union(self, obj, union):
union_params = union.__args__
if NoneType in union_params:
if obj is None:
return None
if len(union_params) == 2:
other = (
union_params[0]
if union_params[1] is NoneTy... | Deal with converting a union. |
def collect_ansible_classes():
def trace_calls(frame, event, arg):
if event != 'call':
return
try:
_locals = inspect.getargvalues(frame).locals
if 'self' not in _locals:
return
_class = _locals['self'].__class__
_class_repr ... | Run playbook and collect classes of ansible that are run. |
def _or_query(self, term_list, field, field_type):
term_list = [self._term_query(term, field, field_type) for term in term_list]
return xapian.Query(xapian.Query.OP_OR, term_list) | Joins each item of term_list decorated by _term_query with an OR. |
def _merge_lib_dict(d1, d2):
for required, requirings in d2.items():
if required in d1:
d1[required].update(requirings)
else:
d1[required] = requirings
return None | Merges lib_dict `d2` into lib_dict `d1` |
def provides_defaults_for(self, rule: 'Rule', **values: Any) -> bool:
defaults_match = all(
values[key] == self.defaults[key] for key in self.defaults if key in values
)
return self != rule and bool(self.defaults) and defaults_match | Returns true if this rule provides defaults for the argument and values. |
def home(self):
self.command(c.LCD_RETURNHOME)
self._cursor_pos = (0, 0)
c.msleep(2) | Set cursor to initial position and reset any shifting. |
def on_episode_end(self, episode, logs={}):
for callback in self.callbacks:
if callable(getattr(callback, 'on_episode_end', None)):
callback.on_episode_end(episode, logs=logs)
else:
callback.on_epoch_end(episode, logs=logs) | Called at end of each episode for each callback in callbackList |
def _load(self, keyframe=True):
if self._cached:
return
pages = self.pages
if not pages:
return
if not self._indexed:
self._seek(-1)
if not self._cache:
return
fh = self.parent.filehandle
if keyframe is not None:
... | Read all remaining pages from file. |
def query_jobs_schedule(repo_name, revision, auth):
url = "%s/%s/rev/%s?format=json" % (SELF_SERVE, repo_name, revision)
LOG.debug("About to fetch %s" % url)
req = requests.get(url, auth=auth, timeout=TCP_TIMEOUT)
if req.status_code not in [200]:
return []
return req.json() | Query Buildapi for jobs. |
def toggle_highlighting(self, state):
if self.editor is not None:
if state:
self.highlight_matches()
else:
self.clear_matches() | Toggle the 'highlight all results' feature |
def setup(cfg):
this_module = sys.modules[__name__]
for name, value in cfg.items():
if hasattr(this_module, name):
setattr(this_module, name, value) | set up the global configuration from an object |
def edit(self):
if platform.system().lower() == 'windows':
os.startfile(str(self.config_file))
else:
if platform.system().lower() == 'darwin':
call = 'open'
else:
call = 'xdg-open'
subprocess.call([call, self.config_... | Edit file with default os application. |
def save_model(model, output_file):
if not output_file:
return
with open(output_file, 'wb') as f:
pickle.dump(model, f)
print("Saved model to file '{}'.".format(output_file)) | Save model to output_file, if given |
def fit_transform(self, input, **fit_kwargs):
self.fit(input, **fit_kwargs)
X = self.transform(input)
return X | Execute fit and transform in sequence. |
def _dhash(self, params):
m = hashlib.new('md5')
m.update(self.hash.encode('utf-8'))
for key in sorted(params.keys()):
h_string = ('%s-%s' % (key, params[key])).encode('utf-8')
m.update(h_string)
return m.hexdigest() | Generate hash of the dictionary object. |
def _get_files_modified():
cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"
_, files_modified, _ = run(cmd)
extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + [".rst"]]
test = "(?:{0})$".format("|".join(extensions))
return list(filter(lambda f: re.search(test, f),... | Get the list of modified files that are Python or Jinja2. |
def delete_collection(db_name, collection_name, host='localhost', port=27017):
client = MongoClient("mongodb://%s:%d" % (host, port))
client[db_name].drop_collection(collection_name) | Almost exclusively for testing. |
def field_function(self, type_code, func_name):
assert func_name in ('to_json', 'from_json')
name = "field_%s_%s" % (type_code.lower(), func_name)
return getattr(self, name) | Return the field function. |
def debug_complete():
if not 'uniqueId' in request.args:
raise ExperimentError('improper_inputs')
else:
unique_id = request.args['uniqueId']
mode = request.args['mode']
try:
user = Participant.query.\
filter(Participant.uniqueid == unique_id).one()
... | Debugging route for complete. |
def process_temperature_sensors(helper, session):
snmp_result_temp_sensor_names = helper.walk_snmp_values(
session, helper,
DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors")
snmp_result_temp_sensor_states = helper.walk_snmp_values(
sess... | process the temperature sensors |
def _set_overlay_verify(name, overlay_path, config_path):
global DEBUG
if os.path.exists(config_path):
print("Config path already exists! Not moving forward")
print("config_path: {0}".format(config_path))
return -1
os.makedirs(config_path)
with open(config_path + "/dtbo", 'wb') a... | _set_overlay_verify - Function to load the overlay and verify it was setup properly |
def to_json(df, columns, confidence={}):
records = []
display_cols = list(columns.keys())
if not display_cols:
display_cols = list(df.columns)
bounds = {}
for c in confidence:
bounds[c] = {
"min": df[confidence[c]["lower"]].min(),
... | Transforms dataframe to properly formatted json response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.