code stringlengths 281 23.7M |
|---|
def get_fiscal_quarter(fiscal_reporting_period):
if (fiscal_reporting_period in [1, 2, 3]):
return 1
elif (fiscal_reporting_period in [4, 5, 6]):
return 2
elif (fiscal_reporting_period in [7, 8, 9]):
return 3
elif (fiscal_reporting_period in [10, 11, 12]):
return 4 |
class no_ns_response(bsn_tlv):
type = 148
def __init__(self):
return
def pack(self):
packed = []
packed.append(struct.pack('!H', self.type))
packed.append(struct.pack('!H', 0))
length = sum([len(x) for x in packed])
packed[1] = struct.pack('!H', length)
... |
class LinkButton(SphinxDirective):
has_content = False
required_arguments = 1
final_argument_whitespace = True
option_spec = {'type': (lambda arg: directives.choice(arg, ('url', 'ref'))), 'text': directives.unchanged, 'tooltip': directives.unchanged, 'classes': directives.unchanged}
def run(self):
... |
def perform_masked_global_pooling_test_dim2_pool_1(feature_dim_1: int, feature_dim_2: int, use_masking: bool, pooling_func_name: str):
batch_dim = 4
in_dict = build_multi_input_dict(dims=[[batch_dim, feature_dim_1, feature_dim_2], [batch_dim, feature_dim_1]])
net: MaskedGlobalPoolingBlock = MaskedGlobalPool... |
class TestVerifyRunAgainstCasavaSampleSheet(unittest.TestCase):
def setUp(self):
self.top_dir = tempfile.mkdtemp()
self.mock_illumina_data = MockIlluminaData('test.MockIlluminaData', 'casava', paired_end=True, top_dir=self.top_dir)
self.mock_illumina_data.add_fastq_batch('AB', 'AB1', 'AB1_GC... |
def get_widget_content(handle, params):
log.debug('getWigetContent Called: {0}', params)
settings = xbmcaddon.Addon()
hide_watched = (settings.getSetting('hide_watched') == 'true')
widget_type = params.get('type')
if (widget_type is None):
log.error('getWigetContent type not set')
re... |
class GetBlockHeadersTracker(BaseGetBlockHeadersTracker):
def _get_request_size(self, request: GetBlockHeaders) -> Optional[int]:
payload = request.payload.query
if isinstance(payload.block_number_or_hash, int):
return len(sequence_builder(start_number=payload.block_number_or_hash, max_l... |
class Uninstall(CommandBase):
def __init__(self):
super().__init__()
self.name = 'uninstall'
self.description = ' Uninstalls emu'
def _uninstall():
print('Are you sure you want to uninstall emu?')
if (input_with_options(['Y', 'n'], 'n')[0] == 0):
run(['sh', UN... |
class UnicodeMap(CMapBase):
def __init__(self, **kwargs):
CMapBase.__init__(self, **kwargs)
self.cid2unichr = {}
return
def __repr__(self):
return ('<UnicodeMap: %s>' % self.attrs.get('CMapName'))
def get_unichr(self, cid):
if self.debug:
logging.debug(('g... |
class JsItemsDef():
def __init__(self, component: primitives.HtmlModel):
self.component = component
def _item(self, item_def):
return ('%(item_def)s; htmlObj.appendChild(item)' % {'item_def': item_def})
def text(self, page: primitives.PageModel):
item_def = '\nvar item = document.cre... |
def tabbify(code):
lines = []
for line in code.splitlines():
line2 = line.lstrip(' \t')
indent_str = line[:(len(line) - len(line2))]
for (s1, s2) in [(' ', '\t'), (' ', '\t'), (' ', '')]:
indent_str = indent_str.replace(s1, s2)
lines.append((indent_str + line2))
... |
def __create_tray_context_menu():
sep = menu.simple_separator
items = []
items.append(playback.PlayPauseMenuItem('playback-playpause', player.PLAYER, after=[]))
items.append(playback.NextMenuItem('playback-next', player.PLAYER, after=[items[(- 1)].name]))
items.append(playback.PrevMenuItem('playback... |
class ChefLaunchd(Processor):
description = 'Produces a cookbook_file Chef block. See
input_variables = {'resource_name': {'required': True, 'description': 'Name for the resource. This can be a single string or an array of strings. If an array is provided, the first item in the array will be the resource name ... |
def main():
struct_env = struct_env_factory(max_pieces_in_inventory=200, raw_piece_size=(100, 100), static_demand=[(30, 15)])
obs_step1 = struct_env.reset()
print('action_space 1: ', struct_env.action_space)
print('observation_space 1:', struct_env.observation_space)
print('observation 1: '... |
def _parse_server_response(json_data):
return Definition(ip=json_data['ip'], lease_time=json_data['lease_time'], subnet=json_data['subnet'], serial=json_data['serial'], hostname=json_data.get('hostname'), gateways=json_data.get('gateway'), subnet_mask=json_data.get('subnet_mask'), broadcast_address=json_data.get('b... |
def tt():
print(' ! ! \n ! ! ! ! \n ! . ! ! . ! \n ^ \n ^ ^ \n ^ (0) (0) ^ \n ^ ^ \n ... |
def gen_int_var_product_str(int_vars: List[IntVar]) -> str:
res = []
for int_var in int_vars:
if isinstance(int_var, IntImm):
res.append(str(int_var._attrs['values'][0]))
elif isinstance(int_var, IntVar):
res.append(int_var._attrs['name'])
else:
raise ... |
def createTempJobTemplate(dut, jobname):
dst_file = 'tmp.fio'
shutil.copyfile(jobname, dst_file)
with open(dst_file, 'a') as tmp_file:
try:
tmp_file.write(dut.dev_list)
except IOError:
print(('cannot write to %s' % tmp_file))
sys.exit(1)
return dst_fil... |
def interpolate_polynomial_without_zeroes(root_of_unity, samples):
precomputable_zero_sample_blocks = 1
while all(((x == None) for x in samples[((- precomputable_zero_sample_blocks) * PREPARED_ZERO_POLYNOMIAL_INTERVAL):])):
precomputable_zero_sample_blocks += 1
precomputable_zero_sample_blocks -= 1
... |
class writer(object):
__buff_queue = None
__size = 0
__lifo = None
def __init__(self):
self.__buff_queue = []
self.__lifo = []
self.__size = 0
def is_empty(self):
if (self.__size < 1):
return True
return False
def write(self, bdata):
si... |
class OptionSeriesErrorbarSonificationContexttracksMappingHighpassResonance(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: st... |
def get_af_dispositions(case_id):
with db.engine.connect() as conn:
rs = conn.execute(AF_DISPOSITION_DATA, case_id)
disposition_data = []
for row in rs:
disposition_data.append({'disposition_description': row['description'], 'disposition_date': row['dates'], 'amount': row['amount... |
class IPyRemoteWidget(RemoteWidget):
def __init__(self, scene_proxy, bridge, *args, **kw):
super(IPyRemoteWidget, self).__init__(scene_proxy, bridge, *args, **kw)
self.image = Image(format='PNG')
self.event = Event(source=self.image, watched_events=['dragstart', 'mouseenter', 'mouseleave', '... |
class OptionPlotoptionsPieAccessibilityPoint(Options):
def dateFormat(self):
return self._config_get(None)
def dateFormat(self, text: str):
self._config(text, js_type=False)
def dateFormatter(self):
return self._config_get(None)
def dateFormatter(self, value: Any):
self._... |
def TryFunctionWithTimeout(func, error_handler, num_tries, sleep_between_attempt_secs, *args, **kwargs):
count = num_tries
while (count > 0):
try:
count -= 1
ret_val = func(*args, **kwargs)
if (not ret_val):
return
else:
pri... |
def render_raster_masks(nodes: List[MapNode], lines: List[MapLine], areas: List[MapArea], canvas: Canvas) -> Dict[(str, np.ndarray)]:
all_groups = ((Groups.areas + Groups.ways) + Groups.nodes)
masks = {k: np.zeros((canvas.h, canvas.w), np.uint8) for k in all_groups}
for area in areas:
canvas.raster ... |
def test_split_action_wrapper() -> None:
base_env = GymMazeEnv(env='LunarLanderContinuous-v2')
split_config = {'action': {'action_up': {'indices': [0]}, 'action_side': {'indices': [1]}}}
env = SplitActionsWrapper.wrap(base_env, split_config=split_config)
assert isinstance(env.action_space, spaces.Dict)
... |
class getCpuProfile_result():
thrift_spec = None
thrift_field_annotations = None
thrift_struct_annotations = None
__init__ = None
def isUnion():
return False
def read(self, iprot):
if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderPro... |
def test_orca_bas():
basis_str = '\n %basis\n newgto 1\n s 2\n 1 0.7 0.5\n 1 0.8 0.6\n p 2\n 1 0.7 0.5\n 1 0.8 0.6\n d 2\n 1 0.7 0.5\n 1 0.8 0.6\n d 3\n 1 0.7 0.5\n 1 0.8 0.6\n 1 0.6 0.4\n end\n end\n '
bas = basis_from_orca_str(basis_str)
... |
def _showColor(color):
color = (('(' + color) + ')')
colorToUse = color
isCF = _colorIsCGColorRef(color)
if isCF:
colorToUse = '[[UIColor alloc] initWithCGColor:(CGColorRef){}]'.format(color)
else:
isCI = objectHelpers.isKindOfClass(color, 'CIColor')
if isCI:
colo... |
class GovRestClient(Gov):
API_URL = '/cosmos/gov/v1beta1'
def __init__(self, rest_api: RestClient) -> None:
self._rest_api = rest_api
def Proposal(self, request: QueryProposalRequest) -> QueryProposalResponse:
json_response = self._rest_api.get(f'{self.API_URL}/proposals/{request.proposal_id... |
class PlotFrame(DemoFrame):
def _create_component(self):
numpoints = 50
low = (- 5)
high = 15.0
x = arange(low, high, ((high - low) / numpoints))
container = OverlayPlotContainer(bgcolor='lightgray')
common_index = None
index_range = None
value_range =... |
.parallel
.parametrize(('degree', 'quads', 'rate'), [(3, False, 3.75), (5, True, 5.75)])
def test_cg_convergence(degree, quads, rate):
import numpy as np
diff = np.array([run_CG_problem(r, degree, quads) for r in range(2, 5)])
conv = np.log2((diff[:(- 1)] / diff[1:]))
assert (np.array(conv) > rate).all(... |
class OptionPlotoptionsBulletDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
... |
class DjangoWebRoot(resource.Resource):
def __init__(self, pool):
self.pool = pool
self._echo_log = True
self._pending_requests = {}
super().__init__()
self.wsgi_resource = WSGIResource(reactor, pool, get_wsgi_application())
def empty_threadpool(self):
self.pool.l... |
class SubmittedTx():
def __init__(self, client: 'LedgerClient', tx_hash: str):
self._client = client
self._response: Optional[TxResponse] = None
self._tx_hash = str(tx_hash)
def tx_hash(self) -> str:
return self._tx_hash
def response(self) -> Optional[TxResponse]:
ret... |
def check_allowed(mmcm_pll_dir, cmt):
if (mmcm_pll_dir == 'BOTH'):
return True
elif (mmcm_pll_dir == 'ODD'):
(x, y) = CMT_XY_FUN(cmt)
return ((x & 1) == 1)
elif (mmcm_pll_dir == 'EVEN'):
(x, y) = CMT_XY_FUN(cmt)
return ((x & 1) == 0)
elif (mmcm_pll_dir == 'NONE'):... |
(scope='session')
def auth0_secrets(saas_config):
return {'domain': (pydash.get(saas_config, 'auth0.domain') or secrets['domain']), 'client_id': (pydash.get(saas_config, 'auth0.client_id') or secrets['client_id']), 'client_secret': (pydash.get(saas_config, 'auth0.client_secret') or secrets['client_secret'])} |
class Input():
_inheritance_done = False
_inheritance_others = None
_do_load = None
def __init__(self, dic):
assert isinstance(dic, dict), dic
assert (len(dic) == 1), dic
self.name = list(dic.keys())[0]
self.config = dic[self.name]
if ((self.name == 'forcing') or ... |
def create_or_update_dataset(connection_config: ConnectionConfig, created_or_updated: List[Dataset], data: dict, dataset: Dataset, db: Session, failed: List[BulkUpdateFailed], create_method: Callable) -> None:
try:
if (connection_config.connection_type == ConnectionType.saas):
_validate_saas_dat... |
def find_item_in_distribution(ctx: Context, item_type: str, item_public_id: PublicId) -> Path:
item_type_plural = (item_type + 's')
item_name = item_public_id.name
package_path = Path(AEA_DIR, item_type_plural, item_name)
config_file_name = _get_default_configuration_file_name_from_type(item_type)
i... |
class TestDfs(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestDfs, self).__init__()
self.results = Results()
def test_dfs(self):
bst = BstDfs(Node(5))
bst.insert(2)
bst.insert(8)
bst.insert(1)
bst.insert(3)
bst.in_order_traversal... |
class AdsPixelStats(AbstractObject):
def __init__(self, api=None):
super(AdsPixelStats, self).__init__()
self._isAdsPixelStats = True
self._api = api
class Field(AbstractObject.Field):
count = 'count'
diagnostics_hourly_last_timestamp = 'diagnostics_hourly_last_timestamp'... |
_io.on('new_event')
def new_event(data):
global match_details
print('new_event', data)
match_details = match_utils.update_match_details(match_details, data['event'])
print('Sending new match_details')
emit('receive_details', {'match_details': match_details}, broadcast=True, include_self=False) |
class CausalConv1d(torch.nn.Conv1d):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True, apply_padding=True):
super(CausalConv1d, self).__init__(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=0, dilation=dilation, groups=groups, b... |
def eol_releases(days: int=30) -> list:
from bodhi.server.models import Release, ReleaseState
active_releases = Release.query.filter(Release.state.not_in([ReleaseState.disabled, ReleaseState.archived])).filter(Release.eol.is_not(None)).order_by(Release.eol.asc())
eol_releases = []
for release in active_... |
def test_configure_project_project_is_none(create_test_db, create_pymel, create_maya_env, create_test_data, temp_project):
from anima.dcc.mayaEnv.render import MayaColorManagementConfigurator
with pytest.raises(TypeError) as cm:
MayaColorManagementConfigurator.configure_project(None, 'scene-linear Rec.7... |
class OptionSeriesBoxplotSonificationTracks(Options):
def activeWhen(self) -> 'OptionSeriesBoxplotSonificationTracksActivewhen':
return self._config_sub_data('activeWhen', OptionSeriesBoxplotSonificationTracksActivewhen)
def instrument(self):
return self._config_get('piano')
def instrument(s... |
class CollectMissingStorage(BaseRequestResponseEvent[MissingStorageResult]):
missing_node_hash: Hash32
storage_key: Hash32
storage_root_hash: Hash32
account_address: Address
urgent: bool
block_number: BlockNumber
def expected_response_type() -> Type[MissingStorageResult]:
return Miss... |
class ExternalData(ExternalBase):
current_version: ExternalFile
new_version: t.Optional[ExternalFile]
def from_source_impl(cls, source_path: str, source: t.Dict, module: t.Optional[BuilderModule]=None) -> ExternalData:
data_type = cls.Type(source['type'])
assert (data_type == cls.type), data... |
def parse_m3u(playlist_file):
with open(playlist_file, errors='ignore', encoding='utf-8') as f:
for line in iter((lambda : f.readline()), ''):
if (not line.startswith('#')):
line = line.lstrip('file:').lstrip('/').rstrip()
if (line != playlist_file):
... |
def extractDevilPendingTranslationsHomeBlog(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... |
class OptionSeriesAreasplineSonificationContexttracksPointgrouping(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):
... |
class ManualFeatures():
def __init__(self, motion, skeleton=feat_utils.Skeleton.PFNN):
self.global_positions = motion.positions(local=False)
self.joints = [joint.name for joint in motion.skel.joints]
self.frame_time = (1 / motion.fps)
self.frame_num = 1
self.offsets = [conver... |
def publishednameinfo(filename):
filename = os.path.basename(filename)
m = publish_name_regex.match(filename)
try:
result = (m.group(1), int(m.group(2)))
except AttributeError as exc:
raise FDroidException((_('Invalid name for published file: %s') % filename)) from exc
return result |
.parametrize('make_chain_id, expect_success', (((lambda w3: w3.eth.chain_id), True), pytest.param((lambda w3: ), False)))
def test_send_transaction_with_valid_chain_id(w3, make_chain_id, expect_success):
transaction = {'to': w3.eth.accounts[1], 'chainId': make_chain_id(w3)}
if expect_success:
txn_hash =... |
class IPToolCurl(LocalComponent):
ACCEPTABLE_CURL_ERRORS = ['Connection timed out', "Couldn't connect to server", 'Could not resolve host', 'Resolving timed out after', 'Operation timed out']
def __init__(self, device, config):
super().__init__(device, config)
self._dyndns = ICanHazIP(self._curl... |
class ShellConnectorHelper():
def __init__(self, device):
self._device = device
def check_command(self, cmd, root=False):
(ret, stdout, stderr) = self._device.connector().execute(cmd, root)
if ret:
raise XVProcessException(cmd, ret, stdout, stderr)
return (ret, stdout... |
def copy_file_from_gcs(file_path, output_path=None, storage_client=None):
if (not storage_client):
storage_client = storage.StorageClient({})
if (not output_path):
(tmp_file, output_path) = tempfile.mkstemp()
os.close(tmp_file)
with open(output_path, mode='wb') as f:
storage_... |
class TestPermissionCheck(BaseEvenniaTest):
def test_check__success(self):
self.assertEqual([perm for perm in self.char1.account.permissions.all()], ['developer', 'player'])
self.assertTrue(self.char1.permissions.check('Builder'))
self.assertTrue(self.char1.permissions.check('Builder', 'Play... |
def extractTeaprincesstranslationsBlogspotCom(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, n... |
('rollback', cls=FandoghCommand)
('-s', '--service', '--name', 'name', prompt='Service Name')
('--version', '-v', 'version', prompt='History Version')
def service_rollback(name, version):
if click.confirm(format_text('Rolling back a quick solution but it does not mean that selected version is healthy\nthis is your ... |
def _option_list(*suboptions):
xyzgrid = get_xyzgrid()
def _log(msg):
print(msg)
xyzgrid.log = _log
xymap_data = xyzgrid.grid
if (not xymap_data):
if xyzgrid.db.map_data:
print('Grid could not load due to errors.')
else:
print("The XYZgrid is currently... |
.parametrize('types, expected', (({'Person': [{'name': 'other_person', 'type': 'OtherPerson'}], 'OtherPerson': [{'name': 'Person', 'type': 'Person'}]}, {'expected_exception': ValueError, 'match': 'Unable to determine primary type'}), ({'Person': [{'name': 'name', 'type': 'string'}], 'Mail': [{'name': 'type', 'type': 's... |
def _validate_award_id(award_id):
if ((type(award_id) is int) or award_id.isdigit()):
filters = {'id': int(award_id)}
else:
filters = {'generated_unique_award_id': award_id}
award = Award.objects.filter(**filters).values_list('id', 'piid', 'fain', 'uri', 'generated_unique_award_id').first()
... |
def _is_supported_type(param):
try:
is_supported_type(param, supported_types, none_support=True)
except TypeError as t:
from eagerx.core.specs import EntitySpec
if isinstance(param, SpecView):
param = param.to_dict()
is_supported_type(param, supported_types, none_... |
def test_get_trace_parent_header(elasticapm_client):
trace_parent = TraceParent.from_string('00-0af7651916cd43dd8448eb211c80319c-b7ad6b-03')
transaction = elasticapm_client.begin_transaction('test', trace_parent=trace_parent)
assert (transaction.trace_parent.to_string() == elasticapm.get_trace_parent_header... |
class InputMediaVideo(InputMedia):
def __init__(self, media, thumbnail=None, caption=None, parse_mode=None, caption_entities=None, width=None, height=None, duration=None, supports_streaming=None, has_spoiler=None):
super(InputMediaVideo, self).__init__(type='video', media=media, caption=caption, parse_mode=... |
.parametrize('degree', [1, 2, 3])
def test_vfs(mesh2D, degree):
V = VectorFunctionSpace(mesh2D, 'CG', degree)
u = Function(V)
u.interpolate(Constant((1.0, 1.0)))
n = FacetNormal(mesh2D)
assert (abs((assemble((dot(u('-'), n('-')) * dS)) + 2.0)) < 1e-10)
assert (abs((assemble((dot(u('+'), n('-')) ... |
def test_pca_bigwig_lieberman_gene_density_intermediate_matrices():
pca1 = NamedTemporaryFile(suffix='.bw', delete=False)
pca2 = NamedTemporaryFile(suffix='.bw', delete=False)
pearson_matrix = NamedTemporaryFile(suffix='.h5', delete=False)
obs_exp_matrix = NamedTemporaryFile(suffix='.h5', delete=False)
... |
class BooleanComparisonsTest(unittest.TestCase):
def test_boolean_comparison_eq(self) -> None:
self.maxDiff = None
observed = BMGInference().to_dot([eq_x_y()], {})
expected = '\ndigraph "graph" {\n N0[label=0.5];\n N1[label=Bernoulli];\n N2[label=Sample];\n N3[label=Sample];\n N4[label=... |
def test_duplicate_disconnect(test_client_factory):
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
(await websocket.accept())
message = (await websocket.receive())
assert (message['type'] == 'websocket.disco... |
def _textformat_to_cellformat(textformat):
bg_brush = textformat.background()
fg_brush = textformat.foreground()
return CellFormat(italics=textformat.fontItalic(), underline=textformat.fontUnderline(), bold=(textformat.fontWeight() == QtGui.QFont.Weight.Bold), bgcolor=_brush_to_color(bg_brush), fgcolor=_bru... |
class OptionPlotoptionsSeriesSonificationContexttracksMappingHighpassFrequency(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 OptionPlotoptionsNetworkgraphOnpoint(Options):
def connectorOptions(self) -> 'OptionPlotoptionsNetworkgraphOnpointConnectoroptions':
return self._config_sub_data('connectorOptions', OptionPlotoptionsNetworkgraphOnpointConnectoroptions)
def id(self):
return self._config_get(None)
def id... |
def highlight_content(content: str, lexer_name: str) -> str:
lexer = get_lexer_by_name('text', stripall=True)
if lexer_name:
try:
lexer = get_lexer_by_name(lexer_name, stripall=True)
except PygmentsClassNotFound:
logger.debug("skipping code highlighting as no lexer was fo... |
_bp.route((app.config['FLICKET'] + 'delete/category/<int:category_id>/'), methods=['GET', 'POST'])
_required
def delete_category(category_id=False):
if category_id:
if (not any([g.user.is_admin, g.user.is_super_user])):
flash(gettext('You are not authorised to delete categories.'), category='war... |
class PrototypeEvMore(EvMore):
def __init__(self, caller, *args, session=None, **kwargs):
self.show_non_use = kwargs.pop('show_non_use', False)
self.show_non_edit = kwargs.pop('show_non_edit', False)
super().__init__(caller, *args, session=session, **kwargs)
def init_pages(self, inp):
... |
('llama_recipes.finetuning.train')
('llama_recipes.finetuning.LlamaForCausalLM.from_pretrained')
('llama_recipes.finetuning.LlamaTokenizer.from_pretrained')
('llama_recipes.finetuning.get_preprocessed_dataset')
('llama_recipes.finetuning.optim.AdamW')
('llama_recipes.finetuning.StepLR')
def test_finetuning_no_validatio... |
class ImportanceSamplingActiveUserSelector(ActiveUserSelector):
def __init__(self, **kwargs):
init_self_cfg(self, component_class=__class__, config_class=ImportanceSamplingActiveUserSelectorConfig, **kwargs)
super().__init__(**kwargs)
def _set_defaults_in_cfg(cls, cfg):
pass
def get_... |
def part_arg(parser):
part = os.getenv('XRAY_PART')
part_kwargs = {}
if (part is None):
part_kwargs['required'] = True
else:
part_kwargs['required'] = False
part_kwargs['default'] = part
parser.add_argument('--part', help='Part name. When not given defaults to XRAY_PART env. ... |
def get_pc_status_from_stage_state(private_computation_instance: PrivateComputationInstance, onedocker_svc: OneDockerService, stage_name: Optional[str]=None) -> PrivateComputationInstanceStatus:
status = private_computation_instance.infra_config.status
stage_instance = private_computation_instance.get_stage_ins... |
def _on_process_signature(app, what, name, obj, options, signature, return_annotation):
if ((what in ('function', 'method')) and signature and ('_' in signature)):
filtered = []
for token in signature[1:(- 1)].split(','):
token = token.strip()
if (not token.startswith('_')):
... |
def get_obtainability(save_stats: dict[(str, Any)]) -> list[int]:
file_data = game_data_getter.get_file_latest('DataLocal', 'nyankoPictureBookData.csv', helper.is_jp(save_stats))
if (file_data is None):
helper.colored_text('Failed to get obtainability', helper.RED)
return []
data = helper.pa... |
def test_setitem(fx_asset):
with Image(filename=str(fx_asset.joinpath('apple.ico'))) as imga:
with Image(filename=str(fx_asset.joinpath('google.ico'))) as imgg:
imga.sequence[2] = imgg
assert (len(imga.sequence) == 4)
assert (imga.sequence[2].size == (16, 16))
expire(imga... |
def test_acceptance():
cfg = ControlFlowGraph()
cfg.add_nodes_from([BasicBlock(0, instructions=[Assignment((x01 := Variable('x', i32.copy(), ssa_label=0)), Constant(4919, i32.copy())), Assignment((x10 := Variable('x', i32.copy(), is_aliased=True, ssa_label=1)), Call(FunctionSymbol('foo', 66), [(x02 := Variable(... |
class TransmitterBase(LogCaptureTestCase):
TEST_SRV_CLASS = TestServer
def setUp(self):
super(TransmitterBase, self).setUp()
self.server = self.TEST_SRV_CLASS()
self.transm = self.server._Server__transm
self.jailName = 'TestJail1'
self.server.addJail(self.jailName, FAST_B... |
class Exploit(BaseBuff):
key = 'exploit'
name = 'Exploit'
flavor = "You are learning your opponent's weaknesses."
duration = (- 1)
maxstacks = 20
triggers = ['hit']
stack_msg = {1: "You begin to notice flaws in your opponent's defense.", 10: "You've begun to match the battle's rhythm.", 20: ... |
def save_strava_token(token_dict):
app.server.logger.debug('Deleting current strava tokens')
app.session.execute(delete(apiTokens).where((apiTokens.service == 'Strava')))
app.server.logger.debug('Inserting new strava tokens')
app.session.add(apiTokens(date_utc=datetime.utcnow(), service='Strava', tokens... |
class DepositLineDetail(QuickbooksBaseObject):
class_dict = {'Entity': Ref, 'ClassRef': Ref, 'AccountRef': Ref, 'PaymentMethodRef': Ref}
def __init__(self):
super(DepositLineDetail, self).__init__()
self.CheckNum = ''
self.TxnType = None
self.Entity = None
self.ClassRef =... |
def upward_continuation_kernel(fft_grid, height_displacement):
dims = fft_grid.dims
freq_easting = fft_grid.coords[dims[1]]
freq_northing = fft_grid.coords[dims[0]]
k_easting = ((2 * np.pi) * freq_easting)
k_northing = ((2 * np.pi) * freq_northing)
da_filter = np.exp(((- np.sqrt(((k_easting ** 2... |
class Decoder():
def __init__(self):
warnings.warn('The :py:class:`mcap_ros1.decoder.Decoder` class is deprecated.\nFor similar functionality, instantiate the :py:class:`mcap.reader.McapReader` with a\n:py:class:`mcap_ros1.decoder.DecoderFactory` instance.', DeprecationWarning)
self._decoder_factory... |
def is_estimated_count(resource, query):
if (resource.use_pk_for_count and resource.model):
primary_key = resource.model.__mapper__.primary_key[0]
query = query.with_entities(primary_key)
if resource.use_estimated_counts:
estimated_count = get_estimated_count(query)
if (estimated... |
class DWI():
def __init__(self, n=4, maxlen=2):
self.n = int(n)
assert (self.n > 0)
assert ((self.n % 2) == 0)
self.maxlen = maxlen
assert (self.maxlen == 2), 'Right now only maxlen=2 is supported!'
self.coords = deque(maxlen=self.maxlen)
self.energies = deque... |
class StmtTransformer(StmtVisitor):
def visit_def(self, stmt, *args, **kwargs):
blk = kwargs['blk']
pc = kwargs['pc']
if (stmt.insn is not None):
make_insn(stmt.insn, blk)
if (type(stmt.lhs) in (VirtualVar, OtherVar)):
lhs = stmt.lhs
rhs = EXP_TRAN... |
class OptionSeriesSunburstDataDragdrop(Options):
def draggableX(self):
return self._config_get(None)
def draggableX(self, flag: bool):
self._config(flag, js_type=False)
def draggableY(self):
return self._config_get(None)
def draggableY(self, flag: bool):
self._config(flag... |
class DiskCheckpointer(TapePackageData):
def __init__(self, dirname=None, comm=COMM_WORLD, cleanup=True):
if (comm.rank == 0):
self.dirname = comm.bcast(tempfile.mkdtemp(prefix='firedrake_adjoint_checkpoint_', dir=(dirname or os.getcwd())))
else:
self.dirname = comm.bcast('')... |
def test_simple_type():
assert (_types.SimpleType.NONE == types_pb2.NONE)
assert (_types.SimpleType.INTEGER == types_pb2.INTEGER)
assert (_types.SimpleType.FLOAT == types_pb2.FLOAT)
assert (_types.SimpleType.STRING == types_pb2.STRING)
assert (_types.SimpleType.BOOLEAN == types_pb2.BOOLEAN)
asse... |
.register(vrrp_event.VRRPInterfaceOpenFlow)
class VRRPInterfaceMonitorOpenFlow(monitor.VRRPInterfaceMonitor):
OFP_VERSIONS = [ofproto_v1_2.OFP_VERSION, ofproto_v1_3.OFP_VERSION]
_TABLE = 0
_PRIORITY = 32768
def __init__(self, *args, **kwargs):
super(VRRPInterfaceMonitorOpenFlow, self).__init__(*... |
def test_callback_blueprint():
cbp = CallbackBlueprint(State('s', 'prop'), Output('o', 'prop'), Input('i', 'prop'))
assert (list(cbp.outputs) == [Output('o', 'prop')])
assert (list(cbp.inputs) == [State('s', 'prop'), Input('i', 'prop')])
cbp = CallbackBlueprint([State('s', 'prop'), State('s2', 'prop')],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.