code stringlengths 281 23.7M |
|---|
class OptionSeriesXrangeSonificationContexttracksMappingLowpassFrequency(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 Shell(wx.StyledTextCtrl):
name = 'PyCrust Shell'
revision = __revision__
def __init__(self, parent, id=(- 1), pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.CLIP_CHILDREN, introText='', locals=None, InterpClass=None, *args, **kwds):
wx.StyledTextCtrl.__init__(self, parent, id, pos, size... |
def room_generator(dungeon_orchestrator, depth, coords):
room_typeclass = EvAdventureDungeonRoom
name_depth_map = {1: ('Water-logged passage', 'This earth-walled passage is dripping of water.'), 2: ('Passage with roots', 'Roots are pushing through the earth walls.'), 3: ('Hardened clay passage', 'The walls of t... |
(IMessageDialog)
class MessageDialog(MMessageDialog, Dialog):
message = Str()
informative = Str()
detail = Str()
severity = Enum('information', 'warning', 'error')
text_format = Enum('auto', 'plain', 'rich')
def _create_contents(self, parent):
pass
def _create_control(self, parent):
... |
def download_file_wrapper(dirpath):
_quota_check
def download_file(r, suc, fail, dirpath=dirpath):
if (r.status_code == 404):
return fail((ERR_HATH_NOT_FOUND, r._real_url, r.url))
p = RE_IMGHASH.findall(r.url)
if ((not r.content_length) or (p and p[(- 1)] and (int(p[(- 1)][1]... |
def print_columns(cipherlist):
cols = 2
while ((len(cipherlist) % cols) != 0):
cipherlist.append('')
else:
split = [cipherlist[i:(i + int((len(cipherlist) / cols)))] for i in range(0, len(cipherlist), int((len(cipherlist) / cols)))]
for row in zip(*split):
print((' ... |
def main():
parser_map = {'new': (new_parsers, 'Create new environment'), 'add': (add_parser, 'Add UI framework to an existing project'), 'app': (app_parser, 'Create a new App'), 'page': (page_parser, 'Add a page to the views'), 'compile': (compile_parser, 'Compile Markdown file to a valid HTML page'), 'translate':... |
class MetaDataRegularSurface(MetaData):
REQUIRED = {'ncol': 1, 'nrow': 1, 'xori': 0.0, 'yori': 0.0, 'xinc': 1.0, 'yinc': 1.0, 'yflip': 1, 'rotation': 0.0, 'undef': xtgeo.UNDEF}
def __init__(self):
super().__init__()
self._required = __class__.REQUIRED
self._optional._datatype = 'Regular ... |
def eval_formula(item, worksheet):
logging.debug(('Item is %s' % item))
if item.startswith('='):
item = item[1:]
logging.debug(('Item reset to %s' % item))
else:
logging.debug(('Returning %s' % item))
return item
ops = '+-/*'
formula = ''
arg = ''
nargs = 0
... |
def LoadTypeLib(spec: Union[(TypelibSpec, PyIIDLike)]) -> Optional[PyITypeLib]:
tlb: Optional[PyITypeLib] = None
if IsPyIIDLike(spec):
spec = GetLatestTypelibSpec(spec)
if spec:
if spec.dll:
tlb = LoadTypeLibFromDLL(spec.dll)
else:
tlb = LoadRegTypeLib(spec.cl... |
class ServiceTestPlanFixtureParser(object):
def __init__(self, fixture_file_name, fixture_name):
self._fixture_file_name = fixture_file_name
self._fixture_name = fixture_name
self._working_directory = os.path.basename(fixture_file_name)
if (not os.path.isabs(self._fixture_file_name))... |
def main():
cerebro = bt.Cerebro()
_strats = cerebro.optstrategy(OrclStrategy, maperiod=range(10, 31))
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, 'data/orcl-1986-2020.csv')
data = bt.feeds.YahooFinanceCSVData(dataname=datapath, fromdate=datetime.datetime... |
class AdminSalesByMarketerSchema(Schema):
class Meta():
type_ = 'admin-sales-by-marketer'
self_view = 'v1.admin_sales_by_marketer'
id = fields.String()
fullname = fields.String()
email = fields.String()
sales = fields.Method('calc_sales')
def calc_sales(obj):
return summa... |
class TestRedirects(unittest.TestCase):
def setUp(self):
(self.mock_server_port, self.mock_server, self.mock_server_thread) = testing_server.start_server(self, {})
def tearDown(self):
self.mock_server.shutdown()
self.mock_server_thread.join()
def test_plain_instantiation_1(self):
... |
def watcher_factory(conf):
watcher_types = {'port_state': {'text': GaugePortStateLogger, 'influx': GaugePortStateInfluxDBLogger, 'prometheus': GaugePortStatePrometheusPoller}, 'port_stats': {'text': GaugePortStatsLogger, 'influx': GaugePortStatsInfluxDBLogger, 'prometheus': GaugePortStatsPrometheusPoller}, 'flow_ta... |
class Solution():
def minAreaRect(self, points: List[List[int]]) -> int:
seen = set()
res = float('inf')
for (x1, y1) in points:
for (x2, y2) in seen:
if (((x1, y2) in seen) and ((x2, y1) in seen)):
area = (abs((x1 - x2)) * abs((y1 - y2)))
... |
def get_episodes(html, url):
lzstring.init(html, url)
episodes = None
cid = re.search('comic/(\\d+)', url).group(1)
episodes = get_list(html, cid)
if (not episodes):
view_state = re.search('id="__VIEWSTATE" value="([^"]+)', html).group(1)
ep_html = lzstring.decompress_from_base64(vie... |
class OptionSeriesNetworkgraphSonification(Options):
def contextTracks(self) -> 'OptionSeriesNetworkgraphSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionSeriesNetworkgraphSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionSeriesNetworkgraphSonificatio... |
def diag_quadrupole3d_32(ax, da, A, bx, db, B, R):
result = numpy.zeros((3, 10, 6), dtype=float)
x0 = ((ax + bx) ** (- 1.0))
x1 = (x0 * ((ax * A[0]) + (bx * B[0])))
x2 = (- x1)
x3 = (x2 + A[0])
x4 = (x2 + B[0])
x5 = ((- 2.0) * x1)
x6 = (x5 + R[0])
x7 = (x6 + B[0])
x8 = (x0 * x7)
... |
def _test_icmptypes_ipset(xmlobjs):
types4 = firewall.core.icmp.ICMP_TYPES
types6 = firewall.core.icmp.ICMPV6_TYPES
for xmlobj in xmlobjs:
should_have4 = ('ipv4' in _get_destination(xmlobj))
should_have6 = ('ipv6' in _get_destination(xmlobj))
assert (should_have4 or should_have6)
... |
def test():
assert ('from spacy.matcher import PhraseMatcher' in __solution__), 'Voce importou corretamente o PhraseMatcher?'
assert ('PhraseMatcher(nlp.vocab)' in __solution__), 'Voce inicializou corretamente o PhraseMatcher?'
assert ('matcher(doc)' in __solution__), 'Voce chamou o Comparador passando o do... |
def execute_cmds(config, input_mods, _mstdout, mstderr):
try:
topic_continuum_set = TopicContinuumSet(input_mods, config)
except RMTException as rmte:
mstderr.write(('+++ ERROR: Problem reading in the continuum [%s]\n' % Encoding.to_unicode(rmte)))
return False
if (not topic_continuu... |
class SeleniumMiddleware():
def __init__(self):
self.driver = None
def process_request(self, request, spider):
self.driver = spider.driver
spider.sleep()
self.driver.get(request.url)
for (cookie_name, cookie_value) in request.cookies.items():
self.driver.add_c... |
class TargetGenerator():
def __init__(self, ast: AbstractSyntaxTree, bounds: ComplexityBounds):
self._ast = ast
self._bounds = bounds
def generate(self) -> Iterator[Target]:
for node in self._ast.get_code_nodes_topological_order():
for simp_target in self._from_code_node(node... |
def test_butterworth_returns_correct_value_with_bandpass_filter_type_and_float32_precision(trace):
(b, a) = signal.butter(3, [(.0 / (.0 / 2)), (.0 / (.0 / 2))], 'bandpass')
b = b.astype('float32')
a = a.astype('float32')
expected = signal.lfilter(b, a, trace)
result = scared.signal_processing.butter... |
def str_to_bool(val, default_val=False):
if isinstance(val, str):
val2 = val.lower().strip()
if (val2 in ('', 'default', '-1')):
return default_val
if (val2 in ('0', 'n', 'no', 'false')):
return False
if (val2 in ('1', 'y', 'yes', 'true')):
return ... |
class Logic(object):
def get_doer(name):
log.debug(('loading %s ...' % name))
return SourceFileLoader('', name).load_module()
def get_symbol(name, symbol):
doer = Logic.get_doer(name)
if (symbol not in doer.__dict__):
return (None, ('%s does not define a %s function' ... |
def test_minimal(mocker):
class Observer():
def on_enter_state(self, event, model, source, target, state):
...
obs = Observer()
on_enter_state = mocker.spy(obs, 'on_enter_state')
class Machine(StateMachine):
a = State('Init', initial=True)
b = State('Fin')
cyc... |
class BCDevRunner(BCRunner):
(BCRunner)
def create_distributed_eval_env(cls, env_factory: Callable[([], Union[(StructuredEnv, StructuredEnvSpacesMixin)])], eval_concurrency: int, logging_prefix: str) -> SequentialVectorEnv:
return SequentialVectorEnv([env_factory for _ in range(eval_concurrency)], loggi... |
class PowerUtil():
def __init__(self, platform, duration):
self.platform = platform
self.data = []
self.duration = duration
def collect(self):
self.data.append(self.platform.currentPower())
self.platform.usb_controller.disconnect(self.platform.platform_hash)
getLo... |
class linuxcooked(packet_base.PacketBase):
_PACK_STR = '!HHH8sH'
_MIN_LEN = struct.calcsize(_PACK_STR)
def __init__(self, pkt_type, arphrd_type, address_length, address, proto_type):
super(linuxcooked, self).__init__()
self.pkt_type = pkt_type
self.arphrd_type = arphrd_type
s... |
def set_capacities_random_zipf_mandelbrot(topology, capacities, capacity_unit='Mbps', alpha=1.1, q=0.0, reverse=False):
if (alpha <= 0.0):
raise ValueError('alpha must be positive')
if (q < 0.0):
raise ValueError('q must be >= 0')
capacities = sorted(capacities, reverse=reverse)
pdf = {c... |
def is_delimiter(recinfo):
if (recinfo is None):
return False
if (recinfo.type == core.lis_rectype.reel_header):
return True
if (recinfo.type == core.lis_rectype.reel_trailer):
return True
if (recinfo.type == core.lis_rectype.tape_header):
return True
if (recinfo.type... |
class AdamGrafting(AdagradGrafting):
def __init__(self, param, beta2: float=0.999, epsilon: float=1e-08, group: Optional[dist.ProcessGroup]=None, group_source_rank: int=0, dist_buffer: Optional[Tensor]=None, use_dtensor: bool=True, communication_dtype: CommunicationDType=CommunicationDType.DEFAULT):
super(A... |
def test_freeu_identity_scales() -> None:
manual_seed(0)
text_embedding = torch.randn(1, 77, 768)
timestep = torch.randint(0, 999, size=(1, 1))
x = torch.randn(1, 4, 32, 32)
unet = SD1UNet(in_channels=4)
unet.set_clip_text_embedding(clip_text_embedding=text_embedding)
with no_grad():
... |
def test_open_session_with_endpoint():
class MySessionInterface(SessionInterface):
def save_session(self, app, session, response):
pass
def open_session(self, app, request):
flask._request_ctx_stack.top.match_request()
assert (request.endpoint is not None)
app... |
.parametrize('input_vars', [['Name', 'City', 'Absent'], 'Absent', ['Absent']])
def test_check_all_variables_raises_errors_when_not_in_dataframe(df_vartypes, input_vars):
msg_ls = "'Some of the variables are not in the dataframe.'"
msg_single = "'The variable Absent is not in the dataframe.'"
with pytest.rai... |
class RangeTextEditor(TextEditor):
low = Any()
high = Any()
evaluate = Any()
def init(self, parent):
if (not self.factory.low_name):
self.low = self.factory.low
if (not self.factory.high_name):
self.high = self.factory.high
self.sync_value(self.factory.low... |
.skip('These tests take a very long time to compute')
.parametrize('skip_hps', [False, True])
def test_fwd_j2(skip_hps):
with set_double_precision():
x = torch.randn(1, 3, 16, 16, device=dev, requires_grad=True)
xfm = DTCWTForward(J=2).to(dev)
input = (x, xfm.h0a, xfm.h1a, xfm.h0b, xfm.h1b, skip... |
def command_method(method):
def wrapper(self, req, *args, **kwargs):
try:
if req.body:
body = ast.literal_eval(req.body.decode('utf-8'))
else:
body = {}
except SyntaxError:
LOG.exception('Invalid syntax: %s', req.body)
r... |
class RxEngineState(Component):
def __init__(self, name: str, address: str, state: Dict, processor: Dict=None, space: Dict=None):
kwargs = locals().copy()
kwargs.pop('self')
super(RxEngineState, self).__init__(**kwargs)
def build(self, ns=''):
params = self.__dict__.copy()
... |
def ensure_stats_downloaded_for_date(date):
filename = get_practice_stats_filename(date)
if os.path.exists(filename):
return
client = Client('hscic')
check_stats_in_bigquery(date, client)
logger.info('Downloading practice statistics for %s', date)
temp_name = get_temp_filename(filename)
... |
class Stp(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION, ofproto_v1_2.OFP_VERSION, ofproto_v1_3.OFP_VERSION]
def __init__(self):
super(Stp, self).__init__()
self.name = 'stplib'
self._set_logger()
self.config = {}
self.bridge_list = {}
def close(self):... |
def log_fortianalyzer2_filter(data, fos):
vdom = data['vdom']
log_fortianalyzer2_filter_data = data['log_fortianalyzer2_filter']
filtered_data = underscore_to_hyphen(filter_log_fortianalyzer2_filter_data(log_fortianalyzer2_filter_data))
return fos.set('log.fortianalyzer2', 'filter', data=filtered_data, ... |
def main(tempdir_root: str, url: str='', video: str='', language: str=''):
with TempDir(dir=tempdir_root) as shared_tmp:
shared_tmp = Path(shared_tmp)
lang = check_language(language)
config = Config(target_lang=lang, speaker_markers=True)
local_input = check_input(url, video)
... |
class BookingAdmin(admin.ModelAdmin):
def rate(self):
if (self.rate is None):
return None
return ('$%d' % self.rate)
def value(self):
return ('$%d' % self.base_value())
def bill(self):
return ('$%d' % self.bill.amount())
def fees(self):
return ('$%d' %... |
class S6HalfRateDDRPHY(Module):
def __init__(self, pads, memtype, rd_bitslip, wr_bitslip, dqs_ddr_alignment):
pads = PHYPadsCombiner(pads)
if (memtype not in ['DDR', 'LPDDR', 'DDR2', 'DDR3']):
raise NotImplementedError('S6HalfRateDDRPHY only supports DDR, LPDDR, DDR2 and DDR3')
a... |
def get_fal_scripts_path(config: RuntimeConfig):
import pathlib
project_path = pathlib.Path(config.project_root)
fal_scripts_path = ''
if hasattr(config, 'vars'):
fal_scripts_path: str = config.vars.to_dict().get(FAL_SCRIPTS_PATH_VAR_NAME, fal_scripts_path)
if hasattr(config, 'cli_vars'):
... |
class CssRadioButtonSelected(CssStyle.Style):
_attrs = {'padding': '2px 5px', 'cursor': 'pointer', 'vertical-align': 'middle'}
def customize(self):
self.css({'border': ('1px solid %s' % self.page.theme.success.base), 'color': self.page.theme.success.base, 'font-size': self.page.body.style.globals.font.n... |
def set_my_default_administrator_rights(token, rights=None, for_channels=None):
method_url = 'setMyDefaultAdministratorRights'
payload = {}
if rights:
payload['rights'] = rights.to_json()
if (for_channels is not None):
payload['for_channels'] = for_channels
return _make_request(token... |
(scope='session')
def tmp_project(tmp_path_factory, pytestconfig, cli_options, request):
request.config.cache.set('app_name', None)
request.config.cache.set('project_id', None)
sd_root_dir = Path(__file__).parent.parent
tmp_proj_dir = tmp_path_factory.mktemp('blog_project')
print(f'''
Temp project d... |
class Score():
def __init__(self):
self.lines = 0
self.level = 0
self.score = 0
def add_lines(self, lines):
self.lines += lines
self.level = (self.lines // 10)
if (lines == 1):
self.score += (40 * (self.level + 1))
elif (lines == 2):
... |
class CometLogger():
def __init__(self):
global comet_installed
self._logging = False
if comet_installed:
try:
self._experiment = Experiment(auto_metric_logging=False, display_summary_level=0)
self._experiment.log_other('Created from', 'sweetviz!')... |
class MPRangeSelection(RangeSelection):
_blobs = Dict()
_moves = Dict()
_axis_blobs = Property(Dict)
_axis_moves = Property(Dict)
def _convert_to_axis(self, d):
if (self.axis == 'index'):
idx = self.axis_index
else:
idx = (1 - self.axis_index)
d2 = {}
... |
class BaseSettings(BaseModel):
ies_inversion: Annotated[(int, Field(ge=0, le=3, title='Inversion algorithm'))] = DEFAULT_IES_INVERSION
enkf_truncation: Annotated[(float, Field(gt=0.0, le=1.0, title='Singular value truncation'))] = DEFAULT_ENKF_TRUNCATION
class Config():
extra = Extra.forbid
... |
def update_patient_email_and_phone_numbers(contact, method):
if (('Healthcare' not in frappe.get_active_domains()) or contact.flags.skip_patient_update):
return
if (contact.is_primary_contact and (contact.email_id or contact.mobile_no or contact.phone)):
patient_links = list(filter((lambda link:... |
class CaiTemporaryStore(BASE):
__tablename__ = 'cai_temporary_store'
name = Column(String(2048, collation='binary'), nullable=False)
parent_name = Column(String(255), nullable=True)
content_type = Column(Enum(ContentTypes), nullable=False)
asset_type = Column(String(255), nullable=False)
asset_d... |
class QueryAjaxModelLoader(AjaxModelLoader):
def __init__(self, name, session, model, **options):
super(QueryAjaxModelLoader, self).__init__(name, options)
self.session = session
self.model = model
self.fields = options.get('fields')
self.order_by = options.get('order_by')
... |
class DUT(Module):
def __init__(self):
self.submodules.phy_model = phy.PHY(8, debug=True)
self.submodules.mac_model = mac.MAC(self.phy_model, debug=True, loopback=False)
self.submodules.arp_model = arp.ARP(self.mac_model, mac_address, ip_address, debug=True)
self.submodules.ip_model ... |
class Ziplatest(JoinOp):
__slots__ = ('_values', '_is_primed', '_source2cbs')
def __init__(self, *sources, partial=True):
JoinOp.__init__(self)
self._is_primed = partial
self._source2cbs = defaultdict(list)
if sources:
self._set_sources(*sources)
def _set_sources(... |
.external
.skipif((has_anthropic_key is False), reason='Anthropic API key unavailable')
def test_anthropic_error_unsupported_model():
incorrect_model = 'x-gpt-3.5-turbo'
with pytest.raises(ValueError, match=re.escape('Ensure that the selected model (x-gpt-3.5-turbo) is supported by the API')):
Anthropic... |
def load_samples(feature: str, subfeature: str, phase: str='', provider_name: Optional[str]=None) -> Dict:
normalized_subfeature = f"{subfeature}{(f'_{phase}' if phase else '')}"
imp = import_module(f"edenai_apis.features.{feature}.{subfeature}{(f'.{phase}' if phase else '')}.{normalized_subfeature}_args")
... |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 84
PLUGIN_NAME = 'Environment - VEML6070 UV sensor (TESTING)'
PLUGIN_VALUENAME1 = 'UV-Raw'
PLUGIN_VALUENAME2 = 'UV-Risk'
PLUGIN_VALUENAME3 = 'UV-Power'
VEML6070_ADDR_H = 57
VEML6070_ADDR_L = 56
VEML6070_RSET_DEFAULT = 270000
VEML6070_UV_M... |
class LMQLTokenizer():
INVALID_CHARACTER = ''
def __init__(self, model_identifier, tokenizer_impl=None, loader=None):
self._tokenizer_impl = None
self.loader_thread = None
self.loader_failed = False
self.model_identifier = model_identifier
self._vocab = None
self.... |
class TestField():
def test_generate_field(self) -> None:
def _is_string_field(f: Field):
return (isinstance(f, ScalarField) and (f.data_type_converter.name == 'string'))
string_field = generate_field(name='str', data_categories=['category'], identity='identity', data_type_name='string',... |
class Solution(object):
def reverseWords(self, s):
def reverse_pos(s, st, ed):
while (st < ed):
(s[ed], s[st]) = (s[st], s[ed])
st += 1
ed -= 1
def reverse_in_words(s):
start_idx = 0
for (i, c) in enumerate(s):
... |
('ui')
def ui(host: str=Option('0.0.0.0', help='Service host'), port: int=Option(8000, help='Service port'), workspace: str=Option('workspace', help='Path to workspace'), demo_projects: str=Option('', '--demo-projects', help='Comma-separated list of demo projects to generate. Possible values: [all|bikes|reviews|adult]'... |
def test_basic_block() -> None:
state = build_state(5)
time = get_current_time()
current_epoch = compute_epoch_at_time(time)
proposer_duties = bn_get_proposer_duties_for_epoch((current_epoch + 1))
filled_proposer_duties = filter_and_fill_proposer_duties_with_val_index(state, proposer_duties)
whi... |
.host_test
def test_reed_solomon_encoding():
pairs = [('a0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebf', '0404992ae0b12cb0ef0d4fd3'), ('11a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbd11bf', 'e001803c2130884c190d57d5'), ('22a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbd22bf... |
class TestFileHelp(TestCase):
('evennia.help.filehelp.variable_from_module')
def test_file_help(self, mock_variable_from_module):
mock_variable_from_module.return_value = HELP_ENTRY_DICTS
storage = filehelp.FileHelpStorageHandler(help_file_modules=['dummypath'])
result = storage.all()
... |
class OptionsSkin(Options):
component_properties = ('color', 'font_size')
def color(self):
return self._config_get(self.page.theme.notch())
def color(self, value: str):
self._config(value)
def font_size(self):
return self._config_get(10)
_size.setter
def font_size(self, n... |
class OptionPlotoptionsItemSonificationTracksMappingTime(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._c... |
def upwardsRecursiveDescription(view, maxDepth=0):
if ((not fb.evaluateBooleanExpression(('[(id)%s isKindOfClass:(Class)[UIView class]]' % view))) and (not fb.evaluateBooleanExpression(('[(id)%s isKindOfClass:(Class)[NSView class]]' % view)))):
return None
currentView = view
recursiveDescription = [... |
class TestUserSettingsView(object):
def test_renders_get_okay(self, mocker):
form = self.produce_form({})
handler = mocker.Mock(spec=ChangeSetHandler)
handler = UserSettings(form=form, settings_update_handler=handler)
handler.get()
def test_update_user_settings_successfully(self,... |
class IndicatorSysmonitor(object):
SENSORS_DISABLED = False
def __init__(self):
self._preferences_dialog = None
self._help_dialog = None
self.ind = Gtk.Button.new()
self.ind.set_label('Init...')
self._create_menu()
self.alive = Event()
self.alive.set()
... |
class OptionSeriesTimelineSonificationTracksMappingTime(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._co... |
def reset_homepages():
import tqdm
import common.database as db
sess = db.get_db_session()
for pageno in tqdm.trange(1, 1001):
url = (' % pageno)
have = sess.query(db.WebPages).filter((db.WebPages.url == url)).scalar()
if have:
have.state = 'new'
have.epoc... |
def test_dataset_schema(tmp_path_factory, root_dir):
temp_directory = tmp_path_factory.mktemp('foundry_dev_tools_test_100').as_posix()
bases = [root_dir, temp_directory]
for base in bases:
filesystem = fs.open_fs(os.fspath(base))
client = MockFoundryRestClient(filesystem=filesystem)
... |
class SPIDevice():
def __init__(self, cs=None):
self.spi = spidev.SpiDev(0, 0)
GPIO.setmode(GPIO.BCM)
self._cs = cs
if cs:
GPIO.setup(self._cs, GPIO.OUT)
GPIO.output(self._cs, GPIO.HIGH)
self.spi.max_speed_hz = 1000000
self.spi.mode = 2
def... |
class TestInlineHiliteCustom5(util.MdCase):
extension = ['pymdownx.highlight', 'pymdownx.inlinehilite']
extension_configs = {'pymdownx.inlinehilite': {'css_class': 'inlinehilite', 'custom_inline': [{'name': '*', 'class': 'overwrite', 'format': _default_format}, {'name': 'test', 'class': 'class-test', 'format': ... |
class FlatPlaylistPanel(panel.Panel):
__gsignals__ = {'append-items': (GObject.SignalFlags.RUN_LAST, None, (object, bool)), 'replace-items': (GObject.SignalFlags.RUN_LAST, None, (object,)), 'queue-items': (GObject.SignalFlags.RUN_LAST, None, (object,))}
ui_info = ('flatplaylist.ui', 'FlatPlaylistPanel')
def... |
class IRHTTPMapping(IRBaseMapping):
prefix: str
headers: List[KeyValueDecorator]
add_request_headers: Dict[(str, str)]
add_response_headers: Dict[(str, str)]
method: Optional[str]
service: str
group_id: str
route_weight: List[Union[(str, int)]]
cors: IRCORS
retry_policy: IRRetryP... |
class OptionPlotoptionsScatter3dSonificationDefaultinstrumentoptionsMappingPlaydelay(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,... |
class DeviceTransferThread(common.ProgressThread):
def __init__(self, device):
common.ProgressThread.__init__(self)
self.device = device
def stop(self):
self.device.transfer.cancel()
common.ProgressThread.stop(self)
def on_track_transfer_progress(self, type, transfer, progres... |
def extractFckyeahdaisukekambeTumblrCom(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, t... |
.parametrize('head,expected_forkid', [(0, ForkID(hash=to_bytes(hexstr='0xfc64ec04'), next=1150000)), (1149999, ForkID(hash=to_bytes(hexstr='0xfc64ec04'), next=1150000)), (1150000, ForkID(hash=to_bytes(hexstr='0x97c2c34c'), next=1920000)), (1919999, ForkID(hash=to_bytes(hexstr='0x97c2c34c'), next=1920000)), (1920000, Fo... |
class TestCLIShrink(CuratorTestCase):
def builder(self):
self.loogger = logging.getLogger('TestCLIShrink.builder')
self.idx = 'my_index'
self.suffix = '-shrunken'
self.target = f'{self.idx}{self.suffix}'
self.create_index(self.idx, shards=2)
self.add_docs(self.idx)
... |
class Worker(_Worker):
EMMETT_CONFIG = {}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
logger = logging.getLogger('uvicorn.error')
logger.handlers = self.log.error_log.handlers
logger.setLevel(self.log.error_log.level)
logger.propagate = False
... |
class OptionPlotoptionsFunnelSonificationDefaultspeechoptionsMappingRate(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):... |
.django_db
def test_award_update_from_contract_transaction():
award = baker.make('search.AwardSearch', award_id=1, generated_unique_award_id='EXAMPLE_AWARD_1')
baker.make('search.TransactionSearch', transaction_id=1, is_fpds=True, award=award, base_and_all_options_value=1000, base_exercised_options_val=100, gen... |
def test_model_last(db):
p = db.Person.insert(name='Walter', age=50)
db.Subscription.insert(name='a', expires_at=(datetime.now() + timedelta(hours=20)), person=p, status=1)
db.Subscription.insert(name='b', expires_at=(datetime.now() + timedelta(hours=20)), person=p, status=1)
db.CustomPKType.insert(id='... |
def gen_freq_range_str(model_obj, concise=False):
freq_range = (model_obj.freq_range if model_obj.has_data else ('XX', 'XX'))
str_lst = ['=', '', 'SpecParam - FIT RANGE', '', 'The model was fit from {} to {} Hz.'.format(*freq_range), '', '=']
output = _format(str_lst, concise)
return output |
class InputOutputGenerator(lg.Node):
OUTPUT = lg.Topic(InputOutputArgumentMessage)
counter: int
def setup(self):
self.counter = 0
(OUTPUT)
async def run(self) -> lg.AsyncPublisher:
while (self.counter < 10):
self.counter += 1
(yield (self.OUTPUT, InputOutputAr... |
class UserServiceTest(RPCTestCase):
def test_create_user(self):
stub = account_pb2_grpc.UserControllerStub(self.channel)
response = stub.Create(account_pb2.User(username='tom', email=''))
self.assertEqual(response.username, 'tom')
self.assertEqual(response.email, '')
self.ass... |
class IBC():
IbcLogLevel: ClassVar = logging.DEBUG
twsVersion: int = 0
gateway: bool = False
tradingMode: str = ''
twsPath: str = ''
twsSettingsPath: str = ''
ibcPath: str = ''
ibcIni: str = ''
javaPath: str = ''
userid: str = ''
password: str = ''
fixuserid: str = ''
... |
.parametrize('iso_x,iso_y,iso_z,g2_x,g2_y', [(FQ2([int('0888F3832AD680917A71A1816CC647B0B196BA0EDF62A0BC1A15D3E87CF6A287137B16C057E1AC808', 16), int('0B3D6E7A20275C100B460A900B23F2D8D5E9A53C3E59066E8D968D07AB0787940C0AC8A6C8C118FAD9068A2ECF00ADD7', 16)]), FQ2([int('08696DF8BAF8C488B7CFCA14CB984D0B78C998C3431E41700B493A... |
def test_non_implemented_class_methods():
with pytest.raises(NotImplementedError):
Contract.get_raw_transaction('ledger_api', 'contract_address')
with pytest.raises(NotImplementedError):
Contract.get_raw_message('ledger_api', 'contract_address')
with pytest.raises(NotImplementedError):
... |
class MaskedTransforms(Transforms):
def __init__(self, parent: Transforms, indices: types.arraydata):
assert isinstance(parent, Transforms), f'parent={parent!r}'
assert (isinstance(indices, types.arraydata) and (indices.dtype == int)), f'indices={indices!r}'
self._parent = parent
sel... |
_log_on_failure_all
class TestLibp2pClientConnectionRouting():
_log_on_failure
def setup_class(cls):
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
os.chdir(cls.t)
cls.log_files = []
cls.multiplexers = []
try:
temp_dir_node_1 = os.path.join(cls.t, 't... |
def test_pstxt_download_success(client, monkeypatch, awards_and_transactions, elasticsearch_award_index):
download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string())
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
resp = _post(client, def_codes=['L', 'M'], award_ty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.