code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def create_key(kwargs=None, call=None):
if call != 'function':
log.error(
'The create_key function must be called with -f or --function.'
)
return False
try:
result = query(
method='account',
command='keys',
args={'name': kwargs['na... | Upload a public key |
def _validate(self):
if self._method not in _RANK_METHODS:
raise UnknownRankMethod(
method=self._method,
choices=set(_RANK_METHODS),
)
return super(Rank, self)._validate() | Verify that the stored rank method is valid. |
def run(self):
processes = []
progress_queue = ProgressQueue(Queue())
num_chunks = ParallelChunkProcessor.determine_num_chunks(self.config.upload_bytes_per_chunk,
self.local_file.size)
work_parcels = ParallelChunkProcessor.... | Sends contents of a local file to a remote data service. |
def save(self, *args, **kwargs):
auto_update = kwargs.get('auto_update', True)
if auto_update:
self.updated = now()
if 'auto_update' in kwargs:
kwargs.pop('auto_update')
super(BaseDate, self).save(*args, **kwargs) | automatically update updated date field |
async def _send_sleep(self, request: Request, stack: Stack):
duration = stack.get_layer(lyr.Sleep).duration
await sleep(duration) | Sleep for the amount of time specified in the Sleep layer |
def update(self):
pixels = len(self.matrix)
for x in range(self.width):
for y in range(self.height):
pixel = y * self.width * 3 + x * 3
if pixel < pixels:
pygame.draw.circle(self.screen,
(self.matrix[p... | Generate the output from the matrix. |
def recreate(cls, *args, **kwargs):
cls.check_arguments(kwargs)
first_is_callable = True if any(args) and callable(args[0]) else False
signature = cls.default_arguments()
allowed_arguments = {k: v for k, v in kwargs.items() if k in signature}
if (any(allowed_arguments) or any(arg... | Recreate the class based in your args, multiple uses |
def replaceData(self, offset: int, count: int, string: str) -> None:
self._replace_data(offset, count, string) | Replace data from offset to count by string. |
def interpret(self, msg):
self.captions = msg.get('captions', '.')
for item in msg['slides']:
self.add(item) | Create a slide show |
def _append_message(self, text, char_format):
self._cursor = self._text_edit.textCursor()
operations = self._parser.parse_text(FormattedText(text, char_format))
for i, operation in enumerate(operations):
try:
func = getattr(self, '_%s' % operation.command)
... | Parses text and executes parsed operations. |
def make_valid_string(self, string=''):
if not self.is_valid_str(string):
if string in self.val_map and not self.allow_dups:
raise IndexError("Value {} has already been given to the sanitizer".format(string))
internal_name = super(_NameSanitizer, self).make_valid_string()... | Inputting a value for the first time |
def maybe_start_recording(tokens, index):
if _is_begin_quoted_type(tokens[index].type):
string_type = _get_string_type_from_token(tokens[index].type)
return _MultilineStringRecorder(index, string_type)
return None | Return a new _MultilineStringRecorder when its time to record. |
def display_warning(self, message, short_message,
style=wx.OK | wx.ICON_WARNING):
dlg = GMD.GenericMessageDialog(self.main_window, message,
short_message, style)
dlg.ShowModal()
dlg.Destroy() | Displays a warning message |
def expand_nested(self, cats):
down = '│'
right = '└──'
def get_children(parent):
return [e() for e in parent._entries.values() if e._container == 'catalog']
if len(cats) == 0:
return
cat = cats[0]
old = list(self.options.items())
name = ne... | Populate widget with nested catalogs |
def type_string(self):
if self.is_tuple:
subtypes = [item.type_string for item in self.children]
return '{}({})'.format(
'' if self.val_guaranteed else '*',
', '.join(subtypes))
elif self.is_list:
return '{}[{}]'.format(
... | Returns a string representing the type of the structure |
def visit_continue(self, node, parent):
return nodes.Continue(
getattr(node, "lineno", None), getattr(node, "col_offset", None), parent
) | visit a Continue node by returning a fresh instance of it |
def main():
startLogging(stdout)
checker = InMemoryUsernamePasswordDatabaseDontUse()
checker.addUser("testuser", "examplepass")
realm = AdditionRealm()
factory = CredAMPServerFactory(Portal(realm, [checker]))
reactor.listenTCP(7805, factory)
reactor.run() | Start the AMP server and the reactor. |
def process_column(self, idx, value):
"Process a single column."
if value is not None:
value = str(value).decode(self.encoding)
return value | Process a single column. |
def find_unconstrained_reactions(model):
lower_bound, upper_bound = helpers.find_bounds(model)
return [rxn for rxn in model.reactions if
rxn.lower_bound <= lower_bound and
rxn.upper_bound >= upper_bound] | Return list of reactions that are not constrained at all. |
def viewer_has_liked(self) -> Optional[bool]:
if not self._context.is_logged_in:
return None
if 'likes' in self._node and 'viewer_has_liked' in self._node['likes']:
return self._node['likes']['viewer_has_liked']
return self._field('viewer_has_liked') | Whether the viewer has liked the post, or None if not logged in. |
def count_generated_adv_examples(self):
result = {}
for v in itervalues(self.data):
s_id = v['submission_id']
result[s_id] = result.get(s_id, 0) + len(v['images'])
return result | Returns total number of all generated adversarial examples. |
def _check_pwm_list(pwm_list):
for pwm in pwm_list:
if not isinstance(pwm, PWM):
raise TypeError("element {0} of pwm_list is not of type PWM".format(pwm))
return True | Check the input validity |
def run(self, messages):
statistics = {}
statistics['time'] = str(datetime.now())
statistics['time-utc'] = str(datetime.utcnow())
statistics['unlock'] = self.args.unlock
if self.args.question:
statistics['question'] = [t.name for t in self.assignment.specified_tests]
... | Returns some analytics about this autograder run. |
def fetchUser(self, username, rawResults = False) :
url = "%s/%s" % (self.URL, username)
r = self.connection.session.get(url)
if r.status_code == 200 :
data = r.json()
if rawResults :
return data["result"]
else :
u = User(self, ... | Returns a single user. if rawResults, the result will be a list of python dicts instead of User objects |
def _objectify(items, container_name):
objects = []
for item in items:
if item.get("subdir", None) is not None:
object_cls = PseudoFolder
else:
object_cls = StorageObject
objects.append(object_cls(item, container_name))
return objects | Splits a listing of objects into their appropriate wrapper classes. |
def _init_composite_fields(self):
self.composite_fields = copy.deepcopy(self.base_composite_fields)
self.forms = OrderedDict()
self.formsets = OrderedDict()
for name, field in self.composite_fields.items():
self._init_composite_field(name, field) | Setup the forms and formsets. |
def map_all(self, prot_alignment, nucl_sequences):
zipped = itertools.zip_longest(prot_alignment, nucl_sequences)
for p, n in zipped:
if p is None:
raise ValueError("Exhausted protein sequences")
elif n is None:
raise ValueError("Exhausted nucleoti... | Convert protein sequences to nucleotide alignment |
def population_feature_values(pops, feature):
pops_feature_values = []
for pop in pops:
feature_values = [getattr(neu, 'get_' + feature)() for neu in pop.neurons]
if any([isinstance(p, (list, np.ndarray)) for p in feature_values]):
feature_values = list(chain(*feature_values))
... | Extracts feature values per population |
def build_catalog_info(self, catalog_info):
cat = SourceFactory.build_catalog(**catalog_info)
catalog_info['catalog'] = cat
catalog_info['catalog_table'] = cat.table
catalog_info['roi_model'] =\
SourceFactory.make_fermipy_roi_model_from_catalogs([cat])
catalog_info['s... | Build a CatalogInfo object |
def read(src):
'Event generator from u2 stream.'
parser, buff_agg = Parser(), ''
while True:
buff = parser.read(src)
if not buff: break
buff_agg += buff
while True:
buff_agg, ev = parser.process(buff_agg)
if ev is None: break
yield ev | Event generator from u2 stream. |
def use_loggly(self, enabled=True,
loggly_token=None,
loggly_tag=None,
level=logging.WARNING,
log_format=None,
date_format=None):
if enabled:
if not self.__loggly_handler:
assert loggly_tok... | Enable handler for sending the record to Loggly service. |
def _recursive_reindex_object_security(self, obj):
if hasattr(aq_base(obj), "objectValues"):
for obj in obj.objectValues():
self._recursive_reindex_object_security(obj)
logger.debug("Reindexing object security for {}".format(repr(obj)))
obj.reindexObjectSecurity() | Reindex object security after user linking |
def _complete_sig(self, symbol, attribute):
fncall = self.context.el_name
iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "executables")
if iexec is None:
iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "interfaces")
if ... | Suggests completion for calling a function or subroutine. |
def run_netsh_command(netsh_args):
devnull = open(os.devnull, 'w')
command_raw = 'netsh interface ipv4 ' + netsh_args
return int(subprocess.call(command_raw, stdout=devnull)) | Execute a netsh command and return the output. |
def _number_xpad(self):
js_path = self._device_path.replace('-event', '')
js_chardev = os.path.realpath(js_path)
try:
number_text = js_chardev.split('js')[1]
except IndexError:
return
try:
number = int(number_text)
except ValueError:
... | Get the number of the joystick. |
def delete_vlan_entry(self, vlan_id):
with self.session.begin(subtransactions=True):
try:
self.session.query(ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | Deletes entry for a vlan_id if it exists. |
def count(self, sqlTail = '') :
"Compile filters and counts the number of results. You can use sqlTail to add things such as order by"
sql, sqlValues = self.getSQLQuery(count = True)
return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0]) | Compile filters and counts the number of results. You can use sqlTail to add things such as order by |
def refresh(self):
strawpoll_response = requests.get('{api_url}/{poll_id}'.format(api_url=api_url, poll_id=self.id))
raise_status(strawpoll_response)
self.status_code = strawpoll_response.status_code
self.response_json = strawpoll_response.json()
self.id = self.response_json['id'... | Refresh all class attributes. |
def _get_bank_redis_key(bank):
opts = _get_redis_keys_opts()
return '{prefix}{separator}{bank}'.format(
prefix=opts['bank_prefix'],
separator=opts['separator'],
bank=bank
) | Return the Redis key for the bank given the name. |
def convert_result(converter):
def decorate(fn):
@inspection.wraps(fn)
def new_fn(*args, **kwargs):
return converter(fn(*args, **kwargs))
return new_fn
return decorate | Decorator that can convert the result of a function call. |
def new_section(self, name, params=None):
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
s = self.sections[name.lower()]
if name.lower() in self.decl_sections:
s.args = self.decl_sections[name.lower()]['args']
return s | Return a new section |
def _fill_buffer(self):
if self._all_results_fetched:
self._eof()
raw_results = self.result_fetcher(page=self._page, per_page=self.per_page)
entities = []
for raw in raw_results:
entities.append(self.entity.deserialize(raw, bind_client=self.bind_client))
s... | Fills the internal size-50 buffer from Strava API. |
def ingest(bundle, assets_version, show_progress):
bundles_module.ingest(
bundle,
os.environ,
pd.Timestamp.utcnow(),
assets_version,
show_progress,
) | Ingest the data for the given bundle. |
def result_type(self):
if not hasattr(self, '_result_type'):
self._result_type = conf.lib.clang_getResultType(self.type)
return self._result_type | Retrieve the Type of the result for this Cursor. |
def ask_string(*question: Token, default: Optional[str] = None) -> Optional[str]:
tokens = get_ask_tokens(question)
if default:
tokens.append("(%s)" % default)
info(*tokens)
answer = read_input()
if not answer:
return default
return answer | Ask the user to enter a string. |
def airspeed_voltage(VFR_HUD, ratio=None):
import mavutil
mav = mavutil.mavfile_global
if ratio is None:
ratio = 1.9936
if 'ARSPD_RATIO' in mav.params:
used_ratio = mav.params['ARSPD_RATIO']
else:
used_ratio = ratio
if 'ARSPD_OFFSET' in mav.params:
offset = mav.pa... | back-calculate the voltage the airspeed sensor must have seen |
def delete_service_settings_on_service_delete(sender, instance, **kwargs):
service = instance
try:
service_settings = service.settings
except ServiceSettings.DoesNotExist:
return
if not service_settings.shared:
service.settings.delete() | Delete not shared service settings without services |
async def jsk_in(self, ctx: commands.Context, channel: discord.TextChannel, *, command_string: str):
alt_ctx = await copy_context_with(ctx, channel=channel, content=ctx.prefix + command_string)
if alt_ctx.command is None:
return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found'... | Run a command as if it were in a different channel. |
def _get_bandfilenames(self):
path = self.path
for band in MODIS_BAND_NAMES:
bnum = int(band)
LOG.debug("Band = %s", str(band))
if self.platform_name == 'EOS-Terra':
filename = os.path.join(path,
"rsr.{0:d}.inb.f... | Get the MODIS rsr filenames |
def _dispatch(self, operation, request, path_args):
request_type = resolve_content_type(self.request_type_resolvers, request)
request_type = self.remap_codecs.get(request_type, request_type)
try:
request.request_codec = self.registered_codecs[request_type]
except KeyError:
... | Wrapped dispatch method, prepare request and generate a HTTP Response. |
def validate(self, node):
assert isinstance(node, Node)
if isinstance(node.operator, Logical):
self.validate(node.left)
self.validate(node.right)
return
assert isinstance(node.left, Name)
assert isinstance(node.operator, Comparison)
assert isin... | Validate DjangoQL AST tree vs. current schema |
def _accumulate_remotes(synapse_parent_id, syn):
remotes = {}
s_base_folder = syn.get(synapse_parent_id)
for (s_dirpath, s_dirpath_id), _, s_filenames in synapseutils.walk(syn, synapse_parent_id):
remotes[s_dirpath] = s_dirpath_id
if s_filenames:
for s_filename, s_filename_id in ... | Retrieve references to all remote directories and files. |
def u_string_check(self, original, loc, tokens):
return self.check_strict("Python-2-style unicode string", original, loc, tokens) | Check for Python2-style unicode strings. |
def words_from_archive(filename, include_dups=False, map_case=False):
bz2 = os.path.join(PATH, BZ2)
tar_path = '{}/{}'.format('words', filename)
with closing(tarfile.open(bz2, 'r:bz2')) as t:
with closing(t.extractfile(tar_path)) as f:
words = re.findall(RE, f.read().decode(encoding='utf... | extract words from a text file in the archive |
def _prepare_resources(self, variables, overrides=None):
if overrides is None:
overrides = {}
res_map = {}
own_map = {}
for decl in self.resources.values():
resource = overrides.get(decl.name)
if resource is None:
args = _complete_param... | Create and optionally open all shared resources. |
def getRandomPairwiseAlignment():
i, j, k, l = _getRandomSegment()
m, n, o, p = _getRandomSegment()
score = random.choice(xrange(-1000, 1000))
return PairwiseAlignment(i, j, k, l, m, n, o, p, score, getRandomOperationList(abs(k - j), abs(o - n))) | Gets a random pairwiseAlignment. |
def cancel(self):
target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id})
r = self._client.request('DELETE', target_url)
logger.info("cancel(): %s", r.status_code) | Cancel a pending publish task |
async def _run_socket(self):
try:
while True:
message = await ZMQUtils.recv(self._socket)
msg_class = message.__msgtype__
if msg_class in self._handlers_registered:
self._loop.create_task(self._handlers_registered[msg_class](message... | Task that runs this client. |
def publish_properties(self):
publish = self.publish
publish(b"$homie", b"3.0.1")
publish(b"$name", self.settings.DEVICE_NAME)
publish(b"$state", b"init")
publish(b"$fw/name", b"Microhomie")
publish(b"$fw/version", __version__)
publish(b"$implementation", bytes(sy... | publish device and node properties |
def profile(script, argv, profiler_factory,
pickle_protocol, dump_filename, mono):
filename, code, globals_ = script
sys.argv[:] = [filename] + list(argv)
__profile__(filename, code, globals_, profiler_factory,
pickle_protocol=pickle_protocol, dump_filename=dump_filename,
... | Profile a Python script. |
def _open_browser(self, single_doc_html):
url = os.path.join('file://', DOC_PATH, 'build', 'html',
single_doc_html)
webbrowser.open(url, new=2) | Open a browser tab showing single |
def _get_ssl_sock(self):
assert self.scheme == u"https", self
raw_connection = self.url_connection.raw._connection
if raw_connection.sock is None:
raw_connection.connect()
return raw_connection.sock | Get raw SSL socket. |
def extras_msg(extras):
if len(extras) == 1:
verb = "was"
else:
verb = "were"
return ", ".join(repr(extra) for extra in extras), verb | Create an error message for extra items or properties. |
def pypy_json_encode(value, pretty=False):
global _dealing_with_problem
if pretty:
return pretty_json(value)
try:
_buffer = UnicodeBuilder(2048)
_value2json(value, _buffer)
output = _buffer.build()
return output
except Exception as e:
from mo_logs import L... | pypy DOES NOT OPTIMIZE GENERATOR CODE WELL |
def plot(self, minx=-1.5, maxx=1.2, miny=-0.2, maxy=2, **kwargs):
import matplotlib.pyplot as pp
grid_width = max(maxx-minx, maxy-miny) / 200.0
ax = kwargs.pop('ax', None)
xx, yy = np.mgrid[minx:maxx:grid_width, miny:maxy:grid_width]
V = self.potential(xx, yy)
if ax is No... | Helper function to plot the Muller potential |
def context_factory(apply_globally=False, api=None):
def decorator(context_factory_):
if apply_globally:
hug.defaults.context_factory = context_factory_
else:
apply_to_api = hug.API(api) if api else hug.api.from_object(context_factory_)
apply_to_api.context_factor... | A decorator that registers a single hug context factory |
def startLoop(self, useDriverLoop):
if useDriverLoop:
self._driver.startLoop()
else:
self._iterator = self._driver.iterate() | Called by the engine to start an event loop. |
def focus_first_reply(self):
mid = self.get_selected_mid()
newpos = self._tree.first_child_position(mid)
if newpos is not None:
newpos = self._sanitize_position((newpos,))
self.body.set_focus(newpos) | move focus to first reply to currently focussed message |
def extension_by_source(source, mime_type):
"Return the file extension used by this plugin"
extension = source.plugin_name
if extension:
return extension
if mime_type:
return mime_type.split("/")[-1] | Return the file extension used by this plugin |
def dag(self) -> Tuple[Dict, Dict]:
from pipelines import dags
operations = self.operations.all().prefetch_related('downstream_operations')
def get_downstream(op):
return op.downstream_operations.values_list('id', flat=True)
return dags.get_dag(operations, get_downstream) | Construct the DAG of this pipeline based on the its operations and their downstream. |
def error_handler(f):
@wraps(f)
def decorated(*args, **kwargs):
try:
return f(*args, **kwargs)
except OAuth2Error as e:
if hasattr(e, 'redirect_uri'):
return redirect(e.in_uri(e.redirect_uri))
else:
return redirect(e.in_uri(oaut... | Handle uncaught OAuth errors. |
def new_parallel(self, function, *params):
if self.ppool is None:
if core_type == 'thread':
from multiprocessing.pool import ThreadPool
self.ppool = ThreadPool(500)
else:
from gevent.pool import Pool
self.ppool = Pool(500)
... | Register a new thread executing a parallel method. |
def unset(self, section, option):
with self._lock:
if not self._config.has_section(section):
return
if self._config.has_option(section, option):
self._config.remove_option(section, option)
self._dirty = True
if not self._config.... | Remove option from section. |
def act(self):
g = get_root(self).globals
fname = filedialog.askopenfilename(
defaultextension='.json',
filetypes=[('json files', '.json'), ('fits files', '.fits')],
initialdir=g.cpars['app_directory'])
if not fname:
g.clog.warn('Aborted load from ... | Carries out the action associated with the Load button |
def add_summaries(self, step, *tags_and_values):
values = []
to_print = []
for tag, value in tags_and_values:
values.append(tf.Summary.Value(tag=tag, simple_value=float(value)))
to_print.append('%s=%g' % (tag, value))
if self._summary_writer:
summary = tf.Summary(value=values)
ev... | Adds summaries to the writer and prints a log statement. |
def update_main_table(self):
data = (json.dumps(self.settings),)
self.cursor.execute(
)
self.cursor.execute('SELECT * FROM main')
if self.cursor.fetchall() == []:
self.cursor.execute('INSERT INTO main (settings) VALUES (?)', data)
else:
self.cursor.execute... | Write generator settings to database. |
def fulltext_add(self, index, docs):
xml = Document()
root = xml.createElement('add')
for doc in docs:
doc_element = xml.createElement('doc')
for key in doc:
value = doc[key]
field = xml.createElement('field')
field.setAttri... | Adds documents to the search index. |
def cds(self):
ces = self.coding_exons
if len(ces) < 1: return ces
ces[0] = (self.cdsStart, ces[0][1])
ces[-1] = (ces[-1][0], self.cdsEnd)
assert all((s < e for s, e in ces))
return ces | just the parts of the exons that are translated |
def find_bled112_devices(cls):
found_devs = []
ports = serial.tools.list_ports.comports()
for port in ports:
if not hasattr(port, 'pid') or not hasattr(port, 'vid'):
continue
if port.pid == 1 and port.vid == 9304:
found_devs.append(port.dev... | Look for BLED112 dongles on this computer and start an instance on each one |
def s3(self, url, account_acessor=None, access=None, secret=None):
from ambry.util.ambrys3 import AmbryS3FS
from ambry.util import parse_url_to_dict
import ssl
pd = parse_url_to_dict(url)
if account_acessor:
account = account_acessor(pd['hostname'])
assert... | Setup an S3 pyfs, with account credentials, fixing an ssl matching problem |
def shell(command, *args):
if args:
command = command.format(*args)
print LOCALE['shell'].format(command)
try:
return subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError, ex:
return ex | Pass a command into the shell. |
def get(name, import_str=False):
value = None
default_value = getattr(default_settings, name)
try:
value = getattr(settings, name)
except AttributeError:
if name in default_settings.required_attrs:
raise Exception('You must set ' + name + ' in your settings.')
if isinstan... | Helper function to use inside the package. |
def _get_window_list(self):
window_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID)
return window_list | Returns a dictionary of details about open windows |
def cases(self):
import nitrate
if self._cases is None:
log.info(u"Searching for cases created by {0}".format(self.user))
self._cases = [
case for case in nitrate.TestCase.search(
author__email=self.user.email,
create_date__... | All test cases created by the user |
def load(self, filething):
fileobj = filething.fileobj
self.metadata_blocks = []
self.tags = None
self.cuesheet = None
self.seektable = None
fileobj = StrictFileObject(fileobj)
self.__check_header(fileobj, filething.name)
while self.__read_metadata_block(f... | Load file information from a filename. |
def registerAPI(self, name, handler, container = None, discoverinfo = None, criteria = None):
self.handler.registerHandler(*self._createHandler(name, handler, container, criteria))
if discoverinfo is None:
self.discoverinfo[name] = {'description': cleandoc(handler.__doc__)}
else:
... | Append new API to this handler |
def start(self):
msg = ''
if not self.running():
if self._port == 0:
self._port = _port_not_in_use()
self._process = start_server_background(self._port)
else:
msg = 'Server already started\n'
msg += 'Server running at {}'.format(self.ur... | Start server if not previously started. |
def transformer_tall_pretrain_lm_tpu():
hparams = transformer_tall_pretrain_lm_tpu_adafactor()
hparams.learning_rate_constant = 2e-4
hparams.learning_rate_schedule = ("linear_warmup * constant * cosdecay")
hparams.optimizer = "adam_w"
return hparams | Hparams for transformer on LM pretraining on TPU with AdamW. |
def server_by_name(self, name):
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
) | Find a server by its name |
def Parse(self, stat, unused_knowledge_base):
value = stat.registry_data.GetValue()
if not str(value).isdigit() or int(value) > 999 or int(value) < 0:
raise parser.ParseError(
"Invalid value for CurrentControlSet key %s" % value)
yield rdfvalue.RDFString(
"HKEY_LOCAL_MACHINE\\SYSTEM\... | Parse the key currentcontrolset output. |
def _set_or_check_remote_id(self, remote_id):
if not self.remote_id:
assert self.closed_state == self.ClosedState.PENDING, 'Bad ClosedState!'
self.remote_id = remote_id
self.closed_state = self.ClosedState.OPEN
elif self.remote_id != remote_id:
raise usb_exceptions.AdbProtocolError(
... | Set or check the remote id. |
def google_get_token(self, config, prefix):
params = {
'code': self.request_args_get(
'code',
default=''),
'client_id': self.google_api_client_id,
'client_secret': self.google_api_client_secret,
'redirect_uri': self.scheme_host_port... | Make request to Google API to get token. |
def create_event(self, timestamp, event_type, hostname, fields, tags=None):
event_payload = fields._asdict()
msg_text = {
'event_type': event_payload.pop('event_type', None),
'event_soft_hard': event_payload.pop('event_soft_hard', None),
'check_name': event_payload.po... | Factory method called by the parsers |
def parse_cl_args(arg_vector):
parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js')
parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory are compiled. Output is saved in the curr... | Parses the command line arguments |
def _create_index(self):
if not self.index_exists:
index_settings = {}
headers = {'Content-Type': 'application/json', 'DB-Method': 'POST'}
url = '/v2/exchange/db/{}/{}'.format(self.domain, self.data_type)
r = self.tcex.session.post(url, json=index_settings, header... | Create index if it doesn't exist. |
def _handle_tag_defineshape(self):
obj = _make_object("DefineShape")
obj.ShapeId = unpack_ui16(self._src)
obj.ShapeBounds = self._get_struct_rect()
obj.Shapes = self._get_struct_shapewithstyle(1)
return obj | Handle the DefineShape tag. |
def _initialize_tables(self):
self.table_struct, self.idnt_struct_size = self._create_struct_table()
self.table_values, self.idnt_values_size = self._create_values_table() | Create tables for structure and values, word->vocabulary |
def __get_idxs(self, words):
if self.bow:
return list(itertools.chain.from_iterable(
[self.positions[z] for z in words]))
else:
return self.positions[words] | Returns indexes to appropriate words. |
def pssm_array2pwm_array(arr, background_probs=DEFAULT_BASE_BACKGROUND):
b = background_probs2array(background_probs)
b = b.reshape([1, 4, 1])
return (np.exp(arr) * b).astype(arr.dtype) | Convert pssm array to pwm array |
def isasteroid(self):
if self.asteroid is not None:
return self.asteroid
elif self.comet is not None:
return not self.comet
else:
return any(self.parse_asteroid()) is not None | `True` if `targetname` appears to be an asteroid. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.