code stringlengths 281 23.7M |
|---|
class _Menu(QtGui.QMenu):
def __init__(self, manager, parent, controller):
QtGui.QMenu.__init__(self, parent)
self._parent = parent
self._manager = manager
self._controller = controller
self.menu_items = []
self.refresh()
self._manager.observe(self.refresh, 'c... |
def _get_kwargs(*, client: Client, multipart_data: BodyUploadFile) -> Dict[(str, Any)]:
url = '{}/storage/upload'.format(client.base_url)
headers: Dict[(str, str)] = client.get_headers()
cookies: Dict[(str, Any)] = client.get_cookies()
multipart_multipart_data = multipart_data.to_multipart()
return ... |
def lambda_handler(event, context):
cognito_id = event['requestContext']['authorizer']['claims']['sub']
print('user id', cognito_id)
user = user_service.get_single_user(cognito_id)
subscribed_lists = []
for subscription in user.subscriptions:
if (subscription.status == 'subscribed'):
... |
def b2i(binaryStringIn):
if (len(binaryStringIn) != 64):
print(('ERROR: Passed string not 64 characters. String length = %s' % len(binaryStringIn)))
print(("ERROR: String value '%s'" % binaryStringIn))
raise ValueError('Input strings must be 64 chars long!')
val = Bits(bin=binaryStringIn... |
class OptionSeriesErrorbarSonificationDefaultspeechoptionsMappingRate(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):
... |
def test_unnamed_typing_tuple():
def z(a: int, b: str) -> typing.Tuple[(int, str)]:
return (5, 'hello world')
result = transform_variable_map(extract_return_annotation(typing.get_type_hints(z).get('return', None)))
assert (result['o0'].type.simple == 1)
assert (result['o1'].type.simple == 3) |
class OptionSeriesFunnel3dSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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... |
def parse_info(wininfo_name, egginfo_name):
egginfo = None
if egginfo_name:
egginfo = egg_info_re.search(egginfo_name)
if (not egginfo):
raise ValueError(('Egg info filename %s is not valid' % (egginfo_name,)))
(w_name, sep, rest) = wininfo_name.partition('-')
if (not sep):
... |
class Luhn():
def __init__(self, card_num):
self.card_num = card_num
self.checksum = (- 1)
digits = card_num.replace(' ', '')
length = len(digits)
if (digits.isdigit() and (length > 1)):
self.checksum = 0
cadence = (length % 2)
for (idx, di... |
class ListEventTestCase(unittest.TestCase):
def test_initialization(self):
foo = MyClass()
self.assertEqual(foo.l, [1, 2, 3])
self.assertEqual(len(foo.l_events), 0)
def test_append(self):
foo = MyClass()
foo.l.append(4)
self.assertEqual(foo.l, [1, 2, 3, 4])
... |
class Instance(atom):
_fields = ('name', 'args')
_attributes = ('lineno', 'col_offset')
def __init__(self, name, args=[], lineno=0, col_offset=0, **ARGS):
atom.__init__(self, **ARGS)
self.name = name
self.args = list(args)
self.lineno = int(lineno)
self.col_offset = i... |
def test_custom_graph_data(dashboard_user, custom_graph, custom_graph_data):
today = datetime.utcnow()
yesterday = (today - timedelta(days=1))
response = dashboard_user.get('dashboard/api/custom_graph/{id}/{start}/{end}'.format(id=custom_graph.graph_id, start=yesterday.strftime('%Y-%m-%d'), end=today.strfti... |
def get_task_results(container):
result_path = '/srv/celery-results'
results = []
with tempfile.TemporaryDirectory() as tempdir:
container.copy_from(result_path, tempdir)
for (root, dirs, files) in os.walk(tempdir):
for filename in files:
with open(os.path.join(ro... |
class TestConfigValidatorComputeZone():
.e2e
.scanner
.server
def test_cv_compute_zone(self, cloudsql_connection, forseti_scan_readonly, forseti_server_vm_name):
(scanner_id, scanner_result) = forseti_scan_readonly
violation_type = 'CV_GCPComputeZoneConstraintV1.compute-zone-denylist'
... |
def bar_chart():
chart = ft.BarChart(bar_groups=[ft.BarChartGroup(x=0, bar_rods=[ft.BarChartRod(from_y=0, to_y=40, width=40, color=ft.colors.AMBER, tooltip='Apple', border_radius=0)]), ft.BarChartGroup(x=1, bar_rods=[ft.BarChartRod(from_y=0, to_y=100, width=40, color=ft.colors.BLUE, tooltip='Blueberry', border_radi... |
class RemoveElementwiseNoOpsIntegrationTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(RemoveElementwiseNoOpsIntegrationTest, self).__init__(*args, **kwargs)
torch.manual_seed(0)
self.BATCH_SIZES = [1, 218]
self.M = 10
def test_remove_elementwise_op(self) -> N... |
class TagInline(admin.TabularInline):
model = None
verbose_name = 'Tag'
verbose_name_plural = 'Tags'
form = InlineTagForm
formset = TagFormSet
related_field = None
extra = 0
def get_formset(self, request, obj=None, **kwargs):
formset = super().get_formset(request, obj, **kwargs)
... |
def test_edit_session_only_state(db, client, user, jwt):
user.is_admin = True
session = get_simple_custom_form_session(db, user)
data = json.dumps({'data': {'type': 'session', 'id': str(session.id), 'attributes': {'state': 'withdrawn'}}})
response = client.patch(f'/v1/sessions/{session.id}', content_typ... |
class _COSERVERINFO(Structure):
_fields_ = [('dwReserved1', c_ulong), ('pwszName', c_wchar_p), ('pAuthInfo', POINTER(_COAUTHINFO)), ('dwReserved2', c_ulong)]
if TYPE_CHECKING:
dwReserved1 = hints.AnnoField()
pwszName = hints.AnnoField()
pAuthInfo = hints.AnnoField()
dwReserved2 =... |
class DiagonalTensor(UnaryOp):
diagonal = True
def __init__(self, A):
assert (A.rank == 2), 'The tensor must be rank 2.'
assert (A.shape[0] == A.shape[1]), 'The diagonal can only be computed on square tensors.'
super(DiagonalTensor, self).__init__(A)
_property
def arg_function_sp... |
def main():
parser = ArgumentParser(description=' Add license notice to every source file if not present.')
parser.add_argument('--check', action='store_true', dest='check', default=False, help=CHECK_HELP)
args = parser.parse_args()
gitignore = get_gitignore(Path('.'))
python_files = [path for path ... |
class OptionPlotoptionsScatterStatesHoverHalo(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def opacity(self):
return self._config_get(0.25)
def opacity(self, num: float):
self._config(nu... |
.django_db
def test_match_from_ata_tas(client, monkeypatch, elasticsearch_award_index, subaward_with_ata_tas):
_setup_es(client, monkeypatch, elasticsearch_award_index)
resp = query_by_tas_subaward(client, {'require': [_tas_path(ATA_TAS)]})
assert (resp.json()['results'] == [_subaward1()]) |
def install():
global rDownloadURL
rURL = rDownloadURL
if os.path.exists('/home/xtreamcodes'):
os.system("kill $(ps aux | grep '[p]hp' | awk '{print $2}')")
os.system("kill $(ps aux | grep '[n]nginx' | awk '{print $2}')")
os.system("kill $(ps aux | grep '[f]fmpeg' | awk '{print $2}')... |
class MultiToolbarWindow(ApplicationWindow):
_tool_bar_managers = List(Instance(ToolBarManager))
_tool_bar_locations = Dict(Instance(ToolBarManager), Enum('top', 'bottom', 'left', 'right'))
def _create_contents(self, parent):
panel = super()._create_contents(parent)
self._create_trim_widgets... |
def upgrade():
op.create_table('user_favourite_sessions', sa.Column('id', sa.Integer(), nullable=False), sa.Column('session_id', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(timezone=True), nullable=True), sa.Column('modified_at', sa.DateTime(t... |
class European(GameItem):
key = 'european'
title = ''
description = 'Roll'
def __init__(self):
pass
def should_usable(self, core: ServerCore, g: ServerGame, u: Client):
cls = self.__class__
from thb.thbrole import THBattleRole
if isinstance(g, THBattleRole):
... |
def test_curr_score():
curr = pd.DataFrame({'user_id': [1, 2, 2, 3, 3], 'item_id': [3, 2, 3, 1, 2], 'prediction': [3, 3, 2, 3, 2]})
train = pd.DataFrame({'user_id': [1, 1, 2, 3], 'item_id': [1, 2, 1, 1]})
metric = PopularityBias(k=3)
report = Report(metrics=[metric])
column_mapping = ColumnMapping(r... |
def test_angle2azimuth():
res = xcalc.angle2azimuth(30)
assert (res == 60.0)
a1 = ((30 * math.pi) / 180)
a2 = ((60 * math.pi) / 180)
res = xcalc.angle2azimuth(a1, mode='radians')
assert (res == a2)
res = xcalc.angle2azimuth((- 30))
assert (res == 120.0)
res = xcalc.angle2azimuth((- 3... |
class OptionPlotoptionsArearangeSonificationDefaultinstrumentoptionsMappingVolume(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, te... |
def build_exp(**kwargs):
t = kwargs['t']
if (t == 'Load'):
return LoadExp(**kwargs)
elif (t == 'Store'):
return StoreExp(**kwargs)
elif (t == 'BinOp'):
return BinOpExp(**kwargs)
elif (t == 'UnOp'):
return UnOpExp(**kwargs)
elif (t == 'Int'):
return IntExp(... |
def find_common_bits_for_tag_groups(lines, tag_groups):
bit_groups = []
for tag_group in tag_groups:
bit_group = set()
for line in lines:
(tag, bits, mode, _) = util.parse_db_line(line)
if (not bits):
continue
bits = set([util.parse_tagbit(b) f... |
def test_reaction_event_removed(session):
data = {'threadKey': {'threadFbId': 1234}, 'messageId': 'mid.$XYZ', 'action': 1, 'userId': 4321, 'senderId': 4321, 'offlineThreadingId': ''}
thread = Group(session=session, id='1234')
assert (ReactionEvent(author=User(session=session, id='4321'), thread=thread, mess... |
def run_action(args):
import time
from collections import Counter
from lib import MAX_SYSCALLS
from lib.ebpf import Probe
from lib.ml import AutoEncoder
from lib.platform import SYSCALLS
probe = Probe(args.pid)
ae = AutoEncoder(args.model, load=True)
print(('monitoring process %d (%s... |
class NmapScan():
def __init__(self, host, port_range, full_scan=None, scripts=None, services=None):
self.target = host.target
self.full_scan = full_scan
self.scripts = scripts
self.services = services
self.port_range = port_range
self.path = HelpUtilities.get_output_... |
class QueryStub(object):
def __init__(self, channel):
self.ClientState = channel.unary_unary('/ibc.core.client.v1.Query/ClientState', request_serializer=ibc_dot_core_dot_client_dot_v1_dot_query__pb2.QueryClientStateRequest.SerializeToString, response_deserializer=ibc_dot_core_dot_client_dot_v1_dot_query__pb... |
def get_source_link(module_path: str, xpath: str, title: str) -> str:
module = import_module(module_path)
module_filepath = pathlib.Path(module.__file__)
(_, attrib) = module_source(module, xpath)[0]
url = ('%s/blob/%s/%s#L%s' % (GITHUB_REPO, HEAD.commit.hexsha, module_filepath.relative_to(WORKSPACE_DIR... |
class Component():
def __init__(self, index, reserved=False):
self._index = index
self._reserved = reserved
self._encoding = None
self.prepared = False
def index(self):
return self._index
def component(self):
return self._index
def reserved(self):
... |
def bench_one(name_module='cmorph', func=None, total_duration=2):
if (func is not None):
raise NotImplementedError
functions = [(mod, func_) for (mod, func_) in statements.keys() if (mod == name_module)]
if (not functions):
raise ValueError(f'bad name_module: {name_module}')
name_functio... |
def test_activate_reload_and_deactivate(testbot):
for command in ('activate', 'reload', 'deactivate'):
testbot.push_message(f'!plugin {command}')
m = testbot.pop_message()
assert ('Please tell me which of the following plugins to' in m)
assert ('ChatRoom' in m)
testbot.push_m... |
.integration
class TestListServerResources():
def test_list_server_resources_passing(self, test_config: FidesConfig) -> None:
resource_type = 'data_category'
result = _api_helpers.list_server_resources(url=test_config.cli.server_url, resource_type=resource_type, headers=test_config.user.auth_header,... |
def make_classification_dataset(n_features=10, n_classes=10):
rng = numpy.random.RandomState(0)
(X, y) = make_classification(n_features=n_features, n_classes=n_classes, n_redundant=0, n_informative=n_features, random_state=rng, n_clusters_per_class=3, n_samples=50)
X += (2 * rng.uniform(size=X.shape))
X... |
def update_trace_rank(file_path: str, rank: int) -> None:
def _add_rank_meta(trace_data: Dict[(str, Any)], rank: int) -> None:
if ('distributedInfo' in trace_data):
trace_data['distributedInfo']['rank'] = rank
else:
trace_data['distributedInfo'] = {'rank': rank}
trace_dat... |
def before_uninstall():
try:
print('Removing customizations created by Frappe Health...')
remove_customizations()
except Exception as e:
BUG_REPORT_URL = '
click.secho(f'Removing Customizations for Frappe Health failed due to an error. Please try again or report the issue on {BUG... |
class AltRadioController(AltGenericController):
__gtype_name = 'AltRadioController'
def __init__(self, header):
super(AltRadioController, self).__init__(header)
self._gicon = Gio.ThemedIcon(name='audio-radio-symbolic')
def valid_source(self, source):
return ('RBIRadioSource' in type(... |
class OptionSeriesPackedbubbleSonificationDefaultinstrumentoptionsMappingPitch(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('y')
def mapTo(self, text: ... |
def extractBllovetranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('CDAW', 'Continuation of the Dream in Another World', 'translated'), ('aak', 'ai wo ata... |
(autouse=True)
def xdg_trinity_root(monkeypatch, tmpdir):
with tempfile.TemporaryDirectory() as tmp_dir:
xdg_root_dir = (Path(tmp_dir) / 'trinity')
monkeypatch.setenv('XDG_TRINITY_ROOT', str(xdg_root_dir))
assert (not is_under_path(os.path.expandvars('$HOME'), get_xdg_trinity_root()))
... |
class Station(ServiceInterface):
def __init__(self, *args, state='', connected_network='', **kwargs):
ServiceInterface.__init__(self, IWD_STATION, *args, **kwargs)
self._state = state
self._connected_network = connected_network
self._scanning = False
_property(access=PropertyAcce... |
def test_pickle_dump_load(assertion, source, target=None, protocol=(0, HIGHEST_PROTOCOL)):
(start, stop) = protocol
failures = []
for protocol in range(start, (stop + 1)):
try:
if (target is None):
assertion(loads(dumps(source, protocol=protocol)), source)
els... |
def test_json_writer_with_validation():
'
schema = {'doc': 'A weather reading.', 'name': 'Weather', 'namespace': 'test', 'type': 'record', 'fields': [{'name': 'station', 'type': 'string'}, {'name': 'time', 'type': 'long'}, {'name': 'temp', 'type': 'int'}]}
records = [{'station': '011990-99999', 'temp': 0, '... |
class CacheDoc(Directive):
required_arguments = 0
has_content = True
def run(self):
zenpy_client = Zenpy(subdomain='party', email='', password='Yer')
node_list = []
cache_node = container()
cache_sections = self.generate_cache_sections(zenpy_client)
for cache_section ... |
class Dependency():
__slots__ = ('_name', '_version', '_index', '_git', '_ref')
def __init__(self, name: Union[(PyPIPackageName, str)], version: Union[(str, SpecifierSet)]='', index: Optional[str]=None, git: Optional[str]=None, ref: Optional[Union[(GitRef, str)]]=None) -> None:
self._name: PyPIPackageNa... |
('guess')
('--only', multiple=True, help='Only guess actions with the given prefix, e.g. Describe (can be passed multiple times)')
def guess(only):
stdin = click.get_text_stream('stdin')
policy = parse_policy_document(stdin)
allowed_prefixes = [s.title() for s in only]
policy = guess_statements(policy, ... |
def check_git_status():
try:
repo = Repo(Path.cwd().resolve(), search_parent_directories=True)
if repo.is_dirty(untracked_files=True):
changedFiles = [item.a_path for item in repo.index.diff(None)]
return (False, f'Found uncommitted changes: {(changedFiles + repo.untracked_fi... |
class ClientFilesTransmitterGroupbox(QGroupBox):
showm_signal = pyqtSignal(str)
def __init__(self, text='', parent=None):
super(ClientFilesTransmitterGroupbox, self).__init__(title=text, parent=parent)
self.Transmitter = ClientFilesTransmitter(self)
self.resize(560, 220)
self.all... |
def extractDlazartureadWordpressCom(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 load_menu(menu_path, menu_file, filters=None):
proto_to_id.clear()
method_to_id.clear()
with open(f'{menu_path}/{menu_file}', 'r', encoding='UTF-8') as f:
for pro_str in f.readlines():
line = pro_str.split('=')
if (len(line) >= 2):
str_key = line[0].strip(... |
def verify_asset_tracking_details(fledge_url, south_service_name, south_asset_name, south_plugin, north_service_name, north_plugin, skip_verify_north_interface):
tracking_details = utils.get_asset_tracking_details(fledge_url, 'Ingest')
assert len(tracking_details['track']), 'Failed to track Ingest event'
tr... |
def compile_from_input_json(input_json: Dict, silent: bool=True, allow_paths: Optional[str]=None) -> Dict:
if (input_json['language'] == 'Vyper'):
return vyper.compile_from_input_json(input_json, silent, allow_paths)
if (input_json['language'] == 'Solidity'):
allow_paths = _get_allow_paths(allow... |
class ConfigRepository(IConfigRepository):
config_search_path: ConfigSearchPath
sources: List[ConfigSource]
def __init__(self, config_search_path: ConfigSearchPath) -> None:
self.initialize_sources(config_search_path)
def initialize_sources(self, config_search_path: ConfigSearchPath) -> None:
... |
def notify_session_state_change(session, actor):
speakers = Speaker.query.filter_by(deleted_at=None, is_email_overridden=False).filter((Speaker.email != None), Speaker.sessions.contains(session)).with_entities(Speaker.email).all()
emails = [val[0] for val in speakers]
users = User.query.filter(User._email.i... |
class FileSaveChooser(BaseChooser):
def __init__(self, title, parent, patterns=[]):
super().__init__(title, parent, Gtk.FileChooserAction.SAVE, _('_Save'))
file_filter = Gtk.FileFilter()
for pattern in patterns:
file_filter.add_pattern(pattern)
self.set_filter(file_filter... |
def test_is_event_version_part_of_edition(manifest):
assert (manifest.is_in_edition('edition-agen', 'EiffelActivityTriggeredEvent', '1.0.0') is False)
assert (manifest.is_in_edition('edition-agen', 'EiffelActivityTriggeredEvent', '2.0.0') is True)
assert (manifest.is_in_edition('edition-agen', 'EiffelActivi... |
.parametrize('workflow, position', [(wf_with_multioutput_error0, 0), (wf_with_multioutput_error1, 1)])
(st.integers())
(deadline=timedelta(seconds=2))
def test_workflow_with_multioutput_error(workflow, position, correct_input):
with pytest.raises(TypeError, match="Encountered error while executing workflow '{}':\\n... |
def extractBaihemtltranslationsWordpressCom(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, nam... |
def log_on_exception(f: T_WrappedCallableOrType) -> T_WrappedCallableOrType:
if inspect.isclass(f):
return wrap_class_methods(f, log_on_exception)
(f)
def wrapper(*args, **kwargs):
try:
f(*args, **kwargs)
except Exception as e:
LOGGER.exception('failed due to ... |
class WSServer():
def __init__(self, enums: Any, request_time_out=0.01, sleep_pause_time=0.1):
self.enums = enums
self.STREAM_LISTS = getattr(enums, 'STREAM_LISTS', set())
self.supported_stream_list = getattr(self.STREAM_LISTS, 'supported_stream_list', set())
self.sleep_pause_streams... |
class GenericZendeskResponseHandler(ResponseHandler):
def applies_to(api, response):
try:
return ((api.base_url in response.request.url) and response.json())
except ValueError:
return False
def deserialize(self, response_json):
response_objects = dict()
if... |
def _test_correct_response_for_place_of_performance_county_with_geo_filters(client):
resp = client.post('/api/v2/search/spending_by_geography', content_type='application/json', data=json.dumps({'scope': 'place_of_performance', 'geo_layer': 'county', 'geo_layer_filters': ['45001', '53005'], 'filters': {'time_period'... |
def PrintBranchToRepos(branch_to_repos, params):
for (branch, repos) in sorted(iteritems(branch_to_repos)):
if (len(repos) == 1):
msg = ('${START_COLOR}%s${RESET_COLOR}' % (branch,))
elif (len(repos) == len(set(params.config.repos))):
msg = ('${START_COLOR}%s${RESET_COLOR} ... |
class APISiteScansTests(APITestCase):
def setUp(self):
create_site()
def test_get_site_scans(self):
url = urljoin(urlroot, 'sites/securethe.news/scans/')
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertE... |
def remove_gold_pass_val(save_stats: dict[(str, Any)]) -> dict[(str, Any)]:
gold_pass = save_stats['gold_pass']
gold_pass['officer_id']['Value'] =
gold_pass['renewal_times']['Value'] = 0
gold_pass['start_date'] = 0
gold_pass['expiry_date'] = 0
gold_pass['unknown_2'][0] = 0
gold_pass['unknow... |
def upgrade():
op.create_table('Payments', sa.Column('id', sa.Integer(), nullable=False), sa.Column('invoice_id', sa.Integer(), nullable=True), sa.Column('amount', sa.Float(), nullable=True), sa.Column('unit', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['id'], ['Entities.id']), sa.ForeignKeyConst... |
class PluginRestRoutes(Resource):
ENDPOINTS = [('/plugins/dummy/rest', ['GET'])]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.config = kwargs.get('config', None)
_accepted(*PRIVILEGES['view_analysis'])
def get(self):
return success_message({'dummy':... |
def test_sel_with_default_parameters(df_test):
(X, y) = df_test
sel = SelectByShuffling(RandomForestClassifier(random_state=1), threshold=0.01, random_state=1)
sel.fit(X, y)
Xtransformed = pd.DataFrame(X['var_7'].copy())
assert (sel.threshold == 0.01)
assert (sel.cv == 3)
assert (sel.scoring... |
class ELU(Fixed):
codomain = constraints.greater_than((- 1.0))
def _forward(self, x: torch.Tensor, params: Optional[Sequence[torch.Tensor]]) -> Tuple[(torch.Tensor, Optional[torch.Tensor])]:
y = F.elu(x)
ladj = self._log_abs_det_jacobian(x, y, params)
return (y, ladj)
def _inverse(se... |
class OptionSeriesPackedbubbleSonificationContexttracksMappingLowpassResonance(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 main():
import grpc
from koapy.backend.kiwoom_open_api_plus.grpc.KiwoomOpenApiPlusServiceClient import KiwoomOpenApiPlusServiceClient
host = 'localhost'
port = 5943
with open('server.crt', 'rb') as f:
server_crt = f.read()
credentials = grpc.ssl_channel_credentials(root_certificates=... |
def schema_mandatory_attributes(schema: FieldEntry) -> None:
current_schema_attributes: List[str] = sorted((list(schema['field_details'].keys()) + list(schema['schema_details'].keys())))
missing_attributes: List[str] = ecs_helpers.list_subtract(SCHEMA_MANDATORY_ATTRIBUTES, current_schema_attributes)
if (len... |
def test_proper_name_argument():
argument = RangeStringArgument()
assert argument.validate('1')
assert argument.validate('1-10')
assert argument.validate('1-10,11-20')
assert argument.validate('1-10,11,12,13,14,15,16-20')
assert (not argument.validate(''))
assert (not argument.validate('s5')... |
class OptionSeriesXrangeEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
self._config(v... |
def Run(params):
args = params.args[1:]
remote = False
if (len(args) > 0):
if (args[0] == '-r'):
del args[0]
remote = True
repos_and_local_branches = GetReposAndLocalBranches(params, patterns=[('*%s*' % x) for x in args], remote=remote)
branch_to_repos = ConvertRepoTo... |
class TCPSocketChannelClientTLS(TCPSocketChannelClient):
DEFAULT_VERIFICATION_SIGNATURE_WAIT_TIMEOUT = 5.0
def __init__(self, in_path: str, out_path: str, server_pub_key: str, logger: logging.Logger=_default_logger, loop: Optional[AbstractEventLoop]=None, verification_signature_wait_timeout: Optional[float]=Non... |
class StartsWith(FunctionSignature):
name = 'startsWith'
argument_types = [TypeHint.String, TypeHint.String]
return_value = TypeHint.Boolean
def run(cls, source, substring):
if (is_string(source) and is_string(substring)):
return fold_case(source).startswith(fold_case(substring)) |
def prompt_for_user_token(client_id: str, client_secret: str, redirect_uri: str, scope=None) -> RefreshingToken:
cred = RefreshingCredentials(client_id, client_secret, redirect_uri)
auth = UserAuth(cred, scope=scope)
print('Opening browser for Spotify login...')
webbrowser.open(auth.url)
redirected ... |
class OptionPlotoptionsSankeySonificationDefaultspeechoptionsMappingPitch(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('undefined')
def mapTo(self, tex... |
def load_c_function(code, name, comm):
cppargs = [('-I%s/include' % d) for d in get_petsc_dir()]
ldargs = (([('-L%s/lib' % d) for d in get_petsc_dir()] + [('-Wl,-rpath,%s/lib' % d) for d in get_petsc_dir()]) + ['-lpetsc', '-lm'])
return load(code, 'c', name, argtypes=[ctypes.c_voidp, ctypes.c_int, ctypes.c_... |
class Parser():
def print_help(self):
print('{fail}usage: {blue}{prog} {green}<command>{reset} [options]'.format(prog='todo', fail=Fore.FAIL, blue=Fore.BLUE, green=Fore.GREEN, reset=Style.RESET_ALL))
def parseopts(self, args):
try:
cmd_name = args[0]
cmd_args = args[1:]
... |
class OptionPlotoptionsSunburstSonificationTracksMappingPan(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):
self... |
class OptionSeriesPictorialStatesSelectMarker(Options):
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._c... |
def test_override_custom_form_name(db):
event = EventFactoryBasic()
overridden_custom_form = CustomForms(event=event, field_identifier='shippingAddress', name='Home Address', form='attendee', type='text')
custom_custom_form = CustomForms(event=event, field_identifier='portNumber', name='Portable Number', fo... |
.parametrize('njit', [True, False])
def test_reflections(njit):
if njit:
reflections = kernel.reflections
else:
reflections = kernel.reflections.py_func
dat = DATAKERNEL['refl'][()]
for (_, val) in dat.items():
(Rp, Rm) = reflections(**val[0])
assert_allclose(Rp, val[1])
... |
class MultiUrl(MultiSource):
def __init__(self, urls, *args, filter=None, merger=None, force=None, **kwargs):
if (not isinstance(urls, (list, tuple))):
urls = [urls]
assert len(urls)
sources = [load_source('url', url, filter=filter, merger=merger, force=force, lazily=True) for ur... |
.requires_tex
def test_pdflatex(cli: CliRunner, temp_with_override: Path):
path_output = temp_with_override.absolute()
path_template = path_tests.parent.joinpath('jupyter_book', 'book_template')
cmd = f'{path_template} --path-output {path_output} --builder pdflatex'
result = cli.invoke(build, cmd.split(... |
class Command():
def __init__(self, func, s: str) -> None:
self.name = func.__name__
self.description = func.__doc__
self.help = (self.description.split('.')[0] if self.description else None)
self.requires_network = ('n' in s)
self.requires_wallet = ('w' in s)
self.re... |
.EventDecorator()
def to_reference_coords_newton_step(ufl_coordinate_element, parameters, x0_dtype='double', dX_dtype=ScalarType):
cell = ufl_coordinate_element.cell
domain = ufl.Mesh(ufl_coordinate_element)
K = ufl.JacobianInverse(domain)
x = ufl.SpatialCoordinate(domain)
x0_element = finat.ufl.Vec... |
class Subscription(BaseModel):
tg_chat = ForeignKeyField(TelegramChat, related_name='subscriptions')
tw_user = ForeignKeyField(TwitterUser, related_name='subscriptions')
known_at = DateTimeField(default=datetime.datetime.now)
last_tweet_id = BigIntegerField(default=0)
def last_tweet(self):
i... |
def prepare_template_reading_from_fogbench():
def _prepare_template_reading_from_fogbench(FOGBENCH_TEMPLATE, ASSET_NAME):
fogbench_template_path = os.path.join(os.path.expandvars('${FLEDGE_ROOT}'), 'data/{}'.format(FOGBENCH_TEMPLATE))
with open(fogbench_template_path, 'w') as f:
f.write(... |
def run() -> None:
logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.info(bold_green(HEADER))
logging.info((construct_evm_runtime_identifier() + '\n'))
if ('--compile-contracts' in sys.argv):
logging.info('Precompiling contracts')
try:
compile_contracts(ge... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.