code stringlengths 281 23.7M |
|---|
def get_surf_distances(surf, orig_vertex, radius_search=100, dryrun=False, suppress_echo=False):
with TempDir() as tmpdir:
surf_distance = os.path.join(tmpdir, 'distancecalc.shape.gii')
run(['wb_command', '-surface-geodesic-distance', surf, str(orig_vertex), surf_distance, '-limit', str(radius_searc... |
def parse_concessions_from_rss(feed_content):
feed = bs4.BeautifulSoup(feed_content, 'xml')
for item in feed.find_all('item'):
url = item.find('link').string
item_content = item.find('content:encoded').string
(yield from parse_concessions_from_html(item_content, url=url)) |
def extractMegajivetranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('a round trip to love', 'A Round Trip to Love', 'translated'), ('PRC', 'PRC', 'transl... |
class OptionPlotoptionsDependencywheelSonificationDefaultinstrumentoptionsMappingLowpassResonance(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)
de... |
def _cmd_run(jobs: Jobs, reqid: RequestID) -> Job:
try:
job = jobs.activate(reqid)
except RequestAlreadyStagedError as exc:
logger.error('%s', exc)
sys.exit(1)
except Exception:
logger.error('could not stage request')
logger.info('')
job_lookup = jobs.get(reqi... |
class UpdateDialog(wx.Dialog):
def __init__(self, cont, *args, **kwargs):
self.textPanel = None
self.contPanel = None
self.sizer = None
self.button = {}
self.H = 30
self.W = 450
self.tH = 60
self.bH = 50
self.yP = 20
self.xP = 20
... |
def test_may_overlap(string_to_well):
well_1 = string_to_well('1.01\nUnknown\nname 0 0 0\n1\nZonelog DISC 1 zone1 2 zone2 3 zone3\n1 1 1 nan\n2 2 1 1\n3 3 1 1')
well_2 = string_to_well('1.01\nUnknown\nname 0 0 0\n1\nZonelog DISC 1 zone1 2 zone2 3 zone3\n1 1 1 nan\n2 2 1 1\n3 3 1 1')
assert well_1.may_overla... |
class LabeledSwitch(Widget):
value = reactive(False)
def __init__(self, label, watch_value=None, id=''):
id = (id or label.lower().replace(' ', '-').replace(':', ''))
super().__init__(id=id)
self.label = label
self.watch_value = watch_value
def compose(self):
(yield L... |
def obtain_recipient_level(recipient_record: dict) -> str:
level = None
if recipient_record['is_parent_recipient']:
level = 'P'
elif (recipient_record['parent_uei'] is None):
level = 'R'
elif (recipient_record['parent_uei'] is not None):
level = 'C'
return level |
def get_pkg_path(package_name):
global _get_pkg_path_var
if (_get_pkg_path_var is None):
try:
import rospkg
rp = rospkg.RosPack()
_get_pkg_path_var = rp.get_path
except ImportError:
_get_pkg_path_var = roslib.packages.get_pkg_dir
return _get_pk... |
class OptionPlotoptionsPolygonSonificationDefaultinstrumentoptionsMappingTremoloDepth(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... |
.parametrize('return_code', [SUCCESS, FAILURE])
def test_fal_hook(mocker, return_code):
task = FalLocalHookTask('something.py', bound_model=FakeModel('model'))
task.set_run_index(DynamicIndexProvider())
fal_dbt = FakeFalDbt('/test')
mock_script_construction(mocker, return_code)
assert (task.execute(... |
class Player(HasStrictTraits):
in_lineup = Bool(True)
name = Str()
at_bats = Int()
strike_outs = Int()
singles = Int()
doubles = Int()
triples = Int()
home_runs = Int()
walks = Int()
average = Property(Float)
def _get_average(self):
if (self.at_bats == 0):
... |
class TestTokenValidator(TestCase):
def setUp(self) -> None:
self.client = MagicMock(spec=BoltGraphAPIClient)
self.trace_logger = MagicMock(spec=TraceLoggingService)
self.validator = TokenValidator(self.client, trace_logging_svc=self.trace_logger)
def test_token_common_rules(self) -> Non... |
def extractMeowyinggWordpressCom(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)... |
class HexResourceType(SuperEnum):
__keys__ = ['id', 'rarity', 'title', 'material', 'yield', 'color']
iron_vein = (1, 15, 'Iron Vein', 1000, 'commonmetals', (100, 0, 0))
copper_vein = (2, 15, 'Copper Vein', 1000, 'commonmetals', (0, 100, 0))
silver_vein = (3, 15, 'Silver Vein', 1000, 'commonmetals', (0, ... |
def test_schema_datetime_serialization():
guest = typesystem.Schema(fields={'id': typesystem.Integer(), 'name': typesystem.String(), 'check_in': typesystem.DateTime(), 'check_out': typesystem.DateTime(allow_null=True)})
guest_id = 123
guest_name = 'Bob'
check_in = datetime.datetime.now(tz=datetime.timez... |
class OptionPlotoptionsDependencywheelSonificationDefaultinstrumentoptionsMappingPlaydelay(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... |
class OptionPlotoptionsSunburstSonificationTracksMappingHighpass(Options):
def frequency(self) -> 'OptionPlotoptionsSunburstSonificationTracksMappingHighpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSunburstSonificationTracksMappingHighpassFrequency)
def resonance(self) -> '... |
.parametrize('elasticapm_client,expected', [({'service_version': 'v2'}, ' v2'), ({'service_version': 'v2 \x00'}, ' v2 _'), ({}, '')], indirect=['elasticapm_client'])
def test_user_agent(elasticapm_client, expected):
assert (elasticapm_client.get_user_agent() == 'apm-agent-python/{} (myapp{})'.format(elasticapm.VERS... |
def translate_per_build_anti_features(apps, apks):
antiFeatures = dict()
for (packageName, app) in apps.items():
d = dict()
for build in app.get('Builds', []):
afl = build.get('antifeatures')
if afl:
d[build.versionCode] = afl
if (len(d) > 0):
... |
def get_cpu_gpu_correlation(df: pd.DataFrame) -> pd.DataFrame:
kernel_indices = df[(df['stream'].gt(0) & df['index_correlation'].gt(0))]['index']
cpu_gpu_correlation = df.loc[kernel_indices][['index', 'index_correlation']].copy().rename(columns={'index': 'gpu_index', 'index_correlation': 'cpu_index'}).reset_ind... |
.host_test
class BaseTestCase():
def setup_class(self):
self.stored_dir = os.getcwd()
os.chdir(TEST_DIR)
def teardown_class(self):
os.chdir(self.stored_dir)
def assertEqualHex(self, expected, actual, message=None):
try:
expected = hex(expected)
except Type... |
def generate_random_factored_numbers(bits, procs, count):
count_per_proc = (count // procs)
processes = [mp.Process(target=generate_random_factored_numbers_mp, args=(gmpy2.mpz((2 ** bits)), random.randint(1, (10 ** 10)), count_per_proc)) for x in range(procs)]
for p in processes:
p.start()
remai... |
def test_hover_literal_bool():
string = write_rpc_request(1, 'initialize', {'rootPath': str(test_dir)})
file_path = ((test_dir / 'hover') / 'parameters.f90')
string += hover_req(file_path, 8, 50)
(errcode, results) = run_request(string, fortls_args=['--sort_keywords'])
assert (errcode == 0)
ref_... |
class Osher_controller(SC_base):
def __init__(self, model, nOptions):
SC_base.__init__(self, model, nOptions)
for ci in list(nOptions.atol_res.keys()):
self.atol = nOptions.atol_res[ci]
self.rtol = nOptions.rtol_res[ci]
self.stepExact = True
for m in model.lev... |
class OptionSeriesWaterfallEvents(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._confi... |
def wrap_workflow_schedule_list_response(workflow_schedule_list: List[WorkflowScheduleProto]):
if ((workflow_schedule_list is None) or (len(workflow_schedule_list) == 0)):
return Response(return_code=str(RESOURCE_DOES_NOT_EXIST), error_msg=ReturnCode.Name(RESOURCE_DOES_NOT_EXIST).lower(), data=None)
els... |
()
def _run_around_tests(tmpdir):
with mock.patch('transforms.api.Input._read_spark_df_with_sql_query', return_df), mock.patch('transforms.api.Input._dataset_has_schema', dataset_has_schema_mock), mock.patch('foundry_dev_tools.foundry_api_client.FoundryRestClient.get_dataset_identity', get_dataset_identity_mock), m... |
def __read_toc_header(fd):
FORMAT_cdrom_tochdr = 'BB'
cdrom_tochdr = struct.pack(FORMAT_cdrom_tochdr, 0, 0)
CDROMREADTOCHDR = 21253
cdrom_tochdr = fcntl.ioctl(fd, CDROMREADTOCHDR, cdrom_tochdr)
(start, end) = struct.unpack(FORMAT_cdrom_tochdr, cdrom_tochdr)
return (start, end) |
def test_con2R():
x = np.array([[(- 1), 0, 0, 1], [(- 0.5), (- 0.5), 0.5, 0.5], [((- 3) / 3), (1 / 3), (1 / 3), (1 / 3)]])
out = con2R(x)
assert (out.shape == (4, 3))
names = ['1 v s4', '1+2 vs 3+4', '1 vs 2+3+4']
out = con2R(x, names=names)
assert isinstance(out, pd.DataFrame)
assert [(x ==... |
def get_workarea_dimensions(window=None):
if (window is None):
screen = Gdk.Screen.get_default()
default_monitor = screen.get_primary_monitor()
return screen.get_monitor_workarea(default_monitor)
else:
display = window.get_window().get_display()
work_area = display.get_mo... |
class ExecutionForbidden(FandoghAPIError):
message = 'Forbidden Execution'
def __init__(self, response, message=None):
self.response = response
if message:
self.message = message
if hasattr(self.response, 'json'):
self.message = self.response.json().get('message',... |
class DataFrame(object):
def __init__(self, data, columns):
self.data = data
self.columns = columns
def _is_h5(file_name):
extension = file_name.split('.')[(- 1)]
if (extension == 'h5'):
return True
else:
return False
def _get_delimiter(file_na... |
class OptionSeriesPolygonSonificationTracksMappingLowpassResonance(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 filter_extender_lte_carrier_by_mcc_mnc_data(json):
option_list = ['sn']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attribute]
return dictionary |
class AvailableOAuthProvider(StrEnum):
DISCORD = 'DISCORD'
FACEBOOK = 'FACEBOOK'
GITHUB = 'GITHUB'
GOOGLE = 'GOOGLE'
LINKEDIN = 'LINKEDIN'
MICROSOFT = 'MICROSOFT'
REDDIT = 'REDDIT'
OPENID = 'OPENID'
def get_display_name(self) -> str:
if (self == AvailableOAuthProvider.OPENID)... |
class AffineFixed(Fixed):
def __init__(self, params_fn: Optional[flowtorch.Lazy]=None, *, shape: torch.Size, context_shape: Optional[torch.Size]=None, loc: float=0.0, scale: float=1.0) -> None:
super().__init__(params_fn, shape=shape, context_shape=context_shape)
self.loc = loc
self.scale = ... |
class RichCallback(Callback):
def __init__(self, rich_kwargs: typing.Optional[typing.Dict]=None, **kwargs):
super().__init__(**kwargs)
rich_kwargs = (rich_kwargs or {})
self._pb = Progress(**rich_kwargs)
self._pb.start()
self._task = None
def set_size(self, size):
... |
class Tee():
def __init__(self, incoming_stream, clients):
self.incoming_stream = incoming_stream
self.clients = clients
def start(self) -> Thread:
t = Thread(target=self.run)
t.start()
return t
def run(self):
nb_clients = len(self.clients)
pipes = [(i... |
class Serializer(Module):
LATENCY = 1
def __init__(self, clkdiv, clk, i_dw, o_dw, i=None, o=None, reset=None, register=True, reset_cnt=(- 1), name=None):
assert (i_dw > o_dw), (i_dw, o_dw)
assert ((i_dw % o_dw) == 0), (i_dw, o_dw)
ratio = (i_dw // o_dw)
sd_clk = getattr(self.sync... |
class TextGridOperations():
def __init__(self, path, pathOut):
self.textGrid = TextGrid(path)
self.fricatives = self.loadDictionaries('dict/fricatives.txt')
self.unvoiced = self.loadDictionaries('dict/unvoiced.txt')
self.xmin = self.textGrid.tiers.xmin
self.xmax = self.textGr... |
class ColorAsserts():
def assertCompare(self, value1, value2, rounding=5):
self.assertEqual(round(value1, rounding), round(value2, rounding))
def assertColorEqual(self, color1, color2, *, fit=False, **kwargs):
self.assertEqual(color1.to_string(fit=fit, **kwargs), color2.to_string(fit=fit, **kwar... |
def extractRubylikesfoodWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('lucia', 'Lucia', 'translated'), ('Volcanic Age', 'Volcanic Age', 'translated'), ('ygtwhv', ... |
class AshesHandler(THBEventHandler):
interested = ['action_after']
execute_before = ['CiguateraHandler']
def handle(self, evt_type, act):
if ((evt_type == 'action_after') and isinstance(act, FinalizeStage)):
tgt = act.target
if (tgt.dead or (not tgt.has_skill(Ashes))):
... |
def run():
print('\nmodule top();\n ')
params = {}
sites = list(gen_sites())
for ((tile_name, sites), isone) in zip(sites, util.gen_fuzz_states(len(sites))):
site_name = sites[0]
params[tile_name] = (site_name, isone)
print('\n (* KEEP, DONT_TOUCH, LOC = "{site}" *)... |
class TickBars(Op):
__slots__ = ('_count', 'bars')
__doc__ = Tickfilter.tickbars.__doc__
bars: BarList
def __init__(self, count, source=None):
Op.__init__(self, source)
self._count = count
self.bars = BarList()
def on_source(self, time, price, size):
if ((not self.bar... |
class PygmentsDoc(Directive):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = False
option_spec = {}
def run(self):
self.filenames = set()
if (self.arguments[0] == 'lexers'):
out = self.document_lexers()
elif (self... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = None
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path': {... |
.django_db
def test_spending_over_time_failure(client, monkeypatch, elasticsearch_transaction_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_over_time/', content_type='application/json', data=json.dumps({'group': 'fiscal_year'}))
as... |
def get_layout(**kwargs):
athlete_info = app.session.query(athlete).filter((athlete.athlete_id == 1)).first()
pmc_switch_settings = json.loads(athlete_info.pmc_switch_settings)
use_run_power = (True if athlete_info.use_run_power else False)
use_cycle_power = (True if athlete_info.use_cycle_power else Fa... |
class Solution(object):
def matrixReshape(self, nums, r, c):
if (not nums):
return nums
(r1, c1) = (len(nums), len(nums[0]))
if ((r1 * c1) != (r * c)):
return nums
(i, j) = (0, 0)
ret = []
for i1 in xrange(r):
row = []
f... |
def add_new_section(new_title):
assert isinstance(new_title, str)
tmp = ''
mode = 'searching for changelog'
with open('CHANGELOG.md', 'r') as fd:
for raw_line in fd:
tmp += raw_line
if (mode == 'searching for changelog'):
if raw_line.startswith('## Changel... |
class OptionSeriesVector(Options):
def accessibility(self) -> 'OptionSeriesVectorAccessibility':
return self._config_sub_data('accessibility', OptionSeriesVectorAccessibility)
def allowPointSelect(self):
return self._config_get(False)
def allowPointSelect(self, flag: bool):
self._con... |
class OptionSeriesLollipopStatesHover(Options):
def animation(self) -> 'OptionSeriesLollipopStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesLollipopStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self.... |
class PDFDict(PDFObject):
def __init__(self, d={}):
PDFObject.__init__(self)
self.dict = {}
for k in d:
self.dict[k] = d[k]
def add(self, name, obj):
self.dict[name] = obj
def __str__(self):
s = '<<'
s += random.choice(['\x00', '\t', '\x00a', '\x0c... |
def test_docs_with_properties():
class User(document.Document):
pwd_hash = field.Text()
def check_password(self, pwd):
return (md5(pwd).hexdigest() == self.pwd_hash)
def password(self):
raise AttributeError('readonly')
def password(self, pwd):
self... |
class OptionPlotoptionsVariwideSonificationTracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
... |
.parametrize('compiled', [True, False])
def test_pointers(compiled):
d = '\n struct test {\n char magic[4];\n wchar wmagic[4];\n uint8 a;\n uint16 b;\n uint32 c;\n char string[];\n wchar wstring[];\n };\n\n struct ptrtest {\n test *pt... |
class SchurPrecon(KSP_Preconditioner):
def __init__(self, L, prefix=None, solver_info=None):
self.PCType = 'schur'
self.L = L
self._initializePC(prefix)
if (solver_info == None):
self._initialize_without_solver_info()
else:
self.model_info = solver_inf... |
def build_neck(config):
from .db_fpn import DBFPN
from .east_fpn import EASTFPN
from .sast_fpn import SASTFPN
from .rnn import SequenceEncoder
from .pg_fpn import PGFPN
from .table_fpn import TableFPN
from .fpn import FPN
support_dict = ['FPN', 'DBFPN', 'EASTFPN', 'SASTFPN', 'SequenceEnc... |
class Executor():
def __init__(self):
self.returncode = None
self._command_line = None
def exec(self, command_path):
global logger
logger = click_web.logger
(root_command, *commands) = command_path.split('/')
self._command_line = CommandLine(click_web.script_file,... |
class OptionPlotoptionsSankeySonificationContexttracksMappingTremoloSpeed(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 _get_mixed_jagged_dense_config(input_accessors: List[TensorAccessor], output_accessors: List[TensorAccessor]) -> Tuple[(bool, List[IntVar], bool)]:
output_shape = output_accessors[0].original_shapes
input_shapes = [acc.original_shapes for acc in input_accessors]
jagged_input_shapes = [s for s in input_s... |
def test_invalidate_simple_config():
invalid_config = {'hello': 1, 'world': 'hi!'}
with pytest.raises(ConfigValidationError) as exc_info:
my_registry._fill(invalid_config, HelloIntsSchema)
error = exc_info.value
assert (len(error.errors) == 1)
assert ('type_error.integer' in error.error_type... |
class TreeAgentPipeline(AgentPipeline):
pipeline: Union[(Dict[(GenericAgentClass, List[GenericAgentClass])], List[GenericAgentClass])] = {}
def __init__(self, module_dict: Dict[(GenericAgent, List[Union[(GenericAgent, GenericAgentClass)]])], args) -> None:
self.check_pipeline_types(module_dict)
... |
def test_get_feature_names_out_w_keywords(df_enc_big_na):
input_features = df_enc_big_na.columns.tolist()
tr = StringSimilarityEncoder(keywords={'var_A': ['XYZ']})
tr.fit(df_enc_big_na)
out = ['var_A_XYZ', 'var_B_A', 'var_B_D', 'var_B_B', 'var_B_G', 'var_B_C', 'var_B_E', 'var_B_F', 'var_C_C', 'var_C_D',... |
class VerifyVersionCommand(install):
description = 'verify that the git tag matches our version'
def run(self):
git_tag = os.getenv('GIT_TAG')
if (git_tag != VERSION):
info = 'Git tag: {0} does not match the version of this app: {1}'.format(git_tag, VERSION)
sys.exit(info... |
def extractRosettaarchiveWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('R.A.M.' in item['tags']):
return buildReleaseMessageWithType(item, 'R.A.M.', vol, chp, fr... |
class VideoChatScheduled(JsonDeserializable):
def de_json(cls, json_string):
if (json_string is None):
return None
obj = cls.check_json(json_string, dict_copy=False)
return cls(**obj)
def __init__(self, start_date, **kwargs):
self.start_date: int = start_date |
('/iterate/<dataset>', methods=['POST'])
def iterate(dataset: str):
item = flask.request.json
global SERVICE
if (SERVICE is None):
return ('Internal Server Error: service not found', 500)
SERVICE.iterate(dataset_name=dataset, new_rows=pd.DataFrame.from_dict(item))
return 'ok' |
class OptionPlotoptionsBubbleSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsBubbleSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsBubbleSonificationDefaultinstrumentoptionsMappingTremoloDepth)... |
class OptionPlotoptionsItemSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionPlotoptionsItemSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsItemSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionPlo... |
class BaseMode(ABC):
keymap: Dict[(Action, bool)] = {}
name: Mode = Mode.none
def __init__(self):
if (not len(self.keymap)):
raise NotImplementedError('Subclasses of BaseMode must have non-empty keymap')
if (self.name == Mode.none):
raise NotImplementedError("Subclass... |
def pwn3():
alloc(96)
free(4)
malloc_hook = (libc_base + libc.symbols['__malloc_hook'])
free_hook = (libc_base + libc.symbols['__free_hook'])
system_addr = (libc_base + libc.symbols['system'])
fill(2, p64(((malloc_hook - 48) + 13)))
alloc(96)
alloc(96)
fill(6, (((p8(0) * 3) + (p64(0)... |
class OptionSeriesXrangeStatesInactive(Options):
def animation(self) -> 'OptionSeriesXrangeStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesXrangeStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
se... |
()
('--sft', '-s')
('--ppo', '-p')
def main(sft, ppo):
keys = json.load(open('openai.key'))
os.environ['OPENAI_API_KEY'] = keys['OPENAI_API_KEY']
with open('prompts.csv') as fp:
reader = csv.DictReader(fp)
prompts = [row['prompt'] for row in reader]
print('Run inference')
if os.path.... |
class SMSSendPasswordResetForm(object):
def __init__(self, user, data=None):
self.user = user
def is_valid(self):
return self.user.is_active
def save(self):
password = User.objects.make_random_password(length=7)
self.user.set_password(password)
self.user.save()
... |
.parametrize('grid', [None, {'max_depth': [1, 2, 3]}, {'max_depth': [1, 2], 'estimators': [10, 12]}])
def test_assigns_param_grid(grid):
encoder = DecisionTreeEncoder(param_grid=grid)
if (grid is None):
assert (encoder._assign_param_grid() == {'max_depth': [1, 2, 3, 4]})
else:
assert (encode... |
_os(*metadata.platforms)
(TARGET_APP)
def main():
common.log('Suspicious Registry Persistence')
winreg = common.get_winreg()
for hive in (common.HKLM, common.HKCU):
common.write_reg(hive, 'Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce\\', 'RunOnceTest', TARGET_APP)
common.write_reg(h... |
def instantiateMVAR(varfont, axisLimits):
log.info('Instantiating MVAR table')
mvar = varfont['MVAR'].table
fvarAxes = varfont['fvar'].axes
varStore = mvar.VarStore
defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
with verticalMetricsKeptInSync(varfont):
setM... |
class ETHV63PeerFactory(ETHPeerFactory):
peer_class = ETHV63Peer
async def get_handshakers(self) -> Tuple[(HandshakerAPI[Any], ...)]:
return tuple((shaker for shaker in (await super().get_handshakers()) if ((shaker.protocol_class == WitnessProtocol) or (shaker.handshake_params.version == ETHProtocolV63.... |
class Mapping(Type):
def __init__(self, keys, items, _dict=Instance(dict)):
self._keys = keys
self._items = items
self._dict = _dict
def __contains__(self, value):
if (not self._dict(value)):
return False
for (key, item) in value.items():
if (key n... |
def install_github_project(project_path: str, commands: list[str]):
log_current_packages((project_path,))
folder_name = Path(project_path).name
_checkout_github_project(project_path, folder_name)
with OperateInDirectory(folder_name, remove=True):
error = None
for command in commands:
... |
.usefixtures('dummyG')
.parametrize('sort_by', ('value', None))
.parametrize('group_by', ('group', None))
def test_matrix(dummyG, group_by, sort_by):
(pos, nt) = get_pos_df(dummyG, layouts.matrix, group_by=group_by, sort_by=sort_by)
assert (pos['x'].min() == 2.0)
assert (pos['y'].min() == 0.0)
assert (p... |
class ArrayPlotData(AbstractPlotData):
arrays = Dict
writable = True
def __init__(self, *data, **kw):
super().__init__()
self._update_data(kw)
data = dict(zip(self._generate_names(len(data)), data))
self._update_data(data)
def list_data(self):
return list(self.arr... |
class set_config(message):
version = 6
type = 9
def __init__(self, xid=None, flags=None, miss_send_len=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
self.flags = 0
... |
def _scan_line_break(stream: StreamBuffer) -> str:
ch = stream.peek()
if (ch in '\r\n\x85'):
if (stream.prefix(2) == '\r\n'):
stream.forward(2)
else:
stream.forward()
return '\n'
elif (ch in '\u2028\u2029'):
stream.forward()
return ch
retur... |
class SystemScans(Base):
__tablename__ = 'plus_system_scans'
id = Column(Integer, primary_key=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
error = Column(String, nullable=True)
is_classified = Column(BOOLEAN, default=False, nullable=False)
result = Column(JSON, n... |
def test_load_schema_top_level_primitive():
'
load_schema_dir = join(abspath(dirname(__file__)), 'load_schema_test_14')
schema_path = join(load_schema_dir, 'A.avsc')
loaded_schema = fastavro.schema.load_schema(schema_path, _write_hint=False)
expected_schema = 'string'
assert (loaded_schema == ex... |
def eval(model, valid_dataloader, post_process_class, eval_class, model_type, use_srn=False):
model.eval()
with paddle.no_grad():
total_frame = 0.0
total_time = 0.0
pbar = tqdm(total=len(valid_dataloader), desc='eval model:')
max_iter = ((len(valid_dataloader) - 1) if (platform.s... |
def _loop_once():
global patch, name, path, monitor
global push, toggle1, toggle2, toggle3, toggle4, slap, model, scale_note, scale_control, offset_note, offset_control, port, mididevice_input, mididevice_output, inputport, Off, Red_Full, Amber_Full, Yellow_Full, Green_Full, ledcolor, note_list, status_list, no... |
def test_trailing_error():
assert (htmlfill.render('<input type="text" name="email">', errors={'email': 'error'}, prefix_error=False) == '<input type="text" name="email" class="error" value=""><!-- for: email -->\n<span class="error-message">error</span><br />\n')
assert (htmlfill.render('<textarea name="conten... |
class OptionSeriesScatter3dSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesScatter3dSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesScatter3dSonificationDefaultinstrumentoptionsMappingTremoloDepth)
d... |
def test_language_group(menu_btn):
langs = ['afr', 'deu', 'eng']
menu_btn.on_languages_changed(langs)
menu_btn.menu().aboutToShow.emit()
settings_group = menu_btn.findChild(QtGui.QActionGroup, 'language_group')
for action in settings_group.children():
action.trigger()
assert (menu_btn.se... |
class TypeWafExclusion(ModelSimple):
allowed_values = {('value',): {'WAF_EXCLUSION': 'waf_exclusion'}}
validations = {}
additional_properties_type = None
_nullable = False
_property
def openapi_types():
return {'value': (str,)}
_property
def discriminator():
return None
... |
def plot_subclade(ax, cfreq, clade, pivots):
if (traitName in clade.traits):
if (clade.traits[traitName] == 'V'):
cmap = mpl.cm.Reds
else:
cmap = mpl.cm.Blues
else:
cmap = mpl.cm.Purples_r
if (clade.branchType == 'node'):
if condition(clade):
... |
def test_parse_requirements_txt(tmp_path: Path) -> None:
fake_requirements_txt = 'click==8.1.3 #123asd\ncolorama==0.4.5\nimportlib-metadata==4.2.0 ; python_version >= "3.7" and python_version < "3.8"\nisort==5.10.1, <6.0\ntoml==0.10.2\ntyping-extensions\nzipp==3.8.1\nfoobar[foo, bar]\nSomeProject ~= 1.4.2\nSomeProj... |
class AsyncEventFilterBuilder(BaseEventFilterBuilder):
async def deploy(self, async_w3: 'AsyncWeb3') -> 'AsyncLogFilter':
if (not isinstance(async_w3, web3.AsyncWeb3)):
raise ValueError(f'Invalid web3 argument: got: {async_w3!r}')
for arg in AttributeDict.values(self.args):
a... |
class SnmpTagValue(TextualConvention, OctetString):
status = 'current'
displayHint = '255t'
subtypeSpec = OctetString.subtypeSpec
subtypeSpec += ConstraintsUnion(ValueSizeConstraint(0, 255))
if mibBuilder.loadTexts:
description = "An octet string containing a tag value. Tag values are prefer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.