content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def invoke_lambda_and_get_duration(lambda_client, payload, function_name):
"""
Invokes Lambda and return the duration.
:param lambda_client: Lambda client.
:param payload: payload to send.
:param function_name: function name.
:return: duration.
"""
response = lambda_client.invoke(
... | 63,000 |
def test_816_edge_case(entities, use_ip, save):
"""
Test that #770 protocol only triggers when the
depending deletion is towards the same asn AND
not already handled (dependency == noop)
"""
data = setup_test_data("ixf.member.1")
network = entities["net"]["UPDATE_DISABLED_2"]
ixlan = en... | 63,001 |
def nsi_show1(ctx, name, literal, filter):
"""shows the content of a Network Slice Instance (NSI)
NAME: name or ID of the Network Slice Instance
"""
logger.debug("")
nsi_show(ctx, name, literal, filter) | 63,002 |
def is_table(doctype):
"""Returns True if `istable` property (indicating child Table) is set for given DocType."""
def get_tables():
return db.sql_list("select name from tabDocType where istable=1")
tables = cache().get_value("is_table", get_tables)
return doctype in tables | 63,003 |
def plotparam_errs(hdulist=None,title=None,out=None) :
""" Plot uncertainties
"""
a=hdulist[1].data
els=hdulist[3].data['PARAM_SYMBOL'][0]
grid=[]
yt=[]
dwarfs=np.where(a['FPARAM'][:,1] > 3.8)[0]
giants=np.where(a['FPARAM'][:,1] < 3.8)[0]
for iel,el in enumerate(els) :
gfig,... | 63,004 |
def _scroll_plot4(images, names, init_z):
"""
Creates a plot 2x2 image plot of 3d volume images
Scrolling changes the displayed slices
Parameters
----------
images: list of 4 arrays
Each array of shape (z,y,x) or (z,y,x,RGB)
names: list of 4 strings
Names for each image
Us... | 63,005 |
def then_result(result: float, data: dict):
""" Check results """
assert result == data['result'] | 63,006 |
def n_tree():
"""
This is the format of this tree
t 1
a b c 3
aa ab ba bb ca cb 6
aaa aab aba abb baa bab bba bbb caa cab cba ... | 63,007 |
def reglux_list(mydict,response):
"""
遍历正则抓取数据
:param mydict: 字典类型{key:正则表达式,}
:param response: request.text需要正则匹配的字符串
:return: 字典类型
"""
temp = {}
for m,n in mydict.items():
if '' != n:
pattern = re.compile(n)
matchs = pattern.findall(response)
... | 63,008 |
def log(sender, message):
"""Log a message in the console"""
logger.info("[%s] " % sender + message) | 63,009 |
def correct_archetype_areas(prop_architecture_df, architecture_DB, list_uses):
"""
Corrects the heated area 'Hs_ag' and 'Hs_bg' for buildings with multiple uses.
:var prop_architecture_df: DataFrame containing each building's occupancy, construction and renovation data as
well as the architectural... | 63,010 |
def add_data(t_name, data):
"""新增一条数据"""
# 创建一个连接
db = pymysql.connect(db_host, db_user, db_pw, db_name)
# 用cursor()创建一个游标对象
cursor = db.cursor()
# 插入数据sql
print('开始新增一条数据:%s' % data)
data.insert('0', t_name)
sql = 'insert into %s (name, age) values (%s, %s);' % data
# 执行插入
c... | 63,011 |
def read_stat():
"""
Mocks read_stat as this is a Linux-specific operation.
"""
return [
{
"times": {
"user": random.randint(0, 999999999),
"nice": random.randint(0, 999999999),
"sys": random.randint(0, 999999999),
"idle... | 63,012 |
def _IsMinikubeClusterUp(cluster_name):
"""Checks if a minikube cluster is running."""
cmd = [_FindMinikube(), 'status', '-p', cluster_name, '-o', 'json']
try:
status = run_subprocess.GetOutputJson(
cmd, timeout_sec=20, show_stderr=False)
return 'Host' in status and status['Host'].strip() == 'Runn... | 63,013 |
def print_encoded(*args):
"""This will replace unsuitable characters and doesn't append a newline
"""
stringArgs = ()
for arg in args:
stringArgs += encode(arg),
msg = b" ".join(stringArgs)
if not msg.endswith(b"\n"):
msg += b" "
if os.name == "nt":
os.write(sys.stdou... | 63,014 |
def getMaxDouble_DImage(Image):
"""getMaxDouble_DImage(Image) -> double"""
return _ImageFunctions.getMaxDouble_DImage(Image) | 63,015 |
def bfs(graph):
"""Function that recreates the Breath First Search
algorithm, using a queue as its data structure.
In this algorithm, when a node is analyzed, it is
marked as visited and all of its children are
added to the queue (if they are not in it already).
The next node to be analyzed is g... | 63,016 |
def create_known_points_layer_2d():
"""Create points layer with known coordinates
Returns
-------
layer : napari.layers.Points
Points layer.
n_points : int
Number of points in the points layer
known_non_point : list
Data coordinates that are known to contain no points. U... | 63,017 |
def opcode_d(renderer, dash_array, dash_phase):
"""Set dash array and phase (see p. 217)"""
renderer.gs.dash_array = dash_array
renderer.gs.dash_phase = dash_phase | 63,018 |
def op_sub(line, *arg):
"""subtracts the top element of the deque
from the second top element of the deque"""
del arg
try:
sub = (SQ[-2] - SQ[-1])
SQ.pop()
SQ.pop()
SQ.append(sub)
except IndexError:
exit_error(9, line) | 63,019 |
def expand_grid_point(point, factor, xoffset, yoffset):
"""Expand a given georeferenced point by an integer factor, knowing the
size of horizontal and vertical area
Parameters
----------
point : shapely.geometry.Point
Raw point that must be expanded
factor : int
Number of new po... | 63,020 |
def weighted_choice(values: Sequence[TValue]) -> TValue:
"""
A simple weighted choice which favors the items later in the list.
Weighting is linear with the first item having a weight of 1, the second
having a weight of 2 and so on.
values = (a, b, c, d)
bound = 10 # 1 + 2 + 3 + 4
VALUES... | 63,021 |
def introspect_routine(routine, routine_doc, module_name=None):
"""Add API documentation information about the function
C{routine} to C{routine_doc} (specializing it to C{Routine_doc})."""
routine_doc.specialize_to(RoutineDoc)
# Extract the underying function
if isinstance(routine, MethodType):
... | 63,022 |
def add_prefix(prefix, name):
"""Adds prefix to name."""
return "/".join((prefix, name)) | 63,023 |
def next_job_id(output_dir: Path) -> str:
"""Return the next job id."""
# The ids are of form "0001", "0002", ...
# Such ids are used for naming log files "0001.log" etc.
# We look for the first id that haven't been used in the output directory.
def make_job_id(n: int) -> str:
return f"{n:0... | 63,024 |
def _update_host_mgmt_address(host, interface):
"""Check if the host has a static management IP address assigned
and ensure the address is populated against the interface. Otherwise,
if using dynamic address allocation, then allocate an address
"""
mgmt_ip = utils.lookup_static_ip_address(
... | 63,025 |
def get_token(request):
"""The same as validate_token, but return the token object to check the
associated user.
"""
# Coming from HTTP, look for authorization as bearer token
token = request.META.get("HTTP_AUTHORIZATION")
if token:
token = token.split(" ")[-1].strip()
try:
... | 63,026 |
def isi(spiketrain, axis=-1):
"""
Return an array containing the inter-spike intervals of the SpikeTrain.
Accepts a Neo SpikeTrain, a Quantity array, or a plain NumPy array.
If either a SpikeTrain or Quantity array is provided, the return value will
be a quantities array, otherwise a plain NumPy ar... | 63,027 |
def instance_power_specs_delete(context, instance_uuid, session=None):
""" Removes an existing Server specs from the Database """
return IMPL.instance_power_specs_delete(context, instance_uuid) | 63,028 |
def POS(POSInt):
"""Returns 'F' if position indicator is present. The AllSportCG sends a * in a specific position to indicate which
team has posession, and this changes that character to an 'F'. Using font Mattbats, F is a football."""
POSText = ""
if POSInt == 42:
POSText = "F"
return(POSText) | 63,029 |
def kwargs_2_list(**kwargs) -> Dict[str, Sequence]:
"""
Convert all single values from keyword arguments into lists.
For each argument provided, if the type is not a sequence,
convert the single value into a list.
Strings are not considered as a sequence in this scenario.
Parameters
------... | 63,030 |
def _resolve_field_reference(field_reference, source_file_name, errors, ir):
"""Resolves the References inside of a FieldReference."""
if field_reference.path[-1].HasField("canonical_name"):
# Already done.
return
previous_field = ir_util.find_object_or_none(field_reference.path[0], ir)
previous_referen... | 63,031 |
def downscale(box, side, fill_color, background):
"""Downscales box by considering each box of length side as one pixel.
If a downscaled pixel contains more than on color this returns None"""
if side == 1:
return None
w, h = int(box.shape[0] / side), int(box.shape[1] / side)
Y = np.full((w... | 63,032 |
def switch_passive(tokenized):
"""Passive verbs are modifying the phrase before them rather than the
phrase following. For consistency, we flip the order of such verbs"""
if all(not t.match(tokens.Verb, active=False) for t in tokenized):
return tokenized
converted, remaining = [], tokenized
... | 63,033 |
def force_500(request):
""" 強制的に HTTP 500 を送出するView
MAIL_ADMINSにエラーレポートが送信されることを想定
settingsは、 `admins_and_managers`
"""
my_local_value = 'ハロー'
raise Exception('Error') | 63,034 |
def unbox_unicode_str(typ, obj, c):
"""
Convert a unicode str object to a native unicode structure.
"""
ok, data, length, kind, is_ascii, hashv = \
c.pyapi.string_as_string_size_and_kind(obj)
uni_str = cgutils.create_struct_proxy(typ)(c.context, c.builder)
uni_str.data = data
uni_str... | 63,035 |
def get_encoded_batch(sentence, lang_obj, use_cuda):
"""
accepts only bsz = 1.
input: one sentence as a string
output: named tuple with vector and length
"""
sentence = sentence + ' ' + global_variables.EOS_TOKEN;
tensor = lang_obj.txt2vec(sentence).unsqueeze(0)
device = torch.device('cuda') if use_cuda and t... | 63,036 |
def copy_collection(source, dest, state_path, percent):
"""
Copies all documents from source to destination collection. Inserts documents in
batches using insert workers, which are each run in their own greenlet. Ensures that
the destination is empty before starting the copy.
Does no safety checks ... | 63,037 |
def ensure_topological_order(nodes: List[base_node.BaseNode]) -> bool:
"""Helper function to check if nodes are topologically sorted."""
visited = set()
for node in nodes:
for upstream_node in node.upstream_nodes:
if upstream_node not in visited:
return False
visited.add(node)
return True | 63,038 |
def eval_wavefront(opt_model, fld, wvl, foc,
image_pt_2d=None, num_rays=21, value_if_none=np.NaN):
"""Trace a grid of rays and evaluate the OPD across the wavefront."""
fod = opt_model['analysis_results']['parax_data'].fod
ref_sphere, cr_pkg = trace.setup_pupil_coords(opt_model, fld, wvl,... | 63,039 |
def task_weekly_update():
"""
send email weekly
"""
trackers = models.TaskTracker.objects.filter(update_type = 2).values_list("id", "task_type", "email")
for tracker in trackers:
tracker_id = tracker['id']
tracker_task_type = tracker['task_type']
tracker_email = tracker['email']
# find list of tasks ... | 63,040 |
def main():
"""Main."""
fauth = os.path.join(os.getenv('HOME'), '.zoerc')
args = Args(fauth)
auth = read_auth(args)
api = ZoeAPI(auth['url'], auth['user'], auth['pass'])
zapps = []
for zapp_file in glob.glob(sys.argv[1] + '/*.json'):
zapps.append(load_zapp(zapp_file))
try:
... | 63,041 |
def cleanup():
"""removes all temporary data"""
if not DEBUG:
rmtree(tmpdir) | 63,042 |
def do_self_test(nlp):
""" Simple self-test with small dataset to prove that this works okay. """
text = "Pierre Vinken, 61 years old, will join the board as a nonexecutive director, Nov. 29. Mr. Vinken is chairman of Elsevier N.V., the Dutch publishing group."
annotations = [
"T1 PER 0 13 Pierre Vi... | 63,043 |
def install(**kwargs):
"""Download and install an image and its binaries.
An image has a name and a version and can be installed as::
damona install NAME:version
If the version is omitted, the latest version is installed. Therefore, the
following two commands are equivalent if 0.11.9 is the l... | 63,044 |
def _ArrayToVec3(vec3):
"""Convert an array of three doubles into a simple_aero.Vec3."""
if len(vec3) != 3:
raise Vec3FormatException(vec3)
c_vec3 = simple_aero.Vec3()
c_vec3.x = vec3[0]
c_vec3.y = vec3[1]
c_vec3.z = vec3[2]
return c_vec3 | 63,045 |
def _save_list(path, data_list):
"""Save list to file."""
print(f"File stored in {path}")
with open(path, 'w') as arq:
for data in data_list:
arq.write(str(data['id'])+'\n') | 63,046 |
def get_storage(request):
""" Gets a Credentials storage object provided by the Django OAuth2 Helper
object.
Args:
request: Reference to the current request object.
Returns:
An :class:`oauth2.client.Storage` object.
"""
storage_model = oauth2_settings.storage_model
user_prop... | 63,047 |
def default_field(obj, **kwargs):
"""
returns field object that can handle default factory functions properly
"""
return field(default_factory=lambda: copy.copy(obj), **kwargs) | 63,048 |
def play_audio_file(fname=DETECT_DING):
"""Simple callback function to play a wave file. By default it plays
a Ding sound.
:param str fname: wave file name
:return: None
"""
ding_wav = wave.open(fname, 'rb')
ding_data = ding_wav.readframes(ding_wav.getnframes())
if pyaudio is None:
... | 63,049 |
def is_visited(state, visited):
"""
Determines whether a State has already been visited.
Args:
state:
visited:
Returns:
"""
for visited_state in visited:
if state.shore == visited_state.shore and state.boat == visited_state.boat:
return True
return False | 63,050 |
def bf_get_snapshot_input_object_stream(key, snapshot=None):
# type: (Text, Optional[Text]) -> Any
"""Returns a binary stream of the content of the snapshot input object with specified key."""
return restv2helper.get_snapshot_input_object(bf_session, key, snapshot) | 63,051 |
def supplierProducts(supplierId):
"""
Lists out all of the supplier products with the ability
to modify list and delist products into the master
database.
:param supplierId: The supplier id.
"""
page = escape(request.args.get("page"))
limit = request.args.get("limit")
if not limit o... | 63,052 |
def pickle_data(pickle_id,*args):
"""
Pickles one or more items fromfrom memory to a file for later use.
Parameters
----------
filter_id : str
An ID string
args: list
list of one or more data variables
"""
with open(pickle_id+".pickle", "wb") as f:
... | 63,053 |
def bprop_scalar_to_array(x, out, dout):
"""Backpropagator for primitive `scalar_to_array`."""
return (F.array_to_scalar(dout),) | 63,054 |
def get_polar_eq(self):
"""Returns a polar equivalent of the lamination
Parameters
----------
self : Lamination
Lamination object
Returns
-------
polar_eq: Lamination
The polar equivalent of the lamination
"""
raise NotImplementedYetError("get_polar_eq available on... | 63,055 |
def _channels_changed(params, len_channels):
"""Deal with the vertical shift of the viewport."""
if params['ch_start'] + params['n_channels'] > len_channels:
params['ch_start'] = len_channels - params['n_channels']
if params['ch_start'] < 0:
params['ch_start'] = 0
params['plot_fun']() | 63,056 |
def make_shared_connection(attr_source, target_attr):
"""
It connects an attribute to other connected attribute by pairblend node.
This way the target attribute does'nt lose their existing connections.
:param attr_source: Source attribute.
:param target_attr: Target attribute.
"""
attr_previ... | 63,057 |
def get_sequences(psms: np.recarray, db_seqs:np.ndarray)-> np.ndarray:
"""Get sequences to add them to a recarray
Args:
psms (np.recarray): Recordarray containing PSMs.
db_seqs (np.ndarray): NumPy array containing sequences.
Returns:
np.ndarray: NumPy array containing a subset of s... | 63,058 |
def dual_basis_hamiltonian(n_dimensions, system_size,
plane_wave=False, spinless=True):
"""Return the plane wave dual basis hamiltonian with the given parameters.
Returns: the Hamiltonian as a normal-ordered FermionOperator.
Args:
n_dimensions (int): The number of dimens... | 63,059 |
def get_subject_for_cell(row_num, row, column_spec, table_about_url, shared_subject, column_info):
""" Get the subject for the given cell."""
if column_spec["aboutUrl"]:
return apply_all_subs(column_spec["aboutUrl"], row_num, row, column_info)
elif table_about_url:
return apply_all_subs(tabl... | 63,060 |
async def test_setup(opp):
"""Test that devices are reported correctly."""
with patch(
"sense_energy.SenseLink",
return_value=Mock(start=AsyncMock(), close=AsyncMock()),
):
assert await async_setup_component(opp, DOMAIN, CONFIG) is True | 63,061 |
def merge_confs(
filenames: Sequence[PathLike], default: Optional[str] = "defaults.yml"
) -> Configuration:
"""
Merge configurations in given files.
:param filenames: files to merge
:param default: default configurations
:return: merged configuration
"""
lst = [default, *filenames] if d... | 63,062 |
def source_add(instrument_name: str, uri: str):
"""Add an instrument source"""
from .service.sanitize import update_tablesanitizer
from .remote.blob import load_blob
click.secho()
progress = progress_callback()
blob = app.add_source(
instrument_name,
uri,
progress,
... | 63,063 |
def add_product(body):
"""
Added a new Product
:param body: Product object that needs to be added to the db.
:type body: dict | bytes
:rtype: AddProductResponse
"""
return Products.add_product(connexion) | 63,064 |
def sineFit(wavelength,frequency,amplitude,phase,offset):
"""
A sine fit function of wavelength, frequency,
amplitude, and phase.
"""
return amplitude * np.sin(frequency * (wavelength - phase)) + offset | 63,065 |
def cast_floats_to_right_precision(to_fp16: bool, no_grad: bool, *args: Any, **kwargs: Any) -> Tuple[Any, Any]:
"""
Cast floating point Tensors in *args or **kwargs to FP16 or FP32 if they are not.
We also retain the requires_grad flag so that casting doesn't affect the autograd graph.
"""
def fn_f... | 63,066 |
def _BuildIsCompleted(build_dict, build_num):
"""Determine whether build was completed successfully.
Get the build test status. Check whether the build given by |build_num]
was terminated by an error, or is not finished building. If so, return
None. Otherwise, return the build test status dictionary.
Args:
... | 63,067 |
def extract_columns(myfile):
"""Returns the columns of a space separated file as a list
let the file be:
a b c
d e f
g h i
the function will return:
[(a,d,g), (b,e,h), (c,f,i)]
"""
lines = extract_lines(myfile)
zipped = zip(*lines)
return list(zipped) | 63,068 |
def trim(filename, output_dir=None, duration=None):
"""Takes a single audio file, and standardizes it based
on the parameters provided.
Heads up! Modifies the file in place...
Parameters
----------
filename : str
Full path to the audio file to work with.
output_dir : str or None
... | 63,069 |
def assign_label(cross_nn, ref_nn, ref_labels, how='mode'):
"""
Assign label to projected cells based on the labels among their nearest neighbors
in the reference dataset.
Parameters
----------
cross_nn
dense numpy array or scipy sparse array (csr) with projected cells as rows and
... | 63,070 |
def parse_floatingips_to_add(floatingips):
"""
Parse "floatingips" values
:param dict floatingips: Floating ips
:rtype: dict (region, quantity)
"""
result = defaultdict(lambda: 0)
for ip in floatingips:
result[ip.get("region")] += ip.get("quantity")
return result | 63,071 |
def edit_profile():
"""
TODO
"""
token = request.cookies.get(TOKEN_COOKIE_NAME)
token_decoded = jwt.decode(token, SECRET, algorithms=['HS256'], verify=True)
subject = token_decoded['subject']
user = registry.get_user(subject=subject)
return_url = request.args.get('return_url')
form =... | 63,072 |
def rgs_var(g, h, xoff, yoff):
"""Radiographs and variance with xoff and yoff offsets"""
gx0, hx0 = xoff, 0
if xoff < 0:
gx0, hx0 = 0, -xoff
nx = min(g.rg.shape[0]-gx0, h.rg.shape[0]-hx0)
gy0, hy0 = yoff, 0
if yoff < 0:
gy0, hy0 = 0, -yoff
ny = min(g.rg.shape[1]-gy0, h.rg.sha... | 63,073 |
def setExternalURL( cls, url ):
"""Set the externproto URL associated with a prototype"""
from vrml import node
return node.Node.externalURL.fset( cls, url ) | 63,074 |
def load_fs(root: Union[FS, str]) -> FS:
"""If str is supplied, returns an instance of OSFS, backed by the filesystem."""
if isinstance(root, str):
return pyfs.open_fs(root, create=True)
if isinstance(root, FS):
return root
raise Exception("Not a filesystem or path!") | 63,075 |
def _getcontextrange(context, config):
"""Return the range of the input context, including the file path.
Return format:
[filepath, line_start, line_end]
"""
file_i = context['_range']['begin']['file']
filepath = config['_files'][file_i]
line_start = context['_range']['begin']['line'][0]
... | 63,076 |
def test_just_right() -> None:
"""Pass/fail"""
result = TopLayer(**JUST_RIGHT)
assert result.tdata01 == JUST_RIGHT["tdata01"]
assert result.tdata02 == NestedLayer(**INNER_NEST)
assert result.tdata03 == JUST_RIGHT["tdata03"]
assert result.tdata04 == [
NestedLayer(**INNER_NEST),
N... | 63,077 |
def pluginMain():
"""Run the Karta (identifier) plugin."""
global logger, disas
# Use the basic logger on the init phase
init_logger = Logger(LIBRARY_NAME)
init_logger.linkHandler(logging.FileHandler(constructInitLogPath(), "w"))
disas = createDisassemblerHandler(init_logger)
# In case of a... | 63,078 |
def prepare_email_content(runresult, subject_name):
"""
:param runresult: 生成的简要分析结果
:param subject_name: html名称
:return: email conetnt
"""
batch_result = {}
batch_result['report_name'] = subject_name
batch_result["tasks"] = runresult["tasks"]
batch_result["pass_task"] = runresult["pa... | 63,079 |
def sample_recipe(user, **params):
"""create a dictionnary of a recipe object."""
defaults = {
'title': 'Pitimi ak Pwa Kongo',
'time_minutes': 10,
'price': 5.00,
'description': 'Manje Ayisyen'
}
defaults.update(params)
return Recipe.objects.create(user=user, **default... | 63,080 |
def flat(iterable: Iterable[Union[T, Iterable]]) -> Generator[T, None, None]:
"""
Flattens an iterable with any levels of nesting, yielding its values into a generator.
>>> array = (3, 4, -1, [232, None, 'Jim', (3, [333, [333, 43]], b'Gregor')])
>>> tuple(flat(array))
(3, 4, -1, 232, No... | 63,081 |
def test_external_dns(aggregator, instance):
"""
Testing external_dns
"""
c = ExternalDNSCheck('external_dns', {}, [instance])
c.check(instance)
for metric in DEFAULT_METRICS.values():
metric = '{}.{}'.format(CHECK_NAME, metric)
for tag in instance['tags']:
aggregat... | 63,082 |
def approx_match(stations, name):
"""
:param stations: dict เก็บข้อมูลพิกัดและอุณหภูมิของสถานีต่าง ๆ ในรูปแบบที่อธิบายมาก่อนนี้
:param name: เป็นสตริง
:return: คืนลิสต์ที่เก็บชื่อสถานีที่มีตัวอักษรใน name เป็นส่วนหนึ่งของชื่อสถานี โดยไม่สนใจว่าเป็นตัวพิมพ์เล็กหรือใหญ่
และไม่สนใจเว้นวรรคภายในด้วย (ชื... | 63,083 |
def update_widget(request):
""" Update single Widget """
result = {}
widgets = get_sidebar_widgets()
widget_id = request.POST.get('widget_id', 0)
try:
widget_item = SidebarWidget.objects.get(pk=widget_id)
except SidebarWidget.DoesNotExist:
return result
else:
widget... | 63,084 |
def test_save_somethings() -> None:
"""Test saving somethings"""
with TestClient(app) as client:
u1 = SomethingDto(
something_id=str(uuid.uuid4()),
event_id_datetime=datetime.datetime.now(),
something="some type",
)
u2 = SomethingDto(
some... | 63,085 |
def test_bundle_alignment_prior() -> None:
"""Test that cameras are aligned to have the Y axis pointing down."""
camera = pygeometry.Camera.create_perspective(1.0, 0.0, 0.0)
camera.id = "camera1"
r = types.Reconstruction()
r.add_camera(camera)
shot = r.create_shot(
"1", camera.id, pygeo... | 63,086 |
def simulate(cycles, initSize, offspring, lifespan, crisprFems, popLimit):
""" cycles: the number of cycles this simulation will run.
initSize: the initial size of the population.
offspring: max number of possible children per reproduction.
lifespan: maximum lifespan of an individual.
... | 63,087 |
def rpn_graph(feature_map, anchors_per_location, anchor_stride):
""" Region Proposal Network hesaplama grafiğini oluşturur.
feature_map: omurga özellikleri [toplu iş, yükseklik, genişlik, derinlik]
anchors_per_location: özellik haritasındaki piksel başına çapa sayısı
anchor_stride: Çapa yoğunluğunu ... | 63,088 |
def get_xml_schema_type():
"""
Get xml schema type.
"""
return '{http://www.w3.org/2001/XMLSchema-instance}type' | 63,089 |
def test_jacobian_ssm_evaluator_same_as_ssm(dummy_ssm_init):
"""
Test if calling jacobian() on the ssm_casadi function results
in the same derivative information as calling predict(..,jacobian = True,..) or linearize_predict(..,jacobian = True,..)
"""
dummy_ssm, n_s, n_u, linearize_mean = dummy_ssm... | 63,090 |
def main_log_set():
"""
メインの統計処理をあれこれする所
"""
# 身内村判定
def get_local_villager(vill_name):
for ng_word in ['ダンガンロンパ', 'ダンロン', 'RP', 'なんJ', '身内', 'クッキー', 'ク☆']: # 除外する村名リスト
if ng_word in vill_name:
return True
return False
# 設定変数
target = dict()
... | 63,091 |
def _get_state(ipaclient, idnsname):
"""Return set of currently defined SRV records."""
current = set()
result = ipaclient.get_dns_record(idnsname)['result']['result']
for item in result:
for record in item.get('srvrecord', []):
_w, _p, port, host = record.split()
current... | 63,092 |
def locate_max_drawdown(returns: pd.Series) -> Tuple[pd.Timestamp, pd.Timestamp, float]:
""" 寻找最大回撤周期
:param returns: 收益序列, 已时间为 ``index``
:return: (最大回撤开始时间, 最大回撤结束时间, 最大回撤比例)
"""
if len(returns) < 1:
raise ValueError('returns is empty.')
cumulative = empyrical.cum_returns(returns, st... | 63,093 |
async def make_result_embed(vote, results):
"""
Create a discord.Embed object from a set of results for a vote
:param vote: the vote the results are for
:param results: the results from the vote
:return: discord.Embed object to send
"""
embed = discord.Embed(title=f"{vote.title} Results:")
... | 63,094 |
def stash(keychain, treasure, value, location):
"""
Dynamically update chest file. Override old value if exists.
\f
:param keychain: Object containing key and spice
:type keychain: :class:`narrenschiff.chest.Keychain`
:param treasure: Name of the variable
:type treasure: ``str``
:param ... | 63,095 |
def count_bits_above(string: int, pos: int) -> int:
"""Return the number of set bits higher than the position
Args:
string (int) - bit string
pos (int) - position in the bit string
"""
return count_bits(string & ~(2**(pos + 1) - 1)) | 63,096 |
def fix_location(record_feature, plus_num):
"""
Fix a subseq loaction problem. If you use position to subseq a child feature from a SeqRecord instance, the start
location of the child feature would return to zero. So we should plus the real start position to it.
:param record_feature: a record feature (... | 63,097 |
def GetEquivalentPatchsets(host, project, change, patchset):
"""Gets equivalent patchsets that are applicable for sharing coverage data.
The reason why this is not just the current patchset number is because there
may have been a succession of "trivial" changes before the current patchset.
Args:
host (str... | 63,098 |
def to_int(value):
"""Convert to integer"""
return value & 0xFF | 63,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.