content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_check_app_table_3(switch):
"""Test check_app_table function negative.
"""
apps = switch.fake_server.applications
switch.fake_server.applications = [{'name': 'SimSwitchApp', 'logLevel': 'test level', 'adminState': 'Run', 'appId': 2, 'operationalState': 'Run'},
... | 5,289,000 |
def validate_noise_probabilities(noise_parameter: Optional[Tuple[float, float, float]]) -> None:
"""
Is noise_parameter a valid specification of noise probabilities for depolarizing noise?
:param tuple noise_parameter: Tuple of 3 noise parameter values to be validated.
"""
if not noise_parameter:
... | 5,289,001 |
def get_workspace(strOrigPath, strType_='flatten', strSuff_=''):
""" Return TDIS working (flatten) path given TDIS path. """
if os.path.split(strOrigPath)[1].startswith('TDISm__'):
strScene = strOrigPath.split(os.sep)[-4].split('_')[0]
p, f = os.path.split(strOrigPath)
strWorkPath =... | 5,289,002 |
def creation_validation(vca_client, **kwargs):
"""
validate node context,
fields from floatingip dict:
* edge_gateway - mandatory,
* public_ip - prefered ip for node, can be empty
fields from vcloud_config:
* service_type - ondemand, subscription
also check av... | 5,289,003 |
def test_multi_files():
"""
Reading multiple files at once.
"""
uv_full = UVData()
uvfits_file = os.path.join(DATA_PATH, 'day2_TDEM0003_10s_norx_1src_1spw.uvfits')
testfile1 = os.path.join(DATA_PATH, 'test/uv1')
testfile2 = os.path.join(DATA_PATH, 'test/uv2')
uvtest.checkWarnings(uv_full... | 5,289,004 |
def _update_firewall(br_label):
"""gets the FORWARD iptable and remove all entries which contain 'br_label'
"""
if _is_firewall_running():
rmv = []
fwd_tbl, err, rc = sub_proc_exec('iptables -nvL FORWARD --line-numbers')
for line in fwd_tbl.splitlines():
if br_label in li... | 5,289,005 |
def remove_dist_img():
"""Remove image from dist measure
1. find dist measure by id, if not found return error msg
2. remove image url from DB
3. return the removed image url as response
"""
# Extract dut_id and img_url from request
dut_id = request.json["dut_id"]
img_url = request.json... | 5,289,006 |
def eval_math(math, compiled_math, workspace):
""" Compile a mathematical expression
Args:
math (:obj:`str`): mathematical expression
compiled_math (:obj:`_ast.Expression`): compiled expression
workspace (:obj:`dict`): values to use for the symbols in the expression
Returns:
... | 5,289,007 |
def LF_CD_PARENTHETICAL_DESC(c):
"""
This label function looks for mentions that are in paranthesis.
Some of the gene mentions are abbreviations rather than names of a gene.
"""
if ")" in c[1].get_span() and "(" in list(get_left_tokens(c[1], window=1)):
if LF_CD_DISTANCE_SHORT(c):
... | 5,289,008 |
def select_rect(action, select_add, screen, screen2):
"""Select units within a rectangle."""
select = action.action_feature_layer.unit_selection_rect
out_rect = select.selection_screen_coord.add()
screen_rect = point.Rect(screen, screen2)
screen_rect.tl.assign_to(out_rect.p0)
screen_rect.br.assign_to(out_re... | 5,289,009 |
def _declare_clang_library_target_files(
ctx,
target,
build_config_path,
clang_custom_info):
"""Declares the outputs for a clang module and returns a struct value describing the clang module.
Args:
ctx: A `ctx` instance.
target: A target `dict` from the package d... | 5,289,010 |
def is_pandas_df(obj):
"""Check if an object is a Pandas dataframe
The benefit here is that Pandas doesn't have to be included
in the dependencies for pydeck
The drawback of course is that the Pandas API might change and break this function
"""
return obj.__class__.__module__ == 'pandas.core.f... | 5,289,011 |
async def add_reviewers(
gh: gidgethub.abc.GitHubAPI, reviewers_to_add: Iterable[str]
) -> None:
"""Add reviewers to a PR."""
event = gidgethub.actions.event()
await gh.post(
"/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers",
url_vars={
"owner": event["repositor... | 5,289,012 |
def dynamic_range_input():
"""
Input: list of all consensus peak files
Method: Loop through each consensus file. Define method,condition,mark.
Method: Use method,condition,mark to glob relevant bam file pairs.
Output: One consensus file with one BAM file. Their condition,mark must match,
Output:... | 5,289,013 |
def collect_vcard_names(vcard):
""" Collect all vcard possible names in fields 'fn', 'n' and 'email' """
if not isinstance(vcard, Component):
raise TypeError("parameter 'vcard' must be a vobject.base.Component (type: '" + str(type(vcard)) + "')")
# collect names
logging.debug("\tcollecting name... | 5,289,014 |
def time(days=0, seconds=0, minutes=0, hours=0, **kwargs):
""" Returns a Time that can be added to a Date object.
Other parameters: microseconds, milliseconds, weeks, months, years.
"""
return Time(days=days, seconds=seconds, minutes=minutes, hours=hours, **kwargs) | 5,289,015 |
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
# output: [B, d]
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
# pred: [B, len(topk)] -> [len(topk), B]
# target.reshape(1, -1)... | 5,289,016 |
def password_login(request):
"""
客户端用户使用密码登录
:param request:
:return:
"""
print('api:password_login')
if request.session.get(USER_SESSION_KEY):
print("###api:password_login request.session.session_key已经存在: ", request.session.session_key)
return fail(ResultCode.COMMONERR, "失败:... | 5,289,017 |
def article_image(instance, file_name):
"""
Fonction pour générer le chemin des images des articles
Récupère l'instance et affecte la valeur à une variable avec la propriété "pk" et "title" de l'instance si elle
est disponible, sinon affecte un UUID généré, puis retourne la variable
... | 5,289,018 |
def test_optional_attrs():
"""Test loading optional GO term field, 'synonym'."""
args = set(sys.argv[1:])
prt = sys.stdout if 'prt' in args else None
exit_if_warning = 'die' in args
# Summary for all fields in a GO DAG
opt_attrs = ['def', 'comment', 'subset', 'synonym', 'xref', 'relationship']
... | 5,289,019 |
def patch_cmdline_parser():
"""
Patches the ``luigi.cmdline_parser.CmdlineParser`` to store the original command line arguments
for later processing in the :py:class:`law.config.Config`.
"""
# store original functions
_init = luigi.cmdline_parser.CmdlineParser.__init__
# patch init
def ... | 5,289,020 |
def gen_node_color_map(table_column,
palette = {'d': palette_color_brewer_q_Set2(),
'c': (palette_color_brewer_s_GnBu(), palette_color_brewer_d_RdYlBu())},
mapping_type='c',
default_color=None,
... | 5,289,021 |
def unpack_qubit(qubit):
"""
Get a qubit from an object.
:param qubit: An int or Qubit.
:return: A Qubit instance
"""
if isinstance(qubit, integer_types):
return Qubit(qubit)
elif isinstance(qubit, Qubit):
return qubit
elif isinstance(qubit, QubitPlaceholder):
re... | 5,289,022 |
def solve(f, x0):
"""
Solve the equation f(x) = x using a fixed point iteration. x0 is the start value.
"""
x = x0
for n in range(10000): # at most 10000 iterations
oldX = x;
x = f(x);
if abs(x - oldX) < 1.0e-15:
return x; | 5,289,023 |
def save(filename, data):
"""Saves the result data to the given a json file.
Overwrites the file if it already exists.
Args:
filename: The name of the output file.
data: An instance of `Result`.
"""
log.debug(f'Saving data to {filename}', data)
def convert(d):
if isins... | 5,289,024 |
def mi_estimate(y_real, gen, enc, masks, k, batch_size, z_dim, s_dim,
z_trans = None):
"""Estimates the MI of the encoder.
Args:
y_real: s_I
gen: generator, (z -> x^)
enc: encoder, (x^ -> dist(z^))
masks: for sampling z_\I from the prior
k: number of samples to estim... | 5,289,025 |
def create_app():
"""Construct core Flask application with embedded Dash app."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.Config')
with app.app_context():
# Import Flask routes
from application import reaction
# Import Dash applicati... | 5,289,026 |
def _transformer_configs(c: Configs):
"""
### Transformer configurations
"""
# We use our
# [configurable transformer implementation](../configs.html#TransformerConfigs)
conf = TransformerConfigs()
# Set the vocabulary sizes for embeddings and generating logits
conf.n_src_vocab = c.n_to... | 5,289,027 |
def te_diff_template(ruletype):
"""
This is a template for the type_* diff functions.
Parameters:
ruletype The rule type, e.g. "type_transition".
"""
def diff(self):
"""Generate the difference in rules between the policies."""
self.log.info(
"Generating {0} dif... | 5,289,028 |
def normalize(v1, Rmin=1.0e-8, Rmax=1.0e15):
"""
Do not normalize in place. Not supported in autograd
"""
n = norm(v1)
if n < Rmin or n > Rmax:
print('vector:', v1)
print('norm:', n)
raise Exception("Could not normalize vector. Vector norm beyond tolerance")
else:
... | 5,289,029 |
def run(*args):
"""Load given `envfile` and run `command` with `params`"""
if not args:
args = sys.argv[1:]
if len(args) < 2:
print('Usage: runenv <envfile> <command> <params>')
sys.exit(0)
os.environ.update(create_env(args[0]))
os.environ['_RUNENV_WRAPPED'] = '1'
runna... | 5,289,030 |
def find_version() -> str:
"""Only define version in one place."""
version_file = read_file("__init__.py")
version_match = re.search(r'^__version__ = ["\']([^"\']*)["\']', version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.") | 5,289,031 |
def p2_allocateByScore(CCA, nameCat, quota, rank, scorelist, final_dic, CCA_dic):
"""
Allocates students to cca where applicants exceed quota
Returns the final dictionaries
"""
cat = ""
for key, value in nameCat.items(): #theoretically it will all be the same anyway
cat = value
... | 5,289,032 |
def test_search_queries_for_replies(query):
"""It should do a second query for replies to the results of the first."""
request = dummy_request()
# Mock the Builder objects that Builder() returns.
builder = mock.Mock()
query.Builder.side_effect = [
mock.Mock(), # We don't care about the fir... | 5,289,033 |
def test_example_app(example_app):
"""Test example app."""
# Testing get index page
cmd = 'curl http://127.0.0.1:5000/'
output = subprocess.check_output(cmd, shell=True).decode("utf-8")
expected = '\nToday is {0}\n<img src="/badge/DOI/invenio.12345.svg">' \
'</img>\nInvenio will not be hacke... | 5,289,034 |
def _total_solves(color_info):
"""
Return total number of linear solves required based on the given coloring info.
Parameters
----------
color_info : dict
dict['fwd'] = (col_lists, row_maps)
col_lists is a list of column lists, the first being a list of uncolored columns.
... | 5,289,035 |
def generat_int_pop(n_particles,n_vars,low_bounds,up_bounds):
"""
Generate initial population function.
Here, random values between the lower and the higer bounds are defined for the initial population:
x1^j = rand[xlb^j, xub^j]
Parameters:
n_particles: int
Number of partic... | 5,289,036 |
def parse_options():
"""Parses command line options"""
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", help="Output file name (e.g oui.h)")
parser.add_argument("-u", "--url", help="Wireshark oui/manuf file url")
opt = parser.parse_args()
return opt | 5,289,037 |
def gettext(msg, domain='python-apt'): # real signature unknown; restored from __doc__
"""
gettext(msg: str[, domain: str = 'python-apt']) -> str
Translate the given string. This is much faster than Python's version
and only does translations after setlocale() has been called.
"""
return "" | 5,289,038 |
def folder_create(strFolderPath=""):
"""
while making leaf directory if any intermediate-level directory is missing,
folder_create() method will create them all.
Parameters:
folderPath (str) : path to the folder where the folder is to be created.
For example consider the following ... | 5,289,039 |
def as_sparse_or_tensor_variable(x, name=None):
"""
If we can't make a sparse variable, we try to make a tensor variable.
"""
try:
return as_sparse_variable(x,name)
except (ValueError, TypeError):
return theano.tensor.as_tensor_variable(x,name) | 5,289,040 |
def freeze(slug):
"""
Prevent a builder from updating it's source code to a newer version.
The software will still be re-built if it's dependants are upated.
"""
freeze_file = settings.get('install_path') + 'etc/build-freeze'
return file_filter.AppendUnique(freeze_file, slug).run() | 5,289,041 |
def get_compressor(alg):
"""Return an instance of a compressor
This function returns an object that can be used for data compression.
"""
return _cmp_compressors[alg]() | 5,289,042 |
def confirm(self, speech, timeout):
"""
Start the view 'confirm'
:param speech: the text that will be use by the Local Manager for tablet and vocal
:type speech: dict
:param timeout: maximum time to wait for a reaction from the local manager
:type timeout: float
"""
goal = RequestToLoca... | 5,289,043 |
def generateAdjMatrix(edgeJsonList, sent_len):
""" Function to generate Adjacency matrix from Depedency Parse Tree """
sparseAdjMatrixPos = [[], [], []]
sparseAdjMatrixValues = []
deptags = []
gov_words = [0] * sent_len
adjMatrix = [0] * sent_len
for i in range(sent_len):
adjMa... | 5,289,044 |
def assert_no_duplicate_router_ids(
snapshot=None,
nodes=None,
protocols=None,
soft=False,
session=None,
df_format="table",
):
# type: (Optional[str], Optional[str], Optional[List[str]], bool, Optional[Session], str) -> bool
"""Assert that there are no duplicate router IDs present in the... | 5,289,045 |
def __find_position_for_conclusion_of_argument(current_arg, list_todos, list_dones, positions):
"""
:param current_arg: Argument
:param list_todos: List of Arguments
:param list_dones: List of Argument.uids
:param positions: List of Statements - return value
:return:
"""
a = [arg.uid fo... | 5,289,046 |
def test_full_uri_protocol_lifecycle():
"""Exercises the following endpoints:
* preconnect
* connect
* shutdown
"""
initialize_agent(
app_name='Python Agent Test (test_full_uri_payloads)',
default_settings=_default_settings)
environment = ()
linked_apps = []
sessio... | 5,289,047 |
def de_bruijn(alphabet: bytes, n: int) -> Generator[str, None, None]:
"""De Bruijn sequence for alphabet and subsequences of length n (for compat. w/ pwnlib)."""
k = len(alphabet)
a = [0] * k * n
def db(t: int, p: int) -> Generator[str, None, None]:
if t > n:
if n % p == 0:
... | 5,289,048 |
def variable_creator_scope_v1(variable_creator):
"""Scope which defines a variable creation function to be used by variable().
variable_creator is expected to be a function with the following signature:
```
def variable_creator(next_creator, **kwargs)
```
The creator is supposed to eventually call the ... | 5,289,049 |
def writexl_alt_getsheetref(path_wbrels, path_wb):
"""
Takes a file path for '/xl/_rels/workbook.xml.rels' and '/xl/workbook.xml' files
and returns a dictionary relationship between sheetID, name and xml worksheet file path
rId: xml's indexing between files (workbook.xml.rels defined rID to xml ... | 5,289,050 |
def createPattern(string):
"""Cria um padrão de comandos de bot."""
return re.compile(f"/{string}|{string}") | 5,289,051 |
def miner_predictions():
"""
Returns a Model Template Prediction Status screen
:return: HTML Template for Model Prediction Status
"""
logger.debug("/predictions - remote addr:" + request.remote_addr)
# render the template
return render_template('predictions.html', version='0.0') | 5,289,052 |
def gnomad_filtered_func(raw_value):
""" We use FILTER in Gnomad3 (GRCh38 only) - need to convert back to bool """
return raw_value not in (None, "PASS") | 5,289,053 |
def parse(html_bytes: bytes, *args, **kwargs) -> BeautifulSoup:
"""Convenience method for ``ZimHtmlParser(html_text).simplify()``."""
return ZimHtmlParser(html_bytes, *args, **kwargs).simplify() | 5,289,054 |
def register(name):
"""Registers a new logs preprocessor function under the given name."""
def add_to_dict(func):
_PREPROCESSORS[name] = func
return func
return add_to_dict | 5,289,055 |
def _gather_proto_info_from_repo(repo):
"""Gathers all protos from the given repo.
Args:
* repo (RecipeRepo) - The repo to gather all protos from.
Returns List[_ProtoInfo]
"""
# Tuples of
# * fwd-slash path relative to repo.path of where to look for protos.
# * fwd-slash namespace prefix of wher... | 5,289,056 |
def load_darwin_common_settings(conf):
"""
Setup all compiler and linker settings shared over all darwin configurations
"""
v = conf.env
# Setup common defines for darwin
v['DEFINES'] += [ 'APPLE', 'MAC', '__APPLE__', 'DARWIN' ]
# This avoid the SDK to add defines for certain macros tha... | 5,289,057 |
def nodes_constructed():
"""
A contextmanager that is used in inherit_stack_trace and keeps track
of all the newly created varaible nodes inside an optimization. A list
of new_nodes is instantiated but will be filled in a lazy manner (when
Variable.notify_construction_observers is called).
`ob... | 5,289,058 |
def path2str(x):
"""Recursively convert pathlib objects to strings to enable serialization"""
for key, val in x.items():
if isinstance(val, dict):
path2str(val)
elif isinstance(val, Path):
x[key] = str(val) | 5,289,059 |
def print_matrix(mat, path=None):
"""Prints the matrix, also with the path through is (if specified)"""
path_set = set(path) if path is not None else None
dims = mat.shape
for i in range(dims[0] - 1, -1, -1):
for j in range(dims[1]):
s = str(mat[i][j])
if path_set is not ... | 5,289,060 |
def load(req, *opts):
"""
General-purpose resource fetcher.
:param req: The request
:param opts: Options: See "Options" below
:return: None
Supports both remote and local resources. Fetching remote resources is done in parallel using threads.
Note: When downloading remote files over HTTPS the TLS ser... | 5,289,061 |
def csv_parse(csv_file, ifilter, tfilter, nfilter, list):
"""
Function for parsing CSV files created by DNSRecon and apply filters.
"""
iplist = []
reader = csv.reader(open(csv_file, 'r'), delimiter=',')
reader.next()
for row in reader:
# Check if IP is in the filter list of addresse... | 5,289,062 |
def _project_z(z, project_method='clip'):
"""To be used for projected gradient descent over z."""
if project_method == 'norm':
z_p = torch.nn.functional.normalize(z, p=2, dim=-1)
#elif project_method == 'clip': #not reimplemented yet
# z_p = tf.clip_by_value(z, -1, 1)
else:
raise ValueError('Unknown ... | 5,289,063 |
def calc_save_property(struct_dir, motif_kwargs={}, output_dir='', overwrite=False):
"""
Adds motif to the property information of each Structure
Arguments
---------
struct_dir: file path
motif_kwargs: see compute_motif
output_dir: file path
If no output_dir is provided tha... | 5,289,064 |
def accumulate(iterator):
"""
Notice:
use itertools.accumulate in python > 3.2
"""
total = 0
for item in iterator:
total += item
yield total | 5,289,065 |
def test():
"""check entropy estimates from known distributions"""
# entropy test is optional: don't test if sklearn is not installed
try:
import sklearn
except ImportError:
return
# Smoke test - do all the methods run in 1-D and 10-D?
_check_smoke(stats.norm(10, 8))
if hasa... | 5,289,066 |
def __dirnames_matching_format(dirnames, format):
"""
Iterates through dirnames and returns a sorted array of directory names
that match the provided format.
"""
matching_dates = []
for dirname in dirnames:
try:
dt = datetime.strptime(dirname, format)
if dt is not... | 5,289,067 |
def solve(s):
"""doc"""
return "".join([w.capitalize() for w in re.split(r"(\W+)", s)]) | 5,289,068 |
def marco_china_hk_trade_diff_ratio() -> pd.DataFrame:
"""
东方财富-经济数据一览-中国香港-香港商品贸易差额年率
https://data.eastmoney.com/cjsj/foreign_8_7.html
:return: 香港商品贸易差额年率
:rtype: pandas.DataFrame
"""
url = "https://datainterface.eastmoney.com/EM_DataCenter/JS.aspx"
params = {
"type": "GJZB",
... | 5,289,069 |
def make_default_sim_env(
interface: Optional[GymTrainedInterface] = None,
) -> CustomSimEnv:
""" A simulator environment with the following characteristics:
The action and observation spaces are continuous.
An action in this environment is a pilot signal for each EVSE,
within the minimum and maxi... | 5,289,070 |
def make_dummy_1d_cube(job_n=0):
"""
Makes a dummy 1d cube filled with dummy data. It has a scalar job coordinate
to make ensemble stacking convenient
"""
from iris.cube import Cube
from iris.coords import DimCoord
x = np.arange(100)
y = np.sin(x) * np.cos(x + 0.3)
obs = DimCoord(x... | 5,289,071 |
def _serve(war_file = None):
""" Launch a SimpleHTTPServer listener to serve up our WAR file
to the requesting host. This is used primarily to serve a WAR
to JBoss' jmx_deployer.
If war_file is provided, this will make a copy of this file into
our temp dir and remove it once its been completed.
... | 5,289,072 |
def edit_delivery(request, delivery):
"""Edit a delivery as a full network admin: act upon its lifecycle, control which subgroups have been validated,
change the products characteristics, change other users' orders."""
dv = m.Delivery.objects.get(id=delivery)
if dv.network.staff.filter(id=request.user.i... | 5,289,073 |
async def call(args: Dict[str, Any], cromwell: api.CromwellAPI) -> None:
"""Execute the subcommand.
Args:
args (Dict): Arguments parsed from the command line.
"""
output_folder = args.get("root-output-folder", "")
workflows = []
if args.get("workflow"):
workflows = await _work... | 5,289,074 |
def download_and_depcapize(url: str, out_dir: str, keep_pcaps: bool = False, ignore_exts: bool = False,
skip_analysis: bool = False) -> None:
"""
Downloads to a tmp folder inside the given folder (./pcap_tmp) and then parses each pcap to a text file
:param url: the page to crawl (... | 5,289,075 |
def print_bullets(lines: List[str]) -> None:
"""
Display a list of text as bullet points.
Args:
lines: List of texts
Returns:
None
"""
bullet_points = "\n".join(f"- `{line}`" for line in sorted(lines))
print_markdown(bullet_points) | 5,289,076 |
def test_mean_stdev():
"""Test calcualtion of the sigma-clipped mean from an image"""
image = np.zeros((50, 50)) + 1.
badx = [1, 4, 10, 14, 16, 20, 22, 25, 29, 30]
bady = [13, 27, 43, 21, 1, 32, 25, 21, 9, 14]
for x, y in zip(badx, bady):
image[y, x] = 100.
meanval, stdval = calculatio... | 5,289,077 |
def get_fields_by_name(model_cls, *field_names):
"""Return a dict of `models.Field` instances for named fields.
Supports wildcard fetches using `'*'`.
>>> get_fields_by_name(User, 'username', 'password')
{'username': <django.db.models.fields.CharField: username>,
'password': <django.d... | 5,289,078 |
def create_input_file(inp_dir, pp_tag):
"""Generates input file for two-particle test"""
sim_inp_dir = str(inp_dir)
## R1 - bottom R2 - top
center = [0., 0., 0.]
R1 = 0.0015
R2 = 0.001
mesh_size = R1 / 10.
if R2 < R1:
mesh_size = R2 / 10.
horizon = 3. * mesh_size
particle_dist = 0.0004
... | 5,289,079 |
def pyramidnet110_a84_svhn(num_classes=10, **kwargs):
"""
PyramidNet-110 (a=84) model for SVHN from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915.
Parameters:
----------
num_classes : int, default 10
Number of classification classes.
pretrained : bool, default Fal... | 5,289,080 |
def print_how_to():
"""
Print the usage instruction
:return:
"""
print "usage 1: -start <date> -end <date> -commodity <commodity>"
print "usage 2: -start -end -commodity -result_amount"
print "-start : start date for retrieving news articles, format YYYY-MM-DD"
print "-end : end date for... | 5,289,081 |
def extract_insn_api_features(f, bb, insn):
""" parse instruction API features
args:
f (IDA func_t)
bb (IDA BasicBlock)
insn (IDA insn_t)
example:
call dword [0x00473038]
"""
for api in check_for_api_call(f.ctx, insn):
for (feature, e... | 5,289,082 |
def doc_handle_move(event: "Event", *args: Sequence[Any]) -> CMoveType:
"""Documentation for handlers bound to ``evt.EVT_C_MOVE``.
User implementation of this event handler is required if one or more
services that use C-MOVE are to be supported. If a handler is
not implemented and bound to ``evt.EVT_C_... | 5,289,083 |
def list_of_comments(fname) :
"""Returns list of str objects - comment records from file.
- fname - file name for text file.
"""
#if not os.path.lexists(fname) : raise IOError('File %s is not available' % fname)
f=open(fname,'r')
cmts = []
for rec in f :
if rec.isspace() : conti... | 5,289,084 |
def test_nearest_neighbor(abcde):
"""
a1 a2 a3 a4 a5 a6 a7 a8 a9
\ | / \ | / \ | / \ | /
b1 b2 b3 b4
Want to finish off a local group before moving on.
This is difficult because all groups are connected.
"""
a, b, c, _, _ = abcde
a1, a2, a3, a4, a5,... | 5,289,085 |
def publish_branch(branch):
"""Publishes given branch."""
repo_check()
return repo.git.execute([git,
'push', '-u', remote.name, branch]) | 5,289,086 |
def test_posttroll_adder_loop_return_value(connect_to_gs_catalog, process_message):
"""Test running posttroll adder."""
from georest.utils import _posttroll_adder_loop
config = {"workspace": "satellite",
"topics": ["/topic1", "/topic2"],
"layers": {"airmass": "airmass_layer_name... | 5,289,087 |
def pil_to_base64(pilimage): # pragma: no cover
"""Returns base64 encoded image given a PIL Image"""
buffer = BytesIO()
pilimage.save(buffer, "png")
return base64.b64encode(buffer.getvalue()).decode() | 5,289,088 |
def save_result(x,time,lev,copy_from_source,dflt_units='k'):
"""Saves results from projection in netcdf output format.
Input parameters:
x: projection indices (2dim array with time,mode)
time: coordinates from input netcdf file
lev: level coordinates (PCA modes)
copy_from_s... | 5,289,089 |
def pick_a_filename(i):
"""
Input: {
(directory) - the directory name from which to pick a filename (defaults to '.' - current directory)
(file_suffix) - the file type (defaults to '' - none)
}
Output: {
return - return... | 5,289,090 |
def linkcode_resolve(domain, info, author, package):
"""Determine the URL corresponding to a Python object."""
try:
module = import_module(info["module"])
except ModuleNotFoundError:
# No URL is returned when the object is not in
# any module, or the module cannot be imported
... | 5,289,091 |
def main(wf):
"""Parse project key, fetch and cache issues."""
parser = argparse.ArgumentParser()
parser.add_argument('--total', type=int, required=True)
parser.add_argument('--max-results', default=50, type=int)
parser.add_argument('--max-age', default=600, type=int)
parser.add_argument('projec... | 5,289,092 |
def _max(self, dim=None, keepdim=False):
"""Map of 'max' pytorch method."""
x = self
dim_orig = dim
if dim is None:
dim = _build_fwd_tuple(x.shape)
elif isinstance(dim, int):
dim = (dim,)
dim = _dim_tuple_explicit(x.shape, dim)
ret_max = P.array_max(x, dim)
ret_argmax =... | 5,289,093 |
def main(list_packed_vars):
"""
Model simulation
Parameters
----------
list_packed_vars : list
list of packed variables that enable the use of parallels
Returns
-------
netcdf files of the simulation output (specific output is dependent on the output option)
"""... | 5,289,094 |
def minify(source):
"""
Removes comments from the source code
"""
multiline = re.compile("(/\*.*?\*/)", re.DOTALL)
singleline = re.compile("//.*?\n")
remove_multiline = lambda f: re.sub(multiline, "", f)
remove_singleline = lambda f: re.sub(singleline, "", f)
return map(remove_multiline, map(remove_s... | 5,289,095 |
def configmap_data_keys():
"""
Build keys for the ``data`` mapping of a ``ConfigMap``.
"""
return builds(
lambda labels, dot: dot + u".".join(labels),
labels=lists(object_name(), average_size=2, min_size=1, max_size=253//2),
dot=sampled_from([u"", u"."]),
).filter(
la... | 5,289,096 |
def handler_assertions(
handler_name: str,
test_case: str,
error_name: str = None,
) -> Callable:
"""Configurable decorator for testing assertions for a given handler"""
def decorator_function(
decorated_function: Callable,
) -> Callable:
"""Return a wrapper for ... | 5,289,097 |
def create_bitmap_dataset(bitmap_data, output_dir, output_name, classnames, output_shards):
"""
Writes the provided bitmap_data as tf.Example in tf.Record
:param bitmap_data: tuple of lists containing (x_train, y_train, x_test, y_test)
:param output_dir: path where to write the output.
:param o... | 5,289,098 |
def with_logger(cls):
"""Class decorator to add a logger to a class."""
attr_name = '_logger'
cls_name = cls.__qualname__
module = cls.__module__
if module is not None:
cls_name = module + '.' + cls_name
else:
raise AssertionError
setattr(cls, attr_name, logging.getLogger(cls... | 5,289,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.