code stringlengths 281 23.7M |
|---|
def ip_from_request(request, exclude=None) -> str:
if (exclude is None):
exclude = settings.UPSTREAM_IPS
if hasattr(request, 'getClientIP'):
remote_addr = request.getClientIP()
forwarded = request.getHeader('x-forwarded-for')
else:
remote_addr = request.META.get('REMOTE_ADDR'... |
class RawValueOp(Node):
def __init__(self, args):
super().__init__([])
(value, final) = args
self.value = value
self.final_value = final
def forward(self, **kwargs):
return self.value
def follow(self, **kwargs):
return fmap(('*', self.value))
def final(sel... |
.slow
.skipif((not GPU_TESTS_ENABLED), reason='requires GPU')
def test_generate_deterministic(dolly_generator):
prompts = ['What is the Rust programming language?', 'What is spaCy?']
answers = ['Rust is a multi-paradigm, high-level, general-purpose programming language. Rust is designed to have a small, consist... |
def build_lm_graph(ngram_counts, vocab):
graph = gtn.Graph(False)
lm_order = len(ngram_counts)
assert (lm_order > 1), "build_lm_graph doesn't work for unigram LMs"
state_to_node = {}
def get_node(state):
node = state_to_node.get(state, None)
if (node is not None):
return ... |
def test_adding_a_extra_volume_with_volume_mount_as_yaml():
config = '\nextraVolumes:\n - name: extras\n emptyDir: {}\nextraVolumeMounts:\n - name: extras\n mountPath: /usr/share/extras\n readOnly: true\n'
r = helm_template(config)
extraVolume = r['statefulset'][uname]['spec']['template']['spec']... |
_os(*metadata.platforms)
def main():
(server, ip, port) = common.serve_web()
url = f'
mshta = 'C:\\Users\\Public\\mshta.exe'
dropped = 'C:\\Users\\Public\\posh.exe'
common.copy_file(EXE_FILE, mshta)
cmd = f'Invoke-WebRequest -Uri {url} -OutFile {dropped}'
common.log('Using a fake mshta to dr... |
class RegReplacePanelSaveCommand(sublime_plugin.TextCommand):
def is_existing_name(self, name):
original_name = self.view.settings().get('regreplace.name', None)
rules = sublime.load_settings('reg_replace_rules.sublime-settings').get('replacements', {})
msg = ("The name '%s' already exists i... |
class OptionSeriesBellcurveSonificationTracksMappingGapbetweennotes(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
.usefixtures('use_tmpdir', 'init_eclrun_config')
.dict(os.environ, {'LSB_JOBID': 'some-id'})
def test_env(eclrun_conf):
with open('eclrun', 'w', encoding='utf-8') as f, open('DUMMY.DATA', 'w', encoding='utf-8'):
f.write('#!/usr/bin/env python\nimport os\nimport json\nwith open("env.json", "w") as f:\n js... |
class OptionSeriesArcdiagramOnpoint(Options):
def connectorOptions(self) -> 'OptionSeriesArcdiagramOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionSeriesArcdiagramOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id(self, text: str):
... |
class Router():
def __init__(self, routes: typing.Optional[typing.Sequence[BaseRoute]]=None, redirect_slashes: bool=True, default: typing.Optional[ASGIApp]=None, on_startup: typing.Optional[typing.Sequence[typing.Callable[([], typing.Any)]]]=None, on_shutdown: typing.Optional[typing.Sequence[typing.Callable[([], ty... |
def verify_privacy_notice_and_historical_records(db: Session, notice_history_list: List[SafeStr]) -> None:
privacy_notice_count: int = db.query(PrivacyNotice).join(PrivacyNoticeHistory, (PrivacyNoticeHistory.privacy_notice_id == PrivacyNotice.id)).filter(PrivacyNoticeHistory.id.in_(notice_history_list)).distinct().... |
class Model(abc.ABC):
def __call__(self, data, axis=(- 1)):
if (not isinstance(data, _np.ndarray)):
raise TypeError(f'Model should take ndarray as input data, not {type(data)}.')
if (data.dtype.kind not in ('b', 'i', 'u', 'f', 'c')):
raise ValueError(f'Model should take numer... |
class StyleDefinition(object):
def __init__(self, name, style, default_highlight, icon_path, minimap):
self.name = name
self.color = style.get('color', default_highlight['color'])
self.style = select_bracket_style(style.get('style', default_highlight['style']), minimap)
self.underlin... |
def _listToString(l):
text = []
for value in l:
if isinstance(value, dict):
value = _dictToString(value)
elif isinstance(value, list):
value = _listToString(value)
elif isinstance(value, tuple):
value = _tupleToString(value)
elif isinstance(val... |
.django_db
def test_double_eclipsing_filters(client, monkeypatch, elasticsearch_award_index, subaward_with_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas_subaward(client, {'require': [_agency_path(BASIC_TAS), _tas_path(BASIC_TAS)], 'exclude': [_fa_path(BASIC_TAS)]})
asse... |
def browse_sortkey_reverse(prop):
if prop.startswith('-'):
prop = prop[1:]
reverse = True
else:
reverse = False
if (prop == 'text'):
return ((lambda x: ((x.is_directory == reverse), (x.link.text.lower() if (x.link and x.link.text) else x.name))), reverse)
if (prop == 'siz... |
def add_data_dictionary_to_zip(working_dir, zip_file_path):
write_to_log(message='Adding data dictionary to zip file')
data_dictionary_file_name = 'Data_Dictionary_Crosswalk.xlsx'
data_dictionary_file_path = os.path.join(working_dir, data_dictionary_file_name)
logger.info(f'Retrieving the data dictionar... |
(scope='function')
def system_with_no_uses(db: Session) -> System:
system = System.create(db=db, data={'fides_key': f'system_fides_key', 'name': f'system-{uuid4()}', 'description': 'tcf_relevant_system', 'organization_fides_key': 'default_organization', 'system_type': 'Service'})
return system |
def extractHeadpatsnovelWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('vorpal bunny and fortress uncle', 'Vorpal Bunny and Fortress Uncle', 'translated'), ('PRC',... |
class TestListItemObserverEqualHash(unittest.TestCase):
def test_not_equal_notify(self):
observer1 = ListItemObserver(notify=False, optional=False)
observer2 = ListItemObserver(notify=True, optional=False)
self.assertNotEqual(observer1, observer2)
def test_not_equal_optional(self):
... |
class EmmetConvertDataUrl(sublime_plugin.TextCommand):
def run(self, edit):
caret = get_caret(self.view)
syntax_name = syntax.from_pos(self.view, caret)
if syntax.is_html(syntax_name):
convert.convert_html(self.view, edit, caret)
elif syntax.is_css(syntax_name):
... |
def upgrade():
enum = ENUM('unverified', 'valid', 'rejected', name='nu_item_enum', create_type=False)
enum.create(op.get_bind(), checkfirst=True)
op.execute('ALTER TABLE nu_release_item ALTER COLUMN reviewed DROP DEFAULT')
op.alter_column('nu_release_item', 'reviewed', existing_type=sa.BOOLEAN(), type_=... |
def nd_grid(*vecs):
vecs = [np.array(v, copy=False).ravel() for v in vecs]
shape = tuple([v.size for v in vecs])
sz = np.prod(shape)
arrs = []
for (i, (v, n)) in enumerate(zip(vecs, shape)):
newshape = list(shape)
newshape.insert(0, newshape.pop(i))
arr = np.repeat(v, (sz / n... |
class ModelRegistry():
def __init__(self, database: databases.Database) -> None:
self.database = database
self.models = {}
self._metadata = sqlalchemy.MetaData()
def metadata(self):
for model_cls in self.models.values():
model_cls.build_table()
return self._me... |
def get_wishbone_user_port_ios(_id, aw, dw):
return [('user_port_{}'.format(_id), 0, Subsignal('adr', Pins(aw)), Subsignal('dat_w', Pins(dw)), Subsignal('dat_r', Pins(dw)), Subsignal('sel', Pins((dw // 8))), Subsignal('cyc', Pins(1)), Subsignal('stb', Pins(1)), Subsignal('ack', Pins(1)), Subsignal('we', Pins(1)), S... |
class TestHashingDataWrapper():
data_loaders = []
if os.path.exists(config['sf1_data_path']):
data_loaders.append(SF1QuarterlyData())
if (secrets['mongodb_adminusername'] is not None):
data_loaders.append(SF1QuarterlyDataMongo())
.parametrize('data_loader', data_loaders)
.parametrize... |
def test_scalar_area(f):
f.assign(1)
assert (abs((assemble((f * ds_t)) - 1.0)) < 1e-07)
assert (abs((assemble((f * ds_b)) - 1.0)) < 1e-07)
assert (abs((assemble((f * ds_tb)) - 2.0)) < 1e-07)
assert (abs((assemble((f * ds_v)) - 4.0)) < 1e-07)
assert (abs((assemble((f('+') * dS_h)) - 3.0)) < 1e-07... |
class EthstatsService(Service):
logger = logging.getLogger('trinity.components.ethstats.Service')
def __init__(self, boot_info: BootInfo, event_bus: EndpointAPI, server_url: str, server_secret: str, node_id: str, node_contact: str, stats_interval: int) -> None:
self.boot_info = boot_info
self.ev... |
class CoverSearchPane(Gtk.Box):
def __init__(self, plugin, selection_color):
super(CoverSearchPane, self).__init__()
self.set_orientation(Gtk.Orientation.VERTICAL)
self.selection_color = selection_color
self.file = ''
self.basepath = ('file://' + plugin.plugin_info.get_data_d... |
('foremast.datapipeline.datapipeline.boto3.Session.client')
('foremast.datapipeline.datapipeline.get_details')
('foremast.datapipeline.datapipeline.get_properties')
def test_create_datapipeline(mock_get_properties, mock_get_details, mock_boto3):
generated = {'project': 'test'}
properties = copy.deepcopy(TEST_PR... |
def test_message_reply(session):
message = {'messageMetadata': {'threadKey': {'otherUserFbId': 1234}, 'messageId': 'mid.$XYZ', 'offlineThreadingId': '', 'actorFbId': 1234, 'timestamp': , 'tags': ['source:messenger:web', 'cg-enabled', 'sent', 'inbox'], 'threadReadStateEffect': 3, 'skipBumpThread': False, 'skipSnippe... |
class ColoredFormatter(logging.Formatter):
YELLOW = '\x1b[33;20m'
RED = '\x1b[31;20m'
BOLD_RED = '\x1b[31;1m'
RESET = '\x1b[0m'
FORMAT = '%(asctime)s %(levelname)s %(message)s'
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
FORMATS = {logging.WARNING: ((YELLOW + FORMAT) + RESET), logging.ERROR: ((RED +... |
class OptionPlotoptionsColumnSonificationTracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
(factory)
_all(__all__)
class Satellite(Score):
def __init__(self, ratio=0.05, name='score-sat', **kwargs):
super(Satellite, self).__init__(**kwargs)
self.name = name
self.ratio = ratio
def compute(image, **kwargs):
colid = kwargs.get('collection_id')
year = kwargs.get('y... |
class TestCreateMessage(BaseEvenniaTest):
msgtext = '\n Qui laborum voluptas quis commodi ipsum quo temporibus eum. Facilis\n assumenda facilis architecto in corrupti. Est placeat eum amet qui beatae\n reiciendis. Accusamus vel aspernatur ab ex. Quam expedita sed expedita\n consequuntur est dolorum non ... |
()
('-k', 'key', default=None, help='Key')
('-d', 'decrypt', is_flag=True, default=False, help='Decrypt instead of encrypt')
('--ttl', 'ttl', default=0, type=click.INT, help='Time To Live for timestamp verification')
('-i', type=click.File('rb'), default='-', help='Input file (default: stdin)')
('-o', type=click.File('... |
def extractCornerofbooksandstuffCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_ty... |
def test_upstream():
def t1(a: int) -> typing.Dict[(str, str)]:
return {'a': str(a)}
def t2(a: typing.Dict[(str, str)]) -> str:
return ' '.join([v for (k, v) in a.items()])
def t3() -> str:
return 'hello'
def my_wf(a: int) -> str:
return t2(a=t1(a=a))
serialized = Ord... |
class OFPFlowStatsRequestBase(OFPMultipartRequest):
def __init__(self, datapath, flags, table_id, out_port, out_group, cookie, cookie_mask, match):
super(OFPFlowStatsRequestBase, self).__init__(datapath, flags)
self.table_id = table_id
self.out_port = out_port
self.out_group = out_gr... |
class DefStmt(Stmt):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.lhs = (build_var(**kwargs['lhs']) if isinstance(kwargs['lhs'], dict) else kwargs['lhs'])
self.rhs = (build_exp(**kwargs['rhs']) if isinstance(kwargs['rhs'], dict) else kwargs['rhs'])
def __re... |
class MVARTest(unittest.TestCase):
def setUpClass(cls):
cls.maxDiff = None
def test_decompile_toXML(self):
mvar = newTable('MVAR')
font = TTFont()
mvar.decompile(MVAR_DATA, font)
self.assertEqual(getXML(mvar.toXML), MVAR_XML)
def test_decompile_toXML_lazy(self):
... |
class ComplexSurfaceApodizer(OpticalElement):
def __init__(self, amplitude, surface, refractive_index):
self.amplitude = amplitude
self.surface = surface
self.refractive_index = refractive_index
def phase_for(self, wavelength):
wavenumber = ((2 * np.pi) / wavelength)
opd ... |
class PerimeterPenTest(unittest.TestCase):
def test_PScontour_clockwise_line_first(self):
pen = PerimeterPen(None)
draw1_(pen)
self.assertEqual(1589, round(pen.value))
def test_PScontour_counterclockwise_line_last(self):
pen = PerimeterPen(None)
draw2_(pen)
self.a... |
_bp.route((app.config['FLICKET'] + 'delete_ticket/<ticket_id>/'), methods=['GET', 'POST'])
_required
def delete_ticket(ticket_id):
if (not g.user.is_admin):
flash(gettext('You are not authorised to delete tickets.'), category='warning')
return redirect(url_for('flicket_bp.ticket_view', ticket_id=tic... |
class ClassTimePicker(GrpCls.ClassHtml):
def __init__(self, component: primitives.HtmlModel=None, page: primitives.PageModel=None):
super(ClassTimePicker, self).__init__(component=component, page=page)
self.classList['main'].add(CssToastTimePicker(self.page))
self.classList['main'].add(CssTo... |
def get_output_options(view: sublime.View, inline=False):
opt = {'output.field': field, 'output.format': (not inline)}
if (syntax.doc_syntax(view) == 'html'):
opt['output.attributeQuotes'] = get_settings('attribute_quotes')
opt['output.selfClosingStyle'] = get_settings('markup_style')
op... |
class ContractEvent(BaseContractEvent):
w3: 'Web3'
def get_logs(self, argument_filters: Optional[Dict[(str, Any)]]=None, fromBlock: Optional[BlockIdentifier]=None, toBlock: Optional[BlockIdentifier]=None, block_hash: Optional[HexBytes]=None) -> Iterable[EventData]:
event_abi = self._get_event_abi()
... |
class AuthTestCase(TestCase):
def setUp(self):
self.username = 'user'
self.password = 'password'
User.objects.create_user(self.username, password=self.password)
self.url_testing = reverse('django_mqtt:mqtt_auth')
self.client = Client()
_settings(MQTT_ACL_ALLOW=True)
d... |
def extractHanuchuWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) i... |
class TestOrganizationFieldsCreateUpdateDelete(SingleCreateApiTestCase, SingleDeleteApiTestCase, SingleUpdateApiTestCase):
__test__ = True
ZenpyType = OrganizationField
object_kwargs = dict(description='test', title='i am test', key='somethingsomethingsomething')
ignore_update_kwargs = ['key']
api_n... |
def _assemble_broker_submission_records() -> list:
base_record = {'created_at': None, 'updated_at': None, 'submission_id': None, 'user_id': None, 'cgac_code': None, 'reporting_start_date': None, 'reporting_end_date': None, 'is_quarter_format': False, 'number_of_errors': 0, 'number_of_warnings': 0, 'publish_status_i... |
def has_traitsui():
try:
import traitsui
except ImportError:
return False
from pyface.toolkit import toolkit
if toolkit.toolkit.startswith('qt'):
from pyface.qt import is_qt6
if is_qt6:
return (Version(traitsui.__version__) >= Version('7.4'))
return True |
def test_request_generator_content_picklable():
def content() -> typing.Iterator[bytes]:
(yield b'test 123')
request = ' content=content())
pickle_request = pickle.loads(pickle.dumps(request))
with pytest.raises(
pickle_request.content
with pytest.raises(
pickle_request.read... |
class ForwardingRuleScannerTest(ForsetiTestCase):
def test_forwarding_rules_scanner_all_match(self):
rules_local_path = get_datafile_path(__file__, 'forward_rule_test_1.yaml')
scanner = forwarding_rule_scanner.ForwardingRuleScanner({}, {}, mock.MagicMock(), '', '', rules_local_path)
project_... |
def api_login_required(f):
(f)
def decorated_function(*args, **kwargs):
if (flask.g.user is not None):
return f(*args, **kwargs)
retval = _shared_api_login_required_wrapper()
if (retval is not None):
return retval
return f(*args, **kwargs)
return decor... |
def test_get_relevant_subnets():
input_path = sb.complete_data_path(0)
def subnets_stay_equal(sb_code_info, hv_subnet, lv_subnets):
(new_hv_subnet, new_lv_subnets) = sb.get_relevant_subnets(sb_code_info, input_path=input_path)
assert (hv_subnet == new_hv_subnet)
assert (lv_subnets == new... |
class OptionSeriesOrganizationMarkerStatesHover(Options):
def animation(self) -> 'OptionSeriesOrganizationMarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesOrganizationMarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(se... |
def _protobuf_python_implementation() -> Generator:
PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION = 'PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'
saved_mods = {}
for (mod_name, mod) in list(sys.modules.items()):
if mod_name.startswith('google.protobuf'):
saved_mods[mod_name] = mod
del sy... |
def test_call_with_init_keyword_args(singleton_cls):
provider = singleton_cls(Example, init_arg1='i1', init_arg2='i2')
instance1 = provider()
instance2 = provider()
assert (instance1.init_arg1 == 'i1')
assert (instance1.init_arg2 == 'i2')
assert (instance2.init_arg1 == 'i1')
assert (instance... |
class Test_gre(unittest.TestCase):
version = 0
gre_proto = ETH_TYPE_IP
nvgre_proto = ETH_TYPE_TEB
checksum = 17421
seq_number = 10
key = 256100
vsid = 1000
flow_id = 100
gre = gre.gre(version=version, protocol=gre_proto, checksum=checksum, key=key, seq_number=seq_number)
def test... |
def test_transaction_name_is_route(app, elasticapm_client):
client = TestClient(app)
response = client.get('/hi/shay')
assert (response.status_code == 200)
assert (len(elasticapm_client.events[constants.TRANSACTION]) == 1)
transaction = elasticapm_client.events[constants.TRANSACTION][0]
assert (... |
def _replace_submodules(gm: GraphModule, replacement: torch.nn.Module) -> None:
gm.delete_all_unused_submodules()
if isinstance(replacement, GraphModule):
replacement.graph.lint()
def try_get_submodule(mod: torch.nn.Module, target: str) -> Optional[torch.nn.Module]:
try:
mod_matc... |
def str2int(number):
number = str(number)
original_input = number
try:
return int(number)
except:
try:
return int(number[:(- 2)])
except:
pass
if (number[(- 2):] == 'th'):
number = number[:(- 2)]
if (number[(- 1)] == 'f'):
n... |
class OptionPlotoptionsNetworkgraphStates(Options):
def hover(self) -> 'OptionPlotoptionsNetworkgraphStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsNetworkgraphStatesHover)
def inactive(self) -> 'OptionPlotoptionsNetworkgraphStatesInactive':
return self._config_sub_data('in... |
class OptionSeriesVariwideSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesVariwideSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesVariwideSonificationDefaultinstrumentoptionsMappingTremoloDepth)
def ... |
class Pianobar(IntervalModule):
settings = ('format', ('songfile', 'File generated by pianobar eventcmd'), ('ctlfile', 'Pianobar fifo file'), ('color', 'The color of the text'))
format = '{songtitle} -- {songartist}'
required = ('format', 'songfile', 'ctlfile')
color = '#FFFFFF'
on_leftclick = 'play... |
.django_db
def test_fabs_quarterly(client, monkeypatch, fabs_award_with_quarterly_submission, helpers, elasticsearch_award_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
helpers.patch_datetime_now(monkeypatch, 2022, 12, 31)
resp = helpers.post_for_count_endpoint(client, url, ['M'],... |
class List(Value):
def __init__(self, elements):
super().__init__()
self.elements = elements
def added_to(self, other):
new_list = self.copy()
if isinstance(other, List):
new_list.elements.extend(other.elements)
else:
new_list.elements.append(other... |
class EventListener():
def __init__(self, event_queue: asyncio.Queue, protect: ProtectApiClient, detection_types: List[str], ignore_cameras: List[str]):
self._event_queue: asyncio.Queue = event_queue
self._protect: ProtectApiClient = protect
self._unsub = None
self.detection_types: L... |
def _scan_flow_scalar(stream: StreamBuffer, style: Literal[("'", '"')], is_key: bool=False) -> (KeyToken | ValueToken):
double = (style == '"')
chunks = []
start_mark = stream.get_position()
quote = stream.peek()
stream.forward()
chunks.extend(_scan_flow_scalar_non_spaces(stream, double, start_m... |
class TestEvAdventureCombatBaseHandler(_CombatTestBase):
def setUp(self):
super().setUp()
self.combathandler = combat_base.EvAdventureCombatBaseHandler.get_or_create_combathandler(self.location, key='combathandler')
def test_combathandler_msg(self):
self.location.msg_contents = Mock()
... |
_action_type(ofproto.OFPAT_SET_FIELD, ofproto.OFP_ACTION_SET_FIELD_SIZE)
class OFPActionSetField(OFPAction):
def __init__(self, field=None, **kwargs):
super(OFPActionSetField, self).__init__()
assert (len(kwargs) == 1)
key = list(kwargs.keys())[0]
value = kwargs[key]
assert i... |
_blueprint.route('/project/<project_id>/delete/versions', methods=['GET', 'POST'])
_required
def delete_project_versions(project_id):
project = models.Project.get(Session, project_id)
if (not project):
flask.abort(404)
if (not is_admin()):
flask.abort(401)
form = anitya.forms.Confirmatio... |
class TiltElement(SurfaceApodizer):
def __init__(self, angle, orientation=0, refractive_index=2.0):
self._angle = angle
self._orientation = orientation
super().__init__(self.tilt_sag, refractive_index)
def angle(self):
return self._angle
def angle(self, new_angle):
se... |
def documentify(symbol, short_description=None, long_description=None, text=None, examples=[], evaluation_examples=[], numerical_examples=[]):
documentified.add(symbol)
title = str(symbol)
if (title == 'True_'):
title = 'True'
if (title == 'False_'):
title = 'False'
if (title == 'Hom... |
_type(ofproto.OFPTMPT_EVICTION)
class OFPTableModPropEviction(OFPTableModProp):
def __init__(self, type_=None, length=None, flags=None):
self.type = type_
self.length = length
self.flags = flags
def parser(cls, buf):
eviction = cls()
(eviction.type, eviction.length, evict... |
('bodhi.server.models.work_on_bugs_task', mock.Mock())
('bodhi.server.models.fetch_test_cases_task', mock.Mock())
class TestUpdateEdit(BasePyTestCase):
def test_add_build_to_locked_update(self):
data = {'edited': model.Update.query.first().alias, 'builds': ["can't", 'do', 'this']}
request = mock.Mag... |
class KeyCode():
def __init__(self, component: Optional[primitives.HtmlModel]=None, source_event: Optional[str]=None, page=None):
(self.__events_per_source, self._component, self.source_event) = ({}, component, (source_event or component.dom.varId))
self._page = (page or self._component.page)
de... |
def try_get_constant_num(arg: Any) -> (bool, Any):
if isinstance(arg, (float, int)):
return (True, arg)
elif isinstance(arg, IntImm):
return (True, arg.value())
elif isinstance(arg, IntVarTensor):
var = arg._attrs['int_var']
return try_get_constant_num(var)
else:
... |
class DcNodeView(APIView):
serializer = DcNodeSerializer
order_by_default = ('node__hostname',)
order_by_field_map = {'hostname': 'node__hostname'}
def __init__(self, request, hostname, data):
super(DcNodeView, self).__init__(request)
self.data = data
self.hostname = hostname
... |
def set_my_description(token, description=None, language_code=None):
method_url = 'setMyDescription'
payload = {}
if (description is not None):
payload['description'] = description
if (language_code is not None):
payload['language_code'] = language_code
return _make_request(token, me... |
class LegacyTransactionFactory(factory.Factory):
class Meta():
model = _FakeTransaction
nonce = factory.Sequence((lambda n: n))
gas_price = 1
gas = 21000
to = ZERO_ADDRESS
value = 0
data = b''
def _create(cls, model_class: Type[BaseTransactionFields], *args: Any, chain_id: int=No... |
class FaucetStackDHCPSingleVLANTest(FaucetTopoTestBase):
NUM_DPS = 2
NUM_HOSTS = 5
NUM_VLANS = 1
N_TAGGED = 1
N_UNTAGGED = 4
SOFTWARE_ONLY = True
def host_ip_address(_host_index, _vlan_index):
return '0.0.0.0'
def setUp(self):
def set_up(self):
super().setUp()
... |
def remap_cb_input(mode=0):
def _remap_cb_input(value):
if (mode == 2):
return value
if isinstance(value, tuple):
mapped_value = tuple([value[0].copy(), value[1].copy()])
for i in mapped_value:
for (key, msg) in i.items():
if (k... |
def get_assign_name(target: Any) -> Any:
if (isinstance(target, astroid.nodes.AssignName) or isinstance(target, astroid.nodes.Name)):
return target.name
elif (isinstance(target, astroid.nodes.AssignAttr) or isinstance(target, astroid.nodes.Attribute)):
return ((get_assign_name(target.expr) + '.'... |
class SKLearnForestRegressorTransformer(SKLearnForestTransformer):
def __init__(self, model: RandomForestRegressor, feature_names: Sequence[str]):
super().__init__(model, feature_names)
def build_aggregator_output(self) -> Dict[(str, Any)]:
return {'weighted_sum': {'weights': ([(1.0 / len(self._... |
def test_agent_fingerprint_different_fingerprints():
config = Mock()
config.fingerprint = {}
package_dir = Path('path', 'to', 'dir')
error_regex = (f'''Fingerprints for package {re.escape(str(package_dir))} do not match:
Expected: {dict()}
Actual: {dict(foo='bar')}
''' + "Please fingerprint the package ... |
class OptionSeriesLollipopSonificationDefaultinstrumentoptionsMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str)... |
class OptionSeriesBulletSonificationDefaultinstrumentoptionsMappingTremoloSpeed(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text... |
def compare_codes(input_code, standard_codes, bitwise_comparison=True):
if isinstance(standard_codes, (list, tuple)):
for code in standard_codes:
if compare_codes(input_code, code, bitwise_comparison):
return True
return False
elif (input_code == standard_codes):
... |
class OptionPlotoptionsStreamgraphSonificationContexttracksMappingHighpassFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, ... |
_grad()
def get_mel_from_audio(audio: torch.Tensor, sample_rate=44100, n_fft=2048, win_length=2048, hop_length=512, f_min=40, f_max=16000, n_mels=128, center=True, power=1.0, pad_mode='reflect', norm='slaney', mel_scale='slaney') -> torch.Tensor:
assert (audio.ndim == 2), 'Audio tensor must be 2D (1, n_samples)'
... |
class TestTabSlugsCombineHeader(util.MdCase):
extension = ['pymdownx.tabbed', 'toc', 'pymdownx.details']
extension_configs = {'pymdownx.tabbed': {'slugify': slugify(case='lower'), 'combine_header_slug': True}}
def test_combine_header_slug(self):
md = '\n ### Here is some text\n\n === "... |
def language_detection_arguments(provider_name: str):
return {'text': "Ogni individuo ha diritto all'istruzione. L'istruzione deve essere gratuita almeno per quanto riguarda le classi elementari e fondamentali. L'istruzione elementare deve essere obbligatoria. L'istruzione tecnica e professionale deve essere messa ... |
_log_on_failure_all
class TestP2PLibp2PReceiveEnvelope(BaseTestP2PLibp2p):
def test_envelope_routed(self):
addr_1 = self.connection1.node.address
addr_2 = self.connection2.node.address
msg = DefaultMessage(dialogue_reference=('', ''), message_id=1, target=0, performative=DefaultMessage.Perfo... |
.django_db
def test_missing_render_inline_actions_from_readonly_fields(rf, admin_user, admin_site, article):
from test_proj.blog import admin
class ArticleAdmin(admin.InlineActionsModelAdminMixin, admin.admin.ModelAdmin):
list_display = ('name',)
inline_actions = None
def get_readonly_fi... |
class TestLoadOutput():
.parametrize(('provider', 'feature', 'subfeature', 'phase'), global_features(return_phase=True)['ungrouped_providers'])
def test_load_output_valid_paramters(self, provider, feature, subfeature, phase):
if (('create' in phase) or ('delete' in phase) or ('upload' in phase)):
... |
class IteratedEnsembleSmoother(BaseRunModel):
_simulation_arguments: SIESRunArguments
def __init__(self, simulation_arguments: SIESRunArguments, config: ErtConfig, storage: StorageAccessor, queue_config: QueueConfig, experiment_id: UUID, analysis_config: IESSettings, update_settings: UpdateSettings):
su... |
class TestBedForMacs2Function(unittest.TestCase):
def test_bed_for_macs2_with_2010_(self):
macsxls = MacsXLS(fp=io.StringIO(MACS2010__data))
bed = bed_for_macs2(macsxls)
self.assertEqual(bed.header(), ['chr', 'abs_summit-100', 'abs_summit+100'])
self.assertEqual(bed[0]['chr'], 'chr1'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.