input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
:vartype client_request_id: str
:param errors: The error details.
:type errors:
list[~azure.mgmt.recoveryservicessiterecovery.models.ReplicationEligibilityResultsErrorInfo]
"""
_validation = {
'client_request_id': {'readonly': True},
}
_attribute_map = {
'client_request_id': {'key': 'clientRequestId', 'type'... | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 30 20:39:24 2018
@author: <NAME>
"""
import pandas as pd
import time
import datetime as datetime
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
import numpy as np
begin = time.ti... | |
<filename>cstatgen/src/egglib/test/t_egglib_binding.py<gh_stars>1-10
import os
from .. import egglib_binding
import example_files
########################################################################
def test_ABC():
"""
Test ABC
"""
print "## Testing egglib_binding.ABC"
f = open("ABC_input1.txt", 'w')
f.... | |
<gh_stars>10-100
"""
==========
Engine
==========
Engine runs the simulation.
"""
import os
import logging as log
import pprint
from typing import (
Any, Dict, Optional, Union, Tuple, Callable)
import math
import datetime
import time as clock
import uuid
from vivarium.composites.toys import Proton, Electron, Sine, ... | |
import sys
import unittest
import copy
import numpy as np
from scipy.linalg import block_diag
import pyinduct as pi
import pyinduct.hyperbolic.feedforward as hff
import pyinduct.parabolic as parabolic
import pyinduct.simulation as sim
from pyinduct.tests import show_plots
import pyqtgraph as pg
class SimpleInput(s... | |
<reponame>ucd-cws/amaptor
import os
import logging
log = logging.getLogger("amaptor.layer")
import arcpy
from amaptor.version_check import PRO, ARCMAP, mapping, mp
from amaptor.errors import NotSupportedError, EmptyFieldError, LayerNotFoundError
from amaptor.functions import get_workspace_type, get_workspace_factory_... | |
import re
from typing import Dict, Union, Iterable, Any
from ._BaseClasses import DOMNode
POSSIBLE_TAG_CHILD = Union[str, int, float, DOMNode]
def maketag(name: str) -> type:
"""
Creates a new class for a tag with the specified name.
The class can be used like those associated with standard HTML tags :
"""
tag... | |
bias or input "
f"node ({src_node.id}->{dest_node.id}). Nodes of this type "
f"don't process input.")
weight = (np.random.uniform(*self.config.new_weight_interval)
if weight is None else weight)
connection = ne.neat.ConnectionGene(cid=cid,
from_node=src_node,
to_node=dest_node,
weight=weight)
connection.enab... | |
<gh_stars>0
from __future__ import print_function
from cloudmesh.config.cm_config import cm_config_server
from cloudmesh_base.util import banner
import os
import sys
from cloudmesh_base.util import path_expand
from cloudmesh.shell.Shell import Shell
# BUG: replace with Shell
import sh
# need to get rid of fabric late... | |
<gh_stars>0
import numpy as np
from Code.JsonChecker import JsonChecker
class EndResults:
"""
In this class, the intervals of growth of the bacteria are calculated using different formulas/equations that are
specifically called in the class.
There are a total of 4 different formulas/equations to calculate the gr... | |
Constraint(expr=m.x556*(10.749094 + m.x2039) - m.x2994 == 0)
m.c557 = Constraint(expr=m.x557*(6.95367819652136 + m.x2091) - m.x2995 == 0)
m.c558 = Constraint(expr=m.x558*(68.611061605179 + m.x2092) - m.x2996 == 0)
m.c559 = Constraint(expr=m.x559*(149.982358690318 + m.x2093) - m.x2997 == 0)
m.c560 = Constraint(expr=... | |
timeout_ctype, count_ctype, voltage_measurements_ctype, current_measurements_ctype, in_compliance_ctype, None if actual_count_ctype is None else (ctypes.pointer(actual_count_ctype)))
errors.handle_error(self, error_code, ignore_warnings=False, is_error_handling=False)
return voltage_measurements_array, current_measur... | |
= None,
shortDesc = u"""""",
longDesc =
u"""
""",
)
entry(
index = -1,
label = "Cds-Cds(Cds-Cdd-Cd)S2s",
group =
"""
1 * Cd u0 {2,S} {4,D} {5,S}
2 Cd u0 {1,S} {3,D}
3 Cdd u0 {2,D} {6,D}
4 Cd u0 {1,D}
5 S2s u0 {1,S}
6 C u0 {3,D}
""",
thermo = None,
shortDesc = u"""""",
longDesc =
u"""
""",
)
entry(
index... | |
one number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should ... | |
expectativa esta me matando','surpresa'),
('vou caminhar sempre na expectativa de encontrá-lo','surpresa'),
('você emudece minhas palavras','surpresa'),
('minhas palavras vão emudecer se não parar de me surpreender','surpresa'),
('a mulher e um efeito deslumbrante da natureza','surpresa'),
('estou deslumbrada com ... | |
<gh_stars>0
# Copyright 2012 <NAME>. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from numpy import array, zeros, ones, hstack, delete, insert, arange
from randnums import FltRand, IntRand, FlipCoin
def SimpleChromo(x, nbases):
"""
Simpl... | |
<gh_stars>0
# coding: utf-8
import numpy as np
import argparse
import matplotlib.pyplot as plt
from time import sleep
import support
from mpl_toolkits.mplot3d import Axes3D
def rungekutta4d( func , argdict = None ,spoint = 0, epoint = 100, initial_value = 1, N = 1000 , numberofvalues = 2 ):
h = ( e... | |
<filename>run_benchmark.py
#!/usr/bin/env python3
import re
import os
import sys
import json
import fileinput
import subprocess
import time
import csv
import platform
import datetime
import configparser
import argparse
import collections
try:
import psutil
except ImportError:
found_psutil = False
print("Was not ab... | |
if not check_sparse_nnz and any(t.is_sparse for t in tupled_inputs if isinstance(t, torch.Tensor)):
return fail_test('gradcheck expects all tensor inputs are dense when check_sparse_nnz is set to False.')
# Make sure that gradients are saved for at least one input
any_input_requiring_grad = False
for idx, inp in en... | |
"""
const_pass.py - AST pass that collects constants.
Immutable string constants like 'new Str("foo")' are moved to the top level of
the generated C++ program for efficiency.
"""
import json
from typing import overload, Union, Optional, Any, Dict, List
from mypy.visitor import ExpressionVisitor, StatementVisitor
fro... | |
<reponame>ArnePlatteau/time_var_extr_index
# -*- coding: utf-8 -*-
"""
Created on Fri May 7 11:22:11 2021
@author: arnep
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from methods_extremal_index import non_parametric_extremal_ind... | |
25*m.b863 <= 0)
m.c684 = Constraint(expr= m.x312 - 22*m.b864 <= 0)
m.c685 = Constraint(expr= m.x313 - 22*m.b865 <= 0)
m.c686 = Constraint(expr= m.x314 - 25*m.b866 <= 0)
m.c687 = Constraint(expr= m.x315 - 22*m.b867 <= 0)
m.c688 = Constraint(expr= m.x316 - 22*m.b868 <= 0)
m.c689 = Constraint(expr= m.x317 - 25*m.b86... | |
from cleverhans.attacks import FastGradientMethod
from cleverhans.attacks_tf import fgm
import tensorflow as tf
import cleverhans.utils as utils
import cleverhans.utils_tf as utils_tf
import collections
from cleverhans.model import Model, CallableModelWrapper
import numpy as np
class MyFastGradientMethod(FastGradient... | |
condition_number = calculate_condition_number(petsc_mat, num_of_factors)
result = ConditionNumberResult(
form=a,
assembled_form=Smat,
condition_number=condition_number,
sparse_operator=Mnp,
number_of_dofs=number_of_dofs,
nnz=nnz,
is_operator_symmetric=is_symmetric,
bcs=bc_multiplier
)
return result
def so... | |
<gh_stars>0
from astropy.io import fits as apfts
from random import uniform as rdunf
from random import choice as rdchc
from random import random as rdrnd
from astropy import convolution as apcvl
from astropy.io import fits as apfts
from Fnc_Syn_Dir import *
from Fnc_Syn_Mth import *
from Fnc_Syn_Tbl import *
####Fnc... | |
#! /usr/bin/env python
# -*- coding: utf-8
import sys
import os
import cv2
import numpy as np
import time
import StringIO
from threading import Lock
from misc import WithTimer
from numpy_cache import FIFOLimitedArrayCache
from app_base import BaseApp
from core import CodependentThread
from image_misc import norm01, n... | |
<filename>test/unit/test_ssl_certificate_api_v1.py
# -*- coding: utf-8 -*-
# (C) Copyright IBM Corp. 2020.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/L... | |
nondimensionalized with :math:`\alpha'=\alpha (4 \pi \varepsilon_{0}) 3k_{B}T e^{-6}`, where the dimensionalized version is the polarizability volume
beadB : dict
Dictionary of Mie and multipole parameters for bead_B.
- epsilon (float) Energy parameter scaled by :math:`k_{B}` in [K], or nondimensionalized as :math... | |
``PermissionDenied`` -- authorization failure
*compliance: mandatory -- This method must be implemented.*
"""
pass
@abc.abstractmethod
def register_for_changed_offset_events(self):
"""Registers for notification of updated offset events.
``OffsetEventReceiver.changedOffsetEvents()`` is invoked when an
offset... | |
import numpy as np
import pandas as pd
import xarray as xr
import Grid
import pf_dynamic_sph
import os
from timeit import default_timer as timer
import sys
from copy import deepcopy
# import matplotlib
# import matplotlib.pyplot as plt
if __name__ == "__main__":
start = timer()
# ---- INITIALIZE GRIDS ----
(Lx, ... | |
from time import time
import cv2
import numpy as np
from scene import Scene
from light import Light
from camera import Camera
from game_object import GameObject
def triangle_area(v0, v1, v2):
"""
| v01[0] v01[1] |
| v02[0] v02[1] | = v01[0]*v02[1] - v01[1]*v02[0]
"""
return (v1[0]-v0[0])*(v2[1]-v0[1]) - (v1[1]... | |
import numpy as np
import time
import math
# auxiliary function for cleaning the workspace
def clear_all():
gl = globals().copy()
for var in gl:
if var[0] == '_': continue
if 'func' in str(globals()[var]): continue
if 'module' in str(globals()[var]): continue
del globals()[var]
# Type: ndarra... | |
np.arange(0, n_j, 1), np.arange(0, n_z, 1))
# query points
xi = (di, dj, dz)
# multidimensional interpolation
output = interpolate.interpn(points, normalized_blurred_grid, xi, method='linear')
return output
# =============================================================
# class: synthetic_image_generate
# cr... | |
int_x, int_y)
def expand_img_column(self):
'''
Expand img column to its id-number and stack-name
'''
if self.has_label('rlnImageName'):
def parse_img_name(img):
img_id, img_name = img.split('@')
img_head, img_tail = os.path.split(img_name)
return int(img_id), img_tail
img_num_list = []
img_head_list = []
... | |
)
} ) )
} )
}
} )
@IsolatedYcmd( { 'global_ycm_extra_conf':
PathToTestFile( 'extra_confs', 'brace_on_same_line.py' ) } )
def test_Subcommands_Format_ExtraConf_BraceOnSameLine( self, app ):
WaitUntilCompleterServerReady( app, 'javascript' )
filepath = PathToTestFile( 'extra_confs', 'func.js' )
RunTest( app, ... | |
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyrig... | |
<filename>IRIS_data_download/IRIS_download_support/obspy/signal/tests/test_quality_control.py
# -*- coding: utf-8 -*-
"""
The Quality Control test suite.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
import os
import unittest
import nump... | |
# -*- coding: utf-8 -*-
"""
Contains the crawling logic.
"""
from __future__ import unicode_literals, absolute_import
import base64
from collections import defaultdict
import logging
import sys
import time
from pylinkvalidator.included.bs4 import BeautifulSoup, UnicodeDammit
import pylinkvalidator.compat as compat
f... | |
<reponame>monferrand/scipy_con_2019<filename>MachineLearning/dtaidistance/dtw_weighted.py
# -*- coding: UTF-8 -*-
"""
dtaidistance.dtw_weighted
~~~~~~~~~~~~~~~~~~~~~~~~~
Dynamic Time Warping (DTW) with custom internal distance function.
:author: <NAME>
:copyright: Copyright 2018 KU Leuven, DTAI Research Group.
:licen... | |
PauliList([j * "X", "-i" + j * "Y", j * "Z"])
self.assertEqual(pauli.delete([0, 2]), PauliList("-i" + j * "Y"))
self.assertEqual(pauli.delete([1, 2]), PauliList(j * "X"))
self.assertEqual(pauli.delete([0, 1]), PauliList(j * "Z"))
with self.subTest(msg="single qubit"):
pauli = PauliList(["IIX", "iIYI", "ZII"])
va... | |
"二级类别":
raise serializers.ValidationError("[三级类别]的父类别必须是[二级类别]")
if self.initial_data['classes'] == "四级类别" and list.classes != "三级类别":
raise serializers.ValidationError("[四级类别]的父类别必须是[三级类别]")
return value
class ClientTypeDefinitionSerialize_List(serializers.ModelSerializer):
"""
客户类型定义--list
"""
cl... | |
to be noised.
Returns:
np.ndarray: Randomly noised image.
"""
if random.random() < self.p:
if self.random_params:
quality = self.get_params(self.min_quality, self.max_quality)
else:
quality = self.max_quality
return EF.compression_jpeg(img, quality=quality)
return img
def __repr__(self):
return self.__cla... | |
# Copyright 2014 Red Hat, Inc.
#
# Author: <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | |
= self._runtime_cxn(basename="both_proxies")
assert cxn.gateway == Connection("winner@everything:777")
def multi_hop_works_ok(self):
cxn = self._runtime_cxn(basename="proxyjump_multi")
innermost = cxn.gateway.gateway.gateway
middle = cxn.gateway.gateway
outermost = cxn.gateway
assert innermost == Connection("ju... | |
1 , 4 , 0 , 192 , (3, 0, None, None) , 0 , )),
(( 'Copy' , 'Item' , ), 61490, (61490, (), [ (16393, 10, None, None) , ], 1 , 1 , 4 , 0 , 196 , (3, 0, None, None) , 0 , )),
(( 'Delete' , ), 61514, (61514, (), [ ], 1 , 1 , 4 , 0 , 200 , (3, 0, None, None) , 0 , )),
(( 'Display' , 'Modal' , ), 61606, (61606, (), [ (12,... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# __
# Author : <NAME> and team
# Tool : Source
# Usage : ./Source.py example.com (or) python Source.py example.com
# Description: This scanner automates the process of security scanning by using a
# multitude of available linux security tools and some custom scripts.
#
# Impo... | |
key_certs):
"""
Validates we're properly signed by the signing certificates.
.. versionadded:: 1.6.0
:param list key_certs: :class:`~stem.descriptor.networkstatus.KeyCertificates`
to validate the consensus against
:raises: **ValueError** if an insufficient number of valid signatures are present.
"""
# sha1 ... | |
<filename>archive/src/indigox/periodictable.py
from indigox.exception import IndigoSearchError
class _Element(object):
def __init__(self, name, symbol, group, period, number, mass, atomic_radii,
covalent_radii, vdw_radii, chi, hyper=None):
self.name = name
self.symbol = symbol
self.group = group
self.period = pe... | |
# Copyright 2008 <NAME>, Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Re... | |
<reponame>eugenevinitsky/cdc_bottlenecks<filename>flow/agents/centralized_PPO.py<gh_stars>1-10
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
"""An example of customizing PPO to leverage a centralized critic."""
import argparse
import numpy as np
from gym.... | |
= None
if 'tags' in kwargs:
tags = tags_to_oset(kwargs.pop('tags'))
# if this tensor has owners, update their ``tag_map``.
if self.check_owners():
for ref, tid in self._owners.values():
ref()._modify_tensor_tags(self.tags, tags, tid)
self._tags = tags
if 'left_inds' in kwargs:
self.left_inds = kwargs.pop('l... | |
<filename>vernon/vkl.py
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 <NAME> and collaborators.
# Licensed under the MIT License.
"""Modeling the population of radiation belt electrons numerically using the
(V_{C_g},K,L^*) PDE coordinate space of Subbotin & Shprits
(2012JGRA..117.5205S, 10.1029/2011JA017467).... | |
<gh_stars>1-10
import cv2
import numpy as np
import warnings
from ..general.parameters import get_param_val, get_method_key
from .cmap import colour_array
from ..customexceptions.annotator_error import *
from ..user_methods import *
warnings.simplefilter('ignore')
"""
-------------------------------------------------... | |
`string` from: `"MIN_COMBINED", "MIN_FIRST", "SCALED"`. Defaults to `"MIN_COMBINED"`.
narrow_range: An optional `bool`. Defaults to `False`.
axis: An optional `int`. Defaults to `-1`.
dtype: An optional `tf.DType` from: `tf.bfloat16, tf.float32`. Defaults to `tf.float32`.
Type of the output tensor. Currently Dequan... | |
#!/usr/bin/env python
########################################################################
#
# To build panda using this script, type 'makepanda.py' on unix
# or 'makepanda.bat' on windows, and examine the help-text.
# Then run the script again with the appropriate options to compile
# panda3d.
#
##################... | |
<filename>yuno/collection.py
"""
collection.py
A collection is a set of documents.
"""
import inspect
import threading
import typing
import pymongo.database
import pymongo.collection
from yuno import encoder, objects, database
from yuno.cursor import Cursor
from yuno.direction import IndexDirectionType, SortDirectio... | |
0,
'flattenType': 'light',
'loadType': 'loadModelCopy',
'modelPath': 'phase_10/models/cashbotHQ/shelf_A1.bam'},
10000: {'type': 'nodepath', 'name': 'crateField',
'comment': '',
'parentEntId': 0,
'pos': Point3(0.0, -51.0, 0.0),
'hpr': Vec3(0.0, 0.0, 0.0),
'scale': Point3(1.0, 1.0, 1.0)},
10004: {'typ... | |
x: Centre of the area to sample (X coordinate).
@param y: Centre of the area to sample (Y coordinate).
@param dx: Optional size of the area to sample (X coordinate).
@param dy: Optional size of the area to sample (Y coordinate).
@return: Floating point value.
"""
pass
def saveToScript():
"""saveToScript(filena... | |
import logging
logging.root.setLevel(logging.INFO)
import six, ptypes
from ptypes import *
import datetime, time
## General structures
class MSTime(pbinary.struct):
_fields_ = [
(5, 'Hour'),
(6, 'Minute'),
(5, '2Seconds'),
]
def time(self):
h, m, ds = (self[fld] for fld in ['Hour', 'Minute', '2Seconds'])
ret... | |
if isinstance(self.nonlin, SVFModel):
# propagate backward by scaling and squaring
g, h = spatial.exp_backward(vel00, g, h, steps=self.nonlin.steps)
sumgrad = g.mul_(factor) if sumgrad is None else sumgrad.add_(g, alpha=factor)
if hess:
sumhess = h.mul_(factor) if sumhess is None else sumhess.add_(h, alpha=factor... | |
import py
import ctypes
from pypy.rlib.objectmodel import specialize, we_are_translated
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.jit.codegen.model import AbstractRGenOp, GenLabel, GenBuilder
from pypy.jit.codegen.model import GenVar, GenConst, CodeGenSwitch
from pypy.jit.codegen.model import Rep... | |
'green')
plt.plot(repression_threshold_results[:,0]/10000,
repression_threshold_results[:,10], color = 'blue')
# plt.axvline( 23000 )
plt.axvline( 3.14 )
# plt.fill_between(repression_threshold_results[:,0],
# repression_threshold_results[:,2] + repression_threshold_results[:,3],
# np.max(repression_threshold_result... | |
<gh_stars>1-10
"""
For comparing a predicted interaction XML against a gold standard
"""
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/..")
#print os.path.dirname(os.path.abspath(__file__))+"/.."
from Utils.ProgressCounter import ProgressCounter
from optparse import OptionParser
import Cor... | |
advice_topic_page.page_ptr,
# NB: article_page is deliberately NOT in this list
]
@pytest.mark.skip(reason='We need more of the page tree ported before we can test this.')
def test_base_content_page__ancestors_in_app__involving_folder_pages():
pass
@pytest.mark.django_db
def test_base_content_page__get_breadcrum... | |
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | |
10), keep_size=False)
pads each side by a random value from the range 0px to 10px (the value
is sampled per side). After padding, the images are NOT resized to
their original size (i.e. the images may end up having different
heights/widths).
>>> aug = iaa.CropAndPad(px=((0, 10), (0, 5), (0, 10), (0, 5)))
pads ... | |
<reponame>kifarid/ray
import gym
import logging
import numpy as np
from ray.rllib.utils.framework import try_import_jax, try_import_tf, \
try_import_torch
jax, _ = try_import_jax()
tf1, tf, tfv = try_import_tf()
if tf1:
eager_mode = None
try:
from tensorflow.python.eager.context import eager_mode
except (ImportE... | |
<filename>src/clims/legacy/utility/testing.py<gh_stars>0
"""
Various helpers for mocking data quickly, in either unit tests or notebooks.
"""
from __future__ import absolute_import
from clims.legacy.domain import *
from clims.legacy.service.dilution.service import *
from mock import MagicMock
from clims.legacy.context... | |
<gh_stars>0
'''Tasks specific to the IsMore project.'''
from __future__ import division
from collections import OrderedDict
import time
import datetime
import os
import re
import pdb
import pickle
import tables
import math
import traceback
import numpy as np
import pandas as pd
import random
import multiprocessing as... | |
<gh_stars>0
#!/usr/bin/env python3 -u -B
import argparse
import contextlib
import errno
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import unittest
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), os.path.pardir))
import backups_lib
__pack... | |
limitations.
event_parser (Parser): parses log stream into events and saves them to
event file.
**kwargs (dict): additional kwargs to pass onto the communication setup.
Returns:
SwitchboardDefault: instance of SwitchboardDefault.
Raises:
SwitchboardCreationError: if communication type not recognized.
"""
if ... | |
< Cursor[0] < 160:
UI.Ba_Slc = 12
rlr = 0
elif 160 < Cursor[0] < 189:
UI.Ba_Slc = 13
rlr = 1
elif 190 < Cursor[0] < 220:
UI.Ba_Slc = 14
rlr = 2
elif 221 < Cursor[0] < 250:
UI.Ba_Slc = 15
if UI.color_picker == -1:
UI.color_picker = 0
UI.color_picked = -1
elif event.button == 2:
if shift:
... | |
if statusbar:
self.statusbar = statusbar
def confirm(self, s):
raise NotImplementedError
def notify(self, s, n=10, wait_for_keypress=False):
raise NotImplementedError
def file_prompt(self, s):
raise NotImplementedError
class SourceNotFound(Exception):
"""Exception raised when the requested source could not... | |
has been provided, record it.
elif name in ("hyphenation", "hyph"):
data_append(config, data, "hyphenation", t_vec(config, t))
# If pinyin reading has been provided, record it (this is reading
# of a Chinese word in romanized forms, i.e., western characters).
elif name == "pinyin reading of":
data_extend(config, ... | |
= JOB_STATUS_DICT['waiting']
# update upload jobs to "running" for files A, B, and C for DABS submissions or for the upload job in FABS
upload_jobs = [job for job in jobs if job.job_type_id in [JOB_TYPE_DICT['file_upload']] and
job.file_type_id in initial_file_types]
for job in upload_jobs:
job.job_status_id = J... | |
import time
import numpy as np
from .peeler_tools import *
from .peeler_tools import _dtype_spike
from .peeler_engine_base import PeelerEngineGeneric
from .peakdetector import get_peak_detector_class
import matplotlib.pyplot as plt
from . import pythran_tools
if hasattr(pythran_tools, '__pythran__'):
HAVE_PYTHR... | |
squares sequentially from 00 to 39 we can concatenate these two-digit numbers to produce strings that correspond with sets of squares.
Statistically it can be shown that the three most popular squares, in order,
are JAIL (6.24%) = Square 10, E3 (3.18%) = Square 24,
and GO (3.09%) = Square 00.
So these three most popula... | |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | |
<reponame>Supybot/Supybot
###
# Copyright (c) 2002-2005, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this ... | |
#!/usr/bin/env python
import numpy as np
def cb_op(oper_A, t_mat):
"""
Change the basis of an operator :math:`\hat{O}` from one basis :math:`A`: :math:`\\psi^{A}_{i}` to another basis :math:`B`: :math:`\\phi^{B}_{j}`.
.. math::
O^{\\prime} = T^{\dagger} O T,
T_{ij} = <\\psi^{A}_{i}|\\phi^{B}_{j}>.
Para... | |
return wordfq
def count_words(wordlst: list):
"""
count words in tweet text from list of list, dict, or str
:param wordlst: list of tweets
:return: word count, tweet count
"""
wrd_count: int = 0
tw_count: int = 0
for tw in wordlst:
if isinstance(tw, dict):
tw_wrds: list = tw['text'].split()
elif isinstance(... | |
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | |
= s1.indexOf(s2);
if (n == -1) return '';
return s1.substring(0, n);
},
'string', false, []],
'substring-after': [function(s1, s2) {
if (arguments.length != 2) {
throw Error('Function substring-after expects (string, string)');
}
s1 = s1.string(this);
s2 = s2.string(this);
var n = s1.indexOf(s2);
if (n == -... | |
ref_log = os.path.join(mr_workdir, '{0}_ref.log'.format(pdb_code))
ref_map = os.path.join(mr_workdir, '{0}_refmac_2fofcwt.map'.format(pdb_code))
diff_map = os.path.join(mr_workdir, '{0}_refmac_fofcwt.map'.format(pdb_code))
pdb, mtz, map_, dmap, mr_log, ref_log = list(self.adjust_paths_of_files(
[ref_pdb, ref_mtz, ... | |
default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.invitation_tickets_id_target_portal_member_get(id, callback=callback_function)
:param callback function: Th... | |
else:
policy_dir = getRequiredDirectory("policydir", "policy")
pd = path(policy_dir)
if not pd.isdir():
print("Policy dir %s does not exist, creating it" % policy_dir)
pd.mkdir()
else:
for domain in domains:
if policytypes[domain] != 'hdc':
if Settings.config.has_section("policy_" + domain):
policy_dir = getR... | |
thr in client_threads]
topic_conf.del_config()
s3_notification_conf.del_config(notification=notification_name)
# delete the bucket
zones[0].delete_bucket(bucket_name)
http_server.close()
def test_ps_topic():
""" test set/get/delete of topic """
_, ps_zones = init_env()
realm = get_realm()
zonegroup = realm.m... | |
does not specify a type.".format(name))
# Rule: If the parameter definition has no default value, the template must provide a value
parameter = parameters.get(name, definition.get('defaultValue'))
if parameter is None:
raise ValueError("A value for parameter '{}' must be provided "
"by the job.".format(name))
# R... | |
<gh_stars>0
import warnings
import numpy as np
import dateutil
import dateutil.parser
import geopandas as gpd
import pandas as pd
import pytz
import warnings
from shapely import wkt
from shapely.geometry import Point
def localize_timestamp(dt_series, pytz_tzinfo, col_name):
"""
Helper function that adds timezone i... | |
# -*- coding: utf-8 -*-
import numpy as np
import json
import os
import sys
import time
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.utils
from torchvision import models
import torchvision.datasets ... | |
Patronymic name, Matronymic name, etc
:ivar code: Indicates the name element code defined by postal
standard groups like ECCMA, ADIS, UN/PROLIST for postal
services.
:ivar other_attributes:
"""
content: List[object] = field(
default_factory=list,
metadata={
"type": "Wildcard",
"namespace": "##any",
"mixed": ... | |
ERROR: type should be string, got "https://en.wikipedia.org/wiki/Prime_number\n 2. http://primes.utm.edu/notes/gaps.html\n\n Examples\n ========\n\n >>> from sympy import primerange, sieve\n >>> print([i for i in primerange(1, 30)])\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n\n The Sieve method, primerange, is generally faster but it will\n occupy more memory as the sieve stores values. The default\n instance of Sieve, named sieve, can be used:\n\n >>> list(sieve.primerange(1, 30))\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n\n See Also\n ========\n\n nextprime : Return the ith prime greater than n\n prevprime : Return the largest prime smaller than n\n randprime : Returns a random prime in a given range\n primorial : Returns the product of primes based on condition\n Sieve.primerange : return range from already computed primes\n or extend the sieve to contain the requested\n range.\n \"\"\"\n from sympy.functions.elementary.integers import ceiling\n\n if a >= b:\n return\n # if we already have the range, return it\n if b <= sieve._list[-1]:\n for i in sieve.primerange(a, b):\n yield i\n return\n # otherwise compute, without storing, the desired range.\n\n # wrapping ceiling in as_int will raise an error if there was a problem\n # determining whether the expression was exactly an integer or not\n a = as_int(ceiling(a)) - 1\n b = as_int(ceiling(b))\n while 1:\n a = nextprime(a)\n if a < b:\n yield a\n else:\n return\n\n\ndef randprime(a, b):\n \"\"\" Return a random prime number in the range [a, b).\n\n Bertrand's postulate assures that\n randprime(a, 2*a) will always succeed for a > 1.\n\n References\n ==========\n\n - https://en.wikipedia.org/wiki/Bertrand's_postulate\n\n Examples\n ========\n\n >>> from sympy import randprime, isprime\n >>> randprime(1, 30) #doctest: +SKIP\n 13\n >>> isprime(randprime(1, 30))\n True\n\n See Also\n ========\n\n primerange : Generate all primes in a given range\n\n \"\"\"\n if a >= b:\n return\n a, b = map(int, (a, b))\n n = random.randint(a - 1, b)\n p = nextprime(n)\n if p >= b:\n p = prevprime(b)\n if p < a:\n raise ValueError(\"no primes exist in the specified range\")\n return p\n\n\ndef primorial(n, nth=True):\n \"\"\"\n Returns the product of the first n primes (default) or\n the primes less than or equal to n (when ``nth=False``).\n\n >>> from sympy.ntheory.generate import primorial, randprime, primerange\n >>> from sympy import factorint, Mul, primefactors, sqrt\n >>> primorial(4) # the first 4 primes are 2, 3, 5, 7\n 210\n >>> primorial(4, nth=False) # primes <= 4 are 2 and 3\n 6\n >>> primorial(1)\n 2\n >>> primorial(1, nth=False)\n 1\n >>> primorial(sqrt(101), nth=False)\n 210\n\n One can argue that the primes are infinite since if you take\n a set of primes and multiply them together (e.g. the primorial) and\n then add or subtract 1, the result cannot be divided by any of the\n original factors, hence either 1 or more new primes must divide this\n product of primes.\n\n In this case, the number itself is a new prime:\n\n >>> factorint(primorial(4) + 1)\n {211: 1}\n\n In this case two new primes are the factors:\n\n >>> factorint(primorial(4) - 1)\n {11: 1, 19: 1}\n\n Here, some primes smaller and larger than the primes multiplied together\n are obtained:\n\n >>> p = list(primerange(10, 20))\n >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))\n [2, 5, 31, 149]\n\n See Also\n ========\n\n primerange : Generate all primes in a given range\n\n \"\"\"\n if nth:\n n = as_int(n)\n else:\n n = int(n)\n if n < 1:\n raise ValueError(\"primorial argument must be >= 1\")\n p = 1\n if nth:\n for i in range(1, n + 1):\n p *= prime(i)\n else:\n for i in primerange(2, n + 1):\n p *= i\n return p\n\n\ndef cycle_length(f, x0, nmax=None, values=False):\n \"\"\"For a given iterated sequence, return a generator that gives\n the length of the iterated cycle (lambda) and the length of terms\n before the cycle begins (mu); if ``values`` is True then the\n terms of the sequence will be returned instead. The sequence is\n started with value ``x0``.\n\n Note: more than the first lambda + mu terms may be returned and this\n is the cost of cycle detection with Brent's method; there are, however,\n generally less terms calculated than would have been calculated if the\n proper ending point were determined, e.g. by using Floyd's method.\n\n >>> from sympy.ntheory.generate import cycle_length\n\n This will yield successive values of i <-- func(i):\n\n >>> def iter(func, i):\n ... while 1:\n ... ii = func(i)\n ... yield ii\n ... i = ii\n ...\n\n A function is defined:\n\n >>> func = lambda i: (i**2 + 1) % 51\n\n and given a seed of 4 and the mu and lambda terms calculated:\n\n >>> next(cycle_length(func, 4))\n (6, 2)\n\n We can see what is meant by looking at the output:\n\n >>> n = cycle_length(func, 4, values=True)\n >>> list(ni for ni in n)\n [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]\n\n There are 6 repeating values after the first 2.\n\n If a sequence is suspected of being longer than you might wish, ``nmax``\n can be used to exit early (and mu will be returned as None):\n\n >>> next(cycle_length(func, 4, nmax = 4))\n (4, None)\n >>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)]\n [17, 35, 2, 5]\n\n Code modified from:\n https://en.wikipedia.org/wiki/Cycle_detection.\n \"\"\"\n\n nmax = int(nmax or 0)\n\n # main phase: search successive powers of two\n power = lam = 1\n tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.\n i = 0\n while tortoise != hare and (not nmax or i < nmax):\n i += 1\n if power == lam: # time to start a new power of two?\n tortoise = hare\n power *= 2\n lam = 0\n if values:\n yield hare\n hare = f(hare)\n lam += 1\n if nmax and i == nmax:\n if values:\n return\n else:\n yield nmax, None\n return\n if not values:\n # Find the position of the first repetition of length lambda\n mu = 0\n tortoise = hare = x0\n for i in range(lam):\n hare = f(hare)\n while tortoise != hare:\n tortoise = f(tortoise)\n hare = f(hare)\n mu += 1\n if mu:\n mu -= 1\n yield lam, mu\n\n\ndef composite(nth):\n \"\"\" Return the nth composite number, with the composite numbers indexed as\n composite(1) = 4, composite(2) = 6, etc....\n\n Examples\n ========\n\n >>> from sympy import composite\n >>> composite(36)\n 52\n >>> composite(1)\n 4\n >>> composite(17737)\n 20000\n\n See Also\n ========\n\n sympy.ntheory.primetest.isprime : Test if n is prime\n primerange : Generate all primes in a given range\n primepi : Return the number of primes less than or equal to n\n prime : Return the nth prime\n compositepi : Return the number of positive composite numbers less than or equal to n\n \"\"\"\n n = as_int(nth)\n if n < 1:\n raise ValueError(\"nth must be a positive integer; composite(1) == 4\")\n composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]\n if n <= 10:\n return composite_arr[n - 1]\n\n a, b = 4, sieve._list[-1]\n if n <= b - primepi(b) - 1:\n while a < b - 1:\n mid = (a + b) >> 1\n if mid - primepi(mid) - 1 > n:\n b = mid\n else:\n a = mid\n if isprime(a):\n a -= 1\n return a\n\n from sympy.functions.special.error_functions import li\n from sympy.functions.elementary.exponential import log\n\n a = 4 # Lower bound for binary search\n b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.\n\n while a < b:\n mid = (a + b) >> 1\n if mid - li(mid) - 1 > n:\n b = mid\n else:\n a = mid + 1\n\n n_composites = a - primepi(a) - 1\n while n_composites > n:\n if not isprime(a):\n n_composites -= 1\n a -= 1\n if isprime(a):\n a -= 1\n return a\n\n\ndef compositepi(n):\n \"\"\" Return the number of positive composite numbers less than or equal to n.\n The first positive composite is 4, i.e. compositepi(4) = 1.\n\n Examples\n ========\n\n >>> from sympy import compositepi\n >>> compositepi(25)\n 15\n >>> compositepi(1000)\n 831\n\n See Also\n ========\n\n sympy.ntheory.primetest.isprime : Test if n is prime\n primerange : Generate all primes in a" | |
<reponame>a2cps/python-vbr
"""Autogenerated 2021-11-16T11:37:36.440435 by redcap_classfiles.py
"""
from ....pgrest import *
from ...constants import Constants
from ..rcconstants import REDCapConstants
from ..rcaptable import RcapTable
__all__ = ["RcapBpisfTheBriefPainInventoryV23ShortFormBpi"]
class RcapBpisfTheBr... | |
<filename>experiments/bnci_horizon_experiment/bnci_utils.py
import numpy as np
import tensorflow as tf
import nengo_dl
from tensorflow.python.keras import Input, Model
import nengo
from tensorflow.python.keras.layers import Conv2D, Dropout, AveragePooling2D, Flatten, Dense, BatchNormalization, LSTM
from sklearn.preproc... | |
<filename>mavsdk/generated/telemetry_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from . import telemetry_pb2 as telemetry__pb2
class TelemetryServiceStub(object):
"""
Allow users to get vehicle telemetry and state information
(e.g. battery, GPS, RC connection, fli... | |
dealing with a unix domain socket
if host.endswith('.sock'):
if not hasattr(socket, "AF_UNIX"):
raise pymongo.errors.ConnectionFailure(
"UNIX-sockets are not supported on this system")
addrinfos = [(socket.AF_UNIX, socket.SOCK_STREAM, 0, host)]
else:
# Don't try IPv6 if we don't support it. Also skip it if hos... | |
_answer_id, 'ct_type': ct_type, 'name': name, 'parent': parent}, private_key=ts4_private_key, expect_ec=ts4_expect_ec, is_debot=ts4_is_debot)
if WrapperGlobal.auto_dispatch_messages:
ts4.dispatch_messages()
return _r_
def S_resolve(self, ct_type, name, parent, _answer_id=0, ts4_expect_ec=0):
"""
Wrapper for D4Ro... | |
for i in self.selected_data:
self.sizes[i, :] = (self.sizes[i, :] > 0) * size
self._set_view_slice()
self.events.size()
@property
def edge_width(self) -> Union[None, int, float]:
"""float: width used for all point markers."""
return self._edge_width
@edge_width.setter
def edge_width(self, edge_width: Union[... | |
"""
@file
@brief Validates runtime for many :epkg:`scikit-learn` operators.
The submodule relies on :epkg:`onnxconverter_common`,
:epkg:`sklearn-onnx`.
"""
import math
import copy
import os
import warnings
from importlib import import_module
import pickle
from time import perf_counter
import numpy
from cpyquickhelper.n... | |
<filename>tests/core/test_views.py
import time
from unittest import mock
from bs4 import BeautifulSoup
from directory_constants import cms
from modeltranslation.utils import build_localized_fieldname
import pytest
from rest_framework.serializers import Serializer
from django.forms.models import model_to_dict
from dja... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.