code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def meson_setup():
meson_exe = shutil.which('meson')
ninja_exe = shutil.which('ninja')
if not meson_exe or not ninja_exe:
raise FileNotFoundError('Meson or Ninja not available')
if not (BINDIR / 'build.ninja').is_file():
subprocess.check_call([meson_exe, str(SRCDIR)], cwd=BINDIR)
ret... | attempt to build with Meson + Ninja |
def _write_log(self, log_type, log_time, message):
timestamp = datetime.datetime.now().strftime(" %Y-%m-%d %H:%M:%S")
log_entry = "[{}{}] {}".format(log_type, timestamp if log_time else "", message)
if self._logger and callable(getattr(self._logger, self._logger_methods[log_type], None)):
... | Private method to abstract log writing for different types of logs |
async def close(self):
if self.__isClosed:
return
self.__isClosed = True
self.__setSignalingState('closed')
for transceiver in self.__transceivers:
await transceiver.stop()
if self.__sctp:
await self.__sctp.stop()
for transceiver in sel... | Terminate the ICE agent, ending ICE processing and streams. |
def mpub(self, topic, *messages):
return self.send(constants.MPUB + ' ' + topic, messages) | Publish multiple messages to a topic |
def generate_file(fname, ns_func, dest_dir="."):
with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f:
tpl = f.read()
out = tpl.format(**ns_func())
dest = pjoin(dest_dir, fname)
info("generating %s from template" % dest)
with open(dest, 'w') as f:
f.write(out) | generate a constants file from its template |
def full_name(self):
formatted_user = []
if self.user.first_name is not None:
formatted_user.append(self.user.first_name)
if self.user.last_name is not None:
formatted_user.append(self.user.last_name)
return " ".join(formatted_user) | Returns the first and last name of the user separated by a space. |
def SetValue(self, row, col, value):
self.dataframe.iloc[row, col] = value | Set value in the pandas DataFrame |
def _add_type_node(self, node, label):
child = node.add_child(name=label)
child.add_feature(TYPE_NODE_TAG, True)
return child | Add a node representing a SubjectInfo type. |
def add_user(self, name, password=None, read_only=None, db=None, **kwargs):
if db is None:
return self.get_connection().admin.add_user(
name, password=password, read_only=read_only, **kwargs)
return self.get_connection()[db].add_user(
name, password=pa... | Adds a user that can be used for authentication |
def find_loops( record, index, stop_types = STOP_TYPES, open=None, seen = None ):
if open is None:
open = []
if seen is None:
seen = set()
for child in children( record, index, stop_types = stop_types ):
if child['type'] in stop_types or child['type'] == LOOP_TYPE:
contin... | Find all loops within the index and replace with loop records |
def run(port, like, use_json, server):
if not port and not server[0]:
raise click.UsageError("Please specify a port")
if server[0]:
app.run(host=server[0], port=server[1])
return
ports = get_ports(port, like)
if not ports:
sys.stderr.write("No ports found for '{0}'\n".for... | Search port names and numbers. |
def listen(self):
while self._listen:
key = u''
key = self.term.inkey(timeout=0.2)
try:
if key.code == KEY_ENTER:
self.on_enter(key=key)
elif key.code in (KEY_DOWN, KEY_UP):
self.on_key_arrow(key=key)
... | Blocking call on widgets. |
def _stmt_from_rule(model, rule_name, stmts):
stmt_uuid = None
for ann in model.annotations:
if ann.predicate == 'from_indra_statement':
if ann.subject == rule_name:
stmt_uuid = ann.object
break
if stmt_uuid:
for stmt in stmts:
if stmt.... | Return the INDRA Statement corresponding to a given rule by name. |
def change_dir(directory):
def cd_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
org_path = os.getcwd()
os.chdir(directory)
func(*args, **kwargs)
os.chdir(org_path)
return wrapper
return cd_decorator | Wraps a function to run in a given directory. |
def change_authentication(self, client_id=None, client_secret=None,
access_token=None, refresh_token=None):
self.client_id = client_id or self.client_id
self.client_secret = client_secret or self.client_secret
self.access_token = access_token or self.access_token
... | Change the current authentication. |
def trigger_frontend_build(self, event):
from hfos.database import instance
install_frontend(instance=instance,
forcerebuild=event.force,
install=event.install,
development=self.development
) | Event hook to trigger a new frontend build |
def toc_print(self):
res = self.toc()
for n, k, v in res:
logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v)) | End collecting and print results. |
def name(self):
if self._name == '' and self.details != None and 'name' in self.details:
self._name = self.details['name']
return self._name | Returns the human-readable name of the place. |
def disconnect(self):
all_conns = chain(
self._available_connections.values(),
self._in_use_connections.values(),
)
for node_connections in all_conns:
for connection in node_connections:
connection.disconnect() | Nothing that requires any overwrite. |
def to_list(self):
ret = OrderedDict()
for attrname in self.attrs:
ret[attrname] = self.__getattribute__(attrname)
return ret | Returns list containing values of attributes listed in self.attrs |
def results(self, request):
"Match results to given term and return the serialized HttpResponse."
results = {}
form = self.form(request.GET)
if form.is_valid():
options = form.cleaned_data
term = options.get('term', '')
raw_data = self.get_query(reques... | Match results to given term and return the serialized HttpResponse. |
def _GeneratorFromPath(path):
if not path:
raise ValueError('path must be a valid string')
if io_wrapper.IsTensorFlowEventsFile(path):
return event_file_loader.EventFileLoader(path)
else:
return directory_watcher.DirectoryWatcher(
path,
event_file_loader.EventFileLoader,
io_wra... | Create an event generator for file or directory at given path string. |
def eject(self, auth_no_user_interaction=None):
return self._assocdrive._M.Drive.Eject(
'(a{sv})',
filter_opt({
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
) | Eject media from the device. |
def shell_context_processor(self, fn):
self._defer(lambda app: app.shell_context_processor(fn))
return fn | Registers a shell context processor function. |
def api_call(endpoint, args, payload):
headers = {'content-type': 'application/json; ; charset=utf-8'}
url = 'https://{}/{}'.format(args['--server'], endpoint)
attempt = 0
resp = None
while True:
try:
attempt += 1
resp = requests.post(
url, data=json.d... | Generic function to call the RO API |
def contains_all(self, other):
dtype = getattr(other, 'dtype', None)
if dtype is None:
dtype = np.result_type(*other)
dtype_str = np.dtype('S{}'.format(self.length))
dtype_uni = np.dtype('<U{}'.format(self.length))
return dtype in (dtype_str, dtype_uni) | Return ``True`` if all strings in ``other`` have size `length`. |
def dump(self):
self.print("Dumping data to {}".format(self.dump_filename))
pickle.dump({
'data': self.counts,
'livetime': self.get_livetime()
}, open(self.dump_filename, "wb")) | Write coincidence counts into a Python pickle |
def _get_dest_file_and_url(self, filepath, page_meta={}):
filename = filepath.split("/")[-1]
filepath_base = filepath.replace(filename, "").rstrip("/")
slug = page_meta.get("slug")
fname = slugify(slug) if slug else filename \
.replace(".html", "") \
.replace(".md... | Return tuple of the file destination and url |
def team(self):
team_dict = self._json_data.get('team')
if team_dict and team_dict.get('id'):
return self._client.team(id=team_dict.get('id'))
else:
return None | Team to which the scope is assigned. |
def convert_row_to_sdpa_index(block_struct, row_offsets, row):
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i, j | Helper function to map to sparse SDPA index values. |
def consume_keys_asynchronous_threads(self):
print("\nLooking up " + self.input_queue.qsize().__str__() + " keys from " + self.source_name + "\n")
jobs = multiprocessing.cpu_count()*4 if (multiprocessing.cpu_count()*4 < self.input_queue.qsize()) \
else self.input_queue.qsize()
pool =... | Work through the keys to look up asynchronously using multiple threads |
def decrypt(crypt_text) -> str:
cipher = Fernet(current_app.config['KEY'])
if not isinstance(crypt_text, bytes):
crypt_text = str.encode(crypt_text)
return cipher.decrypt(crypt_text).decode("utf-8") | Use config.json key to decrypt |
def extend_schema_spec(self) -> None:
super().extend_schema_spec()
identity_field = {
'Name': '_identity',
'Type': BtsType.STRING,
'Value': 'identity',
ATTRIBUTE_INTERNAL: True
}
if self.ATTRIBUTE_FIELDS in self._spec:
self._spe... | Injects the identity field |
def say_tmp_filepath(
text = None,
preference_program = "festival"
):
filepath = shijian.tmp_filepath() + ".wav"
say(
text = text,
preference_program = preference_program,
filepath = filepath
)
return filepath | Say specified text to a temporary file and return the filepath. |
def _submit_results(self):
if self._cur_res_id and self._cur_values:
self._addRawResult(self._cur_res_id, self._cur_values)
self._reset() | Adding current values as a Raw Result and Resetting everything. |
def gen_slot_variables(self, cls: ClassDefinition) -> str:
return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] +
[self.gen_slot_variable(cls, slot)
for slot in cls.slots
if not self.schema.sl... | Generate python definition for class cls, generating primary keys first followed by the rest of the slots |
def make_request_fn():
if FLAGS.cloud_mlengine_model_name:
request_fn = serving_utils.make_cloud_mlengine_request_fn(
credentials=GoogleCredentials.get_application_default(),
model_name=FLAGS.cloud_mlengine_model_name,
version=FLAGS.cloud_mlengine_model_version)
else:
request_fn = se... | Returns a request function. |
def update_from_json(self, json_device):
self.identifier = json_device['Id']
self.license_plate = json_device['EquipmentHeader']['SerialNumber']
self.make = json_device['EquipmentHeader']['Make']
self.model = json_device['EquipmentHeader']['Model']
self.equipment_id = json_device... | Set all attributes based on API response. |
def read_http_header(sock):
buf = []
hdr_end = '\r\n\r\n'
while True:
buf.append(sock.recv(bufsize).decode('utf-8'))
data = ''.join(buf)
i = data.find(hdr_end)
if i == -1:
continue
return data[:i], data[i + len(hdr_end):] | Read HTTP header from socket, return header and rest of data. |
def _mix(color1, color2, weight=0.5, **kwargs):
weight = float(weight)
c1 = color1.value
c2 = color2.value
p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight
w = p * 2 - 1
a = c1[3] - c2[3]
w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0
w2 = 1 - w1
q = [w1, w1... | Mixes two colors together. |
def create_group(cls, prefix: str, name: str) -> ErrorGroup:
group = cls.ErrorGroup(prefix, name)
cls.groups.append(group)
return group | Create a new error group and return it. |
def select(yerrs, amps, amp_errs, widths):
keep_1 = np.logical_and(amps < 0, widths > 1)
keep_2 = np.logical_and(np.abs(amps) > 3*yerrs, amp_errs < 3*np.abs(amps))
keep = np.logical_and(keep_1, keep_2)
return keep | criteria for keeping an object |
def radio_buttons_clicked(self):
for spin_box in list(self.spin_boxes.values()):
spin_box.setEnabled(False)
self.list_widget.setEnabled(False)
radio_button_checked_id = self.input_button_group.checkedId()
if radio_button_checked_id > -1:
selected_value = list(self... | Handler when selected radio button changed. |
def do_opt(self, *args, **kwargs):
args = list(args)
if not args:
largest = 0
keys = [key for key in self.conf if not key.startswith("_")]
for key in keys:
largest = max(largest, len(key))
for key in keys:
print("%s : %s" % ... | Get and set options |
def process_user_input(self):
user_input = self.get_input()
try:
num = int(user_input)
except Exception:
return
if 0 < num < len(self.items) + 1:
self.current_option = num - 1
self.select()
return user_input | Gets the next single character and decides what to do with it |
def ready(self):
self.options = {}
self.options.update(DEFAULT_OPTIONS)
for template_engine in settings.TEMPLATES:
if template_engine.get('BACKEND', '').startswith('django_mako_plus'):
self.options.update(template_engine.get('OPTIONS', {}))
self.registration_l... | Called by Django when the app is ready for use. |
def deferToGreenlet(*args, **kwargs):
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
return deferToGreenletPool(reactor, reactor.getGreenletPool(), *args, **kwargs) | Call function using a greenlet and return the result as a Deferred |
def convert_to_bytes(mem_str):
if str(mem_str)[-1].upper().endswith("G"):
return int(round(float(mem_str[:-1]) * 1024 * 1024))
elif str(mem_str)[-1].upper().endswith("M"):
return int(round(float(mem_str[:-1]) * 1024))
else:
return int(round(float(mem_str))) | Convert a memory specification, potentially with M or G, into bytes. |
def input_flush():
try:
import sys, termios
termios.tcflush(sys.stdin, termios.TCIFLUSH)
except ImportError:
import msvcrt
while msvcrt.kbhit():
msvcrt.getch() | Flush the input buffer on posix and windows. |
def fix_text_escapes(self, txt: str, quote_char: str) -> str:
def _subf(matchobj):
return matchobj.group(0).translate(self.re_trans_table)
if quote_char:
txt = re.sub(r'\\'+quote_char, quote_char, txt)
return re.sub(r'\\.', _subf, txt, flags=re.MULTILINE + re.DOTALL + re.... | Fix the various text escapes |
def _blend_layers(self, imagecontent, z_x_y):
(z, x, y) = z_x_y
result = self._tile_image(imagecontent)
for (layer, opacity) in self._layers:
try:
overlay = self._tile_image(layer.tile((z, x, y)))
except (IOError, DownloadError, ExtractionError)as e:
... | Merge tiles of all layers into the specified tile path |
def update_target(self, name, current, total):
self.refresh(self._bar(name, current, total)) | Updates progress bar for a specified target. |
def _block_shape(values, ndim=1, shape=None):
if values.ndim < ndim:
if shape is None:
shape = values.shape
if not is_extension_array_dtype(values):
values = values.reshape(tuple((1, ) + shape))
return values | guarantee the shape of the values to be at least 1 d |
def _inner(self, x1, x2):
return self.tspace._inner(x1.tensor, x2.tensor) | Raw inner product of two elements. |
def remove(self, item):
self.items.pop(item)
self._remove_dep(item)
self.order = None
self.changed(code_changed=True) | Remove an item from the list. |
def logv(msg, *args, **kwargs):
if settings.VERBOSE:
log(msg, *args, **kwargs) | Print out a log message, only if verbose mode. |
def _update_display(self, event=None):
try:
if self._showvalue:
self.display_value(self.scale.get())
if self._tickinterval:
self.place_ticks()
except IndexError:
pass | Redisplay the ticks and the label so that they adapt to the new size of the scale. |
def char_conv(out):
out_conv = list()
for i in range(out.shape[0]):
tmp_str = ''
for j in range(out.shape[1]):
if int(out[i][j]) >= 0:
tmp_char = int2char(int(out[i][j]))
if int(out[i][j]) == 27:
tmp_char = ''
tmp_st... | Convert integer vectors to character vectors for batch. |
def report(self):
aggregations = dict(
(test, Counter().rollup(values))
for test, values in self.socket_warnings.items()
)
total = sum(
len(warnings)
for warnings in self.socket_warnings.values()
)
def format_test_statistics(test, c... | Performs rollups, prints report of sockets opened. |
def _construct_url(self, endpoint):
parsed_url = urlparse(self.host)
scheme = parsed_url[0]
host = parsed_url[1]
if scheme == "":
scheme = "http"
host = self.host
if not endpoint.startswith("/"):
endpoint = "/" + endpoint
if self.config... | Return the full URL to the specified endpoint |
def enc_name_descr(name, descr, color=a99.COLOR_DESCR):
return enc_name(name, color)+"<br>"+descr | Encodes html given name and description. |
def host_info(host=None):
data = query(host, quiet=True)
for id_ in data:
if 'vm_info' in data[id_]:
data[id_].pop('vm_info')
__jid_event__.fire_event({'data': data, 'outputter': 'nested'}, 'progress')
return data | Return information about the host connected to this master |
def make_request(parameters):
r = requests.get(bcdata.WFS_URL, params=parameters)
return r.json()["features"] | Submit a getfeature request to DataBC WFS and return features |
def reset(self):
self.filename = None
self.dataset = None
self.idx_filename.setText('Open Recordings...')
self.idx_s_freq.setText('')
self.idx_n_chan.setText('')
self.idx_start_time.setText('')
self.idx_end_time.setText('')
self.idx_scaling.setText('')
... | Reset widget to original state. |
def max_spline_jump(self):
sp = self.spline()
return max(self.energies - sp(range(len(self.energies)))) | Get maximum difference between spline and energy trend. |
def insert_statement(table, columns, values):
if not all(isinstance(r, (list, set, tuple)) for r in values):
values = [[r] for r in values]
rows = []
for row in values:
new_row = []
for col in row:
if col is None:
new_col = 'NULL'
elif isinstan... | Generate an insert statement string for dumping to text file or MySQL execution. |
def changes(self):
deprecation_msg = 'Model.changes will be removed in warlock v2'
warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
return copy.deepcopy(self.__dict__['changes']) | Dumber version of 'patch' method |
def nameValue(name, value, valueType=str, quotes=False):
if valueType == bool:
if value:
return "--%s" % name
return ""
if value is None:
return ""
if quotes:
return "--%s '%s'" % (name, valueType(value))
return "--%s %s" % (name, valueType(value)) | Little function to make it easier to make name value strings for commands. |
def dehydrate(self):
result = dict(limit_class=self._limit_full_name)
for attr in self.attrs:
result[attr] = getattr(self, attr)
return result | Return a dict representing this limit. |
def profile(self):
leftmost_idx = np.argmax(self.matrix('dense').astype(bool), axis=0)
return (np.arange(self.num_vertices()) - leftmost_idx).sum() | Measure of bandedness, also known as 'envelope size'. |
def draw_header(self, stream, header):
stream.writeln('=' * (len(header) + 4))
stream.writeln('| ' + header + ' |')
stream.writeln('=' * (len(header) + 4))
stream.writeln() | Draw header with underline |
def _organize_tools_on(data, is_cwl):
if is_cwl:
if tz.get_in(["algorithm", "jointcaller"], data):
val = tz.get_in(["algorithm", "tools_on"], data)
if not val:
val = []
if not isinstance(val, (list, tuple)):
val = [val]
if "gvcf... | Ensure tools_on inputs match items specified elsewhere. |
def distance2_to(self, other: "Point2"):
assert isinstance(other, Point2)
return (self[0] - other[0]) ** 2 + (self[1] - other[1]) ** 2 | Squared distance to a point. |
def stop(self):
self._running = False
if self._self_thread is not None:
self._self_thread.cancel()
self._self_thread = None | Stop running scheduled function. |
def natural_number_with_currency(number, currency, show_decimal_place=True, use_nbsp=True):
humanized = '{} {}'.format(
numberformat.format(
number=number,
decimal_sep=',',
decimal_pos=2 if show_decimal_place else 0,
grouping=3,
thousand_sep=' ',
... | Return a given `number` formatter a price for humans. |
def detect_encoding(sample, encoding=None):
from cchardet import detect
if encoding is not None:
return normalize_encoding(sample, encoding)
result = detect(sample)
confidence = result['confidence'] or 0
encoding = result['encoding'] or 'ascii'
encoding = normalize_encoding(sample, encod... | Detect encoding of a byte string sample. |
def async_get_ac_state_log(self, uid, log_id, fields='*'):
return (
yield from self._get('/pods/{}/acStates/{}'.format(uid, log_id),
fields=fields)) | Get a specific log entry. |
def _parse_vmconfig(config, instances):
vmconfig = None
if isinstance(config, (salt.utils.odict.OrderedDict)):
vmconfig = salt.utils.odict.OrderedDict()
for prop in config:
if prop not in instances:
vmconfig[prop] = config[prop]
else:
if no... | Parse vm_present vm config |
def dshield_ip_check(ip):
if not is_IPv4Address(ip):
return None
headers = {'User-Agent': useragent}
url = 'https://isc.sans.edu/api/ip/'
response = requests.get('{0}{1}?json'.format(url, ip), headers=headers)
return response.json() | Checks dshield for info on an IP address |
def place_data_on_block_device(blk_device, data_src_dst):
mount(blk_device, '/mnt')
copy_files(data_src_dst, '/mnt')
umount('/mnt')
_dir = os.stat(data_src_dst)
uid = _dir.st_uid
gid = _dir.st_gid
mount(blk_device, data_src_dst, persist=True)
os.chown(data_src_dst, uid, gid) | Migrate data in data_src_dst to blk_device and then remount. |
def enable_aliases_autocomplete_interactive(_, **kwargs):
subtree = kwargs.get('subtree', None)
if not subtree or not hasattr(subtree, 'children'):
return
for alias, alias_command in filter_aliases(get_alias_table()):
if subtree.in_tree(alias_command.split()):
subtree.add_child(C... | Enable aliases autocomplete on interactive mode by injecting aliases in the command tree. |
def do_it(self, dbg):
try:
frame = dbg.find_frame(self.thread_id, self.frame_id)
completions_xml = pydevd_console.get_completions(frame, self.act_tok)
cmd = dbg.cmd_factory.make_send_console_message(self.sequence, completions_xml)
dbg.writer.add_command(cmd)
... | Get completions and write back to the client |
def backend_calibration(self, backend='ibmqx4', hub=None, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
raise CredentialsErro... | Get the calibration of a real chip |
def get(self, aspect):
classification = [(network, self.networks), (system, self.systems),
(configure, self.configures)]
aspect_list = [l for t, l in classification if isinstance(aspect, t)]
assert len(aspect_list) == 1, "Unexpected aspect for RADL."
aspect_list... | Get a network, system or configure or contextualize with the same id as aspect passed. |
def on_feed_key(self, key_press):
if key_press.key in {Keys.Escape, Keys.ControlC}:
echo(carriage_return=True)
raise Abort()
if key_press.key == Keys.Backspace:
if self.current_command_pos > 0:
self.current_command_pos -= 1
return key_press... | Handles the magictyping when a key is pressed |
def IsImage(self, filename):
mimetype = mimetypes.guess_type(filename)[0]
if not mimetype:
return False
return mimetype.startswith("image/") | Returns true if the filename has an image extension. |
def include(self, path):
for extension in IGNORE_EXTENSIONS:
if path.endswith(extension):
return False
parts = path.split(os.path.sep)
for part in parts:
if part in self.ignore_dirs:
return False
return True | Returns `True` if the file is not ignored |
def _condition_as_sql(self, qn, connection):
def escape(value):
if isinstance(value, bool):
value = str(int(value))
if isinstance(value, six.string_types):
if '%' in value:
value = value.replace('%', '%%')
if "'" in valu... | Return sql for condition. |
def pivot(self):
self.op_data = [list(i) for i in zip(*self.ip_data)] | transposes rows and columns |
def foreign(self, value, context=None):
if self.none and value is None:
return ''
try:
value = self.native(value, context)
except Concern:
value = bool(value.strip() if self.strip and hasattr(value, 'strip') else value)
if value in self.truthy or value:
return self.truthy[self.use]
return self.fal... | Convert a native value to a textual boolean. |
def json_formatter(subtitles):
subtitle_dicts = [
{
'start': start,
'end': end,
'content': text,
}
for ((start, end), text)
in subtitles
]
return json.dumps(subtitle_dicts) | Serialize a list of subtitles as a JSON blob. |
def create(cls, path, encoding='utf-8'):
cmd = [GIT, 'init', '--quiet', '--bare', path]
subprocess.check_call(cmd)
return cls(path, encoding) | Create a new bare repository |
def setup_mimetypes(self):
mimetypes.add_type('text/xml', '.ui')
mimetypes.add_type('text/x-rst', '.rst')
mimetypes.add_type('text/x-cython', '.pyx')
mimetypes.add_type('text/x-cython', '.pxd')
mimetypes.add_type('text/x-python', '.py')
mimetypes.add_type('text/x-python',... | Setup additional mime types. |
def create_widget(self):
widget = QDoubleSpinBox(self.parent_widget())
widget.setKeyboardTracking(False)
self.widget = widget | Create the underlying QDoubleSpinBox widget. |
def send_error_json(self, code, message, headers=None):
"send an error to the client. text message is formatted in a json stream"
if headers is None:
headers = {}
self.end_response(HttpResponseJson(code,
{'code': code,
... | send an error to the client. text message is formatted in a json stream |
def add_cmd_handler(self, cmd, func):
len_args = len(inspect.getargspec(func)[0])
def add_meta(f):
def decorator(*args, **kwargs):
f(*args, **kwargs)
decorator.bytes_needed = len_args - 1
decorator.__name__ = f.__name__
return decorator
... | Adds a command handler for a command. |
def _extract(self, raw: str, station: str) -> str:
report = raw[raw.find(station.upper() + ' '):]
report = report[:report.find(' =')]
return report | Extracts the reports message using string finding |
def class_name(obj):
name = obj.__name__
module = getattr(obj, '__module__')
if module:
name = f'{module}.{name}'
return name | Get the name of an object, including the module name if available. |
def _structure_frozenset(self, obj, cl):
if is_bare(cl) or cl.__args__[0] is Any:
return frozenset(obj)
else:
elem_type = cl.__args__[0]
dispatch = self._structure_func.dispatch
return frozenset(dispatch(elem_type)(e, elem_type) for e in obj) | Convert an iterable into a potentially generic frozenset. |
def determine_hostname(display_name=None):
if display_name:
return display_name
else:
socket_gethostname = socket.gethostname()
socket_fqdn = socket.getfqdn()
try:
socket_ex = socket.gethostbyname_ex(socket_gethostname)[0]
except (LookupError, socket.gaierror)... | Find fqdn if we can |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.