code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def testPokerPlayerIsAllIn(self): <NEW_LINE> <INDENT> self.failUnlessEqual(self.player.isAllIn(), False) <NEW_LINE> self.player.all_in = True <NEW_LINE> self.failUnlessEqual(self.player.isAllIn(), True) | Test Poker Player : Is all in | 625941ec5f7d997b87174faa |
def post1(self,row,data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r=requests.post(url=self.excel.get_Url(row=row), json=data, headers=getHeadersValue()) <NEW_LINE> return r <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise RuntimeError('接口请求发生异常') | 参数中存在data中的变量参数时使用 | 625941eccc40096d61595e5c |
def test_no_messages_in_queue_after_stop(self): <NEW_LINE> <INDENT> support.import_module('multiprocessing.synchronize') <NEW_LINE> for i in range(self.repeat): <NEW_LINE> <INDENT> queue = multiprocessing.Queue() <NEW_LINE> self.setup_and_log(queue, '%s_%s' %(self.id(), i)) <NEW_LINE> items = list(self.get_all_from_que... | Five messages are logged then the QueueListener is stopped. This
test then gets everything off the queue. Failure of this test
indicates that messages were not registered on the queue until
_after_ the QueueListener stopped. | 625941ec236d856c2ad44cef |
def then_by(self, func): <NEW_LINE> <INDENT> if func is None: <NEW_LINE> <INDENT> raise NullArgumentError(u"then by requires a lambda function arg") <NEW_LINE> <DEDENT> self._key_funcs.append(OrderingDirection(key=func, reverse=False)) <NEW_LINE> return SortedEnumerable(self, self._key_funcs) | Subsequent sorting function in ascending order
:param func: lambda expression for secondary sort key
:return: SortedEnumerable instance | 625941ec1d351010ab856028 |
def _CreateZip(self, name, *paths): <NEW_LINE> <INDENT> empty_path = self._CreateFile("empty") <NEW_LINE> zip_path = os.path.join(self._temp_dir, name) <NEW_LINE> with zipfile.ZipFile(zip_path, "w") as zip_file: <NEW_LINE> <INDENT> for path in paths: <NEW_LINE> <INDENT> zip_file.write(empty_path, path) <NEW_LINE> <DEDE... | Creates a zip file containing empty files.
Args:
name: string, the name of the zip file.
*paths: strings, the file paths to create in the zip file.
Returns:
string, the path to the zip file. | 625941ec63b5f9789fde75f4 |
def setCRResistance(resistance, serial): <NEW_LINE> <INDENT> value = int(resistance * 1000) <NEW_LINE> cmd = [0] * 26 <NEW_LINE> cmd[2] = 0x30 <NEW_LINE> cmd[3] = value & 0xFF <NEW_LINE> cmd[4] = (value >> 8) & 0xFF <NEW_LINE> cmd[5] = (value >> 16) & 0xFF <NEW_LINE> cmd[6] = (value >> 24) & 0xFF <NEW_LINE> command(cmd... | Set CR mode resistance value | 625941ec67a9b606de4a83c4 |
def make_tube_proposals(self, raw_clips: torch.tensor) -> np.array: <NEW_LINE> <INDENT> tube_props = raw_clips.numpy() <NEW_LINE> tube_props = np.meshgrid(tube_props[:, 0], *np.vsplit(tube_props[:, 1:].T, len(tube_props))) .T.reshape(-1, self.n_clips) <NEW_LINE> return tube_props | Cartesian product of proposed tubes to find best pairings | 625941ec091ae35668667463 |
def test_tag_str(self): <NEW_LINE> <INDENT> tag = models.Tag.objects.create( user=sample_user(), name='Almoço' ) <NEW_LINE> self.assertEqual(str(tag), tag.name) | Testa a string da tag | 625941ec50485f2cf553d2aa |
def hadamard_product(*matrices): <NEW_LINE> <INDENT> if not matrices: <NEW_LINE> <INDENT> raise TypeError("Empty Hadamard product is undefined") <NEW_LINE> <DEDENT> validate(*matrices) <NEW_LINE> if len(matrices) == 1: <NEW_LINE> <INDENT> return matrices[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> matrices = [i fo... | Return the elementwise (aka Hadamard) product of matrices.
Examples
========
>>> from sympy.matrices import hadamard_product, MatrixSymbol
>>> A = MatrixSymbol('A', 2, 3)
>>> B = MatrixSymbol('B', 2, 3)
>>> hadamard_product(A)
A
>>> hadamard_product(A, B)
HadamardProduct(A, B)
>>> hadamard_product(A, B)[0, 1]
A[0, 1]... | 625941ec9c8ee82313fbbc85 |
def _parse_initial_state_0(cur_char, cur_token, token_stack): <NEW_LINE> <INDENT> if cur_char in ' \t': <NEW_LINE> <INDENT> return _parse_initial_state_0 <NEW_LINE> <DEDENT> del cur_token[:] <NEW_LINE> cur_token.append(cur_char) <NEW_LINE> if cur_char.isalpha() or cur_char.isdigit() or cur_char in '_-': <NEW_LINE> <IND... | a function that analyze character in initial state of finite automaton | 625941ecd99f1b3c44c67a93 |
def _actionMinutesTenths(m): <NEW_LINE> <INDENT> global _countMinutesTenths <NEW_LINE> hh = int(m.group(1)) <NEW_LINE> mm = float(m.group(2)) <NEW_LINE> ss = 0 <NEW_LINE> prec = 6 <NEW_LINE> _countMinutesTenths += 1 <NEW_LINE> return (hh, mm, ss, prec) | action for HH MM.m | 625941ec460517430c394685 |
def main(): <NEW_LINE> <INDENT> scheduler = BackgroundScheduler() <NEW_LINE> scheduler.add_job(do_alerts, 'interval', minutes=1) <NEW_LINE> scheduler.start() <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> <DEDENT> <DEDENT> except (KeyboardInterrupt, SystemExit): <NEW_LINE> ... | This function will loop forever (block) while looking
for h1 reports to pager duty alert on. | 625941ec796e427e537b0ad9 |
def main(global_config, **settings): <NEW_LINE> <INDENT> config = Configurator(settings=settings) <NEW_LINE> config.include('pyramid_jinja2') <NEW_LINE> config.add_jinja2_search_path("templates") <NEW_LINE> config.add_static_view('static', 'static', cache_max_age=3600) <NEW_LINE> config.add_route('home', '/') <NEW_LINE... | This function returns a Pyramid WSGI application.
| 625941ecfbf16365ca6f66dd |
def validate_license(key: str) -> bool: <NEW_LINE> <INDENT> return bool(pattern.fullmatch(key)) | Write a regex that matches a PyBites license key
(e.g. PB-U8N435EH-PG65PW87-IXPWQG5T-898XSZI4) | 625941ecb830903b967e9e13 |
def ProjectValidator(project): <NEW_LINE> <INDENT> if project is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if re.match(_VALID_PROJECT_REGEX, project): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not isinstance(project, basestring): <NEW_LINE> <INDENT> raise InvalidValueError('project must be a string')... | Checks to see if the project string is valid. | 625941ec925a0f43d254a38a |
def clip(func2, func1, t, t_switch): <NEW_LINE> <INDENT> if np.isnan(func1) or np.isnan(func2): <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if t <= t_switch: <NEW_LINE> <INDENT> return func1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return func2 | Logical function used as time switch to change parameter value.
Parameters
----------
func2 : any
func1 : any
t : float
current time value.
t_switch : float
time threshold.
Returns
-------
func2 if t>t_switch, else func1. | 625941ec0383005118ecfaef |
def __init__(self, *conditions): <NEW_LINE> <INDENT> self.conditions = list(conditions) | Create list of condition
Parameters
----------
*conditions : Condition
Multiple conditions | 625941ecfb3f5b602dac3ba7 |
def generate_random_column(column_name): <NEW_LINE> <INDENT> data[column_name] = np.random.rand(50) | Adds a new column in the dataframe (or recalculates existing) | 625941ec71ff763f4b549ba3 |
def ruleOfThirds(self): <NEW_LINE> <INDENT> lineMatches = map((lambda line: self.clusterIsAlongLine(line)), self.gridlines) <NEW_LINE> maxLineMatch = max(lineMatches) <NEW_LINE> pointMatches = map((lambda point: self.clusterIsAtPoint(point)), self.intersections) <NEW_LINE> maxPointMatch = max(pointMatches) <NEW_LINE> p... | returns a confidence value for the object of the PeekaboomRound
adhering to the rule of thirds in the image | 625941ec091ae35668667464 |
def p_textsuffix(p): <NEW_LINE> <INDENT> if len(p) == 2: <NEW_LINE> <INDENT> p[0] = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if type(p[1]) is str: <NEW_LINE> <INDENT> p[0] = [(p[1], p.lineno(1))] + p[2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = [p[1]] + p[2] | textsuffix : IDENT textsuffix
| ATKEYWORD textsuffix
| ATBRACES textsuffix
| COLON textsuffix
| HASH textsuffix
| DELIM textsuffix
| NUMBER textsuffix
| DIMENSION textsuffix
| PERCENTAGE textsuffix
| URI textsuffix
| STRING textsuffix
| UNICODE_RANGE textsuffix
| INCLUDES textsuffix
| DASHMATCH textsuffix
| function te... | 625941ec283ffb24f3c55e0a |
def _build_argument_parser(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( usage='%(prog)s [options] <file...>', description='Do packagename stuff.', formatter_class=argparse.RawDescriptionHelpFormatter, ) <NEW_LINE> parser.add_argument( '-o', '--output', type=argparse.FileType('w'), default='-', help='Output ... | Build parser for command line options.
:return: argument parser
:rtype: argparse.ArgumentParser | 625941ec7d847024c06be7cf |
def message_contains(self, flag: Optional[str]) -> bool: <NEW_LINE> <INDENT> if not self.message: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not flag: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return flag in self.message | If the string is in the message | 625941ecf8510a7c17cf9c0e |
def _cb_ignore_listen_exception(self, exception, server): <NEW_LINE> <INDENT> if isinstance(exception, ssl.SSLError): <NEW_LINE> <INDENT> if exception.errqueue[-1][0] == ssl.ERR_TLSV1_ALERT_UNKNOWN_CA: <NEW_LINE> <INDENT> _logger.debug("Ignoring ERR_TLSV1_ALERT_UNKNOWN_CA from client %s" % ('unknown' if not hasattr(exc... | In the CoAP server listen method, different exceptions can arise from the DTLS stack. Depending on the type of exception, a
continuation might not be possible, or a logging might be desirable. With this callback both needs can be satisfied.
:param exception: What happened inside the DTLS stack
:param server: Reference... | 625941ec3c8af77a43ae3cb5 |
def check_txrcv_ids_in_channel(self): <NEW_LINE> <INDENT> self._check_ids_in_channel_for_optional_branch('TxRcv') | If the TxRcv branch exists, then TxRcv is also present in /Channel/Parameters | 625941ec56ac1b37e62646d3 |
def present_ribbon_length(dimensions): <NEW_LINE> <INDENT> ribbon_length = product(dimensions) <NEW_LINE> sorted_dims = sorted(dimensions) <NEW_LINE> ribbon_length += 2 * (sorted_dims[0]+sorted_dims[1]) <NEW_LINE> return ribbon_length | :param dimensions: list of 3 floats: length, width and height
:return: length of ribbon | 625941eca8ecb033257d35d9 |
def evaluate_block(self, template, context=None, escape=None, safe_wrapper=None): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with self._evaluation_context(escape, safe_wrapper): <NEW_LINE> <INDENT> template = self._environment.from_string(templa... | Evaluate a template block. | 625941ec462c4b4f79d1dbde |
def test_json_output_for_notes(self): <NEW_LINE> <INDENT> test_project_notes = os.path.join(self.test_workspaces['NORMAL'], "test_files", "notes") <NEW_LINE> extract_cmd = ['CodeChecker', 'parse', "-e", "json", test_project_notes] <NEW_LINE> out, _, result = call_command(extract_cmd, cwd=self.test_dir, env=self.env) <N... | Test parse json output for notes. | 625941ec38b623060ff0b2fb |
def midpoint(a, b): <NEW_LINE> <INDENT> pp = (a + b) / 2.0 <NEW_LINE> ll = np.sqrt(np.sum(pp * pp, axis=-1)) <NEW_LINE> ll = two_d(ll) <NEW_LINE> return pp / ll | Returns the midpoint on the great circle arc between *A* and *B*.
Parameters
----------
a, b : (*x*, *y*, *z*) triples or Nx3 arrays of triples
The endpoints of the great circle arc. It is assumed that
these points are already normalized.
Returns
-------
midpoint : (*x*, *y*, *z*) triple or Nx3 arrays of tri... | 625941ec5fc7496912cc3e8c |
def load(configuration, logger): <NEW_LINE> <INDENT> auth_type = configuration.get("auth", "type") <NEW_LINE> logger.debug("Authentication type is %s" % auth_type) <NEW_LINE> if auth_type == "None": <NEW_LINE> <INDENT> return lambda user, password: True <NEW_LINE> <DEDENT> elif auth_type == "htpasswd": <NEW_LINE> <INDE... | Load the authentication manager chosen in configuration. | 625941ecd8ef3951e3243a4c |
def evaluate(expression): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> for c in expression.split()[::-1]: <NEW_LINE> <INDENT> if is_operand(c): <NEW_LINE> <INDENT> stack.append(int(c)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> o1 = stack.pop() <NEW_LINE> o2 = stack.pop() <NEW_LINE> stack.append(calc[c](o1, o2)) <NEW_L... | Evaluate a given expression in prefix notation.
Asserts that the given expression is valid.
>>> evaluate("+ 9 * 2 6")
21
>>> evaluate("/ * 10 2 + 4 1 ")
4.0 | 625941ecdc8b845886cb5a45 |
def _profile_path(self): <NEW_LINE> <INDENT> if self.label: <NEW_LINE> <INDENT> label = self.label <NEW_LINE> if " " in label: <NEW_LINE> <INDENT> label = label.replace(" ", "_") <NEW_LINE> <DEDENT> names = (self.short_name, label) <NEW_LINE> name_fmt = "%s-%s" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> names = (sel... | Return the path to this profile's on-disk data.
Return the full path to this HostProfile in the Boom profiles
directory (or the location to which it will be written, if
it has not yet been written).
:rtype: str
:returns: The absolute path for this HostProfile's file | 625941ec44b2445a339325a0 |
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> if (n < 3): <NEW_LINE> <INDENT> return n <NEW_LINE> <DEDENT> p = 1 <NEW_LINE> for c in range(2, n): <NEW_LINE> <INDENT> if (nums[c] == nums[p] and nums[c] == nums[p - 1]): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT... | :type nums: List[int]
:rtype: int | 625941ec97e22403b379d4aa |
def is_valid_email(email): <NEW_LINE> <INDENT> return "@" in email and "." in email | Light validation on email address: require @ and at least one dot. | 625941ec44b2445a339325a1 |
def validate(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> valid = checksum(number, alphabet) == 1 <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise InvalidFormat() <NEW_LINE> <DEDENT> if not valid: <NEW_LINE> <INDENT> raise InvalidChecksum() <NEW_... | Checks whether the check digit is valid. | 625941ec66656f66f7cbc6bb |
def mark_moved(self, axis_iter: Sequence[str]) -> None: <NEW_LINE> <INDENT> now = time.monotonic() <NEW_LINE> self._moved_at.update({ax: now for ax in axis_iter}) | Indicate that a set of axes just moved | 625941ec96565a6dacc8fbd8 |
@noop <NEW_LINE> def hello_noop(): <NEW_LINE> <INDENT> print("Hello, world!") | Print a well-known message. | 625941ec3617ad0b5ed68405 |
def poly(self, deflection=1e-3): <NEW_LINE> <INDENT> c1 = _BRep_Tool.Curve(_TopoDS_edge(self.shape)) <NEW_LINE> gac1 = _GeomAdaptor_Curve(c1[0], c1[1], c1[2]) <NEW_LINE> ud = _GCPnts_QuasiUniformDeflection(gac1, deflection) <NEW_LINE> retval = [] <NEW_LINE> for count in range(1, ud.NbPoints() + 1): <NEW_LINE> <INDENT> ... | Returns a polyline approximation to the edge | 625941ec26238365f5f0f384 |
def is_safe_url(url, host=None): <NEW_LINE> <INDENT> if not url: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> netloc = urlparse.urlparse(url)[1] <NEW_LINE> return not netloc or netloc == host | Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host).
Always returns ``False`` on an empty url. | 625941ecd10714528d6001f8 |
def get_num_replaced(self): <NEW_LINE> <INDENT> return CPX_PROC.getsolnpoolnumreplaced(self._env._e, self._cplex._lp) | Returns the number of solution pool members that have been replaced.
>>> import cplex
>>> c = cplex.Cplex()
>>> out = c.set_results_stream(None)
>>> out = c.set_log_stream(None)
>>> c.read("ind.lp")
>>> c.solve()
>>> c.solution.pool.get_num_replaced()
0 | 625941ecd7e4931a7ee9e42e |
def __len__(self) -> Integer: <NEW_LINE> <INDENT> return len(self._records) | Return *Zenodo* community records count.
Returns
-------
:class:`int`
*Zenodo* community records count.
Examples
--------
# Doctests skip for Python 2.x compatibility.
>>> len(Community.from_id('colour-science-datasets-tests'))
... # doctest: +SKIP
3 | 625941ec4527f215b584c960 |
def fetch_eth1_validator_data( self, addresses: List[ChecksumEthAddress], ) -> List[ValidatorID]: <NEW_LINE> <INDENT> dbeth2 = DBEth2(self.database) <NEW_LINE> all_validators = [] <NEW_LINE> pubkeys = set() <NEW_LINE> for address in addresses: <NEW_LINE> <INDENT> validators = self.beaconchain.get_eth1_address_validator... | Query all eth1 addresses for their validators and get all corresponding deposits.
Returns the list of all tracked validators. It's ValidatorID since
for validators that are in the deposit queue we don't get a finalized validator index yet.
So index may be missing for some validators.
This is the only function that wi... | 625941eca219f33f34628e70 |
def get_type(bwo): <NEW_LINE> <INDENT> return bwo.data_type | Get the type of the Object. | 625941ec82261d6c526ab9b6 |
def deco_2(func): <NEW_LINE> <INDENT> print('enter into deco_2') <NEW_LINE> def wrapper(a, b): <NEW_LINE> <INDENT> print('enter into deco_2_wrapper') <NEW_LINE> func(a, b) <NEW_LINE> <DEDENT> return wrapper | 统计方法执行耗时
:param func:
:return: | 625941ec21a7993f00bc8208 |
def date_is_valid(dates): <NEW_LINE> <INDENT> if (int(dates[0]) < 1 or int(dates[0]) > 31 or int(dates[1]) < 1 or int(dates[1]) > 12): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Checks if dates (e.g. ["17", "11"] ) is valid and returns bool
Checks if the first element is between 1 and 31
and the second element is between 1 and 12.
Keyword arguments:
dates -- list of numbers
Returns:
True if the date is valid, False otherwise. | 625941ec2ae34c7f2600d63f |
def unpack_event_arming_status_report(self, event): <NEW_LINE> <INDENT> status = event.data_dehex()[self._index] <NEW_LINE> arm_up = event.data_dehex()[8+self._index] <NEW_LINE> alarm = event.data_dehex(True)[16+self._index] <NEW_LINE> if (self._status == status) and (self._arm_up == arm_up) and (self._alarm == alarm):... | Unpack EVENT_ARMING_STATUS_REPORT.
Event data format: SSSSSSSSUUUUUUUUAAAAAAAA
S[8]: Array of 8 area armed status
U[8]: Array of 8 area arm up state
A[8]: Array of 8 area alarm state | 625941ec4428ac0f6e5bad05 |
def check(d, child, parents): <NEW_LINE> <INDENT> if child not in ans: <NEW_LINE> <INDENT> ans[child] = 1 <NEW_LINE> <DEDENT> if len(parents) > 0: <NEW_LINE> <INDENT> for i in parents: <NEW_LINE> <INDENT> if i not in ans: <NEW_LINE> <INDENT> ans[i] = 1 <NEW_LINE> <DEDENT> ans[i] += 1 <NEW_LINE> <DEDENT> for j in d: <NE... | Функция проверки предков и наследников | 625941ec004d5f362079a83e |
def create_labels(self, cr=None): <NEW_LINE> <INDENT> title_layout, params_layout = self._surface_layouts = [ Gtk.DrawingArea().create_pango_layout(''), Gtk.DrawingArea().create_pango_layout(''), ] <NEW_LINE> if cr: <NEW_LINE> <INDENT> PangoCairo.update_layout(cr, title_layout) <NEW_LINE> PangoCairo.update_layout(cr, p... | Create the labels for the signal block. | 625941ec45492302aab5e7d7 |
def getColumnsClass(): <NEW_LINE> <INDENT> pass | Returns CSS Class for Column Content Based on Columns Presence.
| 625941ec507cdc57c63071f6 |
def _generate_communities(degree_sequence, community_sizes, mu, max_iters): <NEW_LINE> <INDENT> result = [set() for _ in community_sizes] <NEW_LINE> n = len(degree_sequence) <NEW_LINE> free = list(range(n)) <NEW_LINE> for i in range(max_iters): <NEW_LINE> <INDENT> v = free.pop() <NEW_LINE> c = random.choice(range(len(c... | Returns a list of sets, each of which represents a community in
the graph.
``degree_sequence`` is the degree sequence that must be met by the
graph.
``community_sizes`` is the community size distribution that must be
met by the generated list of sets.
``mu`` is a float in the interval [0, 1] indicating the fraction ... | 625941ecc4546d3d9de72f47 |
def obs_counter(df, obs, idc="id", alphac="alpha"): <NEW_LINE> <INDENT> df_cnt = df.groupby(idc).count() <NEW_LINE> lt_idx = df_cnt[df_cnt[alphac] < obs].index <NEW_LINE> return lt_idx.to_numpy() | Count the observations. A minimum is needed to the fits.
Parameters
----------
df: ``pandas.DataFrame``
The dataframe must with the values
idc : ``str``, optional (default=id)
Column with the mpc number of the asteroids.
alphac : ``str``, optional (default=alpha)
Column with the phase angle of the asteroid... | 625941ec31939e2706e4d371 |
def outdated(): <NEW_LINE> <INDENT> return get_outdated_packages() | Output all outdated packages.
| 625941ec596a897236089fc8 |
def get_vm_lease_data(data): <NEW_LINE> <INDENT> return {'instance_uuid': data['instance_uuid'], 'tenant_uuid': data['tenant_uuid'], 'expiry': data['expiry'], 'created_at': data['created_at'], 'created_by': data['created_by'], 'updated_at': data['updated_at'], 'updated_by': data['updated_by']} | Simple function to transform instance database proxy object into an externally
consumable dictionary.
:param data: database row object | 625941ec851cf427c661aa19 |
def get_external_image_link(self): <NEW_LINE> <INDENT> if not self.description_link: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> mimetype, encoding = mimetypes.guess_type(self.description_link) <NEW_LINE> if mimetype and mimetype.startswith('image'): <NEW_LINE> <INDENT> return self.description_link <NEW_LINE> <... | Returns the description link if it is an image, otherwise returns None | 625941ec10dbd63aa1bd30b1 |
def getEggNogHeaders(input): <NEW_LINE> <INDENT> IDi, DBi, OGi, Genei, COGi, Desci = (None,)*6 <NEW_LINE> with open(input, 'r') as infile: <NEW_LINE> <INDENT> for line in infile: <NEW_LINE> <INDENT> if line.startswith('#query_name'): <NEW_LINE> <INDENT> line = line.rstrip() <NEW_LINE> headerCols = line.split('\t') <NEW... | function to get the headers from eggnog mapper annotations
web-based eggnog mapper has no header....
#web based 'guess'
0 query_name
1 seed_eggNOG_ortholog
2 seed_ortholog_evalue
3 seed_ortholog_score
4 predicted_gene_name
5 GO_terms
6 KEGG_KOs
7 BiGG_reactions
8 Annotation_tax_scope
9 OGs
10 bestO... | 625941ec9c8ee82313fbbc86 |
def rule_action(label=None, params=None): <NEW_LINE> <INDENT> def wrapper(func): <NEW_LINE> <INDENT> _validate_action_parameters(func, params) <NEW_LINE> func.is_rule_action = True <NEW_LINE> func.label = label or fn_name_to_pretty_label(func.__name__) <NEW_LINE> func.params = params <NEW_LINE> return fu... | Decorator to make a function into a rule action
| 625941eccc40096d61595e5d |
def test_open(self, cfgFile=None): <NEW_LINE> <INDENT> dut = simChamber() <NEW_LINE> self.assertTrue(dut.open()) | @note test open of sim class | 625941ec8a43f66fc4b5456e |
def display_point(self, point=None, plane=None, mask=None): <NEW_LINE> <INDENT> dp = None <NEW_LINE> if point: <NEW_LINE> <INDENT> dp = point <NEW_LINE> <DEDENT> if dp: <NEW_LINE> <INDENT> if self.mask in ('y', 'z'): <NEW_LINE> <INDENT> self.form.input_c_x.setProperty('rawValue', dp.x) <NEW_LINE> <DEDENT> else: <NEW_LI... | Display the coordinates in the x, y, and z widgets.
This function should be used in a Coin callback so that
the coordinate values are automatically updated when the
mouse pointer moves.
This was copied from `DraftGui.py` but needs to be improved
for this particular command.
point :
is a vector that arrives by the... | 625941ec435de62698dfe15c |
def EMAC_IPGT_BBIPG(n): <NEW_LINE> <INDENT> return (n&0x7F) | Programmable field representing the nibble time offset of the minimum
possible period between the end of any transmitted packet to the beginning of
the next. | 625941ecb7558d58953c5418 |
def test_dns_dict_to_string(self): <NEW_LINE> <INDENT> d = {'a': 'vala', 'c': 'valc', 'b': 'valb'} <NEW_LINE> s = "{'a': 'vala', 'b': 'valb', 'c': 'valc'}" <NEW_LINE> foo = dns_dict_to_string(d) <NEW_LINE> assert foo == s | Test with a simple dict | 625941ec8c0ade5d55d3eece |
def placeholders_from_spaces(*args): <NEW_LINE> <INDENT> return [placeholder_from_space(space) for space in args] | Create a list of computational graph placeholders for spaces. | 625941ec3d592f4c4ed1d56e |
def forward(self, graph, current_layer=1): <NEW_LINE> <INDENT> g = graph.local_var() <NEW_LINE> src_name = f'src_feat{current_layer - 1}' <NEW_LINE> dst_name = f'dst_feat{current_layer - 1}' <NEW_LINE> src_feat, dst_feat = g.edata[src_name], g.edata[dst_name] <NEW_LINE> g.edata[src_name] = self.encode_time(src_feat, g.... | We utilize ``dgl.DGLGraph.group_apply_edges`` to compute TGraphSAGE layer.
Parameters
----------
graph : DGLGraph
The graph.
current_layer : int, default as `1`.
As we compute embeddings for each node at its each edge, the count of total embeddings are ``4 * E`` (E is the number of edges), comprise of source ... | 625941ec91f36d47f21aca07 |
def get_unified_routes(self): <NEW_LINE> <INDENT> unified_routes = [] <NEW_LINE> for route in self.curr_routes: <NEW_LINE> <INDENT> unified_routes.append([route.depot_node] + route.linehauls + route.backhauls + [route.depot_node]) <NEW_LINE> <DEDENT> return unified_routes | Concatenates the deposit, the linehauls, the backhauls and finally again the deposit
in a single list.
It's used in the exchange phase, when it's required to have the customers in a single list
:return: a list of routes, i.e. a list of list of Nodes | 625941ec99fddb7c1c9de89d |
def getJson(self): <NEW_LINE> <INDENT> r = Json("object") <NEW_LINE> r.add_pair("reactionid", self.name) <NEW_LINE> s = [] <NEW_LINE> for t in self.substrates: <NEW_LINE> <INDENT> s.append(str(self.stoichiometry[t]) + ' ' + self._get_long_name(t)) <NEW_LINE> <DEDENT> r.add_pair("reactants", " + ".join(s)) <NEW_LINE> s ... | Return a JSON object | 625941ec29b78933be1e5bb5 |
def submit_search_query(query_string, query_limit, query_offset, class_resource): <NEW_LINE> <INDENT> search_result = class_resource.search( query='%s' % query_string, limit=query_limit, offset=query_offset) <NEW_LINE> return search_result | Submit a search query request to the RETS API | 625941ec293b9510aa2c37a0 |
def includeme(config): <NEW_LINE> <INDENT> add_resource_type_to_registry(paragraph_meta, config) <NEW_LINE> add_resource_type_to_registry(paragraphversion_meta, config) | Add resource type to registry. | 625941ec56b00c62f0f14b6c |
def isArchiveSupported(self, tree: mobase.IFileTree) -> bool: <NEW_LINE> <INDENT> data_name = self._organizer.managedGame().dataDirectory().dirName() <NEW_LINE> checker: mobase.ModDataChecker = self._organizer.managedGame().feature( mobase.ModDataChecker ) <NEW_LINE> base = self._getWizardArchiveBase(tree, data_name, c... | Check if the given file-tree (from the archive) can be installed by this
installer.
Args:
tree: The tree to check.
Returns:
True if the file-tree can be installed, false otherwise. | 625941ecde87d2750b8602a7 |
@script <NEW_LINE> def move_by(view, dx, dy, **kwargs): <NEW_LINE> <INDENT> if isnode(view): <NEW_LINE> <INDENT> slide_tuple(view, 'position', (view.position.x+dx, view.position.y+dy), **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> slide_value(view, 'x', view.x + dx, **kwargs) <NEW_LINE> slide_value(view, 'y',... | Adjust position by dx, dy. | 625941ec0a366e3fb873ed2e |
def get_categories(): <NEW_LINE> <INDENT> bu = 'https://www.bdmoviezone.com/' <NEW_LINE> r = requests.get(bu, headers=mozhdr) <NEW_LINE> if r.url != bu: <NEW_LINE> <INDENT> bu = r.url <NEW_LINE> <DEDENT> items = {} <NEW_LINE> cats = re.findall('<li class="cat-item cat-item-.*?"><a href="(.*?)" >(.*?) Movies<\/a>',r.tex... | Get the list of categories.
:return: list | 625941ec6aa9bd52df0372b6 |
def __init__(self, init_settings, screen): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.init_settings = init_settings <NEW_LINE> self.image = pygame.image.load('resources/sprites/pipe_down.png') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.init_set... | 初始化 | 625941ecff9c53063f47c700 |
def reverseString(self, s): <NEW_LINE> <INDENT> if not s: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> chars = [char for char in s] <NEW_LINE> for i in range(len(chars)/2): <NEW_LINE> <INDENT> chars[i], chars[len(chars) - 1 - i] = chars[len(chars) - 1 - i], chars[i] <NEW_LINE> <DEDENT> return ''.join(chars) | :type s: str
:rtype: str | 625941eca934411ee3751ba4 |
def filter_track(track, remove_encapsulated_texts=False, remove_filter_words=False, clean=False): <NEW_LINE> <INDENT> track = track.lower() <NEW_LINE> if remove_encapsulated_texts: <NEW_LINE> <INDENT> for opening, closing in [['\\(', '\\)'], ['\\[', '\\]'], ["'", "'"], ['"', '"'], ['{', '}'], ['<', '>']]: <NEW_LINE> <I... | This function returns the track name as a string. Removes words, and which might impede finding the lyrics.
:type remove_encapsulated_texts: bool
When remove_encapsulated_texts is True an aggressive regex is used which removes encapsulated substrings | 625941ec8e71fb1e9831dcb6 |
def sync(self): <NEW_LINE> <INDENT> with shelve.open("accounts", 'c') as shelf: <NEW_LINE> <INDENT> shelf[self.name] = self | Function to write the account to the shelf after modifying.
Call after user commands. | 625941ec4f6381625f114f4a |
def paint(self, painter, option, index): <NEW_LINE> <INDENT> if option.state & QStyle.State_Selected: <NEW_LINE> <INDENT> painter.fillRect(option.rect, qApp.palette().highlight()) <NEW_LINE> <DEDENT> super().paint(painter, option, index) | Paints selected items using the highlight brush. | 625941ecd8ef3951e3243a4d |
def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> W1, W2, b1, b2 = self.params['W1'], self.params['W2'], self.params['b1'], self.params['b2'] <NEW_LINE> hidden, hidden_cache = affine_relu_forward(X, W1, b1) <NEW_LINE> scores, out_cache = affine_forward(hidden, W2, b2) <NEW_LINE> if y is Non... | Compute loss and gradient for a minibatch of data.
Inputs:
- X: Array of input data of shape (N, d_1, ..., d_k)
- y: Array of labels, of shape (N,). y[i] gives the label for X[i].
Returns:
If y is None, then run a test-time forward pass of the model and return:
- scores: Array of shape (N, C) giving classification scor... | 625941ec656771135c3ebd84 |
def test_powerview_remove_resource_unassociated_resource(self): <NEW_LINE> <INDENT> sysadmin = Sysadmin() <NEW_LINE> r1 = Resource() <NEW_LINE> r2 = Resource() <NEW_LINE> powerview_dict = factories.PowerView(resources=[r1['id']]) <NEW_LINE> with nosetools.assert_raises(ValidationError): <NEW_LINE> <INDENT> toolkit.get_... | Calling powerview_remove_resource with an unassociated resource id
raises an error. | 625941ecbe7bc26dc91cdb05 |
def check_required_body_fields(json_data, required_fields): <NEW_LINE> <INDENT> log( 'Checking json data, {}, against required fields: {}'.format( json_data, required_fields ), 'debug' ) <NEW_LINE> keys = json_data.keys() <NEW_LINE> missing_keys = [] <NEW_LINE> for required_field in required_fields: <NEW_LINE> <INDENT>... | Checks for our required quote fields in the give jsonbody | 625941ec8c3a8732951588d0 |
def test_make_ok(self): <NEW_LINE> <INDENT> node = Node(PUBLIC_KEY, PRIVATE_KEY, self.event_loop, self.connector, self.reply_port) <NEW_LINE> result = node.make_ok(self.message) <NEW_LINE> self.assertIsInstance(result, OK) | Ensure an OK message is correctly constructed to be sent to the remote
peer. An OK is fire-and-forget. | 625941ecd268445f265b537e |
def export_header(data, reference): <NEW_LINE> <INDENT> return sorted(data[0], key=lambda i: reference.index(i)) | Return the column names ordered as they are found in the reference. | 625941ec63d6d428bbe44a00 |
def _run_upload(self, upload_dest, filepath): <NEW_LINE> <INDENT> threads = [] <NEW_LINE> for dest, dest_json in upload_dest.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> attr = { "api_key": dest_json.get('api_key'), "username": dest_json.get('username'), "domain": self.domain, "url": dest_json.get('url'), "por... | Create Forum object for uploading of recon results
Args:
filepath (String): Filepath of files to upload
boards (Dict): dictionary of given upload destination
Example:
{
"Mattermost":
{
"class_name" : "Mattermost",
... | 625941ec8a349b6b435e8682 |
def get_auth_header(self): <NEW_LINE> <INDENT> return {'Authorization': 'Token ' + self.token} | Return the toke in the header authorization format. | 625941ecd4950a0f3b08c857 |
def pc_work_time(self): <NEW_LINE> <INDENT> return _blocks_swig3.integrate_cc_sptr_pc_work_time(self) | pc_work_time(integrate_cc_sptr self) -> float | 625941ec97e22403b379d4ab |
def align_kallisto(kallisto_idx_dir, datadir, output): <NEW_LINE> <INDENT> if not os.path.exists(output): <NEW_LINE> <INDENT> os.makedirs(output) <NEW_LINE> <DEDENT> for i in range(49, 50, 1): <NEW_LINE> <INDENT> outdir = os.path.join(output, "SRR" + str(first_srr + i)) <NEW_LINE> if not os.path.exists(outdir): <NEW_LI... | The pipeline that aligns the _1 and _2 gene | 625941ec187af65679ca562f |
def test_deferredChild(self): <NEW_LINE> <INDENT> wrapped = CompressingResourceWrapper(TestDeferredResource()) <NEW_LINE> child, segments = self._locateChild(wrapped, ['foo']) <NEW_LINE> self.assertEqual(type(child.underlying), TestDeferredResource) <NEW_LINE> self.assertEqual(segments, []) | The wrapper should deal with a resource wrapped in a deferred returned
from locateChild. | 625941ece8904600ed9f2445 |
def scan_info(self, scan_id): <NEW_LINE> <INDENT> return self._request('GET', '/v0.1/scan/%s' % scan_id) | :param scan_id:
:return: | 625941ec3d592f4c4ed1d56f |
def deactivate(self): <NEW_LINE> <INDENT> if self._active: <NEW_LINE> <INDENT> self._active = False | Removes this unit from the active roster. | 625941ecbe7bc26dc91cdb06 |
def get_tagcloud(articles, offset=1): <NEW_LINE> <INDENT> def thresholds(mn, mx, steps=5): <NEW_LINE> <INDENT> mn = float(mn) <NEW_LINE> mx = float(mx) <NEW_LINE> th = [] <NEW_LINE> for x in range(steps-1): <NEW_LINE> <INDENT> th.append(mn + (1+x)*(mx-mn)/(steps)) <NEW_LINE> <DEDENT> th.append(mx) <NEW_LINE> return th ... | Get all tags from a set of articles | 625941ec76d4e153a657f042 |
def callback_before_collection_insert( self, custom, collection, doc_or_docs, manipulate=True, safe=None, check_keys=True, continue_on_error=False, **kwargs): <NEW_LINE> <INDENT> command = { 'db': collection.database.name, 'collection': collection.name, 'op': custom['f'], 'doc_or_docs': doc_or_docs, 'manipulate': manip... | Callback used with pymongo collection insert call | 625941eca4f1c619b28b053c |
def optimal_value(n_states, n_actions, transition_probabilities, reward, discount, threshold=1e-2): <NEW_LINE> <INDENT> v = np.zeros(n_states) <NEW_LINE> diff = float("inf") <NEW_LINE> while diff > threshold: <NEW_LINE> <INDENT> diff = 0 <NEW_LINE> for s in range(n_states): <NEW_LINE> <INDENT> max_v = float("-inf") <NE... | Find the optimal value function.
n_states: Number of states. int.
n_actions: Number of actions. int.
transition_probabilities: Function taking (state, action, state) to
transition probabilities.
reward: Vector of rewards for each state.
discount: MDP discount factor. float.
threshold: Convergence threshold, defaul... | 625941ecfbf16365ca6f66de |
def dom_to_dict(node, encoding='utf8', data=None, xlist=False): <NEW_LINE> <INDENT> if data == None: <NEW_LINE> <INDENT> data = {} <NEW_LINE> <DEDENT> if node.nodeType == node.DOCUMENT_NODE: <NEW_LINE> <INDENT> dom_to_dict(node.firstChild, encoding, data, xlist) <NEW_LINE> return data <NEW_LINE> <DEDENT> d = {} <NEW_LI... | 把minidom解析成dict
node minidom当前节点
encoding 输出dict的字符集
data dict的当前节点
xlist 重复的xpath合并成list | 625941ec73bcbd0ca4b2c585 |
def getFax(self): <NEW_LINE> <INDENT> pass | Avatar fax | 625941ecbaa26c4b54cb162a |
@click.command("delete", cls=FandoghCommand) <NEW_LINE> @click.option('--name', '-n', 'secret_name', help='name of the secret to delete', prompt='Name for the secret') <NEW_LINE> def delete(secret_name): <NEW_LINE> <INDENT> if click.confirm("You are about to delete a secret named '{}', you cannot undo this action. Are ... | Delete a secret by name | 625941eccc0a2c11143dd3a1 |
def release_allocation(self, alloc): <NEW_LINE> <INDENT> if alloc: <NEW_LINE> <INDENT> if alloc not in self._active_allocations: <NEW_LINE> <INDENT> raise InvalidAllocation() <NEW_LINE> <DEDENT> self._active_allocations.remove(alloc) <NEW_LINE> alloc.release() | Release resources assigned for the specificated allocation.
Args:
alloc (Allocation): allocation to release
Raises:
InvalidAllocation: when the allocation is not registered in the scheduler (it
might be released earlier) | 625941ec24f1403a92601071 |
def delete_tag_using_delete(self, tag_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.delete_tag_using_delete_with_http_info(tag_id, **kwargs) | Delete a tag # noqa: E501
Use this resource to delete the tag. <a href="../../news/2018-09-24-tagi-zalaczniki/#UsunTagZKonta" target="_blank">Read more</a>. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_t... | 625941ec009cb60464c638bd |
def tanh(x): <NEW_LINE> <INDENT> return np.tanh(x) | The tanh activation function. | 625941ec30c21e258bdfa9b3 |
@u.wraps(u.cm, [u.m**3/u.s, u.m, None, u.degK, u.m], False) <NEW_LINE> def width_HS_min(q_plant, hl, Gt, T, depth_end): <NEW_LINE> <INDENT> nu = pc.viscosity_kinematic(T).magnitude <NEW_LINE> w = con.RATIO_HS_MIN*((K_e/(2 * depth_end * (G_avg(hl, Gt, T).magnitude**2) * nu))**(1/3))*q_plant/depth_end <NEW_LINE> return w | Return the minimum channel width required to achieve H/S > 3.
The channel can be wider than this, but this is the absolute minimum width
for a channel. The minimum width occurs when there is only one expansion per
baffle and thus the distance between expansions is the same as the depth of
water at the end of the flocc... | 625941ec5f7d997b87174fac |
def get_entity(self, entity): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.session.entities[entity] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if isinstance(entity, int) or ( isinstance(entity, TLObject) and type(entity).SUBCLASS_OF_ID in (0xc91c90b6, 0x2d45687)): <NEW... | Turns the given entity into a valid Telegram user or chat.
:param entity:
The entity to be transformed.
If it's a string which can be converted to an integer or starts
with '+' it will be resolved as if it were a phone number.
If it doesn't start with '+' or starts with a '@' it will be
be resolve... | 625941ecec188e330fd5aca4 |
def save_mappings(id_to_word, id_to_tag, mappings_path): <NEW_LINE> <INDENT> with open(mappings_path, 'wb') as f: <NEW_LINE> <INDENT> mappings = { 'id_to_word': id_to_word, 'id_to_tag': id_to_tag, } <NEW_LINE> cPickle.dump(mappings, f) | We need to save the mappings if we want to use the model later. | 625941ec63f4b57ef000161a |
@app.route('/') <NEW_LINE> def home(): <NEW_LINE> <INDENT> favicon = 'static\images\logo.ico' <NEW_LINE> get_news(False) <NEW_LINE> get_weather(False) <NEW_LINE> get_covid_data(False) <NEW_LINE> title = "Smart Alarm Clock" <NEW_LINE> alarm_list = get_alarms() <NEW_LINE> notification_list = update_notifications() <NEW_L... | This function is responsible for fetching a list of alarms, current
weather, latest news and lates covid data. This data is
fetched to be displayed on the main page.
Whenever the html page refreshes news , weather and covid information
is also fetched. | 625941ec21a7993f00bc8209 |
def test_multi_diff_rosws_outside(self): <NEW_LINE> <INDENT> cmd = ["rosws", "diff", "-t", "ws"] <NEW_LINE> os.chdir(self.test_root_path) <NEW_LINE> sys.stdout = output = StringIO() <NEW_LINE> rosws_main(cmd) <NEW_LINE> sys.stdout = sys.__stdout__ <NEW_LINE> output = output.getvalue() <NEW_LINE> self.check_diff_output(... | Test rosws diff output from outside workspace.
In particular asserts that there are newlines between diffs, and no overlaps | 625941ecbe8e80087fb2114a |
def shutdown_plugin(self): <NEW_LINE> <INDENT> pass | Callback function when shutdown is requested | 625941ec24f1403a92601072 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.