code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def uploadAudio(self, file, artist='VK Advanced API', title='Sound uploaded via vk_advanced_api'): <NEW_LINE> <INDENT> if self.token_type == 'group': <NEW_LINE> <INDENT> return 'Данный метод не доступен для токена сообществ.' <NEW_LINE> <DEDENT> url = self.api.audio.getUploadServer() <NEW_LINE> url['upload_url'] = re.s... | Загрузка аудиозаписей
:param file: - Имя файла для загрузки
:param artist: - Названия исполнителя трека
:param title: - Название трека
:return: audio<owner_id>_<id> | 625941f2d18da76e23532abd |
def calc_corr_factor_sasha(calc_corr_factor_sasha_common_lines): <NEW_LINE> <INDENT> weights = [] <NEW_LINE> weighted_ki = 0. <NEW_LINE> total_weight = 0. <NEW_LINE> for line in calc_corr_factor_sasha_common_lines: <NEW_LINE> <INDENT> ki = line[2] <NEW_LINE> aln_line = line[0] <NEW_LINE> cln_line = line[1] <NEW_LINE> c... | Returns the weighted average of delta sigma over sigma for all good,
common lines. This correction factor is weighted against SNR of the
lines | 625941f28e7ae83300e4b5ae |
def addSuccess(self, test): <NEW_LINE> <INDENT> self.stats["successes"] += 1 | Duplicates parent class addSuccess functionality.
:param test: The test that was run
:type test: :class:`syntribos.tests.base.BaseTestCase` | 625941f2046cf37aa974d321 |
def add_device_error(self, err): <NEW_LINE> <INDENT> self.logger.error("Error creating device: {0}".format(err)) <NEW_LINE> return err | Callback for errors returned when creating device server factory.
:param err: Error object
:return: | 625941f2796e427e537b0bab |
def toggle_fuzzy(self): <NEW_LINE> <INDENT> log.debug('Toggling fuzzy completion.') <NEW_LINE> self._fuzzy = not self._fuzzy <NEW_LINE> self._profile_completer.enable_fuzzy = to_filter(self._fuzzy) <NEW_LINE> self._region_completer.enable_fuzzy = to_filter(self._fuzzy) <NEW_LINE> self._cache_completer.enable_fuzzy = to... | Toggle the fuzzy completions on/off for all of the relevant
subcompleters. The QueryCompleter and NestedCompleter do not
support fuzzy completions. | 625941f2498bea3a759ba08d |
def getWeekdaysNames(self): <NEW_LINE> <INDENT> pass | Get names of days
| 625941f2566aa707497f4b40 |
def get_norm_volume(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> process1 = subprocess.Popen([path.get_tools_path('intern-ffmpeg'), '-loglevel', 'quiet', '-i', filename, '-f', 'sox', '-'], stdout=subprocess.PIPE) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> return "1.0", "FFMPEG wurde nicht ... | Gets the volume correction of a movie using ffmpeg and sox.
Returns without error:
norm_vol, None
with error:
1.0, error_message | 625941f230c21e258bdfaa84 |
def load_from_json_file(filename): <NEW_LINE> <INDENT> import json <NEW_LINE> with open(filename, 'r') as file: <NEW_LINE> <INDENT> new_obj = json.load(file) <NEW_LINE> <DEDENT> return new_obj | Reads and loads a JSON file | 625941f2b545ff76a89143f5 |
def _build_workflow(self): <NEW_LINE> <INDENT> workflow = { "apiVersion": "argoproj.io/v1alpha1", "kind": "Workflow", "metadata": { "name": self.name, "namespace": self.namespace, "labels": argo_build_util.add_dicts([{ "workflow": self.name, "workflow_template": TEMPLATE_LABEL, }, argo_build_util.get_prow_labels()]), }... | Create the scaffolding for the Argo workflow | 625941f296565a6dacc8fca9 |
def get(self, request, page): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> orders = OrderInfo.objects.filter(user=user).order_by('-create_time') <NEW_LINE> for order in orders: <NEW_LINE> <INDENT> order_skus = OrderGoods.objects.filter(order_id=order.order_id) <NEW_LINE> for order_sku in order_skus: <NEW_LINE> <I... | 显示 | 625941f24f6381625f11501a |
def happycat(self, x, alpha=1. / 8): <NEW_LINE> <INDENT> s = sum(x**2) <NEW_LINE> return ((s - len(x))**2)**alpha + (s / 2 + sum(x)) / len(x) + 0.5 | a difficult sharp ridge type function.
Proposed by HG Beyer. | 625941f28e7ae83300e4b5af |
def test_user_exists(self): <NEW_LINE> <INDENT> UserFactory(username='test_user', email='test_user@example.com') <NEW_LINE> assert user_exists({'username': 'test_user', 'email': 'test_user@example.com'}) <NEW_LINE> assert user_exists({'username': 'test_user'}) <NEW_LINE> assert user_exists({'email': 'test_user@example.... | Verify that user_exists function returns correct response. | 625941f297e22403b379d57c |
def test_011(self): <NEW_LINE> <INDENT> self.my_order_page.click_order_one() <NEW_LINE> self.assertTrue(self.order_details_page.assert_cx_life(), msg="没有进入订单详情页") | 查看订单详情 | 625941f2507cdc57c63072c9 |
def coerce_boolean(value): <NEW_LINE> <INDENT> if is_string(value): <NEW_LINE> <INDENT> normalized = value.strip().lower() <NEW_LINE> if normalized in ('1', 'yes', 'true', 'on'): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif normalized in ('0', 'no', 'false', 'off', ''): <NEW_LINE> <INDENT> return False <NEW... | Coerce any value to a boolean.
:param value: Any Python value. If the value is a string:
- The strings '1', 'yes', 'true' and 'on' are coerced to :data:`True`.
- The strings '0', 'no', 'false' and 'off' are coerced to :data:`False`.
- Other strings raise an exception.
... | 625941f263d6d428bbe44ad1 |
def PrintNewLine(self): <NEW_LINE> <INDENT> raise NotImplementedError | Adds a new or blank line to the output. | 625941f28e05c05ec3eea95a |
def __init__(self, userid, userkey, mediaid): <NEW_LINE> <INDENT> super(ProcessMedia, self).__init__(userid, userkey, mediaid) | start encoding of previously downloaded media (one that added with AddMediaBenchmark action)
:param mediaid: A unique identifier for the media to be processed | 625941f2e8904600ed9f2517 |
def recv(self, byte=4096): <NEW_LINE> <INDENT> ret = self.ser.read(size=byte) <NEW_LINE> return ret | Receive the response of the device.
Note:
This method override the "recv" in the base class.
Args:
byte (int): Bytes to read. Defaults to 4096.
Return:
ret (bytes): The response of the device. | 625941f2099cdd3c635f1238 |
def convert(self, s, numRows): <NEW_LINE> <INDENT> if numRows == 1: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> cycle = 2 * numRows - 2 <NEW_LINE> n = len(s) <NEW_LINE> res = [] <NEW_LINE> for i in range (numRows): <NEW_LINE> <INDENT> for j in range (0, n, cycle): <NEW_LINE> <INDENT> if j + i >= n: <NEW_LINE> <IND... | :type s: str
:type numRows: int
:rtype: str | 625941f27b25080760e39a35 |
def inv(s: npy.ndarray) -> npy.ndarray: <NEW_LINE> <INDENT> t = s2t(s) <NEW_LINE> tinv = npy.linalg.inv(t) <NEW_LINE> sinv = t2s(tinv) <NEW_LINE> return sinv | Calculates 'inverse' s-parameter matrix, used for de-embedding
This is not literally the inverse of the s-parameter matrix.
Instead, it is defined such that the inverse of the s-matrix cascaded
with itself is a unity scattering transfer parameter (T) matrix.
.. math::
inv(s) = t2s({s2t(s)}^{-1})
where :math... | 625941f2f548e778e58cdb60 |
def test_tag_str(self): <NEW_LINE> <INDENT> tag = models.Tag.objects.create( user=sample_user(), name="Barbecue" ) <NEW_LINE> self.assertEqual(str(tag), tag.name) | test the tag string representional | 625941f27d847024c06be8a1 |
def test_OpenFF(self): <NEW_LINE> <INDENT> OpenFF(self.molecule) <NEW_LINE> self.assertEqual(len(self.molecule.HarmonicBondForce), len(list(self.molecule.topology.edges))) <NEW_LINE> self.assertEqual(len(self.molecule.HarmonicAngleForce), len(self.molecule.angles)) <NEW_LINE> self.assertEqual(len(self.molecule.Periodic... | Parametrise with OpenFF and ensure parameters have all been assigned. | 625941f24d74a7450ccd47a5 |
def get_person_age(name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> name = name.lower() <NEW_LINE> value = ChainMap(group3, group2, group1).get(name) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return NOT_FOUND <NEW_LINE> <DEDENT> return value | Look up name (case insensitive search) and return age.
If name in > 1 dict, return the match of the group with
greatest N (so group3 > group2 > group1) | 625941f27c178a314d6efa4a |
def unregister_hierarchy_users(self, users, timeout=5): <NEW_LINE> <INDENT> if not isinstance(users, list): <NEW_LINE> <INDENT> raise TypeError('users must be an instance of {0}'.format(list)) <NEW_LINE> <DEDENT> for user in users: <NEW_LINE> <INDENT> if not isinstance(user, HierarchyUser): <NEW_LINE> <INDENT> raise Ty... | The unregister_hierarchy_users method unregisters the user
completely from the hierarchy and deletes the account. All set
privileges are revoked.
:param users: The users whose privileges to unregister
:param timeout: Number of seconds requests will wait to
establish a connection and to receive a response
:return: A Hi... | 625941f255399d3f05588c98 |
def getStartParameters(self): <NEW_LINE> <INDENT> post = {} <NEW_LINE> post['size'] = self._getShiftMagnitude() <NEW_LINE> post['type'] = self._getShiftDirection() <NEW_LINE> return post | Return the parameters for the start of this spanners required by MusicXML output.
>>> from music21 import *
>>> os = spanner.Ottava(type='15mb')
>>> os.getStartParameters()
{'type': 'up', 'size': 15}
>>> os.getEndParameters()
{'type': 'stop', 'size': 15} | 625941f24d74a7450ccd47a6 |
def displayFrames(self, playback_speed=20, dynamic_colorbar=True, figsize=(10, 8)): <NEW_LINE> <INDENT> fig, ax = plt.subplots(figsize=figsize) <NEW_LINE> shape = (self.file.attrs['resX'], self.file.attrs['resY']) <NEW_LINE> data = np.random.rand(*shape) <NEW_LINE> im = ax.imshow(data, cmap='jet', animated=True, vmin=0... | Produces an animated display of the simulation.
Arguments:
playback_speed: An integer that determines the delay inbetween two frames.
dynamic_colorbar: A boolean that determines whether the range of the colorbar changes dynamically.
figsize: A 2-tuple of integers that determines the size of the display. | 625941f2dd821e528d63b784 |
def run(self): <NEW_LINE> <INDENT> m_args = self.module.params <NEW_LINE> exclude_ips = [] <NEW_LINE> ip_list = m_args['exclude_ips'] <NEW_LINE> for ip in ip_list: <NEW_LINE> <INDENT> exclude_ips.append(IPAddress(ip)) <NEW_LINE> <DEDENT> self.generate_ips(m_args['num'], m_args['prefix'], exclude_ips) <NEW_LINE> self.mo... | Main method of the class | 625941f2a8370b7717052e7d |
def assert_str(a, b): <NEW_LINE> <INDENT> def clean(x): <NEW_LINE> <INDENT> x = str(x) <NEW_LINE> x = x.replace("u'", "'") <NEW_LINE> x = x.replace("lepl.matchers.error.Error", "Error") <NEW_LINE> x = x.replace("lepl.stream.maxdepth.FullFirstMatchException", "FullFirstMatchException") <NEW_LINE> x = sub('<(.+) 0x[0-9a-... | Assert two strings are approximately equal, allowing tests to run in
Python 3 and 2. | 625941f2442bda511e8be9f0 |
def testProcess(self): <NEW_LINE> <INDENT> test_file = self._GetTestFilePath(['History']) <NEW_LINE> cache = sqlite.SQLiteCache() <NEW_LINE> event_queue_consumer = self._ParseDatabaseFileWithPlugin( self._plugin, test_file, cache) <NEW_LINE> event_objects = self._GetEventObjectsFromQueue(event_queue_consumer) <NEW_LINE... | Tests the Process function on a Chrome History database file. | 625941f276d4e153a657f112 |
def _convert_num_to_colname(num: int) -> str: <NEW_LINE> <INDENT> if num > 0: <NEW_LINE> <INDENT> num_of_letters = len(letters) <NEW_LINE> DIVMOD = divmod(num, num_of_letters) <NEW_LINE> if DIVMOD[0] == 0: <NEW_LINE> <INDENT> return letters[DIVMOD[1]-1] <NEW_LINE> <DEDENT> elif DIVMOD[1] == 0: <NEW_LINE> <INDENT> retur... | Converts positive integer into string representing corresponding column in A1 notation without sheet name
A1 notation: https://developers.google.com/sheets/api/guides/concepts#a1_notation
:param num: number to be converted
:return: name of the column in A1 notation, e.g. 'AAB' | 625941f2293b9510aa2c3870 |
def buildTables(self): <NEW_LINE> <INDENT> raise NotImplementedError | Compile OpenType feature tables from the source.
**This should not be called externally.** Subclasses
must override this method. | 625941f291f36d47f21acada |
def json_input(): <NEW_LINE> <INDENT> return json.load(sys.stdin) | returns decoded json read from stdin | 625941f2e5267d203edce275 |
def glob_ext(self): <NEW_LINE> <INDENT> if self.all_paths: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.path = self.path.glob_path_withext() <NEW_LINE> self.raw_rule = None | Change path to next possible glob with extension | 625941f232920d7e50b287b6 |
def request_vpc_peering_connection( requester_vpc_id, peer_vpc_id, name='', peer_owner_id=None, region=None, key=None, keyid=None, profile=None, dry_run=False): <NEW_LINE> <INDENT> conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) <NEW_LINE> if name and _vpc_peering_conn_id_for_name(name, conn): <... | Request a VPC peering connection between two VPCs.
:param requester_vpc_id: Your VPC's ID. String type.
:param peer_vpc_id: ID of the VPC tp crete VPC peering connection with.
This can be a VPC in another account. String type.
:param name: The name to use for this VPC peering connection. String type.
:param peer_owner_... | 625941f2656771135c3ebe56 |
def destroy_all_by_user(self, context, user_id, project_id): <NEW_LINE> <INDENT> db.quota_destroy_all_by_user(context, user_id, project_id) | Destroy all quotas, usages, and reservations associated with a
user.
:param context: The request context, for access checks.
:param user_id: The ID of the user being deleted.
:param project_id: The ID of the project being deleted. | 625941f244b2445a33932672 |
def test_repr(mock_session): <NEW_LINE> <INDENT> response = CachedResponse.from_response(mock_session.get(MOCKED_URL)) <NEW_LINE> expected_values = ['GET', MOCKED_URL, 200, 'ISO-8859-1', response.headers] <NEW_LINE> print(repr(response)) <NEW_LINE> assert repr(response).startswith('CachedResponse(') and repr(response).... | Just ensure that a subset of relevant attrs get included in the response repr | 625941f2cc0a2c11143dd472 |
def generateForwardDISET(self): <NEW_LINE> <INDENT> result = self.commit() <NEW_LINE> commitOp = None <NEW_LINE> if not result['OK']: <NEW_LINE> <INDENT> commitOp = Operation() <NEW_LINE> commitOp.Type = 'SetFileStatus' <NEW_LINE> commitOp.Arguments = DEncode.encode({'transformation': self.transformation, 'statusDict':... | Commit the accumulated records and generate request eventually
| 625941f28c3a8732951589a3 |
def test_update_nonexistent_group(self): <NEW_LINE> <INDENT> builder = DummyBuilder() <NEW_LINE> builder.add_group('test', a=1, b=2) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> builder.update_group('nottest', b=3, c=4) <NEW_LINE> <DEDENT> self.assertDictEqual(builder.group_configs, {'test': dict(... | Tests updating an non-existing group. | 625941f256b00c62f0f14c3e |
def get_srv_keyspace(self, keyspace): <NEW_LINE> <INDENT> raise NotImplemented('Child class needs to implement this') | Returns a SrvKeyspace object.
Args:
keyspace: name of the keyspace to retrieve.
Returns:
srv_keyspace: a keyspace.Keyspace object.
Raises:
TBD | 625941f24e4d5625662d49af |
def __call__(self): <NEW_LINE> <INDENT> history_ids = filter(bool, self.filtered_history_ids()) <NEW_LINE> logger.info('Got %s ids to purge' % len(history_ids)) <NEW_LINE> if not history_ids: <NEW_LINE> <INDENT> return 'No ids' <NEW_LINE> <DEDENT> for history_id in history_ids: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDE... | Not to be done like this
| 625941f266656f66f7cbc78d |
def validate_error_navigation( self, task_name, expected_result=None, summary_message=None): <NEW_LINE> <INDENT> self.navigate_to_entity() <NEW_LINE> self.click(locators['dashboard.lwe_task.name'] % task_name) <NEW_LINE> if self.wait_until_element(locators['task.selected.id']) is None: <NEW_LINE> <INDENT> raise UIError... | Find specific task on Latest Warning/Error Tasks widget and then
click on it. After application navigate on expected task details page,
check whether correct result information and error message is displayed
in summary section | 625941f2c4546d3d9de7301a |
def datafile(filename): <NEW_LINE> <INDENT> return os.path.join(testdata_dir, filename) | prepend testdata_dir to filename
| 625941f20a50d4780f667478 |
def filter_dict(self, key="", value_query=""): <NEW_LINE> <INDENT> if not key: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> r = re.compile(r"%s" % value_query, re.IGNORECASE) <NEW_LINE> def _filter(d): <NEW_LINE> <INDENT> ret = None <NEW_LINE> v = d.get(key, "") <NEW_LINE> if r.search(v): <NEW_LINE> <INDENT> ret... | 辞書型のkeyバリューがqueryに合致すればそれを返却する関数を返却
Arguments:
key {str} -- 該当するキー
value_query {str} -- 比較用の文字列
Returns:
function -- 辞書型オブジェクトを引数にとり、一致した場合にそれを返却する | 625941f2de87d2750b86037a |
def append(self, val): <NEW_LINE> <INDENT> new_node = Node(val) <NEW_LINE> if len(self) == 0: <NEW_LINE> <INDENT> self.tail_node = new_node <NEW_LINE> self.head_node = new_node <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tail_node.next_node = new_node <NEW_LINE> new_node.previous_node = self.tail_node <NEW_LINE>... | Insert a new node to the tail of a doubly linked list. | 625941f25f7d997b8717507e |
def is_elapsed_secs(self, duration_secs): <NEW_LINE> <INDENT> return duration_secs is not None and self.value_secs >= duration_secs | Returns True if this timer has measured at least ``duration_secs`` seconds.
Otherwise, returns False. If ``duration_secs`` is None, returns False. | 625941f2d164cc617578332f |
def request_naver_endic_url(naver_endic_url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = requests.get(naver_endic_url) <NEW_LINE> <DEDENT> except requests.ConnectionError: <NEW_LINE> <INDENT> raise NdicConnectionError() <NEW_LINE> <DEDENT> return response | Send a GET request to NAVER dictionary url | 625941f2596a89723608a099 |
def to_utf8(match): <NEW_LINE> <INDENT> return unichr(long(match.group(1))) | convert to utf-8 | 625941f2091ae35668667535 |
def test_desc(self, elem): <NEW_LINE> <INDENT> des = elem.describe() <NEW_LINE> assert isinstance(des, OrderedDict) <NEW_LINE> assert len(des) > 0 | every elements should return a Ordered Dict for description | 625941f2b57a9660fec33e6d |
def GetLayerCount(self): <NEW_LINE> <INDENT> pass | Get the layer count.
return : The layer count. | 625941f2d8ef3951e3243b1e |
def gen(x, name): <NEW_LINE> <INDENT> y = special.logit(x) <NEW_LINE> data = { "x": x.tolist(), "expected": y.tolist() } <NEW_LINE> filepath = os.path.join(DIR, name) <NEW_LINE> with open(filepath, 'w') as outfile: <NEW_LINE> <INDENT> json.dump(data, outfile) | Generates fixture data and writes them to file.
# Arguments
* `x`: domain
* `name::str`: output filename
# Examples
``` python
python> x = linspace(0.0, 1.0, 2001);
python> gen(x, "./data.json");
``` | 625941f215fb5d323cde10fa |
def test10_copy_link_to_file(self): <NEW_LINE> <INDENT> h5fname2 = tempfile.mktemp(".h5") <NEW_LINE> try: <NEW_LINE> <INDENT> with tables.open_file(h5fname2, "a") as h5file2: <NEW_LINE> <INDENT> h5file2.create_array('/', 'arr1', [1, 2]) <NEW_LINE> h5file2.create_group('/', 'group1') <NEW_LINE> lgroup1 = self.h5file.roo... | Checking copying a link to another file. | 625941f2cad5886f8bd275b9 |
def add(self, widget, session_name): <NEW_LINE> <INDENT> QtGui.QStackedWidget.addWidget(self, widget) <NEW_LINE> LOGGER.debug("added widget %s for session %s"% (widget, session_name)) | the addTab method | 625941f27d847024c06be8a2 |
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): <NEW_LINE> <INDENT> host, port = address <NEW_LINE> err = None <NEW_LINE> for res in getaddrinfo(host, port, 0, SOCK_STREAM): <NEW_LINE> <INDENT> af, socktype, proto, canonname, sa = res <NEW_LINE> sock = None <NEW_LINE> try: <NEW_LIN... | Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default ... | 625941f2cb5e8a47e48b8080 |
def write_output(args, out_epsg, out_folder): <NEW_LINE> <INDENT> if not "filter_bbox" in args["filter_bbox"]: <NEW_LINE> <INDENT> bands = ["B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08", "B09", "B10", "B11", "B12", "TCI"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bands = args["filter_bbox"]["bands"] <NEW_L... | Writes output's metadata to file | 625941f2bd1bec0571d90c10 |
def find_feed_forward_layers(inputs, connections): <NEW_LINE> <INDENT> layers = [] <NEW_LINE> prev_nodes = set(inputs) <NEW_LINE> prev_nodes.add(0) <NEW_LINE> while 1: <NEW_LINE> <INDENT> candidate_set = set(b for (a, b) in connections if a in prev_nodes and b not in prev_nodes) <NEW_LINE> keeper_set = set() <NEW_LINE>... | Collect the layers whose members can be evaluated in parallel in a feed-forward network.
Adapted from: https://github.com/CodeReclaimers/neat-python, accessed May 2016
:param inputs: list of the network input nodes
:param connections: list of (input, output) connections in the network.
Returns a list of layers, with e... | 625941f2d164cc6175783330 |
def nexson_source_path(self, filename=None): <NEW_LINE> <INDENT> if filename is None: <NEW_LINE> <INDENT> filename = "" <NEW_LINE> <DEDENT> return os.path.join(self.tests_data_dir, "nexson", filename) | Returns the fullpath for testing a NexSON in `filename`. | 625941f2e1aae11d1e74a29e |
def __init__(self, event_class): <NEW_LINE> <INDENT> if not isinstance(event_class, EventClass): <NEW_LINE> <INDENT> raise TypeError("Invalid event_class argument.") <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self._e = event_class._ec() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError("Event creation ... | Creates an event linked with the :class:`EventClass`
*event_class*.
:exc:`ValueError` is raised on error. | 625941f221bff66bcd684f2e |
def onSourceAfterFaint(**bvalues): <NEW_LINE> <INDENT> pass | function (length, target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({ spa: length }, source, source, this.dex.abilities.get('grimneigh'));
}
} | 625941f24c3428357757c905 |
def __init__(self,name,age): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.age = age <NEW_LINE> global COUNT <NEW_LINE> COUNT +=1 | Creates student objects and keeps a running total. | 625941f26e29344779a62bf2 |
def __init__(self): <NEW_LINE> <INDENT> self.Definition = None | :param Definition: 采样截图模板唯一标识。
:type Definition: int | 625941f2ec188e330fd5ad73 |
def parse_args(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='PyCC Compiler') <NEW_LINE> common.register_arguments(parser) <NEW_LINE> return parser.parse_args() | Get user input. | 625941f221a7993f00bc82dc |
@transform((buildCpGComposition, buildReferenceCpGComposition), suffix(".tsv.gz"), ".composition.load") <NEW_LINE> def loadCpGComposition(infile, outfile): <NEW_LINE> <INDENT> P.load(infile, outfile) | Load CpG genomic composition data into database
as table genomic.covered.composition
Parameters
----------
infile: tuple
filenames of CpG composition of regions covered by reads (infile[0])
and permuted reference version (infile[1])
outfile: str
filename of database loading logfile. | 625941f2293b9510aa2c3871 |
@set_module("numpy.char") <NEW_LINE> def asarray(obj, itemsize=None, unicode=None, order=None): <NEW_LINE> <INDENT> return array(obj, itemsize, copy=False, unicode=unicode, order=order) | Convert the input to a `chararray`, copying the data only if
necessary.
Versus a regular NumPy array of type `str` or `unicode`, this
class adds the following functionality:
1) values automatically have whitespace removed from the end
when indexed
2) comparison operators automatically remove whitespace from... | 625941f230bbd722463cc3aa |
def list_security_groups(self, **params): <NEW_LINE> <INDENT> url = 'os-security-groups' <NEW_LINE> if params: <NEW_LINE> <INDENT> url += '?%s' % urllib.urlencode(params) <NEW_LINE> <DEDENT> resp, body = self.get(url) <NEW_LINE> body = json.loads(body) <NEW_LINE> self.validate_response(schema.list_security_groups, resp... | List all security groups for a user. | 625941f2a934411ee3751c76 |
@app.route('/pets', methods=("POST","GET")) <NEW_LINE> def search(): <NEW_LINE> <INDENT> form = Search() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <INDENT> search = form.name.data <NEW_LINE> pets = Pet.query.filter(Pet.name.like('%'+search+'%')) <NEW_LINE> return render_template('search_results.html', pets=pe... | The search by name return page the lists pets with the searched name | 625941f263d6d428bbe44ad2 |
def insert_sequence(dna1,dna2,index): <NEW_LINE> <INDENT> return dna1[:index]+dna2+dna1[index:] | (str, str, int) -> str
Return the dna sequence by adding the second dna sequence in the first dna sequence at the given index.
>>>insert_sequence("ACTGGGAC", "GG",2)
"ACGGTGGGAC"
| 625941f20a366e3fb873ee01 |
def getVisible(self, hidden_data): <NEW_LINE> <INDENT> num_examples = hidden_data.shape[0] <NEW_LINE> visible_states = np.ones((num_examples, self.num_visible + 1)) <NEW_LINE> hidden_data = np.insert(hidden_data, 0, 1, axis=1) <NEW_LINE> visible_activations = np.dot(hidden_data, self.weights.T) <NEW_LINE> visible_probs... | 根据隐藏层得到输入层
hidden_data是一个matrix,每行代表一个样本 | 625941f266673b3332b92672 |
def p_repeat_init_declarator(p): <NEW_LINE> <INDENT> if(len(p) == 2): <NEW_LINE> <INDENT> p[0] = p[1] | repeat_init_declarator : init_declarator
| repeat_init_declarator init_declarator | 625941f210dbd63aa1bd3183 |
def extended_gcd(p, q): <NEW_LINE> <INDENT> (a, b) = (p, q) <NEW_LINE> if a < 0: <NEW_LINE> <INDENT> a = -1 * a <NEW_LINE> <DEDENT> if b < 0: <NEW_LINE> <INDENT> b = -1 * b <NEW_LINE> <DEDENT> x0 = 0 <NEW_LINE> y1 = 0 <NEW_LINE> x1 = 1 <NEW_LINE> y0 = 1 <NEW_LINE> while(b != 0): <NEW_LINE> <INDENT> quotient = a // b <N... | Find the greatest common divisor and returns them.
:param a: An integer.
:param b: An integer.
:rtype: A tuple representing the greatest common divisor. | 625941f2d7e4931a7ee9e501 |
def update(self, loc_name, new_name=None, users=None, proxies=None, subnets=None, resources=None, medias=None, templates=None, domains=None, envs=None, hostgroups=None, organizations=None, new_organizations=None, new_users=None, new_proxies=None, new_subnets=None, new_resources=None, new_medias=None, new_templates=None... | Update Location in UI. | 625941f294891a1f4081c08d |
def __init__(self, max_length): <NEW_LINE> <INDENT> self.head = None <NEW_LINE> self.length = 0 <NEW_LINE> self.max_length = max_length | Initialize a linked list with fixed length.
Args:
length(int): the fixed maximum length of the linked list. | 625941f26fb2d068a760f688 |
def __init__(self, app, portName): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.portName = portName <NEW_LINE> self.bOpen = False <NEW_LINE> self.serial = serial.Serial() | Constructor | 625941f245492302aab5e8ab |
def text_out(self): <NEW_LINE> <INDENT> return self.ans | Возвращает написанное игроком (так нагляднее) | 625941f22ae34c7f2600d711 |
def html(self, wrap=None, div_wrap=True, do_print=False, editing=False, publish=False): <NEW_LINE> <INDENT> return render_template( 'html/notebook/text_cell.html', cell=self, wrap=wrap, div_wrap=div_wrap, do_print=do_print, editing=editing, publish=publish) | Returns HTML code for this text cell, including its contents
and associated script elements.
INPUT:
- ``wrap`` -- an integer (default: None); number of columns to
wrap at (not used)
- ``div_wrap`` -- a boolean (default: True); whether to wrap
in a div (not used)
- ``do_print`` - a boolean (default: False); whet... | 625941f23eb6a72ae02ecacf |
def get_by_ids(self, ids): <NEW_LINE> <INDENT> result = ClientResult(self.context) <NEW_LINE> params = { "ids": ids } <NEW_LINE> qry = ServiceOperationQuery(self, "getByIds", params, None, None, result) <NEW_LINE> self.context.add_query(qry) <NEW_LINE> return result | Returns the directory objects specified in a list of IDs.
:type ids: list[str] | 625941f2236d856c2ad44dc5 |
def _cleanse(self): <NEW_LINE> <INDENT> self._keys = [] <NEW_LINE> self._values = [] <NEW_LINE> self._items = [] | Drops everything | 625941f2ad47b63b2c50a561 |
def __init__ (self, db_entry, manager=None): <NEW_LINE> <INDENT> self.db_entry = db_entry <NEW_LINE> self.year = db_entry.year <NEW_LINE> self.player_key = db_entry.player_key <NEW_LINE> self.name = db_entry.name <NEW_LINE> self.pos = db_entry.pos <NEW_LINE> self.club = db_entry.club <NEW_... | Create a new player from a FFDBPlayer object | 625941f20fa83653e4657598 |
def _anonymize_message(message, *format_args, **format_kwargs): <NEW_LINE> <INDENT> return message.format( *(value if (value == '' or isinstance(value, BaseException)) else ANONYMIZED_VALUE for value in format_args), **dict((key, value if (value == '' or isinstance(value, BaseException)) else ANONYMIZED_VALUE) for key,... | >>> _anonymize_message("hello")
'hello'
>>> _anonymize_message("hello: {}", "John")
'hello: <ANONYMIZED>'
>>> _anonymize_message("hello: {name}", name="John")
'hello: <ANONYMIZED>'
>>> _anonymize_message("exception: {}", SystemExit(1))
'exception: 1'
>>> _anonymize_message("exception: {exc}", exc=SystemExit(1))
'ex... | 625941f2e1aae11d1e74a29f |
def __init__(self, label, mass, position, velocity, prev_force=[0,0,0], current_force=[0,0,0]): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.label = str(label) <NEW_LINE> self.mass = float(mass) <NEW_LINE> self.position = array(position, dtype=np.float64) <NEW_LINE> self.velocity = array(velocity, dtype=np.float64... | This method creates the particle from input
:string label: The label wanted for the particle
:float mass: The mass wanted for the particle
:numpy array position: The initial position wanted for the particle
:numpy array velocity: The initial velocity wanted for the particle
:numpy array prev_force: previous force appli... | 625941f24f88993c3716c642 |
@press_title_bp.route('/', methods=['GET']) <NEW_LINE> @press_title_bp.route('/page/<int:page>', methods=['GET']) <NEW_LINE> @press_title_bp.route('/page/<int:page>/order_by/<string:order_by>/sort/<string:sort>', methods=['GET']) <NEW_LINE> def list(page=1, order_by='name', sort='asc'): <NEW_LINE> <INDENT> return CrudA... | List items | 625941f23346ee7daa2b3353 |
def expand_marker(idx, s, markers): <NEW_LINE> <INDENT> for m in markers: <NEW_LINE> <INDENT> if idx == m[2]: <NEW_LINE> <INDENT> return s[m[3]:m[3] + m[0]] * m[1], m[3] + m[0] | :param idx:
:param s:
:param markers:
:return: a new seq with expansion, next_pos to start copying again | 625941f2566aa707497f4b41 |
def process_results(self): <NEW_LINE> <INDENT> data = [] <NEW_LINE> results_dir = self.get_results_dir() <NEW_LINE> for datafile in os.listdir(results_dir): <NEW_LINE> <INDENT> path = os.path.join(results_dir, datafile) <NEW_LINE> with open(path) as f: <NEW_LINE> <INDENT> data.append(pickle.load(f)) <NEW_LINE> <DEDENT>... | Processes the data in the results dir and creates the data file
ready for plotting. | 625941f26aa9bd52df037389 |
def add(self, clearer): <NEW_LINE> <INDENT> assert isinstance(clearer, CacheClearerInterface); <NEW_LINE> self._clearers.append(clearer); | Adds a cache clearer to the aggregate.
@param CacheClearerInterface clearer | 625941f201c39578d7e7541d |
def createQ(self, state): <NEW_LINE> <INDENT> if self.learning: <NEW_LINE> <INDENT> if state in self.Q.keys(): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Q[state] = self.Q.get(state, {None:0.0, 'left':0.0, 'right':0.0, 'forward':0.0}) <NEW_LINE> <DEDENT> <DEDENT> return | The createQ function is called when a state is generated by the agent. | 625941f2498bea3a759ba08f |
def _cetp_policy_payload_validator(**kwargs): <NEW_LINE> <INDENT> kwargs['local_fqdn'] = "'" + str(kwargs['local_fqdn']) + "'" <NEW_LINE> kwargs['remote_fqdn'] = "'*'" if 'remote_fqdn' not in kwargs or not kwargs['remote_fqdn'] else "'" + str(kwargs['remote_fqdn']) + "'" <NEW_LINE> kwargs['payload_type'] = "'" + str(kw... | # Validate input bootstrap policy for bootstrap table. Put quotation marks at the ends to validate the policies to
insert in table. Also set Null value for empty fiels
:param kwargs: Dictionary of all the values received from user
:return: Either raise an error in case of validation failure or returns a dictionary | 625941f2cdde0d52a9e5361a |
def _restrict_children(self): <NEW_LINE> <INDENT> width = self._get_optimal_width() <NEW_LINE> for section in self.sections: <NEW_LINE> <INDENT> section.setMaximumWidth(width) <NEW_LINE> <DEDENT> self._restrict_recent_buttons(width) | Ensure each section is as wide as possible. | 625941f296565a6dacc8fcab |
def file_to_csv(fprefix, filename, file_path=None, file_fields=None): <NEW_LINE> <INDENT> version = get_latest_version(fprefix).lstrip('F') <NEW_LINE> if file_path is None: <NEW_LINE> <INDENT> file_path = os.path.join(get_download_dir(), fprefix, filename) <NEW_LINE> <DEDENT> if file_fields is None: <NEW_LINE> <INDENT>... | A file can have multiple record types. Output separate
CSV files for each one | 625941f28e05c05ec3eea95b |
def random_color_distort(img, brightness_delta=32, hue_vari=18, sat_vari=0.5, val_vari=0.5): <NEW_LINE> <INDENT> def random_hue(img_hsv, hue_vari, p=0.5): <NEW_LINE> <INDENT> if np.random.uniform(0, 1) > p: <NEW_LINE> <INDENT> hue_delta = np.random.randint(-hue_vari, hue_vari) <NEW_LINE> img_hsv[:, :, 0] = (img_hsv[:, ... | randomly distort image color. Adjust brightness, hue, saturation, value.
param:
img: a BGR uint8 format OpenCV image. HWC format. | 625941f2507cdc57c63072cb |
def pblm_textureFilterTypeIncorrect(): <NEW_LINE> <INDENT> global gTextureFilterType <NEW_LINE> return [tex for tex in mc.ls(type='file') if mc.getAttr(tex+'.filterType') != gTextureFilterType] | Texture Filter Type Incorrect | 625941f2d268445f265b5451 |
def plot_init(): <NEW_LINE> <INDENT> ax1 = plt.subplots()[1] <NEW_LINE> plt.title("KNN") <NEW_LINE> plt.xlabel("Density") <NEW_LINE> plt.ylabel("Sugar rate") <NEW_LINE> return ax1 | 初始化matplotlib | 625941f21b99ca400220b096 |
def update(self): <NEW_LINE> <INDENT> global foreground <NEW_LINE> if not Game.paused and not Game.over: <NEW_LINE> <INDENT> if self.alive: <NEW_LINE> <INDENT> if self.bottom < 0 or self.right < 0 or self.left > 1370: <NEW_LINE> <INDENT> self.destroy() <NEW_LINE> <DEDENT> if self.directionCount < 100: <NEW_LINE> <INDEN... | Update the sprite | 625941f250812a4eaa59c8fd |
def apply_filter(self, tweet, label): <NEW_LINE> <INDENT> raise NotImplementedError("Class %s doesn't implement " % (self.__class__.__name__,)) | Interface for tweet filtering by sentiment weights
:param tweet: input tweet, is converted to lowercase for filter
application
:param label: assumed label of the tweet
:return: True if the tweet passed the filter, False if not | 625941f2adb09d7d5db6cd6e |
def test_deny(self): <NEW_LINE> <INDENT> with override_settings(X_FRAME_OPTIONS='DENY'): <NEW_LINE> <INDENT> r = XFrameOptionsMiddleware(get_response_empty)(HttpRequest()) <NEW_LINE> self.assertEqual(r.headers['X-Frame-Options'], 'DENY') <NEW_LINE> <DEDENT> with override_settings(X_FRAME_OPTIONS='deny'): <NEW_LINE> <IN... | The X_FRAME_OPTIONS setting can be set to DENY to have the middleware
use that value for the HTTP header. | 625941f20a366e3fb873ee02 |
def __init__(self, name, load_headers=False, split_headers='space'): <NEW_LINE> <INDENT> self.load_headers = load_headers <NEW_LINE> self.filepath = os.path.abspath(name) <NEW_LINE> self.split_headers=split_headers <NEW_LINE> indexFile = self.filepath + '.pin' <NEW_LINE> sequenceFile = self.filepath + '.psq' <NEW_LINE>... | :param name: str
:param load_headers: bool
:return: self: BinaryBlast
Upon initialisation, this class reads index file and creates lists of header and sequence offsets.
If load_headers is set to true, it also loads complete offset by ID dictionary. It improves speed, but is
RAM-costly. Work only with protein DBs (.pin/... | 625941f2004d5f362079a910 |
def getSurveyReports(request): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> adminId = request.session.get('userId', None) <NEW_LINE> if adminId == None: <NEW_LINE> <INDENT> return render_to_response('Account/login.html') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user = User.objects.get(id = ... | Description:
Get all possible reports of a reported survey
Entry Parameters:
*surveyId: id of the reported survey
Result:
*survey_not_exist: "true" if the survey does not exist (Json)
*listReport = ["explanationMessage1", "explanationMessage2", ...] (Json) | 625941f2ac7a0e7691ed46a2 |
def load_algorithm_with_subdrivers_config( algo: str, all_drivers: List[str], driver_pos: int, config: Dict[str, str] ): <NEW_LINE> <INDENT> with suppress(KeyError): <NEW_LINE> <INDENT> key = (algo, tuple(all_drivers[driver_pos + 1 :])) <NEW_LINE> logger.debug("Try algo_base[%s]", key) <NEW_LINE> update = run_config.al... | Algorithm + sub-drivers config
example key: (SPEA2, () )
example key: (HGS, (SPEA2) )
example key: (IMGA, (HGS, SPEA2)) | 625941f2b545ff76a89143f8 |
def will_focus_out (self, *ignore): <NEW_LINE> <INDENT> self.commitValue() <NEW_LINE> self.dirty() <NEW_LINE> return Unknown | Called when the focus goes out the Entry.
Copies the shown value to the value property.
Do not call directly. | 625941f229b78933be1e5c87 |
def train(self): <NEW_LINE> <INDENT> for epoch in range(self.number_epoches): <NEW_LINE> <INDENT> self._run_one_epoch(epoch) <NEW_LINE> print() <NEW_LINE> <DEDENT> time_elapsed = time.time() - self.since <NEW_LINE> print(f'Training completed in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s') <NEW_LINE> print(f'Bes... | Trains for specified number of epoches.
After each epoch, runs a full validation step.
:return:
The best performing model and validation accuracy history | 625941f28c0ade5d55d3efa2 |
def get_webpage_output(webpage,output): <NEW_LINE> <INDENT> response = urllib2.urlopen(webpage) <NEW_LINE> html = response.read() <NEW_LINE> try: <NEW_LINE> <INDENT> soup = BeautifulSoup(html, 'html.parser') <NEW_LINE> for script in soup(["script", "style"]): <NEW_LINE> <INDENT> script.extract() <NEW_LINE> <DEDENT> tex... | This function takes in a URL and returns the body text contained in the processed URL
:param webpage: A URL
:return: Body of Text | 625941f2507cdc57c63072cc |
def finish_battle(self, city_id, request): <NEW_LINE> <INDENT> timer = Timer(city_id) <NEW_LINE> req = unit_pb2.UnitCheckLegendCityReq() <NEW_LINE> req.ParseFromString(request) <NEW_LINE> defer = DataBase().get_data(city_id) <NEW_LINE> defer.addCallback(self._calc_finish_battle, req, timer) <NEW_LINE> defer.addErrback(... | 结束战斗
| 625941f2925a0f43d254a45f |
def test_clean_address_invalid_ip_address_as_str(self): <NEW_LINE> <INDENT> for invalid_str in ( "", "address", "20018:db8::", "192.0.2.256", "192.0.2.0/24", "2001:db8::/32", ): <NEW_LINE> <INDENT> with self.subTest(invalid_str=invalid_str): <NEW_LINE> <INDENT> self.assertEqual( clean_address(invalid_str), None, ) | Test for invalid IP Addresses from str to None. | 625941f299cbb53fe67931c6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.