code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def draw_ticks(self):
self._canvas_ticks.create_line((0, 10, self.pixel_width, 10), fill="black")
self._ticks = list(TimeLine.range(self._start, self._finish, self._tick_resolution / self._zoom_factor))
for tick in self._ticks:
string = TimeLine.get_time_string(tick, self._unit)
... | Draw the time tick markers on the TimeLine Canvas |
def jars(self, absolute=True):
jars = glob(os.path.join(self._jar_path, '*.jar'))
return jars if absolute else map(lambda j: os.path.abspath(j), jars) | List of jars in the jar path |
def coerce(cls, key, value):
if isinstance(value, string_types):
value = value.strip()
if value[0] == '[':
try:
value = json.loads(value)
except ValueError:
raise ValueError("Failed to parse JSON: '{}' ".format(value... | Convert plain list to MutationList. |
def OnPageSetup(self, event):
print_data = self.main_window.print_data
new_print_data = \
self.main_window.interfaces.get_print_setup(print_data)
self.main_window.print_data = new_print_data | Page setup handler for printing framework |
def delete(self, endpoint: str, **kwargs) -> dict:
return self._request('DELETE', endpoint, **kwargs) | HTTP DELETE operation to API endpoint. |
def scene_color(frames):
reader = MessageReader(frames)
results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get()
if results.command != "scene.color":
raise MessageParserError("Command is not 'scene.color'")
return (results.scene_id, np.array([... | parse a scene.color message |
def force_utc(time, name='field', precision=6):
if not isinstance(time, datetime.datetime):
raise CloudValueError("%s should be of type datetime" % (name,))
clip = 6 - precision
timestring = time.isoformat()
if clip:
timestring = timestring[:-clip]
return timestring + "Z" | Appending 'Z' to isoformatted time - explicit timezone is required for most APIs |
def createTileUrl(self, x, y, z):
return self.tileTemplate.replace('{{x}}', str(x)).replace('{{y}}', str(
y)).replace('{{z}}', str(z)) | returns new tile url based on template |
def _validate_overriden_fields_are_not_defined_in_superclasses(class_to_field_type_overrides,
schema_graph):
for class_name, field_type_overrides in six.iteritems(class_to_field_type_overrides):
for superclass_name in schema_graph.get_inheritanc... | Assert that the fields we want to override are not defined in superclasses. |
def process_request(self, request):
domain, host = map(lower,
(self.get_domain_for_request(request), request.get_host()))
pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re.escape(domain)
matches = re.match(pattern, host)
if matches:
request.subdomain = match... | Adds a ``subdomain`` attribute to the ``request`` parameter. |
def stop(self):
if self._http_server:
self._http_server.shutdown()
self._http_server.server_close()
self._http_server = None
self._http_thread = None
if self._https_server:
self._https_server.shutdown()
self._https_server.server_clo... | Stop the WBEM listener threads, if they are running. |
def endpoint_from_name(endpoint_name):
if endpoint_name is None:
return None
factory = relation_factory(endpoint_name)
if factory:
return factory.from_name(endpoint_name) | The object used for interacting with the named relations, or None. |
def _writeContaminantTable(self, session, fileObject, mapTable, contaminants, replaceParamFile):
fileObject.write('%s\n' % (mapTable.name))
fileObject.write('NUM_CONTAM %s\n' % (mapTable.numContam))
for contaminant in contaminants:
fileObject.write(
'"%s" "%s" %s\n'... | This method writes the contaminant transport mapping table case. |
def main(argv=None):
arguments = cli_common(__doc__, argv=argv)
campaign_file = arguments['CAMPAIGN_FILE']
if arguments['-g']:
if osp.exists(campaign_file):
raise Exception('Campaign file already exists')
with open(campaign_file, 'w') as ostr:
Generator().write(ostr)
... | ben-sh entry point |
def lin_sim(goid1, goid2, godag, termcnts):
sim_r = resnik_sim(goid1, goid2, godag, termcnts)
return lin_sim_calc(goid1, goid2, sim_r, termcnts) | Computes Lin's similarity measure. |
def _len_objid(self):
try:
return self._size
except AttributeError:
temp = (self.object_id, self.birth_vol_id, self.birth_object_id, self.birth_domain_id)
self._size = sum([ObjectID._UUID_SIZE for data in temp if data is not None])
return self._size | Get the actual size of the content, as some attributes have variable sizes |
def xyz2lonlat(x, y, z):
lon = xu.rad2deg(xu.arctan2(y, x))
lat = xu.rad2deg(xu.arctan2(z, xu.sqrt(x**2 + y**2)))
return lon, lat | Convert cartesian to lon lat. |
def register_new_suffix_tree(case_insensitive=False):
assert isinstance(case_insensitive, bool)
root_node = register_new_node()
suffix_tree_id = uuid4()
event = SuffixTree.Created(
originator_id=suffix_tree_id,
root_node_id=root_node.id,
case_insensitive=case_insensitive,
)
... | Factory method, returns new suffix tree object. |
def check_has_version(self, api):
if not hasattr(api, 'version'):
msg = 'The Api class "{}" lacks a `version` attribute.'
return [msg.format(api.__name__)] | An API class must have a `version` attribute. |
def write_data(self, command, data, timeout=None):
self.write_message(FilesyncMessageTypes.DataMessage(command, data), timeout) | Shortcut for writing specifically a DataMessage. |
def key_to_metric(self, key):
return ''.join(l if l in string.letters else '_' for l in key) | Replace all non-letter characters with underscores |
def _get_branch(repo, name):
try:
return [x for x in _all_branches(repo) if x[0] == name][0]
except IndexError:
return False | Find the requested branch in the specified repo |
def iter_surrounding(self, center_key):
for shift in self.neighbor_indexes:
key = tuple(np.add(center_key, shift).astype(int))
if self.integer_cell is not None:
key = self.wrap_key(key)
bin = self._bins.get(key)
if bin is not None:
... | Iterate over all bins surrounding the given bin |
def _check_repo_sign_utils_support(name):
if salt.utils.path.which(name):
return True
else:
raise CommandExecutionError(
'utility \'{0}\' needs to be installed or made available in search path'.format(name)
) | Check for specified command name in search path |
def match_namespace(self, el, tag):
match = True
namespace = self.get_tag_ns(el)
default_namespace = self.namespaces.get('')
tag_ns = '' if tag.prefix is None else self.namespaces.get(tag.prefix, None)
if tag.prefix is None and (default_namespace is not None and namespace != defa... | Match the namespace of the element. |
def check_is_an_array(var, allow_none=False):
if not is_an_array(var, allow_none=allow_none):
raise TypeError("var must be a NumPy array, however type(var) is {}"
.format(type(var))) | Calls is_an_array and raises a type error if the check fails. |
def process_models(attrs, base_model_class):
attrs.update(base_model_class._DEFAULT_BASE_FIELDS)
attrs['_instance_registry'] = set()
attrs['_is_unpermitted_fields_set'] = False
attrs['save_meta_data'] = None
attrs['_pre_save_hook_called'] = False
attrs['_post_save_hook_ca... | Attach default fields and meta options to models |
def generate_data_for_registered_problem(problem_name):
tf.logging.info("Generating data for %s.", problem_name)
if FLAGS.num_shards:
raise ValueError("--num_shards should not be set for registered Problem.")
problem = registry.problem(problem_name)
task_id = None if FLAGS.task_id < 0 else FLAGS.task_id
d... | Generate data for a registered problem. |
def checksum(digits):
weights_for_check_digit = [9, 7, 3, 1, 9, 7, 3, 1, 9, 7]
check_digit = 0
for i in range(0, 10):
check_digit += weights_for_check_digit[i] * digits[i]
check_digit %= 10
return check_digit | Calculates and returns a control digit for given list of digits basing on PESEL standard. |
def from_date(self, value: date) -> datetime:
assert isinstance(value, date)
self.value = datetime(value.year, value.month, value.day)
return self.value | Initializes from the given date value |
def cmd_ok(cmd):
try:
sp.check_call(cmd, stderr=sp.PIPE, stdout=sp.PIPE)
except sp.CalledProcessError:
pass
except:
sys.stderr.write("{} not found, skipping\n".format(cmd))
return False
return True | Returns True if cmd can be run. |
def saturate_color(color, amount):
r, g, b = hex_to_rgb(color)
r, g, b = [x/255.0 for x in (r, g, b)]
h, l, s = colorsys.rgb_to_hls(r, g, b)
s = amount
r, g, b = colorsys.hls_to_rgb(h, l, s)
r, g, b = [x*255.0 for x in (r, g, b)]
return rgb_to_hex((int(r), int(g), int(b))) | Saturate a hex color. |
def add_pii_permissions(self, group, view_only=None):
pii_model_names = [m.split(".")[1] for m in self.pii_models]
if view_only:
permissions = Permission.objects.filter(
(Q(codename__startswith="view") | Q(codename__startswith="display")),
content_type__model_... | Adds PII model permissions. |
def trigger_streamer(self, index):
self._logger.debug("trigger_streamer RPC called on streamer %d", index)
if index >= len(self.graph.streamers):
return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED)
if index in self._stream_manager.in_progress():
return _pack_sge... | Pass a streamer to the stream manager if it has data. |
def _chk_fld(self, ntd, name, qty_min=0, qty_max=None):
vals = getattr(ntd, name)
num_vals = len(vals)
if num_vals < qty_min:
self.illegal_lines['MIN QTY'].append(
(-1, "FIELD({F}): MIN QUANTITY({Q}) WASN'T MET: {V}".format(F=name, Q=qty_min, V=vals)))
if qty_... | Further split a GAF value within a single field. |
def main():
dem = '../tests/data/Jamaica_dem.tif'
num_proc = 2
wp = '../tests/data/tmp_results/wtsd_delineation'
TauDEMWorkflow.watershed_delineation(num_proc, dem, workingdir=wp) | The simplest usage of watershed delineation based on TauDEM. |
def write(self):
if self.path is None:
raise Exception('Scrim.path is None')
dirname = os.path.dirname(os.path.abspath(self.path))
if not os.path.exists(dirname):
try:
os.makedirs(dirname)
except:
raise OSError('Failed to create... | Write this Scrims commands to its path |
def mfcc(wav_path):
(rate, sig) = wav.read(wav_path)
feat = python_speech_features.mfcc(sig, rate, appendEnergy=True)
delta_feat = python_speech_features.delta(feat, 2)
all_feats = [feat, delta_feat]
all_feats = np.array(all_feats)
all_feats = np.swapaxes(all_feats, 0, 1)
all_feats = np.swap... | Grabs MFCC features with energy and derivates. |
def _load_start_paths(self):
" Start the Read-Eval-Print Loop. "
if self._startup_paths:
for path in self._startup_paths:
if os.path.exists(path):
with open(path, 'rb') as f:
code = compile(f.read(), path, 'exec')
... | Start the Read-Eval-Print Loop. |
def guard_assign(analysis):
if not is_worksheet_context():
return False
if not analysis.isSampleReceived():
return False
if analysis.getWorksheet():
return False
return user_can_manage_worksheets() | Return whether the transition "assign" can be performed or not |
def delete_group_action(model, request):
try:
groups = model.parent.backend
uid = model.model.name
del groups[uid]
groups()
model.parent.invalidate()
except Exception as e:
return {
'success': False,
'message': str(e)
}
localize... | Delete group from database. |
def schedule(self, job, when):
pjob = pickle.dumps(job)
self._redis.zadd('ss:scheduled', when, pjob) | Schedule job to run at when nanoseconds since the UNIX epoch. |
def _updateKW(image, filename, exten, skyKW, Value):
image.header[skyKW] = Value
if isinstance(exten,tuple):
strexten = '[%s,%s]'%(exten[0],str(exten[1]))
else:
strexten = '[%s]'%(exten)
log.info('Updating keyword %s in %s' % (skyKW, filename + strexten))
fobj = fileutil.openImage(fi... | update the header with the kw,value |
def _maybe_reseed(self, normal):
self._y += self._rate
self._life -= 1
if self._life <= 0:
self._clear = not self._clear if normal else True
self._rate = randint(1, 2)
if self._clear:
self._y = 0
self._life = self._screen.height... | Randomly create a new column once this one is finished. |
def log(self, *args, **kwargs):
if self.verbose:
print(' ' * self.depth, *args, **kwargs) | Convenience function for printing indenting debug output. |
def main(**options):
configure_logging(log_all=options.get('log'))
stdin_stream = click.get_text_stream('stdin')
stdin_text = stdin_stream.read()
click.echo(stdin_text)
ci = find_ci_provider()
config = Config(options, ci=ci)
build = LintlyBuild(config, stdin_text)
try:
build.exec... | Slurp up linter output and send it to a GitHub PR review. |
def to_row(advice):
return [
advice.id,
advice.administration,
advice.type,
advice.session.year,
advice.session.strftime('%d/%m/%Y'),
advice.subject,
', '.join(advice.topics),
', '.join(advice.tags),
', '.join(advice.meanings),
ROMAN_NU... | Serialize an advice into a CSV row |
def _TypecheckFunction(function, parent_type_check_dict, stack_location,
self_name):
type_check_dict = _CollectTypeChecks(function, parent_type_check_dict,
stack_location + 1, self_name)
if not type_check_dict:
return function
def TypecheckWrapper(*a... | Decorator function to collect and execute type checks. |
def visit_module(self, node, modname, modpath, package):
node, doc = self._get_doc(node)
newnode = nodes.Module(
name=modname,
doc=doc,
file=modpath,
path=[modpath],
package=package,
parent=None,
)
newnode.postinit([... | visit a Module node by returning a fresh instance of it |
def op(cls,text,*args,**kwargs):
return cls.fn(text,*args,**kwargs) | This method must be overriden in derived classes |
def ax(self):
if self._ax is None:
import matplotlib.pyplot as plt
plt.figure()
self._ax = plt.axes(projection=self._get_sample_projection())
return self._ax | Axes instance of the plot |
def _validate_jpx_box_sequence(self, boxes):
self._validate_label(boxes)
self._validate_jpx_compatibility(boxes, boxes[1].compatibility_list)
self._validate_singletons(boxes)
self._validate_top_level(boxes) | Run through series of tests for JPX box legality. |
def client_list_entries(client, to_delete):
for entry in client.list_entries():
do_something_with(entry)
FILTER = "logName:log_name AND textPayload:simple"
for entry in client.list_entries(filter_=FILTER):
do_something_with(entry)
from google.cloud.logging import DESCENDING
for entry... | List entries via client. |
def on_config(self, config):
"Fetch the variables and functions"
self._variables = config.get(YAML_SUBSET)
module_reader.load_variables(self._variables, config)
print("Variables:", self.variables) | Fetch the variables and functions |
def remove_forms(self, form_names):
for form in form_names:
try:
self.parentApp.removeForm(form)
except Exception as e:
pass
return | Remove all forms supplied |
def create_ellipse(width,height,angle):
angle = angle / 180.0 * np.pi
thetas = np.linspace(0,2*np.pi,200)
a = width / 2.0
b = height / 2.0
x = a*np.cos(thetas)*np.cos(angle) - b*np.sin(thetas)*np.sin(angle)
y = a*np.cos(thetas)*np.sin(angle) + b*np.sin(thetas)*np.cos(angle)
z = np.zeros(thet... | Create parametric ellipse from 200 points. |
def write_array(self, data):
try:
data.tofile(self._fh)
except Exception:
self._fh.write(data.tostring()) | Write numpy array to binary file. |
def _parse_reverse_json(self, page, exactly_one=True):
place = page.get('result')
if not place:
self._check_status(page.get('status'))
return None
location = place.get('formatted_address').encode('utf-8')
latitude = place['location']['lat']
longitude = pla... | Parses a location from a single-result reverse API call. |
def remove_getdisplay(field_name):
str_ini = 'get_'
str_end = '_display'
if str_ini == field_name[0:len(str_ini)] and str_end == field_name[(-1) * len(str_end):]:
field_name = field_name[len(str_ini):(-1) * len(str_end)]
return field_name | for string 'get_FIELD_NAME_display' return 'FIELD_NAME' |
def with_partitions(self, partitions_to_add):
new_metadata = ClusterMetadata(**self.config)
new_metadata._brokers = copy.deepcopy(self._brokers)
new_metadata._partitions = copy.deepcopy(self._partitions)
new_metadata._broker_partitions = copy.deepcopy(self._broker_partitions)
new... | Returns a copy of cluster metadata with partitions added |
def validate(obj, schema):
if not framework.EvaluationContext.current().validate:
return obj
if hasattr(obj, 'tuple_schema'):
obj.tuple_schema.validate(obj)
if schema:
schema.validate(obj)
return obj | Validate an object according to its own AND an externally imposed schema. |
def content(self):
content_list = wrap_list(self._content_preprocessed)
content_list.extend(self._content_stash)
content_to_render = '\n'.join(content_list)
return typogrify(self.content_renderer.render(content_to_render, self.format)) | The post's content in HTML format. |
def wrap_async(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
fut = asyncio.ensure_future(func(*args, **kwargs))
cur = greenlet.getcurrent()
def callback(fut):
try:
cur.switch(fut.result())
except BaseException as e:
cu... | Wraps an asynchronous function into a synchronous function. |
def compare_numpy_dict(a, b, exact=True):
if type(a) != type(b) and type(a) != np.ndarray and type(b) != np.ndarray:
return False
if type(a) == dict and type(b) == dict:
if not a.keys() == b.keys():
return False
for key in a.keys():
res = compare_numpy_dict(a[key]... | Compare two recursive numpy dictionaries |
def push(h, x):
h.push(x)
up(h, h.size()-1) | Push a new value into heap. |
def userKicked(self, kickee, channel, kicker, message):
self.dispatch('population', 'userKicked', kickee, channel, kicker,
message) | Called when I see another user get kicked. |
def help_box():
style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
dialog_box = wx.Dialog(None, wx.ID_ANY, HELP_TITLE,
style=style, size=(620, 450))
html_widget = HtmlHelp(dialog_box, wx.ID_ANY)
html_widget.page = build_help_html()
dialog_box.ShowModal()
dialog_box.Des... | A simple HTML help dialog box using the distribution data files. |
def _handler(func):
"Decorate a command handler"
def _wrapped(*a, **k):
r = func(*a, **k)
if r is None: r = 0
return r
return staticmethod(_wrapped) | Decorate a command handler |
def backup(target_file, config=None):
storm_ = get_storm_instance(config)
try:
storm_.backup(target_file)
except Exception as error:
print(get_formatted_message(str(error), 'error'), file=sys.stderr)
sys.exit(1) | Backups the main ssh configuration into target file. |
def sanitize_gff_file(gff_fname,
in_memory=True,
in_place=False):
db = None
if is_gff_db(gff_fname):
db = gffutils.FeatureDB(gff_fname)
else:
if in_memory:
db = gffutils.create_db(gff_fname, ":memory:",
... | Sanitize a GFF file. |
def InstanceOf(cls, **kwargs):
return Property(types=cls, load=cls.load, **kwargs) | A property that is an instance of `cls`. |
def create_reward_encoder():
last_reward = tf.Variable(0, name="last_reward", trainable=False, dtype=tf.float32)
new_reward = tf.placeholder(shape=[], dtype=tf.float32, name='new_reward')
update_reward = tf.assign(last_reward, new_reward)
return last_reward, new_reward, update_reward | Creates TF ops to track and increment recent average cumulative reward. |
def _read_config(self):
try:
self.config = self.componentmodel.find_one(
{'name': self.uniquename})
except ServerSelectionTimeoutError:
self.log("No database access! Check if mongodb is running "
"correctly.", lvl=critical)
if self.con... | Read this component's configuration from the database |
def _run_raw(self, cmd, ignore_errors=False):
result = os.system(cmd)
if result != 0:
if ignore_errors:
self.log(f"command ({cmd}) failed.")
assert False, "_run_raw failed" | Runs command directly, skipping tmux interface |
def _compute_acq_withGradients(self, x):
means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x)
f_acqu = None
df_acqu = None
for m, s, dmdx, dsdx in zip(means, stds, dmdxs, dsdxs):
f = -m + self.exploration_weight * s
df = -dmdx + self.explorati... | Integrated GP-Lower Confidence Bound and its derivative |
def node_insert_after(self, node, new_node):
assert(not self.node_is_on_list(new_node))
assert(node is not new_node)
next = self.node_next(node)
assert(next is not None)
self.node_set_next(node, new_node)
self.node_set_prev(new_node, node)
self.node_set_next(new_n... | Insert the new node after node. |
def convert2phylip(convert):
out = '%s.phy' % (convert.rsplit('.', 1)[0])
if check(out) is False:
convert = open(convert, 'rU')
out_f = open(out, 'w')
alignments = AlignIO.parse(convert, "fasta")
AlignIO.write(alignments, out, "phylip")
return out | convert fasta to phylip because RAxML is ridiculous |
async def stop(self):
if self._task is not None:
self._task.cancel()
self._task = None
if self._state in [State.CONNECTING, State.CONNECTED]:
lib.SSL_shutdown(self.ssl)
try:
await self._write_ssl()
except ConnectionError:
... | Stop and close the DTLS transport. |
async def main():
pyvlx = PyVLX('pyvlx.yaml')
await pyvlx.load_devices()
print(pyvlx.devices[1])
print(pyvlx.devices['Fenster 4'])
await pyvlx.load_scenes()
print(pyvlx.scenes[0])
print(pyvlx.scenes['Bath Closed'])
await pyvlx.scenes[1].run()
await pyvlx.disconnect() | Load devices and scenes, run first scene. |
def uniqueof20(k, rep=10000):
alphabet = 'ACDEFGHIKLMNPQRSTVWY'
reps = [len(set(random.choice(alphabet)
for i in range(k)))
for j in range(rep)]
return sum(reps) / len(reps) | Sample k times out of alphabet, how many different? |
def validate_schema(schema_name):
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
try:
instance.validator(instance.schemas[schema_name]).validate(request.get_json())
except ValidationError, e:
ret_dict = ins... | Validate the JSON against a required schema_name. |
def watch_and_wait(self, poll_interval=10, idle_log_timeout=None,
kill_on_timeout=False, stash_log_method=None,
tag_instances=False, **kwargs):
return wait_for_complete(self._job_queue, job_list=self.job_list,
job_name_prefix=self.ba... | This provides shortcut access to the wait_for_complete_function. |
def output_datacenter(gandi, datacenter, output_keys, justify=14):
output_generic(gandi, datacenter, output_keys, justify)
if 'dc_name' in output_keys:
output_line(gandi, 'datacenter', datacenter['name'], justify)
if 'status' in output_keys:
deactivate_at = datacenter.get('deactivate_at')
... | Helper to output datacenter information. |
def package_contents(self):
'Returns a dictionary of file information'
if self.contents_cache:
return self.contents_cache
files = self.zf.infolist()
out_files = {}
for file_ in files:
file_doc = {'name': file_.filename,
'size': file... | Returns a dictionary of file information |
def clear(self):
self.mark_incomplete()
for suffix in list(CLIMATE_SEASON_SUFFIXES.values()):
try:
indicator = self.session.query(models.ClimateIndicator) \
.filter(models.ClimateIndicator.description == self.description + suffix) \
.on... | Clear output of one climate variable |
def parse_if(self):
node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
while 1:
node.test = self.parse_tuple(with_condexpr=False)
node.body = self.parse_statements(('name:elif', 'name:else',
'name:endif'))
... | Parse an if construct. |
def weeks_per_year(year):
jan1 = jwday(gregorian.to_jd(year, 1, 1))
if jan1 == THU or (jan1 == WED and isleap(year)):
return 53
else:
return 52 | Number of ISO weeks in a year |
def pipeline(names, steps):
steps, times = zip(*map(_maybe_timed, steps))
fit_time = sum(times)
if any(s is FIT_FAILURE for s in steps):
fit_est = FIT_FAILURE
else:
fit_est = Pipeline(list(zip(names, steps)))
return fit_est, fit_time | Reconstruct a Pipeline from names and steps |
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None:
filename = self.filename
else:
raise ValueError(cookiejar.MISSING_FILENAME_TEXT)
go_cookies = []
now = time.time()... | Implement the FileCookieJar abstract method. |
def clear(self) -> None:
self._best_so_far = None
self._epochs_with_no_improvement = 0
self._is_best_so_far = True
self._epoch_number = 0
self.best_epoch = None | Clears out the tracked metrics, but keeps the patience and should_decrease settings. |
def wrap_conn(conn_func):
def call(*args, **kwargs):
try:
conn = conn_func(*args, **kwargs)
cursor_func = getattr(conn, CURSOR_WRAP_METHOD)
wrapped = wrap_cursor(cursor_func)
setattr(conn, cursor_func.__name__, wrapped)
return conn
except E... | Wrap the mysql conn object with TraceConnection. |
def interp(x, xp, *args, **kwargs):
return interpolate_1d(x, xp, *args, **kwargs) | Wrap interpolate_1d for deprecated interp. |
def num_tasks(self, work_spec_name):
return self.num_finished(work_spec_name) + \
self.num_failed(work_spec_name) + \
self.registry.len(WORK_UNITS_ + work_spec_name) | Get the total number of work units for some work spec. |
def transfers_complete(self):
for transfer in self.transfers:
if not transfer.is_complete:
error = {
'errorcode': 4003,
'errormessage': 'You must complete transfer before logout.'
}
hellraiser(error) | Check if all transfers are completed. |
def ExecuteQuery(self, query, args=None):
def Action(connection):
connection.cursor.execute(query, args)
rowcount = connection.cursor.rowcount
results = connection.cursor.fetchall()
return results, rowcount
return self._RetryWrapper(Action) | Get connection from pool and execute query. |
def __expand_limits(ax, limits, which='x'):
if which == 'x':
getter, setter = ax.get_xlim, ax.set_xlim
elif which == 'y':
getter, setter = ax.get_ylim, ax.set_ylim
else:
raise ValueError('invalid axis: {}'.format(which))
old_lims = getter()
new_lims = list(limits)
if np.i... | Helper function to expand axis limits |
def sockets(self):
return [Socket(self._device, i) for i in range(len(self.raw))] | Return socket objects of the socket control. |
def _get_file(self, path, prepend=False):
if prepend:
path = os.path.join(self._dirname(), path)
extracted = self._tar.extractfile(path)
if extracted:
return extracted
raise DapFileError(('Could not read %s from %s, maybe it\'s a directory,' +
'bad lin... | Extracts a file from dap to a file-like object |
def create_highlight(self, artist):
highlight = copy.copy(artist)
highlight.set(color=self.highlight_color, mec=self.highlight_color,
lw=self.highlight_width, mew=self.highlight_width)
artist.axes.add_artist(highlight)
return highlight | Create a new highlight for the given artist. |
def create_default_file(cls, data=None, mode=None):
filepath = cls.get_default_filepath()
if not filepath:
return False
filename = os.path.basename(filepath)
config = read_file(get_data_path(), filename)
data = data or {}
for k, v in six.iteritems(data):
... | Create a config file and override data if specified. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.