content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def write_label_file(labels_to_class_names, dataset_dir, filename=LABELS_FILENAME):
"""Writes a file with the list of class names.
Args:
labels_to_class_names: A map of (integer) labels to class names.
dataset_dir: The directory in which the labels file should be written.
filename: The filename where... | 38,400 |
def generate_balanced_tree(branching, depth, return_all=False):
""" Returns a DirectedGraph that is a balanced Tree and the root of the tree. (From left to right)
branching = 2, depth = 2
Depth 0 : "ROOT"
Depth 1 : "!#_B0_" "!#_B1_"
Depth 2 : "B0_B0_" "B1_B0_" "B0_B1_" "B1_B1_"
"""
total_siz... | 38,401 |
def rand_ssn():
"""Random SSN. (9 digits)
Example::
>>> rand_ssn()
295-50-0178
"""
return "%s-%s-%s" % (rand_str(3, string.digits),
rand_str(2, string.digits),
rand_str(4, string.digits)) | 38,402 |
def create_queue(queue_name: str,
durable: bool = True,
auto_delete: bool = False,
priorities: int = 0,
extra_properties: Optional[dict] = None,
server_url: Optional[str] = None):
"""Create a queue on the AMQP broker.
Args:
... | 38,403 |
def cast_arguments(args: Dict[str, Any]) -> Dict[str, str]:
"""Cast arguments.
:param args: args
:return: casted args
"""
casted_args = {}
for arg_name, arg_value in args.items():
casted_args[arg_name] = cast_argument(arg_value)
return casted_args | 38,404 |
def lmax_modes(lmax):
"""Compute all (l, m) pairs with 2<=l<=lmax"""
return [(l, m) for l in range(2, lmax + 1) for m in range(-l, l + 1)] | 38,405 |
def websocket_get_alarm_entities(hass, connection, msg):
"""Publish alarm entity data."""
result = [
{
"entity_id": entity.entity_id,
"area_id": area_id
}
for (area_id, entity) in hass.data[const.DOMAIN]["areas"].items()
]
if hass.data[const.DOMAI... | 38,406 |
async def test_cover_update(
hass: HomeAssistant, component_factory: ComponentFactory
) -> None:
"""Test cover."""
await component_factory.configure_component()
component_data = await component_factory.run_config_flow(
config_data={
CONF_IP_ADDRESS: "127.0.0.2",
CONF_USER... | 38,407 |
def scale_image(image, flag, nodata_value=VALUE_NO_DATA):
""" Scale an image based on preset flag.
Arguments:
image - 3d array with assumed dimensions y,x,band
flag - scaling flag to use (None if no scaling)
Return:
An image matching the input image dimension with scaling applied to it.
"""... | 38,408 |
def import_student_to_module(request, pk):
"""
Take .xlsx file, as produced by def:export_student_import_format and retrieve all students and metainformation from it.
Case 1 - Known User - Add the user to the active module edition with the right study and role by making a new Studying object
Case 2 - Un... | 38,409 |
def adjust_poses(poses,refposes):
"""poses, poses_ref should be in direct"""
# atoms, take last step as reference
for i in range(len(poses)):
for x in range(3):
move = round(poses[i][x] - refposes[i][x], 0)
poses[i][x] -= move
refposes = poses.copy()
return poses, re... | 38,410 |
def eval_validation(
left: pd.DataFrame,
right: pd.DataFrame,
left_on: IndexLabel,
right_on: IndexLabel,
validate: str,
):
"""
Evaluate the validation relationship between left and right and ensures
that the left and right dataframes are compatible with the validation
strategy.
... | 38,411 |
def update_SMILES_list(
ID_SMILES_tuples: List[Tuple[str, str]],
path: str,
) -> Tuple[List[str], List[str]]:
"""
This function takes a List of tuples containing IDs (str) and SMILES (str)
and the output path (str). It checks which of the corresponding structures
already have been depicted and r... | 38,412 |
def get_region_props_binary_fill(heatmapbinary, heatmap):
"""
The function is to get location and probability of heatmap
using ndimage.
:param heatmapbinary: the binarized heatmap
:type heatmap_binary: array
:param heatmap: the original heat_map
:type heatmap: array
:returns: regionprop... | 38,413 |
def login_response(request, username, password):
"""
Authenticates user and redirects with the appropriate state.
"""
user = authenticate(username=username, password=password)
if user:
login(request, user)
logger.info("User '{}' logged in.".format(user.username))
return red... | 38,414 |
def instrument_module(module):
"""
Force (re-)instrumentation of a module.
This can be useful if a module was already loaded before appmap hooks
were set up or configured to instrument that module.
"""
Recorder().do_import(module) | 38,415 |
def is_metageneration_specified(query_params):
"""Return True if if_metageneration_match is specified."""
if_metageneration_match = query_params.get("ifMetagenerationMatch") is not None
return if_metageneration_match | 38,416 |
def converter(fmt):
"""
Create a converter function for some specific format
Parameters
----------
fmt : str
The format to convert to, e.g. `"html"` or `"latex"`.
Returns
-------
function
"""
return functools.partial(convert, fmt=fmt) | 38,417 |
def a_node_name_group1(step, node_name):
""" Set the 'installator' value to be used in the test execution: 'chef' or 'puppet' """
world.node_name = CONFIG_VM_HOSTNAME if CONFIG_FILE in node_name else node_name | 38,418 |
def createRunner(name, account, user, conf={}):
"""
Creates a reusable spark runner
Params:
name: a name for the runner
account: an account
user: a user
conf: a json encoded configuration dictionary
"""
master = ""
if LOCAL:
master = "local"
else:
... | 38,419 |
def write_contests(contests, contest_type):
"""Prints the contests based on the parameters passed"""
write_contest_header(contest_type)
for index, contest in enumerate(contests):
time_diff_string = get_time_string(contest, contest_type)
contest_name = contest["contest_name"].encode('utf-8')
click.e... | 38,420 |
def pack_file(x, fn, encoding='utf8'):
""" Pack numpy array into filename
Supports binary data with bloscpack and text data with msgpack+blosc
>>> pack_file(np.array([1, 2, 3]), 'foo.blp') # doctest: +SKIP
See also:
unpack_file
"""
if x.dtype != 'O':
bloscpack.pack_ndarray_fi... | 38,421 |
def test_zero_stream_single_read():
"""Test the ZeroStream class with a single .read() call."""
length = 23523
zero_stream = utils.ZeroStream(length=length)
data = zero_stream.read()
assert len(data) == length, "The zero stream produced data of the wrong length"
assert data == b"\x00" * length, ... | 38,422 |
def auth_req_generator(
rf, mocker, rq_mocker, jwks_request, settings, openid_configuration
):
"""Mock necessary functions and create an authorization request"""
def func(id_token, user=None, code="code", state="state", nonce="nonce"):
# Mock the call to the external token API
rq_mocker.pos... | 38,423 |
def get_current_time():
"""
Returns the current system time
@rtype: string
@return: The current time, formatted
"""
return str(datetime.datetime.now().strftime("%H:%M:%S")) | 38,424 |
def mock_addon_options(addon_info):
"""Mock add-on options."""
return addon_info.return_value["options"] | 38,425 |
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
global dic
with open(FILE, "r") as f:
for word in f:
sub = word[0:1]
word = word[:"\n".find(word)]
if sub in dic:
dic[sub] += [word]
else:
dic[sub] = []
... | 38,426 |
def tokenize_documents(fulltext_dir, summary_dir, tokenized_documents_dir,
tokenized_summary_dir, tokenize_docs,
tokenize_summaries):
"""
Maps a whole directory of .story files to a tokenized version using
Stanford CoreNLP Tokenizer
"""
print("Preparing ... | 38,427 |
def init(width, height, title=None, fullscreen=False, renderer='OPENGL'):
"""Start the main console with the given width and height and return the
root console.
Call the consoles drawing functions. Then remember to use L{tdl.flush} to
make what's drawn visible on the console.
@type width: int
... | 38,428 |
def run(
task: Task,
num_samples: int,
num_simulations: int,
num_observation: Optional[int] = None,
observation: Optional[torch.Tensor] = None,
population_size: Optional[int] = None,
distance: str = "l2",
epsilon_decay: float = 0.2,
distance_based_decay: bool = True,
ess_min: Opt... | 38,429 |
def _preprocess_symbolic_input(x, data_format, mode, **kwargs):
"""Preprocesses a tensor encoding a batch of images.
# Arguments
x: Input tensor, 3D or 4D.
data_format: Data format of the image tensor.
mode: One of "caffe", "tf" or "torch".
- caffe: will convert the images f... | 38,430 |
def email_inbox():
"""
RESTful CRUD controller for the Email Inbox
- all Inbound Email Messages go here
@ToDo: Deprecate
"""
if not auth.s3_logged_in():
session.error = T("Requires Login!")
redirect(URL(c="default", f="user", args="login"))
etable = s3db.msg_ema... | 38,431 |
def line_column(position: Position) -> Dict[str, int]:
"""Translate pygls Position to Jedi's line / column
Returns a dictionary because this return result should be unpacked as a
function argument to Jedi's functions.
Jedi is 1-indexed for lines and 0-indexed for columns. LSP is 0-indexed for
line... | 38,432 |
async def mw_capability(app, capa_handler):
"""
Transform the request data to be passed through a capability and
convert the result into a web response.
"""
POST_METHODS = web.Request.POST_METHODS - {'DELETE'}
async def middleware(request):
# Ensure a content-type check is necessary
... | 38,433 |
def generate_median_by_profession(df):
"""Generates a csv file with the most popular professions.
Parameters
----------
df : pandas.DataFrame
The DataFrame to be plotted.
"""
with open("medians.csv", "w", encoding="utf-8", newline="") as temp_file:
temp_list = list()
t... | 38,434 |
def rotZ(theta):
""" returns Rotation matrix such that R*v -> v', v' is rotated about z axis through theta_d.
theta is in radians.
rotZ = Rz'
"""
st = math.sin(theta)
ct = math.cos(theta)
return np.matrix([[ ct, -st, 0. ],
[ st, ct, 0. ],
... | 38,435 |
def main(event, context):
"""Validate POST request and trigger Lambda copy function."""
try:
body = json.loads(event['body'])
bucket = body['bucket']
project = body['project']
token = body['token']
except (TypeError, KeyError):
return {
"statusCode": 400... | 38,436 |
def random_k(word_vectors, k):
"""
:return: ({cluster_id: [cluster elements]})
"""
clusters = defaultdict(list)
for word in word_vectors.vocab:
chosen_cluster = random.randint(0, k-1)
clusters[chosen_cluster].append(word)
return clusters | 38,437 |
def pie(items):
"""Draw a pie chart"""
items = list(_list_to_dict(items).items())
labels = [str(i) for i in items[0][1]]
_, sizes = items[-1]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.show() | 38,438 |
def case_insensitive_update(dct1, dct2):
"""
Given two dicts, updates the first one with the second, but considers keys
that are identical except for case to be the same.
No return value; this function modified dct1 similar to the update() method.
"""
lowkeys = dict([(key.lower(), key) for key ... | 38,439 |
def get_human_label(scope: str) -> Optional[str]:
"""The the human-readable label for a scope, for display to end users."""
return _HUMAN_LABELS.get(scope) | 38,440 |
def lineno():
"""Returns the current line number in our program."""
return str(' - RuleDumper - line number: '+str(inspect.currentframe().f_back.f_lineno)) | 38,441 |
def run_simulation(input_dataframe, num_cells_per_module, temperature_series, lookup_table, mod_temp_path,
module_start, module_end, database_path, module_name, bypass_diodes, subcells, num_irrad_per_module):
"""
:param input_dataframe: irradiation on every cell/subcell
:param num_cells_p... | 38,442 |
def qualified_name(obj):
"""Return the qualified name (e.g. package.module.Type) for the given object."""
try:
module = obj.__module__
qualname = obj.__qualname__ if six.PY3 else obj.__name__
except AttributeError:
type_ = type(obj)
module = type_.__module__
qualname ... | 38,443 |
def cast_mip_start(mip_start, cpx):
"""
casts the solution values and indices in a Cplex SparsePair
Parameters
----------
mip_start cplex SparsePair
cpx Cplex
Returns
-------
Cplex SparsePair where the indices are integers and the values for each variable match the variable type sp... | 38,444 |
def encode(value, unchanged = None):
"""
encode/decode are performed prior to sending to mongodb or after retrieval from db.
The idea is to make object embedding in Mongo transparent to the user.
- We use jsonpickle package to embed general objects. These are encoded as strings and can be dec... | 38,445 |
def ConvertToCamelCase(input):
"""Converts the input string from 'unix_hacker' style to 'CamelCase' style."""
return ''.join(x[:1].upper() + x[1:] for x in input.split('_')) | 38,446 |
def test_parse_nodoutR61():
"""correctly parse data from R6.1 nodout files
"""
from fem.post.create_disp_dat import parse_line
nodout = open(testPath / "nodout", "r")
n = nodout.readlines()
line = n[8]
raw_data = parse_line(line)
assert raw_data[0] == 6
assert raw_data[1] == 0.0
... | 38,447 |
def flatten(time,
flux,
window_length=None,
edge_cutoff=0,
break_tolerance=None,
cval=None,
return_trend=False,
method='biweight',
kernel=None,
kernel_size=None,
kernel_period=None,
... | 38,448 |
def frequency(seq, useall=False, calpc=False):
"""Count the frequencies of each bases in sequence including every letter"""
length = len(seq)
if calpc:
# Make a dictionary "freqs" to contain the frequency(in % ) of each base.
freqs = {}
else:
# Make a dictionary "base_counts" to ... | 38,449 |
def static_warning(message, desc='', file_only=False):
""" creates temp logger class instance and writes log message, should only used if a instance was created before """
stat_logger = Logger()
stat_logger.warning(message, desc=desc, file_only=file_only) | 38,450 |
def packages(request):
"""
Return a list of all packages or add a list of packages
"""
if request.method == "GET":
package_list = Package.objects.all()
serializer = PackageSerializer(package_list, many=True)
return Response(serializer.data)
if request.method == "POST":
... | 38,451 |
def maybe_download_and_extract(data_url):
"""Download and extract model tar file.
If the pretrained model we're using doesn't already exist, this function
downloads it from the TensorFlow.org website and unpacks it into a directory.
Args:
data_url: Web location of the tar file containing the pretra... | 38,452 |
def progressive_multiple_alignment(
Gs, cost_params, similarity_tuples, method, max_iters,
max_algorithm_iterations, max_entities, shuffle, self_discount,
do_evaluate, update_edges=False):
"""
Merge input graphs one graph at a time using any 2-network alignment method.
Input:
... | 38,453 |
def meet_sigalg(dist, rvs, rv_mode=None):
"""
Returns the sigma-algebra of the meet of random variables defined by `rvs`.
Parameters
----------
dist : Distribution
The distribution which defines the base sigma-algebra.
rvs : list
A list of lists. Each list specifies a random va... | 38,454 |
def ongoing_series():
""" Retrieve all series that are supposedly ongoing.
This call is *very* slow and expensive when not cached;
in practice, users should *never* get a non-cached response.
:return: json list with subset representation of
:class:`marvelous.Series` instances
"""
r... | 38,455 |
def check_inputs(Y, T, X, W=None, multi_output_T=True, multi_output_Y=True):
"""
Input validation for CATE estimators.
Checks Y, T, X, W for consistent length, enforces X, W 2d.
Standard input checks are only applied to all inputs,
such as checking that an input does not have np.nan or np.inf targe... | 38,456 |
def register(request):
""" Register a new node
"""
if request.method != 'POST':
return HttpResponse("Invalid GET")
#
# Registration requires only the exchange of a PSK.
#
# hash
skey = request.POST.get('skey')
node_id = None
if 'node_id' in request.POST:
node_i... | 38,457 |
def toDate(value):
"""Coerce the input value to a Date instance. None values and empty strings are mapped to None.
If an optional parser function is provided, it is used to perform date parsing, otherwise Date.parse is used.
Be aware that Date.parse has different implementations across browsers!
"""
... | 38,458 |
def removeMirroringData(node):
"""
Remove mirroring data from a node. This does NOT
remove mirroring data from the other node, if there
is one. See `unpairMirrorNode` for removing mirroring
data from two nodes at once.
Args:
node: A PyNode, MObject, or node name
"""
meta.removeM... | 38,459 |
def test_p_type():
"""
:return:
:rtype:
"""
net = pandapipes.create_empty_network("net")
d = 75e-3
pandapipes.create_junction(net, pn_bar=5, tfluid_k=293.15)
pandapipes.create_junction(net, pn_bar=5, tfluid_k=293.15)
pandapipes.create_pipe_from_parameters(net, 0, 1, 10, diameter_m=d... | 38,460 |
def get_tag_messages(tags_range, log_info):
"""
Add tag messages, commit objects and update the max author length in
`log_info`.
Args:
tags_range(list[:class:`~git.refs.tag.TagReference`]): Range of tags to
get information from
log_info(dict): Dictionary containing log infor... | 38,461 |
def test_repeat():
"""test escapes"""
myinput = "(ab){3,}"
# myinput = "a(wy){1,}?"
dfa = MyDFA.fromRegex(myinput)
dfa.drawGraph("repeat")
print(dfa.match("ab"))
print(dfa.match("abab"))
print(dfa.match("ababab"))
print(dfa.match("abababab")) | 38,462 |
def save_function(elements, module_path):
""" Recursively save functions with module name and signature. """
for elem, signature in elements.items():
if isinstance(signature, dict): # Submodule case
save_function(signature, module_path + (elem,))
elif signature.isstaticfunction():
... | 38,463 |
def median(numbers: list[int]):
"""Median Maintenance"""
heap_low = [-numbers[0]]
yield abs(heap_low[0])
if numbers[1] < numbers[0]:
heap_low, heap_high = [-numbers[1]], [numbers[0]]
else:
heap_high = [numbers[1]]
yield abs(heap_low[0])
diff = 0
for value in numbers[2:... | 38,464 |
def _profile_info(user, username=None, following=False, followers=False):
"""
Helper to give basic profile info for rendering the profile page or its child pages
"""
follows = False
if not username or user.username == username: #viewing own profile
username = user.username
if fo... | 38,465 |
def levelorder(root):
"""
广度优先遍历
:param root:
"""
queue = deque()
queue.append(root)
while len(queue) > 0:
node = queue.popleft()
print(node.value)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
pa... | 38,466 |
def _ProcessMergedIntoSD(fmt):
"""Convert a 'mergedinto' sort directive into SQL."""
left_joins = [
(fmt('IssueRelation AS {alias} ON Issue.id = {alias}.issue_id '
'AND {alias}.kind = %s'),
['mergedinto'])]
order_by = [(fmt('ISNULL({alias}.dst_issue_id) {sort_dir}'), []),
(fm... | 38,467 |
def _find_major_vars(data):
"""
Splits data into those variables likely to require a lot of storage space
(defined as those which depend on time and at least one other dimension).
These are normally the variables of physical interest.
"""
# TODO Use an Ordered Set instead to preserve order of v... | 38,468 |
def Plot3DImage(rgb_image,depth_image,sample=True,samplerate=.5,ignoreOutliers=True):
"""
Input:
rgb_image[pixely,pixelx,rgb] - Standard rgb image [0,255]
depth_image[pixely,pixelx,depth] - Image storing depth measurements as greyscale - 255=5m, 0=0m
sample(Bool) - Plot full image or... | 38,469 |
def smooth_curve(x, y, npts=50, deg=12):
"""Smooth curve using a polyfit
Parameters
----------
x : numpy array
X-axis data
y : numpy array
Y-axis data
npts : int
Optional, number of points to resample curve
deg : int
Optional, polyfit degree
Returns
... | 38,470 |
async def test_get_by_key_under_namespace(
session_id: uuid.UUID, redis_backend: RedisBackend
):
"""Check whether a key is under a namespace."""
key, value = f"{session_id}:fastapi_session", "cool"
await redis_backend.set(key, value)
assert key in await redis_backend.keys(session_id) | 38,471 |
def test_if_else():
"""
>>> d = {'v':True}
>>> txt = '''
... {{if v:}}ok{{else:}}no{{pass}}
... '''
>>> print (template(txt, d))
<BLANKLINE>
ok
<BLANKLINE>
>>> print (template(txt, {'v':False}))
<BLANKLINE>
no
<BLANKLINE>
""" | 38,472 |
def gather_allele_freqs(record, samples, males_set, females_set, parbt, pop_dict, pops,
sex_chroms, no_combos=False):
"""
Wrapper to compute allele frequencies for all sex & population pairings
"""
# Add PAR annotation to record (if optioned)
if record.chrom in sex_chroms an... | 38,473 |
def get_history_events_closest():
""" Получение полного списка страниц в json"""
try:
event_schema = HistoryEventsSchema(many=True)
datef = datetime.today()
further_date = datef + timedelta(days=14)
if further_date.year > datetime.today().year:
further_date = date(ye... | 38,474 |
def get_archive_url(url, timestamp):
"""
Returns the archive url for the given url and timestamp
"""
return WEB_ARCHIVE_TEMPLATE.format(timestamp=timestamp.strftime(WEB_ARCHIVE_TIMESTAMP_FORMAT), url=url) | 38,475 |
def test_set_domain_ip_acl(c):
"""
test_set_domain_ip_acl
"""
blackList = ['1.1.1.2', '1.1.1.3']
response = c.set_domain_ip_acl(
domain = 'www.example.com',
blackList = blackList)
print(response) | 38,476 |
def get_text(pathToImage):
"""
Accesses API to get json file containing recognized text
"""
print('Processing: ' + pathToImage)
headers = {
'Ocp-Apim-Subscription-Key': API_KEY,
'Content-Type': 'application/octet-stream'
}
params = {
'language': 'en',
'detectO... | 38,477 |
def plot_2(data2,best_array,n,rates,noises,save):
"""plot lines for all error rather than just best
Parameters
------
data2,best_array : array_like
`data2` and `best_array` defined above
n,rates,noises: list
`n` `rates` `list` lists of each p... | 38,478 |
def match_summary(df):
""" summarize the race and ethnicity information in the dataframe
Parameters
----------
df : pd.DataFrame including columns from race_eth_cols
"""
s = pd.Series(dtype=float)
s['n_match'] = df.pweight.sum()
for col in race_eth_cols:
if col in df.columns:
... | 38,479 |
def parse_git_version(git) :
"""Parses the version number for git.
Keyword arguments:
git - The result of querying the version from git.
"""
return git.split()[2] | 38,480 |
def onRequestLogin(loginName, password, clientType, datas):
"""
KBEngine method.
账号请求登陆时回调
此处还可以对登陆进行排队,将排队信息存放于datas
"""
INFO_MSG('onRequestLogin() loginName=%s, clientType=%s' % (loginName, clientType))
errorno = KBEngine.SERVER_SUCCESS
if len(loginName) > 64:
errorno = KBEngine.SERVER_ERR_NAME
if len(... | 38,481 |
def log_calls(
logger: logging.Logger, log_result: bool = True
) -> GenericDecorator:
"""
Log calls to the decorated function.
Can also decorate classes to log calls to all its methods.
:param logger: object to log to
"""
def log_function(
target: Callable[..., TargetRetur... | 38,482 |
def bag(n, c, w, v):
"""
测试数据:
n = 6 物品的数量,
c = 10 书包能承受的重量,
w = [2, 2, 3, 1, 5, 2] 每个物品的重量,
v = [2, 3, 1, 5, 4, 3] 每个物品的价值
"""
# 置零,表示初始状态
value = [[0 for j in range(c + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, c + 1):
value[i][... | 38,483 |
def _to_bytes(key: type_utils.Key) -> bytes:
"""Convert the key to bytes."""
if isinstance(key, int):
return key.to_bytes(128, byteorder='big') # Use 128 as this match md5
elif isinstance(key, bytes):
return key
elif isinstance(key, str):
return key.encode('utf-8')
else:
... | 38,484 |
def _online(machine):
""" Is machine reachable on the network? (ping)
"""
# Skip excluded hosts
if env.host in env.exclude_hosts:
print(red("Excluded"))
return False
with settings(hide('everything'), warn_only=True, skip_bad_hosts=True):
if local("ping -c 2 -W 1 %s" % machin... | 38,485 |
def download_subs_from_public_amara(amara, ytid, lang):
"""Returns tuple subtitles downloaded from Public Amara"""
# Check whether the video is already on Amara
video_url = 'https://www.youtube.com/watch?v=%s' % ytid
amara_response = amara.check_video(video_url)
if amara_response['meta']['total_cou... | 38,486 |
def profile_exists_at(path):
"""
Check that a profile exists at the given path.
:param path: path to a profile
:type path: str
:returns: True if profile exists in given path, else False
:rtype: bool
"""
import os
return os.path.isdir(path) and os.path.isfile(
os.path.join(p... | 38,487 |
def update_user_permissions(sender, **kwargs):
"""
Update the content of EMPUIAppsCache for the user logging in.
This allows updated user specific permissions, like per object level
permissions of pages to take effect. Also update the AnonymousUser,
as an update for this users permissions can never... | 38,488 |
def get_expectation_value(
qubit_op: QubitOperator, wavefunction: Wavefunction, reverse_operator: bool = False
) -> complex:
"""Get the expectation value of a qubit operator with respect to a wavefunction.
Args:
qubit_op: the operator
wavefunction: the wavefunction
reverse_operator: ... | 38,489 |
def create_proxy_to(logger, ip, port):
"""
:see: ``HostNetwork.create_proxy_to``
"""
action = CREATE_PROXY_TO(
logger=logger, target_ip=ip, target_port=port)
with action:
encoded_ip = unicode(ip).encode("ascii")
encoded_port = unicode(port).encode("ascii")
# The fir... | 38,490 |
def get_output_shape(tensor_shape, channel_axis):
"""
Returns shape vector with the number of channels in the given channel_axis location and 1 at all other locations.
Args:
tensor_shape: A shape vector of a tensor.
channel_axis: Output channel index.
Returns: A shape vector of a tensor... | 38,491 |
def process_padding(pad_to_length, lenTrials):
"""
Simplified padding interface, for all taper based methods
padding has to be done **before** tapering!
Parameters
----------
pad_to_length : int, None or 'nextpow2'
Either an integer indicating the absolute length of
the trials ... | 38,492 |
def angular_to_physical_size(angsize,zord,usez=False,**kwargs):
"""
Converts an observed angular size (in arcsec or as an AngularSeparation
object) to a physical size.
:param angsize: Angular size in arcsecond.
:type angsize: float or an :class:`AngularSeparation` object
:param zord: Redsh... | 38,493 |
def handle_arguments():
""" verifies the presence of all necessary arguments and returns the data dir """
if len ( sys.argv ) == 1:
stderr( "no arguments provided." )
show_help()
try: # check for the right arguments
keys, values = getopt.getopt( sys.argv[1:], "hf:" )
except getopt.GetoptError:... | 38,494 |
def main(args=None):
"""Run the application."""
if args is not None:
sys.argv = args
args = _setup_argparser()
if args.version:
print(f"movescu.py v{__version__}")
sys.exit()
APP_LOGGER = setup_logging(args, "movescu")
APP_LOGGER.debug(f"movescu.py v{__version__}")
... | 38,495 |
def is_tuple(x):
"""
Check that argument is a tuple.
Parameters
----------
x : object
Object to check.
Returns
-------
bool
True if argument is a tuple, False otherwise.
"""
return isinstance(x, tuple) | 38,496 |
def find_verbalizer(tagged_text: str) -> pynini.FstLike:
"""
Given tagged text, e.g. token {name: ""} token {money {fractional: ""}}, creates verbalization lattice
This is context-independent.
Args:
tagged_text: input text
Returns: verbalized lattice
"""
lattice = tagged_text @ ver... | 38,497 |
def get_color_pattern(input_word: str, solution: str) -> str:
"""
Given an input word and a solution, generates the resulting
color pattern.
"""
color_pattern = [0 for _ in range(5)]
sub_solution = list(solution)
for index, letter in enumerate(list(input_word)):
if letter == solution... | 38,498 |
def getargspec(obj):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'def... | 38,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.