code stringlengths 281 23.7M |
|---|
def run_harness_generation(view, func: Function) -> None:
log.log_debug('Grabbing closed-source template from project folder')
template_file = os.path.join(binaryninja.user_plugin_path(), 'fuzzable/templates/linux_closed_source_harness.cpp')
path = view.file.filename
binary = lief.parse(path)
symbol... |
def extractLbDiaryBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return False
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, ... |
def blur2d_compute_root(n: size, consumer: i8[(n, n)], sin: i8[((n + 1), (n + 1))]):
assert ((n % 4) == 0)
producer: i8[((n + 1), (n + 1))]
for i in seq(0, (n + 1)):
for j in seq(0, (n + 1)):
producer[(i, j)] = sin[(i, j)]
for i in seq(0, n):
for j in seq(0, n):
c... |
class SaveImageAction(Action):
def __init__(self, window):
self._window = window
self.name = 'S&ave Scene'
def perform(self):
extensions = ['*.png', '*.jpg', '*.tiff', '*.bmp', '*.ps', '*.eps', '*.pdf', '*.tex', '*.rib', '*.wrl', '*.oogl', '*.vrml', '*.obj', '*.iv', '*.pov', '*.x3d']
... |
class GetBlockHeadersRequest(BaseRequestResponseEvent[GetBlockHeadersResponse]):
session: SessionAPI
block_number_or_hash: BlockIdentifier
max_headers: int
skip: int
reverse: bool
timeout: float
def expected_response_type() -> Type[GetBlockHeadersResponse]:
return GetBlockHeadersResp... |
(version_base=None, config_path='conf', config_name='config')
def main(cfg: DictConfig) -> None:
ray.init(**cfg.ray.init)
results = []
for model in ['alexnet', 'resnet']:
for dataset in ['cifar10', 'imagenet']:
overrides = [f'dataset={dataset}', f'model={model}']
run_cfg = hy... |
class JzCzhz(LCh):
BASE = 'jzazbz'
NAME = 'jzczhz'
SERIALIZE = ('--jzczhz',)
WHITE = WHITES['2deg']['D65']
DYNAMIC_RANGE = 'hdr'
CHANNEL_ALIASES = {'lightness': 'jz', 'chroma': 'cz', 'hue': 'hz'}
ACHROMATIC = Jzazbz.ACHROMATIC
CHANNELS = (Channel('jz', 0.0, 1.0, limit=(0.0, None)), Chann... |
class Chip(Component):
css_classes = ['mdc-chip-set']
name = 'Material Design Chip'
str_repr = '\n<span {attrs} role="grid">\n <span class="mdc-evolution-chip-set__chips" role="presentation">\n <span class="mdc-evolution-chip" role="row" id="c0">\n <span class="mdc-evolution-chip__cell mdc-evolutio... |
class PythonWheelBuilder(BuilderBase):
dist_info_dir: str
template_format_dict: Dict[(str, str)]
def _build(self, install_dirs: List[str], reconfigure: bool) -> None:
wheel_name = self._parse_wheel_name()
name_version_prefix = '-'.join((wheel_name.distribution, wheel_name.version))
d... |
def get_size(data: bytes):
size = len(data)
if ((size >= 10) and (data[:6] in (b'GIF87a', b'GIF89a'))):
(w, h) = struct.unpack('<HH', data[6:10])
return (int(w), int(h))
if ((size >= 24) and data.startswith(b'\x89PNG\r\n\x1a\n') and (data[12:16] == b'IHDR')):
(w, h) = struct.unpack('... |
class OptionPlotoptionsLollipopSonificationTracksActivewhen(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):
... |
class InputFile(Input):
name = 'InputFile'
_option_cls = OptInputs.OptionsInputFile
def __init__(self, page: primitives.PageModel, text, placeholder, width, height, html_code, options, attrs, profile):
super(InputFile, self).__init__(page, text, placeholder, width, height, html_code, options, attrs,... |
.parametrize('vm_class, val1, val2, expected', ((ConstantinopleVM, '0x', '0x00', '0x'), (ConstantinopleVM, '0x', '0x01', '0x'), (ConstantinopleVM, '0x', '0xff', '0x'), (ConstantinopleVM, '0x', '0x0100', '0x'), (ConstantinopleVM, '0x', '0x0101', '0x'), (ConstantinopleVM, '0xffffffffffffffffffffffffffffffffffffffffffffff... |
def main():
run('rm', '-rf', 'build/', 'dist/', '*.egg-info', '.eggs')
run('python', 'setup.py', 'sdist', 'bdist_wheel')
for dist in os.listdir(os.path.join(base_dir, 'dist')):
test_dist(os.path.join(base_dir, 'dist', dist))
print('\n\n\n\n * Releases are ready! *\n\n$ python -m twine upload ... |
def create_sensitivity():
records = [{'doctype': 'Sensitivity', 'sensitivity': _('Low Sensitivity')}, {'doctype': 'Sensitivity', 'sensitivity': _('High Sensitivity')}, {'doctype': 'Sensitivity', 'sensitivity': _('Moderate Sensitivity')}, {'doctype': 'Sensitivity', 'sensitivity': _('Susceptible')}, {'doctype': 'Sens... |
class OptionPlotoptionsXrangeDatalabels(Options):
def align(self):
return self._config_get('undefined')
def align(self, text: str):
self._config(text, js_type=False)
def allowOverlap(self):
return self._config_get(False)
def allowOverlap(self, flag: bool):
self._config(fl... |
class MullerBrownPot(Calculator):
def __init__(self):
super(MullerBrownPot, self).__init__()
def get_energy(self, atoms, coords):
(x, y, z) = coords
A = ((- 200), (- 100), (- 170), 15)
x0 = (1.0, 0.0, (- 0.5), (- 1.0))
y0 = (0.0, 0.5, 1.5, 1.0)
a = ((- 1.0), (- 1.... |
def _get_sub_func_metadata(ops: List[Operator], data_t: str, op_t: str, backend_spec: BackendSpec, float32_t: str) -> Tuple[(List[ElementwiseMetaData], str)]:
use_fp32_acc = Target.current()._kwargs.get('elementwise_use_fp32_acc', False)
if use_fp32_acc:
op_t = data_t
candidate_op_types = [float... |
class Solution():
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def find_vals(node, x, y, lvl, pos1, pos2):
if (node.left is not None):
if (node.left.val == x):
pos1[0] = (lvl + 1)
pos1[1] = node
if (node.left... |
class BaseIsolatedComponent(BaseComponent):
endpoint_name: str = None
loop_monitoring_wakeup_interval = 2
loop_monitoring_max_delay_debug = 0.1
loop_monitoring_max_delay_warning = 1
async def run_in_process(self) -> None:
...
async def _do_run(self) -> None:
...
def get_subpr... |
class SusAcc(BasicAuthWithTopicTestCase):
def setUp(self):
BasicAuthWithTopicTestCase.setUp(self)
topic = models.Topic.objects.create(name='#')
self.acc_allow = False
self.acc = models.PROTO_MQTT_ACC_SUS
models.ACL.objects.create(acc=models.PROTO_MQTT_ACC_PUB, topic=topic)
... |
()
('dockerfile')
('--show-tag-only/--no-show-tag-only', help='skip build, only print out image tag name', default=False)
_log.simple_verbosity_option(logger)
def build(dockerfile, show_tag_only):
image_tag = assert_image_tag_from_dockerfile(logger, dockerfile)
if show_tag_only:
print(image_tag)
... |
class GEMMBiasReluTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(GEMMBiasReluTestCase, self).__init__(*args, **kwargs)
self._test_id = 0
def _test_gemm_rcr_bias_relu(self, M=128, K=1024, N=64, dtype='float16', test_suffix=None):
X = Tensor(shape=[M, K], dtype=dty... |
class KiwoomOpenApiPlusDialogToHandle(DialogToHandle, Logging):
def should_handle_by_title(cls, dialog: WindowSpecification, title: str):
try:
cls.logger.debug('Checking dialog title')
dialog_text = dialog.wrapper_object().window_text()
except ElementNotFoundError:
... |
class EventManager(models.Manager):
def get_queryset(self):
today = timezone.localdate()
return super().get_queryset().annotate(attendees_count=models.Count('attendee', distinct=True)).annotate(last_date=models.Max('eventdate__date')).annotate(activity_proposal_is_open=models.Case(models.When(models... |
def test_simple_with_ignore() -> None:
dependencies = [Dependency('click', Path('pyproject.toml')), Dependency('toml', Path('pyproject.toml'))]
modules_locations = [ModuleLocations(ModuleBuilder('toml', {'foo'}, frozenset(), dependencies).build(), [Location(Path('foo.py'), 1, 2)])]
assert (DEP002UnusedDepen... |
_defaults()
class CustomFormOptionSchema(SoftDeletionSchema):
class Meta():
type_ = 'custom-form-option'
self_view = 'v1.custom_form_option_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Integer(dump_only=True)
value = fields.Str(required=True)
... |
class LocalServer(object):
_queue = None
def run(self, classobjects):
result = windll.ole32.CoInitialize(None)
if (RPC_E_CHANGED_MODE == result):
_debug('Server running in MTA')
self.run_mta()
else:
_debug('Server running in STA')
if (resul... |
class LPopup():
def __init__(self, latlng=None, options: dict=None, selector=None):
self._selector = selector
(self._js, self.__is_attached) = ([], False)
self.varId = ('L.marker(%s)' % latlng)
def openPopup(self, latlng=None):
if (latlng is not None):
self.setLatLng(... |
def delete_atoms_bonds_inplace(as_dict: dict, inds: list[int], atom_offset: int=0, bond_offset: int=0) -> dict[(int, int)]:
to_del = set(inds)
axs = as_dict['atoms_xyzs']
axs_mod = list()
atoms_del = 0
atom_map = {}
for ax in axs:
if (ax['atom_id'] in to_del):
warnings.warn('... |
def deploy_archived_service(service_name):
response = get_session().post((base_url + 'service-archives/{}'.format(service_name)))
if (response.status_code != 200):
if (response.status_code == 400):
_check_for_manifest_errors(response)
raise get_exception(response)
else:
r... |
class EnergyCharging(object):
swagger_types = {'charging_mode': 'str', 'charging_rate': 'int', 'next_delayed_time': 'str', 'plugged': 'bool', 'remaining_time': 'str', 'status': 'ChargingStatusEnum'}
attribute_map = {'charging_mode': 'chargingMode', 'charging_rate': 'chargingRate', 'next_delayed_time': 'nextDela... |
class WebSocketManager(object):
def __init__(self):
self._connections = []
def add_connection(self, ws):
self._connections.append(ws)
def delete_connection(self, ws):
self._connections.remove(ws)
def broadcast(self, msg):
for connection in self._connections:
c... |
def main(path):
import sys
import pytest
args = ['-p', 'no:parallel', '-E', 'release']
if ((len(sys.argv) > 1) and (sys.argv[1] == '--no-debug')):
args += ['-o', 'log_cli=False']
else:
logging.basicConfig(level=logging.DEBUG)
args += ['-o', 'log_cli=True']
args += [path]
... |
class PrimaryKeyGeneratorBase():
def __init__(self, primary_key: Type[PrimaryKeyBase], query_classes: Set[Type[object]], allowed_id_range: Optional[range]=None) -> None:
self.primary_key = primary_key
self.query_classes = query_classes
self.pks: Dict[(str, Tuple[(int, int)])] = {}
if... |
class Controller(controller.ControllerProto):
CONTROLLER_ID = 14
CONTROLLER_NAME = 'Generic MQTT'
def __init__(self, controllerindex):
controller.ControllerProto.__init__(self, controllerindex)
self.usesID = False
self.usesAccount = True
self.usesPassword = True
self.... |
class TestOFPActionSetNwSrc(unittest.TestCase):
type_ = {'buf': b'\x00\x06', 'val': ofproto.OFPAT_SET_NW_SRC}
len_ = {'buf': b'\x00\x08', 'val': ofproto.OFP_ACTION_NW_ADDR_SIZE}
nw_addr = {'buf': b'\xc0\xa8z\n', 'val': }
buf = ((type_['buf'] + len_['buf']) + nw_addr['buf'])
c = OFPActionSetNwSrc(nw_... |
def convert_keys_to_camel_case(data: dict[(str, _typing.Any)]) -> dict[(str, _typing.Any)]:
def snake_to_camel(word: str) -> str:
components = word.split('_')
return (components[0] + ''.join((x.capitalize() for x in components[1:])))
return {snake_to_camel(key): value for (key, value) in data.it... |
class GradientBoostingClassifier(GradientBoosting):
def __init__(self, n_estimators=200, learning_rate=0.5, min_samples_split=2, min_info_gain=1e-07, max_depth=2, debug=False):
super(GradientBoostingClassifier, self).__init__(n_estimators=n_estimators, learning_rate=learning_rate, min_samples_split=min_samp... |
class OptionSeriesSplineSonificationDefaultinstrumentoptionsMapping(Options):
def frequency(self) -> 'OptionSeriesSplineSonificationDefaultinstrumentoptionsMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesSplineSonificationDefaultinstrumentoptionsMappingFrequency)
def gapBetweenN... |
class AbstractExpert(metaclass=abc.ABCMeta):
def __init__(self, blackboard: Blackboard) -> None:
self.blackboard = blackboard
def is_eager_to_contribute(self):
raise NotImplementedError('Must provide implementation in subclass.')
def contribute(self):
raise NotImplementedError('Must ... |
class TorchActorCritic(TorchModel):
def __init__(self, policy: TorchPolicy, critic: Union[(TorchStateCritic, TorchStateActionCritic)], device: str):
assert ((critic is not None) and isinstance(critic, (TorchStateCritic, TorchStateActionCritic))), 'Make sure to provide an appropriate critic when training wit... |
def _firestore_endpoint_handler(func: (_C1 | _C2), event_type: str, document_pattern: _path_pattern.PathPattern, raw: _ce.CloudEvent) -> None:
event_attributes = raw._get_attributes()
event_data: _typing.Any = raw.get_data()
firestore_event_data: _firestore.DocumentEventData
content_type: str = event_at... |
class OpenAIEmbedder(BaseEmbedder):
def __init__(self, config: Optional[BaseEmbedderConfig]=None):
super().__init__(config=config)
if (self.config.model is None):
self.config.model = 'text-embedding-ada-002'
api_key = (self.config.api_key or os.environ['OPENAI_API_KEY'])
... |
_blueprint.route('/project/<project_id>/delete', methods=['GET', 'POST'])
_required
def delete_project(project_id):
project = models.Project.get(Session, project_id)
if (not project):
flask.abort(404)
if (not is_admin()):
flask.abort(401)
project_name = project.name
form = anitya.for... |
def arm_epilogue(blk):
if (len(blk.bap.stmts) > 1):
last_stmt = blk.bap.stmts[(- 1)]
if (isinstance(last_stmt, JmpStmt) and isinstance(last_stmt.kind, RetKind)):
stmt = blk.bap.stmts[(- 2)]
if (isinstance(stmt.lhs, RegVar) and (stmt.lhs.name == 'SP') and isinstance(stmt.rhs, ... |
def main():
segmk = Segmaker('design.bits')
tiledata = {}
pipdata = {}
ignpip = set()
tile_ports = {}
read_pip_data('pcie_int_interface_l.txt', pipdata, tile_ports)
read_pip_data('pcie_int_interface_r.txt', pipdata, tile_ports)
print('Loading tags from design.txt.')
with open('design... |
class TestIssuesV3(TestCase):
def test_auto_multi_int_1(self):
class Measurement(int, AddValueEnum, MultiValueEnum, start=0):
one = ''
two = ''
three = ''
self.assertEqual([m.value for m in Measurement], [0, 1, 2])
self.assertEqual([m.name for m in Measure... |
class PcapPktHdr(object):
_PKT_HDR_FMT = 'IIII'
_PKT_HDR_FMT_BIG_ENDIAN = ('>' + _PKT_HDR_FMT)
_PKT_HDR_FMT_LITTLE_ENDIAN = ('<' + _PKT_HDR_FMT)
PKT_HDR_SIZE = struct.calcsize(_PKT_HDR_FMT)
def __init__(self, ts_sec=0, ts_usec=0, incl_len=0, orig_len=0):
self.ts_sec = ts_sec
self.ts_... |
class JsHtmlNumeric(JsHtmlRich):
def to(self, number: float, timer: int=1, profile: types.PROFILE_TYPE=None):
return JsUtils.jsConvertFncs([self.page.js.objects.number(self.content.unformat(), js_code=('%s_counter' % self.htmlCode), set_var=True), self.page.js.window.setInterval([self.page.js.if_((self.page... |
class IsolateController(object):
def Run(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None):
return grpc.experimental.unary_stream(request, target, '/controller.IsolateController/Run', controller__... |
def _api_remote(path, method='GET'):
def decorator(func):
async def wrapper(self, *args, **kwargs):
import
(return_type, actual_dataclass, request_params) = _build_request(self, func, path, method, *args, **kwargs)
async with as client:
response = (await... |
class Chorolet(GraphPlotly.Chart):
requirements = ('plotly.js',)
__reqJs = ['plotly.js']
def chart(self) -> JsPlotly.Pie:
if (self._chart is None):
self._chart = JsPlotly.Pie(page=self.page, js_code=self.js_code, component=self)
return self._chart
def layout(self) -> LayoutGe... |
class Tags(JsHtml.JsHtmlRich):
def content(self):
return JsHtml.ContentFormatters(self.page, ("\n(function(dom){var content = {}; \n dom.childNodes.forEach(function(rec){\n var label = rec.getAttribute('data-category');\n if(!(label in content) && (label != null)){ content[label] = [] }; \n ... |
()
('--model-path', default='RealESRGAN_x4plus.safetensors', help='model path. supports torch or safetensors')
('--width', default=(64, 1024), type=(int, int), nargs=2, help='Minimum and maximum width')
('--height', default=(64, 1024), type=(int, int), nargs=2, help='Minimum and maximum height')
('--batch-size', defaul... |
class StaticAnalysisPatternProvider(PatternProvider):
__patterns = {}
def get(cls, *args) -> List[AbstractPattern]:
patterns = cls.__list_static_patterns()
patterns = list(map(cls.__build_pattern, patterns))
return patterns
def __list_static_patterns(cls):
patterns = static_a... |
class ShadowIGUserCatalogProductVariant(AbstractObject):
def __init__(self, api=None):
super(ShadowIGUserCatalogProductVariant, self).__init__()
self._isShadowIGUserCatalogProductVariant = True
self._api = api
class Field(AbstractObject.Field):
product_id = 'product_id'
v... |
def cookies_check(cookies, url, method, req_headers, req_body, scan_id, res_headers, res_body):
for cookie in cookies:
if ((not cookie.secure) or (not cookie.has_nonstandard_attr('HttpOnly'))):
attack_result = {'id': 22, 'scanid': scan_id, 'url': url, 'alert': 'Cookie not marked secure or 'impa... |
def test_shuffle_seeds() -> None:
perform_rollout_seeding_test({'seeding.env_base_seed': '1234', 'seeding.agent_base_seed': '1234', 'seeding.shuffle_seeds': 'true'}, {'seeding.env_base_seed': '1234', 'seeding.agent_base_seed': '1234', 'seeding.shuffle_seeds': 'true'})
perform_rollout_seeding_test({'seeding.env_... |
class PipelineBrowser(HasTraits):
tree_generator = Trait(FullTreeGenerator(), Instance(TreeGenerator))
renwins = List
root_object = List(TVTKBase)
selected = Instance(TVTKBase)
object_edited = Event
_root = Any
_ui = Any
def __init__(self, renwin=None, **traits):
super(PipelineBr... |
class HStoreField(DictField):
child = CharField(allow_blank=True, allow_null=True)
def __init__(self, **kwargs):
super().__init__(**kwargs)
assert isinstance(self.child, CharField), 'The `child` argument must be an instance of `CharField`, as the hstore extension stores values as strings.' |
class BaseInference(metaclass=ABCMeta):
_MAX_SEED_VAL: int = ((2 ** 32) - 1)
def get_proposers(self, world: World, target_rvs: Set[RVIdentifier], num_adaptive_sample: int) -> List[BaseProposer]:
raise NotImplementedError
def _get_default_num_adaptive_samples(self, num_samples: int) -> int:
r... |
class CopyPayloadTestCase(unittest.TestCase):
def payload_setup(self, **payload_kwargs):
payload = CopyPayload(**payload_kwargs)
table_obj = parse_create(' CREATE TABLE a ( ID int primary key ) ')
payload._old_table = table_obj
payload._new_table = table_obj
payload._current_... |
class ValveTestOrderedBidirectionalTunnelACLwithExitInstructions(ValveTestBases.ValveTestTunnel):
TUNNEL_ID = 2
CONFIG = "\nacls:\n tunnel_acl:\n - rule:\n in_port: 1\n dl_type: 0x0800\n ip_proto: 1\n actions:\n output:\n - ... |
def test_mft_precomputations():
input_grid = make_pupil_grid(128)
output_grid = make_fft_grid(input_grid, 1, 0.25)
for precompute_matrices in [True, False]:
for allocate_intermediate in [True, False]:
mft = MatrixFourierTransform(input_grid, output_grid, precompute_matrices=precompute_ma... |
class String_Literal(Literal):
def __init__(self, t_string):
super().__init__()
assert isinstance(t_string, MATLAB_Token)
assert (t_string.kind == 'STRING')
self.t_string = t_string
self.t_string.set_ast(self)
def __str__(self):
return (('"' + self.t_string.value)... |
class TrainingJob(_common.FlyteIdlEntity):
def __init__(self, algorithm_specification: AlgorithmSpecification, training_job_resource_config: TrainingJobResourceConfig):
self._algorithm_specification = algorithm_specification
self._training_job_resource_config = training_job_resource_config
def a... |
.skipif((zopfli is None), reason='zopfli not installed')
def test_ttcompile_ttf_to_woff_with_zopfli(tmpdir):
inttx = os.path.join('Tests', 'ttx', 'data', 'TestTTF.ttx')
outwoff = tmpdir.join('TestTTF.woff')
options = ttx.Options([], 1)
options.flavor = 'woff'
options.useZopfli = True
ttx.ttCompi... |
class OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMappingPan(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: ... |
class StartWorkflowExecutionRequest():
domain: str = None
workflow_id: str = None
workflow_type: WorkflowType = None
task_list: TaskList = None
input: bytes = None
execution_start_to_close_timeout_seconds: int = None
task_start_to_close_timeout_seconds: int = None
identity: str = None
... |
class XiAiNovelPageProcessor(HtmlProcessor.HtmlPageProcessor):
wanted_mimetypes = ['text/html']
want_priority = 80
loggerPath = 'Main.Text.XiAiNovel'
def spotPatch(self, soup):
for pre in soup.find_all('pre'):
pre.name = 'div'
contentstr = pre.encode_contents().decode('ut... |
def test_mul_param(some_thr, any_dtype):
input = get_test_array((1000,), any_dtype)
p1 = get_test_array((1,), any_dtype)[0]
p2 = get_test_array((1,), any_dtype)[0]
input_dev = some_thr.to_device(input)
output_dev = some_thr.empty_like(input_dev)
test = get_test_computation(input_dev)
scale =... |
class ColourHandler(logging.Handler):
def __init__(self, level=logging.DEBUG):
logging.Handler.__init__(self, level)
self.formatter = logging.Formatter(('\r%(name)s%(padding)s - %(style)s%(levelname)s - %(message)s' + clr.Style.RESET_ALL))
clr.init()
self.logPaths = {}
def emit(s... |
def test_download_file(isolated_client, mock_fal_persistent_dirs):
from fal.toolkit.utils.download_utils import FAL_PERSISTENT_DIR
EXAMPLE_FILE_URL = '
relative_directory = 'test'
output_directory = (FAL_PERSISTENT_DIR / relative_directory)
expected_path = (output_directory / 'README.md')
_clien... |
def extractSapphicdallianceWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('My Disciple Consumes Too Much', 'My Disciple Consumes Too Much', 'translated'), ('PRC', ... |
class TestFem(unittest.TestCase):
def setUp(self):
n_el = 16
self.n_el = n_el
self.mesh_obj = mesh.create(self.n_el, h0=0.1)
self.anomaly = {'center': [0.5, 0.5], 'r': 0.1, 'perm': 10.0, 'sign': True}
anomaly = PyEITAnomaly_Circle(center=self.anomaly['center'], r=self.anomaly... |
class OptionSeriesSankeySonificationPointgrouping(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):
self._confi... |
('cuda.ndhwc3to8.gen_function')
def gen_function(func_attrs, template_path, shape_eval_template, shape_save_template):
func_name = func_attrs['name']
backend_spec = CUDASpec()
elem_input_type = backend_spec.dtype_to_backend_type(func_attrs['inputs'][0]._attrs['dtype'])
shape_eval_func = shape_eval_templ... |
class Display():
def __init__(self):
self.W = 960
self.H = 540
def display_points2d(self, img, kpts, matches):
if (kpts != 0):
for kpt in kpts:
cv2.circle(img, (int(kpt.pt[0]), int(kpt.pt[1])), radius=2, color=(0, 255, 0), thickness=(- 1))
if (matches ... |
def test_empty_doc():
nlp = English.from_config(load_config_from_str(CONFIG))
train_examples = []
for t in TRAIN_DATA:
train_examples.append(Example.from_dict(nlp.make_doc(t[0]), t[1]))
optimizer = nlp.initialize(get_examples=(lambda : train_examples))
for i in range(2):
losses = {}
... |
class NewTopic(MethodView):
decorators = [login_required, allows.requires(CanAccessForum(), CanPostTopic, on_fail=FlashAndRedirect(message=_('You are not allowed to post a topic here'), level='warning', endpoint=(lambda *a, **k: current_forum.url)))]
def get(self, forum_id, slug=None):
forum_instance = ... |
def _convert_resources_to_resource_entries(resources: Resources) -> List[_ResourceEntry]:
resource_entries = []
if (resources.cpu is not None):
resource_entries.append(_ResourceEntry(name=_ResourceName.CPU, value=resources.cpu))
if (resources.mem is not None):
resource_entries.append(_Resour... |
class EmbedderFactory():
provider_to_class = {'azure_openai': 'embedchain.embedder.openai.OpenAIEmbedder', 'gpt4all': 'embedchain.embedder.gpt4all.GPT4AllEmbedder', 'huggingface': 'embedchain.embedder.huggingface.HuggingFaceEmbedder', 'openai': 'embedchain.embedder.openai.OpenAIEmbedder', 'vertexai': 'embedchain.em... |
def transform_class_name(name):
new_name = transform_name(name)
res = []
for c in new_name:
if ((c in string.ascii_uppercase) and (len(res) > 0)):
res.append('-')
res.append(c.lower())
else:
res.append(c.lower())
return ''.join(res) |
def setup_cache_dirs():
config = get_config()
if ('PYOP2_CACHE_DIR' not in os.environ):
os.environ['PYOP2_CACHE_DIR'] = os.path.join(config['options']['cache_dir'], 'pyop2')
if ('FIREDRAKE_TSFC_KERNEL_CACHE_DIR' not in os.environ):
os.environ['FIREDRAKE_TSFC_KERNEL_CACHE_DIR'] = os.path.join... |
class LLMOperator(BaseLLM, MapOperator[(ModelRequest, ModelOutput)], ABC):
def __init__(self, llm_client: Optional[LLMClient]=None, **kwargs):
super().__init__(llm_client=llm_client)
MapOperator.__init__(self, **kwargs)
async def map(self, request: ModelRequest) -> ModelOutput:
(await se... |
def unify(x):
if isinstance(x, (tuple, list)):
x = ''.join(x)
if ((x[0] in '\'"') and (x[0] == x[(- 1)]) and (x.count(x[0]) == 2)):
return x
elif re.match('^[\\.\\w]*$', x, re.UNICODE):
return x
elif (re.match('^[\\.\\w]*\\(.*\\)$', x, re.UNICODE) and (x.count(')') == 1)):
... |
def test():
assert (len(pattern1) == 2), 'pattern1'
assert (len(pattern2) == 3), 'pattern2'
assert (len(pattern1[0]) == 1), 'pattern1'
assert any(((pattern1[0].get(attr) == 'ADJ') for attr in ('pos', 'POS'))), 'pattern1'
assert (len(pattern1[1]) == 1), 'pattern1'
assert any(((pattern1[1].get(att... |
class group_stats_reply(stats_reply):
version = 2
type = 19
stats_type = 6
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
... |
def test_custom_configs_are_loaded(app):
settings = Settings(SIMPLELOGIN_BLUEPRINT='custom_blueprint', SIMPLELOGIN_LOGIN_URL='/custom_login/', SIMPLELOGIN_LOGOUT_URL='/custom_logout/', SIMPLELOGIN_HOME_URL='/custom_home/')
sl = create_simple_login(settings)
assert (sl.config['blueprint'] == 'custom_blueprin... |
class StatisticalMiddleware(MiddlewareMixin):
def process_request(self, request):
ip = get_ip(request)
online_ips = list(cache.get('online_ips', []))
if online_ips:
online_ips = list(cache.get_many(online_ips).keys())
cache.set(ip, 0, 10)
if (ip not in online_ips)... |
class RandomIP(object):
def _generateip(self, string):
notvalid = [10, 127, 169, 172, 192]
first = randrange(1, 256)
while (first is notvalid):
first = randrange(1, 256)
_ip = '.'.join([str(first), str(randrange(1, 256)), str(randrange(1, 256)), str(randrange(1, 256))])
... |
class MWidget(HasTraits):
tooltip = Str()
context_menu = Instance('pyface.action.menu_manager.MenuManager')
def create(self, parent=None):
if (parent is not None):
self.parent = parent
self.control = self._create_control(self.parent)
self._initialize_control()
sel... |
.skipif((sys.version_info < (3, 5)), reason='requires python3.5 or higher due to incompatible pickle file in tests.')
def test_read_results_xarray():
(inputs, results) = ds.get_sim_results(path=SIM_DIR, return_xarray=True, return_status=False)
assert isinstance(inputs, xr.Dataset)
assert isinstance(results,... |
class LexerTest(unittest.TestCase):
def __init__(self, methodName):
unittest.TestCase.__init__(self, methodName)
if (not hasattr(self, 'assertRaisesRegex')):
self.assertRaisesRegex = self.assertRaisesRegexp
def test_empty(self):
self.assertEqual(lex(''), [])
self.asse... |
def test_variance_2_correlated_groups(df_test):
(X, y) = df_test
transformer = SmartCorrelatedSelection(variables=None, method='pearson', threshold=0.8, missing_values='raise', selection_method='variance', estimator=None)
Xt = transformer.fit_transform(X, y)
df = X[['var_1', 'var_2', 'var_3', 'var_5', '... |
class Event(object):
swagger_types = {'created_at': 'datetime', 'embedded': 'object', 'links': 'EventLinks', 'event_id': 'str', 'id': 'str', 'type': 'str'}
attribute_map = {'created_at': 'createdAt', 'embedded': '_embedded', 'links': '_links', 'event_id': 'eventId', 'id': 'id', 'type': 'type'}
def __init__(... |
def format_sentence(text: str) -> str:
text = re.sub('(?<!\\w)[\'\\"](.*?)[\'\\"](?!\\w)', '\\1', text)
text = text.replace('\n', '').replace('\t', '')
text = re.sub('^[^a-zA-Z]*', '', text)
text = re.sub("\\s*([)'.!,?;:])(?!\\.\\s*\\w)", '\\1', text)
text = re.sub('(\\()\\s*', '\\1', text)
text... |
(name='api.mon.base.tasks.mon_hostgroup_create', base=MgmtTask)
_task(log_exception=True)
def mon_hostgroup_create(task_id, dc_id, hostgroup_name, dc_bound=True, **kwargs):
dc = Dc.objects.get_by_id(int(dc_id))
mon = get_monitoring(dc)
try:
result = mon.hostgroup_create(hostgroup_name, dc_bound=dc_b... |
def _build_usas_data_for_spark():
baker.make('recipient.RecipientLookup', recipient_hash='53aea6c7-bbda-4e4b-1ebe-bbf', uei='FABSUEI12345', duns='FABSDUNS12345', legal_business_name='FABS TEST RECIPIENT', parent_uei='PARENTUEI12345', _fill_optional=True)
baker.make('recipient.RecipientLookup', uei='PARENTUEI123... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.