code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_story_titles_in_topic(topic): <NEW_LINE> <INDENT> canonical_story_references = topic.canonical_story_references <NEW_LINE> story_ids = [story.story_id for story in canonical_story_references] <NEW_LINE> stories = story_fetchers.get_stories_by_ids(story_ids) <NEW_LINE> story_titles = [story.title for story in st... | Returns titles of the stories present in the topic.
Args:
topic: Topic. The topic domain objects.
Returns:
list(str). The list of story titles in the topic. | 625941c0d53ae8145f87a1dd |
@add_arg_scope <NEW_LINE> def conv2d(name, x, output_channels, filter_size=None, stride=None, logscale_factor=3.0, init=True, apply_actnorm=True, conv_init="default"): <NEW_LINE> <INDENT> if init == "zeros" and apply_actnorm: <NEW_LINE> <INDENT> raise ValueError("apply_actnorm is unstable when init is set to zeros.") <... | conv2d layer with edge bias padding and optional actnorm.
Args:
name: variable scope.
x: 4-D Tensor of shape (NHWC)
output_channels: Number of output channels.
filter_size:
stride:
logscale_factor: see actnorm for parameter meaning.
init: Whether to apply data-dependent initialization Valid only if
... | 625941c0dd821e528d63b114 |
def __init__(self, parameters): <NEW_LINE> <INDENT> if 'AZURE_ACCOUNT_NAME' not in parameters: <NEW_LINE> <INDENT> raise BadConfigurationException("AZURE_ACCOUNT_NAME needs to be " + "specified") <NEW_LINE> <DEDENT> if 'AZURE_ACCOUNT_KEY' not in parameters: <NEW_LINE> <INDENT> raise BadConfigurationException("AZURE_ACC... | Creates a new AzureStorage object, with the account name and account key
and that the user has specified.
Args:
parameters: A dict that contains the credentials necessary to authenticate
with the Blob Storage.
Raises:
BadConfigurationException: If the account name or account key are not
specified. | 625941c015fb5d323cde0a76 |
def task_reader(self): <NEW_LINE> <INDENT> msg_dict = self.msg_temp() <NEW_LINE> code = msg_dict.get('code') <NEW_LINE> task_name = msg_dict.get('task_name') <NEW_LINE> make_file(task_name) <NEW_LINE> make_main_script(task_name, code) <NEW_LINE> pass | 拿到msg | 625941c01f037a2d8b946168 |
def getConfig(s=None, default=None): <NEW_LINE> <INDENT> readIfRequired() <NEW_LINE> if s is None: <NEW_LINE> <INDENT> return configs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return configs.get(s, default) | Get the dictionnary of configs. If a name is given, return the
object with this name if it exists.
reads if required. | 625941c0956e5f7376d70dd8 |
def grayCodeBacktracking(self, n): <NEW_LINE> <INDENT> res = [] <NEW_LINE> num = [0] <NEW_LINE> def backtrack(res, n, num): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> res.append(num[0]) <NEW_LINE> return <NEW_LINE> <DEDENT> backtrack(res, n-1, num) <NEW_LINE> num[0] = num[0] ^ (1 << (n-1)) <NEW_LINE> backtrack(... | :type n: int
:rtype: List[int] | 625941c0fff4ab517eb2f3a4 |
def scoreMotifs(motifs): <NEW_LINE> <INDENT> z = zip(*motifs) <NEW_LINE> totalscore = 0 <NEW_LINE> for string in z: <NEW_LINE> <INDENT> score = len(string)-max([string.count('A'),string.count('C'), string.count('G'), string.count('T')]) <NEW_LINE> totalscore += score <NEW_LINE> <DEDENT> return totalscore | This function computes the score of list of motifs | 625941c0167d2b6e31218aff |
def query_price(self, country_code, start, end, as_series=False): <NEW_LINE> <INDENT> domain = DOMAIN_MAPPINGS[country_code] <NEW_LINE> params = { 'documentType': 'A44', 'in_Domain': domain, 'out_Domain': domain } <NEW_LINE> response = self.base_request(params=params, start=start, end=end) <NEW_LINE> if response is Non... | Parameters
----------
country_code : str
start : pd.Timestamp
end : pd.Timestamp
as_series : bool
Default False
If True: Return the response as a Pandas Series
If False: Return the response as raw XML
Returns
-------
str | pd.Series | 625941c05fdd1c0f98dc019c |
def download_command_as_json(request, command_id): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> comm = CommandEntry.objects.filter(id=command_id).first() <NEW_LINE> json_response = {} <NEW_LINE> if comm: <NEW_LINE> <INDENT> json_response = comm.as_object() <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | Retrieves a command by id and generates a file to be downloaded | 625941c023849d37ff7b2ffa |
def get_available_audio_languages(): <NEW_LINE> <INDENT> call_args = { 'paths': [['spokenAudioLanguages', {'from': 0, 'to': 25}, ['id', 'name']]] } <NEW_LINE> response = common.make_call('path_request', call_args) <NEW_LINE> lang_list = {} <NEW_LINE> for lang_dict in itervalues(response.get('spokenAudioLanguages', {}))... | Get the list of available audio languages of videos | 625941c024f1403a92600ad2 |
@login_required <NEW_LINE> def order_details(request, order_id, template_name="registration/order_details.html"): <NEW_LINE> <INDENT> page_title = 'Order Details for Order #' + order_id <NEW_LINE> return render_to_response(template_name, locals(), context_instance=RequestContext(request)) | displays the details of a past customer order; order details can only be loaded by the same
user to whom the order instance belongs. | 625941c0498bea3a759b9a19 |
@connection <NEW_LINE> def send_release(): <NEW_LINE> <INDENT> return "<RELEASE>" | sending a release-signal so that the tvpaintplugin stops listening
So tvpaint can continue.. | 625941c056b00c62f0f145c2 |
def get_result_string(self, join = '\n'): <NEW_LINE> <INDENT> return join.join(self.last_result) | get_result_string(self) -> string
Gets the last result in a single string. | 625941c0a79ad161976cc0af |
@content_type('application/json; charset=utf-8') <NEW_LINE> def pretty_json(content, **kwargs): <NEW_LINE> <INDENT> return json(content, indent=4, separators=(',', ': '), **kwargs) | JSON (Javascript Serialized Object Notion) pretty printed and indented | 625941c010dbd63aa1bd2b0e |
def emit(self, record): <NEW_LINE> <INDENT> msg = self.format(record) <NEW_LINE> if not msg.startswith('\n') or msg.endswith('\n'): <NEW_LINE> <INDENT> msg += '\n' <NEW_LINE> <DEDENT> if (self.client is None) or (self.transport is None): <NEW_LINE> <INDENT> raise ScribeTransportError('No transport defined') <NEW_LINE> ... | Emit a record.
If a formatter is specified, it is used to format the record.
The record is then logged to Scribe with a trailing newline. | 625941c015baa723493c3edd |
def OnItemDrag(self,*args): <NEW_LINE> <INDENT> pass | OnItemDrag(self: TreeView,e: ItemDragEventArgs)
Raises the System.Windows.Forms.TreeView.ItemDrag event.
e: An System.Windows.Forms.ItemDragEventArgs that contains the event data. | 625941c0851cf427c661a47b |
def test_full_binary_tree(self): <NEW_LINE> <INDENT> self.root = BinaryNode(18) <NEW_LINE> self.root.left = BinaryNode(15) <NEW_LINE> self.root.right = BinaryNode(20) <NEW_LINE> self.root.left.left = BinaryNode(40) <NEW_LINE> self.root.left.right = BinaryNode(50) <NEW_LINE> self.root.right.left = BinaryNode(16) <NEW... | Full (Perfect) Binary Tree
Each node has exactly 0 or 2 children and all leaf nodes are on
the same level.
18
/ / / 15 20
/ \ / ... | 625941c0b57a9660fec337eb |
def failure_message(context): <NEW_LINE> <INDENT> pg = context.scene.pdt_pg <NEW_LINE> pg.error = f"{PDT_ERR_SEL_1_E_1_F}" <NEW_LINE> context.window_manager.popup_menu(oops, title="Error", icon="ERROR") | Warn to the user to select 1 edge and 1 face.
Args:
context: Blender bpy.context instance.
Returns:
Nothing. | 625941c0bde94217f3682d5d |
def unpack_float(self, offset): <NEW_LINE> <INDENT> o = self._offset + offset <NEW_LINE> try: <NEW_LINE> <INDENT> return struct.unpack_from("<f", self._buf, o)[0] <NEW_LINE> <DEDENT> except struct.error: <NEW_LINE> <INDENT> raise OverrunBufferException(o, len(self._buf)) | Returns a single-precision float (4 bytes) from
the relative offset. IEEE 754 format.
Arguments:
- `offset`: The relative offset from the start of the block.
Throws:
- `OverrunBufferException` | 625941c0435de62698dfdbb6 |
def test_wiki_samples(self): <NEW_LINE> <INDENT> grid = DataGrid(fields=[ ('ID', 'userId'), ('Name', 'displayName'), ('E-mail', 'emailAddress')]) <NEW_LINE> users = [User(1, 'john', '[email protected]'), User(2, 'fred', '[email protected]')] <NEW_LINE> output = grid.render(users) <NEW_LINE> assert '<td>2</td><td>Fred</td><td>fre... | Test that sample code on DataGridWidget wiki page actually works. | 625941c045492302aab5e22b |
def which(prog): <NEW_LINE> <INDENT> return common.lookup_prog([prog], os.getenv("PATH").split(":")); | Look for a program in the system PATH. | 625941c06aa9bd52df036d0c |
def paintEvent(self, event): <NEW_LINE> <INDENT> logger.debug('开始画图') <NEW_LINE> x = self.start[0] <NEW_LINE> y = self.start[1] <NEW_LINE> w = self.end[0] - x <NEW_LINE> h = self.end[1] - y <NEW_LINE> pp = QPainter(self) <NEW_LINE> pp.drawRect(x, y, w, h) | 给出截图的辅助线
:param event:
:return: | 625941c04c3428357757c294 |
def remove(self, item, priority=None): <NEW_LINE> <INDENT> if priority is None: <NEW_LINE> <INDENT> priority = self.priority(item) <NEW_LINE> <DEDENT> self.values[priority].remove(item) <NEW_LINE> if not self.values[priority]: <NEW_LINE> <INDENT> del self.values[priority] | Remove the given item from the queue.
If given a priority, will only remove from that priority. | 625941c0f9cc0f698b140567 |
def _create(tensorsSize, floatsSize, intsSize): <NEW_LINE> <INDENT> return lib.cnn_create_extraData(tensorsSize, floatsSize, intsSize) | ExtraData의 포인터를 반환합니다. | 625941c0091ae35668666ecc |
def gooding(k, r, v, tofs, numiter=150, rtol=1e-8): <NEW_LINE> <INDENT> k = k.to_value(u.m**3 / u.s**2) <NEW_LINE> r0 = r.to_value(u.m) <NEW_LINE> v0 = v.to_value(u.m / u.s) <NEW_LINE> tofs = tofs.to_value(u.s) <NEW_LINE> results = np.array( [gooding_fast(k, r0, v0, tof, numiter=numiter, rtol=rtol) for tof in tofs] ) <... | Propagate the orbit using the Gooding method.
The Gooding method solves the Elliptic Kepler Equation with a cubic convergence,
and accuracy better than 10e-12 rad is normally achieved. It is not valid for
eccentricities equal or greater than 1.0.
Parameters
----------
k : ~astropy.units.Quantity
Standard gravitat... | 625941c091af0d3eaac9b980 |
def test_register_success(self): <NEW_LINE> <INDENT> self.fill_submit_form_with_values(self.register_form, self.user_form_user) <NEW_LINE> user = USER_MODEL.objects.get() <NEW_LINE> for field in self.user_without_password_fields(): <NEW_LINE> <INDENT> field_value = getattr(user, field) <NEW_LINE> self.assertEqual(field... | Registration is successful and all provided fields are stored. | 625941c030dc7b76659018d3 |
def zigzagencode(value): <NEW_LINE> <INDENT> if value >= 0: <NEW_LINE> <INDENT> return value << 1 <NEW_LINE> <DEDENT> return (value << 1) ^ (~0) | zigzag transform: encodes signed integers so that they can be
effectively used with varint encoding. see wire_format.h for
more details. | 625941c071ff763f4b5495f1 |
def get_crd(self, axis, shaped=False, center="none"): <NEW_LINE> <INDENT> return self.get_crds([axis], shaped=shaped, center=center)[0] | if axis is not specified, return all coords,
shaped makes axis capitalized and returns ogrid like crds
shaped is only used if axis == None
sfx can be none, node, cell, face, edge
raises KeyError if axis not found | 625941c032920d7e50b28138 |
def maj_dico_compte(dico, mot, ligne): <NEW_LINE> <INDENT> if mot.lower() not in dico: <NEW_LINE> <INDENT> dico[mot.lower()] = [ligne] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dico[mot.lower()].append(ligne) | Ajoute la ligne à la clé mot dans le dico.
:param dico: Dictionnaire à modifier.
:param mot: Clé à incrémenter. | 625941c00fa83653e4656f26 |
def showKeywords(self, lst_of_pairs, tfidf_list, rel_freq_lst, lst_pnn): <NEW_LINE> <INDENT> keywords = [] <NEW_LINE> lst_pnn = list(lst_pnn) <NEW_LINE> lst_pnn_lowered = [name.lower() for name in lst_pnn] <NEW_LINE> freq_lst = [] <NEW_LINE> for w in tfidf_list: <NEW_LINE> <INDENT> for rel_f in rel_freq_lst: <NEW_LINE>... | Функция сопоставляет стеммы ключевых слов непосредственно со словами,
чтобы вывести их в резултат.
На вход принимает список пар (стемма, слово), список весов, список
относительных частот (для web) и список имен собственных.
Список имен собственных нужен для правильного вывода слов
с заглавной буквы и аббревиатур. Во... | 625941c02c8b7c6e89b3572c |
def process_options(arglist=None): <NEW_LINE> <INDENT> global options, args <NEW_LINE> parser = OptionParser(version=__version__, usage="%prog [options] input ...") <NEW_LINE> parser.add_option('-v', '--verbose', default=0, action='count', help="print status messages, or debug with -vv") <NEW_LINE> parser.add_option('-... | Process options passed either via arglist or via command line args. | 625941c09c8ee82313fbb6df |
def symb(self, s): <NEW_LINE> <INDENT> right = '' <NEW_LINE> d = { '(': ')', '{': '}', '[': ']', } <NEW_LINE> for x in s: <NEW_LINE> <INDENT> if x in d: <NEW_LINE> <INDENT> right = d[x] + right <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if x == right[:1]: <NEW_LINE> <INDENT> right = right[1:] <NEW_LINE> <DEDENT> els... | :type s: str
:rtype: bool | 625941c03eb6a72ae02ec441 |
def xor_cycle(data: bytes, key: bytes) -> bytes: <NEW_LINE> <INDENT> return bytes([x^y for x, y in zip(data, cycle(key))]) | Cyclically xor key over data. | 625941c073bcbd0ca4b2bfe0 |
def check(self): <NEW_LINE> <INDENT> self.check_was_run = True <NEW_LINE> if not "Architecture" in self.sections: <NEW_LINE> <INDENT> print("eDeb Package Error: No Architecture field in the package") <NEW_LINE> return "Package was created poorly. No Architecture field in the package" <NEW_LINE> <DEDENT> arch = self.sec... | Check if the package is installable. | 625941c030c21e258bdfa406 |
def _compute_results_per_page(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results_per_page = int(request.args.get('results_per_page')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> results_per_page = self.results_per_page <NEW_LINE> <DEDENT> if results_per_page <= 0: <NEW_LINE> <INDENT> results_per_p... | Helper function which returns the number of results per page based
on the request argument ``results_per_page`` and the server
configuration parameters :attr:`results_per_page` and
:attr:`max_results_per_page`. | 625941c06fb2d068a760f005 |
def xmlrpc_protocol(self, server, params, function=None, key_word=None): <NEW_LINE> <INDENT> def core_cohort_create_cohorts(params): <NEW_LINE> <INDENT> return proxy.core_cohort_create_cohorts(params) <NEW_LINE> <DEDENT> def core_course_get_courses(params): <NEW_LINE> <INDENT> return proxy.core_course_get_courses() <NE... | Select the correct function to call | 625941c099cbb53fe6792b51 |
def checkInclusion(self, s1, s2): <NEW_LINE> <INDENT> s1_dic, s2_dic = {}, {} <NEW_LINE> if len(s1) > len(s2): return False <NEW_LINE> for c in s1: <NEW_LINE> <INDENT> s1_dic[c] = s1_dic.get(c, 0) + 1 <NEW_LINE> <DEDENT> for i in range(len(s1)): <NEW_LINE> <INDENT> s2_dic[s2[i]] = s2_dic.get(s2[i], 0) + 1 <NEW_LINE> <D... | :type s1: str
:type s2: str
:rtype: bool | 625941c03617ad0b5ed67e63 |
def visit_family( self, results: Any, level: int, w: Node, ix: int, prod: Production ) -> None: <NEW_LINE> <INDENT> return | At a family of children | 625941c06aa9bd52df036d0d |
def notification(message, height, pause): <NEW_LINE> <INDENT> pass | Displays a string message
:param str message: Message to display
:param int height: Height of dialog box if applicable
:param bool pause: Whether or not the application should pause for
confirmation (if available) | 625941c0e76e3b2f99f3a77a |
def due_mapper(attribute): <NEW_LINE> <INDENT> def _fn(v): <NEW_LINE> <INDENT> today = date.today() <NEW_LINE> due = v['due'] <NEW_LINE> days = [(dateformat.format(d, 'l'), d) for d in [ (today + timedelta(days=d)) for d in range(2, 7)]] <NEW_LINE> days.append((_('Today'), today)) <NEW_LINE> days.append((_('Tomorrow'),... | Understands ``Today``, ``Tomorrow``, the following five localized
week day names or (partial) dates such as ``20.12.`` and ``01.03.2012``. | 625941c023e79379d52ee4d0 |
def vigsquare(printable=False): <NEW_LINE> <INDENT> alpha = string.ascii_uppercase <NEW_LINE> rotater = collections.deque(alpha) <NEW_LINE> vigsquare_list = [] <NEW_LINE> for i in range(26): <NEW_LINE> <INDENT> vigsquare_list.append(''.join(rotater)) <NEW_LINE> rotater.rotate(-1) <NEW_LINE> <DEDENT> if printable: <NEW_... | Returns a string like a vigenere square,
printable joins each row with a newline so it's literally square
printable=False (defaul) joins without newlines for easier
searching by row and column index | 625941c03d592f4c4ed1cfdd |
def crop_to(image_to_crop, reference_image): <NEW_LINE> <INDENT> reference_size = reference_image.size <NEW_LINE> current_size = image_to_crop.size <NEW_LINE> dx = current_size[0] - reference_size[0] <NEW_LINE> dy = current_size[1] - reference_size[1] <NEW_LINE> left = dx / 2 <NEW_LINE> upper = dy / 2 <NEW_LINE> right ... | Crops image to the size of a reference image. This function assumes that the relevant image is located in the center
and you want to crop away equal sizes on both the left and right as well on both the top and bottom.
:param image_to_crop
:param reference_image
:return: image cropped to the size of the reference image | 625941c0a934411ee37515fe |
def test_read_code_position_handles_malformed_input(self): <NEW_LINE> <INDENT> def assert_is_parsed(code_position_string): <NEW_LINE> <INDENT> code_position = parser._read_code_position([code_position_string], 0) <NEW_LINE> self.assertEqual(len(code_position), 4) <NEW_LINE> self.assertTrue(isinstance(code_position[3], ... | Malformed code positions are handled. | 625941c0d4950a0f3b08c2bb |
@dsym.command(name='import-system-symbols', short_help='Import system debug symbols.') <NEW_LINE> @click.argument('bundles', type=click.Path(), nargs=-1) <NEW_LINE> @click.option('--threads', default=8, help='The number of threads to use') <NEW_LINE> @click.option('--trim-symbols', is_flag=True, help='If enabled symbol... | Imports system symbols from preprocessed zip files into Sentry.
It takes a list of zip files as arguments that contain preprocessed
system symbol information. These zip files contain JSON dumps. The
actual zipped up dsym files cannot be used here, they need to be
preprocessed. | 625941c0187af65679ca5088 |
def resize(self, size): <NEW_LINE> <INDENT> dimension = (2 * self.border + self.width) <NEW_LINE> factor = size / dimension <NEW_LINE> self._img.attrib['transform'] = 'scale(%f)' % factor | resize the code by applying a scale transform | 625941c0cdde0d52a9e52f9b |
def _fetchRequirement(self, requirement: str) -> Union[int, float, bool, None]: <NEW_LINE> <INDENT> if requirement in self._requirementOverrides: <NEW_LINE> <INDENT> value = self._requirementOverrides[requirement] <NEW_LINE> if value is None: <NEW_LINE> <INDENT> raise AttributeError( f"Encountered explicit None for '{r... | Get the value of the specified requirement ('blah').
Done by looking it up in our requirement storage and querying 'defaultBlah'
on the config if it isn't set. If the config would be queried but isn't
associated, raises AttributeError.
:param requirement: The name of the resource | 625941c0a17c0f6771cbdfbd |
def calculateMainRecord(self, record: QtSql.QSqlRecord, fieldName: str): <NEW_LINE> <INDENT> lst = [r for r in self._widgetsInformation if r.fieldIndex == -1] <NEW_LINE> s = ('存在计算列,但没有实现calculateSubViewCell函数。' '该函数给定当前行数据及列名,应该返回计算列的值') <NEW_LINE> if lst: <NEW_LINE> <INDENT> raise UserWarning(s) <NEW_LINE> <DEDENT> r... | 用于计算主表的计算字段 | 625941c0796e427e537b052e |
def verifyBond1(self, records): <NEW_LINE> <INDENT> self.assertEqual(len(records), 1) <NEW_LINE> record = records[0] <NEW_LINE> self.assertTrue(not 'portfolio' in record) <NEW_LINE> self.assertEqual('DBANFB12014 Dragon Days Ltd 6.0%', record['description']) <NEW_LINE> self.assertEqual('HKD', record['currency']) <NEW_LI... | DBANFB12014 Dragon Days Ltd 6.0%, the bond exists in both
portfolio 12229 and 12734. | 625941c0e1aae11d1e749c20 |
def p_tfpdef(self, p): <NEW_LINE> <INDENT> p1 = p[1] <NEW_LINE> kwargs = {'arg': p1.value, 'annotation': p[2]} <NEW_LINE> if PYTHON_VERSION_INFO >= (3, 5, 1): <NEW_LINE> <INDENT> kwargs.update({ 'lineno': p1.lineno, 'col_offset': p1.lexpos, }) <NEW_LINE> <DEDENT> p[0] = ast.arg(**kwargs) | tfpdef : name_tok colon_test_opt | 625941c015baa723493c3ede |
def load(self, obj, parent=None, public=True): <NEW_LINE> <INDENT> if isinstance(obj, str): <NEW_LINE> <INDENT> obj = Node.factory(obj).target <NEW_LINE> <DEDENT> objpackage = getattr(obj, '__package__', None) <NEW_LINE> for name in dir(obj): <NEW_LINE> <INDENT> if name == '__call__': <NEW_LINE> <INDENT> target = obj <... | Load a Python object callables into sub-commands. | 625941c0cad5886f8bd26f44 |
def contains(self, item): <NEW_LINE> <INDENT> return self._search(item) is not None | Return True if this binary search tree contains the given item.
TODO: Best case running time: ??? under what conditions?
TODO: Worst case running time: ??? under what conditions? | 625941c0d6c5a10208143fb3 |
def test_create_valid_account(self): <NEW_LINE> <INDENT> self.session.execute_cmd("NEW") <NEW_LINE> self.session.execute_cmd("mark") <NEW_LINE> prompt = self.menutree.nodetext <NEW_LINE> self.assertEqual(self.default_node, "create_password") | Try to create an account. | 625941c0ad47b63b2c509eeb |
def promptForInputCategorical(message, options): <NEW_LINE> <INDENT> response = '' <NEW_LINE> options_list = ', '.join(options) <NEW_LINE> while response not in options: <NEW_LINE> <INDENT> response = input('{} ({}): '.format(message, options_list)) <NEW_LINE> <DEDENT> return response | Prompts for user input with limited number of options
:param message: Message displayed to the user
:param options: limited number of options.
Prompt will repeat until user input matches one of the provided options.
:return: user response | 625941c05f7d997b87174a00 |
def run(self,): <NEW_LINE> <INDENT> if not self.image_width or not self.image_height: <NEW_LINE> <INDENT> self.set_size() <NEW_LINE> <DEDENT> directory = os.path.abspath(self.image_path) <NEW_LINE> for file in os.listdir(directory): <NEW_LINE> <INDENT> filename = os.fsdecode(file) <NEW_LINE> if filename.endswith(".png"... | Create structures of folders and subfolders, convert image ans save this image. | 625941c08e7ae83300e4af37 |
def categorical_crossentropy(output, target, from_logits=False): <NEW_LINE> <INDENT> if not from_logits: <NEW_LINE> <INDENT> output /= tf.reduce_sum( output, axis=len(output.get_shape()) - 1, keep_dims=True) <NEW_LINE> epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype) <NEW_LINE> output = tf.clip_by_value(output, ... | Categorical crossentropy between an output tensor
and a target tensor, where the target is a tensor of the same
shape as the output.
# TODO(rbharath): Should probably swap this over to tf mode. | 625941c0046cf37aa974ccb4 |
def create_recordset(self, zone, **attrs): <NEW_LINE> <INDENT> zone = self._get_resource(_zone.Zone, zone) <NEW_LINE> attrs.update({'zone_id': zone.id}) <NEW_LINE> return self._create(_rs.Recordset, prepend_key=False, **attrs) | Create a new recordset in the zone
:param zone: The value can be the ID of a zone
or a :class:`~otcextensions.sdk.dns.v2.zone.Zone` instance.
:param dict attrs: Keyword arguments which will be used to create
a :class:`~otcextensions.sdk.dns.v2.recordset.Recordset`,
comprised of the properties on the Record... | 625941c01b99ca400220aa1c |
def set_data(self, items, checked_items): <NEW_LINE> <INDENT> self._icons = [self._make_icon(i + 1) for i in range(len(items))] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> qitem = QStandardItem(item) <NEW_LINE> qitem.setFlags(~Qt.ItemIsEditable) <NEW_LINE> qitem.setData(qApp.palette().window(), Qt.BackgroundRole)... | Sets data and updates geometry.
Args:
items (Sequence(str)): All items.
checked_items (Sequence(str)): Initially checked items. | 625941c03539df3088e2e2b6 |
def parse_genotypes(variant, individuals, individual_positions): <NEW_LINE> <INDENT> genotypes = [] <NEW_LINE> for ind in individuals: <NEW_LINE> <INDENT> pos = individual_positions[ind["individual_id"]] <NEW_LINE> genotypes.append(parse_genotype(variant, ind, pos)) <NEW_LINE> <DEDENT> return genotypes | Parse the genotype calls for a variant
Args:
variant(cyvcf2.Variant)
individuals: List[dict]
individual_positions(dict)
Returns:
genotypes(list(dict)): A list of genotypes | 625941c04a966d76dd550f78 |
@listify <NEW_LINE> def prefix(iterable, prefix): <NEW_LINE> <INDENT> for item in iterable: <NEW_LINE> <INDENT> yield prefix + item | Prefix each item from the iterable with a prefix | 625941c0ff9c53063f47c15f |
def free(ds): <NEW_LINE> <INDENT> if isinstance(ds, TypeVar): <NEW_LINE> <INDENT> return [ds] <NEW_LINE> <DEDENT> elif isinstance(ds, Mono) and not isinstance(ds, Unit): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for x in ds.parameters: <NEW_LINE> <INDENT> result.extend(free(x)) <NEW_LINE> <DEDENT> return result <NEW_L... | Return the free variables (TypeVar) of a blaze type (Mono). | 625941c06fb2d068a760f006 |
def getPdg(name): <NEW_LINE> <INDENT> for (pdg, pname) in rOdd.items(): <NEW_LINE> <INDENT> if name == pname: <NEW_LINE> <INDENT> return abs(pdg) <NEW_LINE> <DEDENT> <DEDENT> for (pdg, pname) in rEven.items(): <NEW_LINE> <INDENT> if name == pname: <NEW_LINE> <INDENT> return abs(pdg) <NEW_LINE> <DEDENT> <DEDENT> return ... | Convert a name to the pdg number according to the dictionaries rOdd and
rEven.
:type name: string
:returns: particle pdg; None, if name could not be resolved | 625941c0ac7a0e7691ed403b |
def __init__(self, username, password, pin, language="en"): <NEW_LINE> <INDENT> self._username = username <NEW_LINE> self._password = password <NEW_LINE> self._pin = pin <NEW_LINE> self._language = language <NEW_LINE> self._access_token = None <NEW_LINE> self._session_id = None <NEW_LINE> self._site_id = None <NEW_LINE... | Initialize the object. | 625941c010dbd63aa1bd2b0f |
def minimax(state, depth, alpha, beta, MAXI, MINI): <NEW_LINE> <INDENT> if end_state(state) or depth == 0: <NEW_LINE> <INDENT> return [static_value(state, MAXI, MINI), ""] <NEW_LINE> <DEDENT> next_moves = get_all_next_moves(state, MAXI, MINI) <NEW_LINE> move = [] <NEW_LINE> if state[9] == MAXI: <NEW_LINE> <INDENT> for ... | Parameters
----------
state : list
A list of length 10, representing a particular state of the game.
depth : int
The depth of the search tree.
alpha : int
Alpha value.
beta : TYPE
Beta value.
MAXI : str
The Maximizer player.
MINI : str
The Minimizer player.
Returns
-------
list
Implements t... | 625941c0d8ef3951e32434a8 |
def main(period, doc_type, borough, block, lot, *_): <NEW_LINE> <INDENT> if borough in BOROUGHS: <NEW_LINE> <INDENT> borough = BOROUGHS[borough] <NEW_LINE> <DEDENT> block = str(block).zfill(5) <NEW_LINE> lot = str(lot).zfill(4) <NEW_LINE> bbl = ''.join([borough, block, lot]) <NEW_LINE> bbldir = os.path.join('data', bor... | Download a single tax bill | 625941c0a4f1c619b28affa9 |
def unmatched_existing_values(self, new_values, existing_values): <NEW_LINE> <INDENT> new_value_pks = map(lambda value: self.resolve_pk(value), new_values) <NEW_LINE> return filter(lambda value: self.resolve_key(value.pk) not in new_value_pks, existing_values) | Find existing values that do not match the new_values according to the result of resolve_pk. For obj._set operations, these unmatched values will need to be removed
:param new_values: values meant to replace the existing_values.
:param existing_values: The existing values of the attribute collections
:return: The u... | 625941c0a219f33f346288d7 |
def test_get_nonexistent_bucketlist(self): <NEW_LINE> <INDENT> url = '/bucketlists/10' <NEW_LINE> get_response = self.client.get(url, headers=self.headers) <NEW_LINE> self.assertEqual(get_response.status_code, 202) <NEW_LINE> self.assertIn("Bucketlist not found", get_response.data.decode()) | test get a non existant bucketlist | 625941c099fddb7c1c9de2fd |
def generate_cartesian_path(path, frame_id, time, commander, start_state=None, n_points=50, max_speed=np.pi/4): <NEW_LINE> <INDENT> pose_eef_approach = commander.get_fk(frame_id, start_state) <NEW_LINE> waypoints = [] <NEW_LINE> for num in range(n_points): <NEW_LINE> <INDENT> p = deepcopy(pose_eef_approach) <NEW_LINE> ... | Generate a cartesian path of the end effector of "descent" meters where path = [x, y, z] wrt frame_id
move_group.compute_cartesian_path does not allow to start from anything else but the current state, use this instead
:param start_state: The start state to compute the trajectory from
:param path: [x, y, z] The vector ... | 625941c08a349b6b435e80de |
def merge(L1: list, L2: list) -> list: <NEW_LINE> <INDENT> newL = [] <NEW_LINE> i1 = 0 <NEW_LINE> i2 = 0 <NEW_LINE> while i1 != len(L1) and i2 != len(L2): <NEW_LINE> <INDENT> if L1[i1] <= L2[i2]: <NEW_LINE> <INDENT> newL.append(L1[i1]) <NEW_LINE> i1 += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> newL.append(L2[i2])... | Merge sorted lists L1 and L2 into a new list and return that new list.
>>> merge([1, 3, 4, 6], [1, 2, 5, 7])
[1, 1, 2, 3, 4, 5, 6, 7] | 625941c045492302aab5e22c |
def insert_after(self, other): <NEW_LINE> <INDENT> self.parent_collection.insert( self.parent_collection.index(other) + 1, self ) | Insert at index after `other`.
Args:
other: An instance of the same model to place `self` after. | 625941c0be7bc26dc91cd56f |
def main(opt): <NEW_LINE> <INDENT> clr = pickle.load(opt.model) <NEW_LINE> clr_info = pickle.load(opt.model) <NEW_LINE> D = np.loadtxt(opt.infile) <NEW_LINE> y = np.array(D[:, -1]) <NEW_LINE> if opt.ns: <NEW_LINE> <INDENT> X = D[:, :-(1 + N_NS)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> X = D[:, :-1] <NEW_LINE> <DE... | Main routine that exits with status code 0
| 625941c055399d3f0558861e |
def is_state_valid(self, state): <NEW_LINE> <INDENT> is_valid = True <NEW_LINE> split = state.split(",") <NEW_LINE> is_valid = is_valid and len(split) == 3 <NEW_LINE> is_valid = is_valid and bool(re.findall("continue|loss|win", split[0])) <NEW_LINE> is_valid = is_valid and bool(re.match("[0-9 ]+", split[1])) <NEW_LINE>... | Checks if state string is valid.
:return: True if valid else False | 625941c0aad79263cf3909a9 |
def skip_on_devices(*disabled_devices): <NEW_LINE> <INDENT> def skip(test_method): <NEW_LINE> <INDENT> @functools.wraps(test_method) <NEW_LINE> def test_method_wrapper(self, *args, **kwargs): <NEW_LINE> <INDENT> device = FLAGS.jax_test_dut or xla_bridge.get_backend().platform <NEW_LINE> if device in disabled_devices: <... | A decorator for test methods to skip the test on certain devices. | 625941c082261d6c526ab407 |
def allowTypes(self, *types): <NEW_LINE> <INDENT> for typ in types: <NEW_LINE> <INDENT> if not isinstance(typ, str): <NEW_LINE> <INDENT> typ = qual(typ) <NEW_LINE> <DEDENT> self.allowedTypes[typ] = 1 | SecurityOptions.allowTypes(typeString): Allow a particular type, by its
name. | 625941c0cad5886f8bd26f45 |
def common_req(self, execute, send_body=True): <NEW_LINE> <INDENT> self._SERVER = {'CLIENT_ADDR_HOST': self.client_address[0], 'CLIENT_ADDR_PORT': self.client_address[1]} <NEW_LINE> self._to_log = True <NEW_LINE> self._cmd = None <NEW_LINE> self._payload = None <NEW_LINE> self._path ... | Common code for GET and POST requests | 625941c00383005118ecf54f |
def get_nom(self, nombre): <NEW_LINE> <INDENT> if nombre <= 0: <NEW_LINE> <INDENT> raise ValueError("le nombre {} est négatif ou nul".format(nombre)) <NEW_LINE> <DEDENT> if nombre == 1: <NEW_LINE> <INDENT> return self.nom_singulier <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nombre = get_nom_nombre(nombre) <NEW_LINE>... | Retourne le nom singulier ou pluriel. | 625941c05166f23b2e1a50c4 |
def iter_tree(jottapath, JFS): <NEW_LINE> <INDENT> filedirlist = JFS.getObject('%s?mode=list' % jottapath) <NEW_LINE> logging.debug("got tree: %s", filedirlist) <NEW_LINE> if not isinstance(filedirlist, JFSFileDirList): <NEW_LINE> <INDENT> yield ( '', tuple(), tuple() ) <NEW_LINE> <DEDENT> for folder in filedirlist.tre... | Get a tree of of files and folders. use as an iterator, you get something like os.walk | 625941c076e4537e8c3515dc |
def convert_celsius_to_fahrenheit(deg_celsius): <NEW_LINE> <INDENT> return (9/5) * deg_celsius + 32 | Convert degress celsius to fahrenheit
Returns float value - temp in fahrenheit
Keyword arguments:
def_celcius -- temp in degrees celsius | 625941c07d43ff24873a2c0a |
def __init__(self, topname, trajname=None, frame_start=0): <NEW_LINE> <INDENT> FrameReader.__init__(self, topname, trajname, frame_start) <NEW_LINE> try: <NEW_LINE> <INDENT> import mdtraj <NEW_LINE> <DEDENT> except ImportError as e: <NEW_LINE> <INDENT> if "scipy" in repr(e): <NEW_LINE> <INDENT> e.msg = "The MDTraj Fram... | Open input XTC file from which to read coordinates using mdtraj library.
:param topname: GROMACS GRO file from which to read topology
:param trajname: GROMACS XTC file to read subsequent frames | 625941c0596a897236089a2e |
def renormalize_binary_logits(a, b): <NEW_LINE> <INDENT> norm = elementwise_logsumexp(a, b) <NEW_LINE> return a - norm, b - norm | Normalize so exp(a) + exp(b) == 1 | 625941c0cb5e8a47e48b7a18 |
def __init__(self, profile: Optional[object] = None, branch: Optional[str] = 'master'): <NEW_LINE> <INDENT> super().__init__(profile, branch) <NEW_LINE> self.utils = Utils() | Initialize Class properties. | 625941c0460517430c3940f6 |
def getInputDim(self): <NEW_LINE> <INDENT> r <NEW_LINE> return sum(self.attribSize) | Size of the latent vector given by self.buildRandomCriterionTensor | 625941c0a8ecb033257d3039 |
def test_log_fail(self): <NEW_LINE> <INDENT> self.logger.open_test_case(self.some_test_case_id) <NEW_LINE> self.logger.log_fail(self.some_log_fail_msg) <NEW_LINE> self.virtual_file.seek(0) <NEW_LINE> self.assertRegexpMatches(self.virtual_file.readline(), LOGGER_PREAMBLE + re.escape("open test case,,,Test case "+self.so... | Given: FuzzLoggerCsv with a virtual file handle.
When: Calling open_test_case with some test_case_id.
and: Calling log_fail with some description.
Then: open_test_case logs as expected.
and: log_fail logs as expected. | 625941c0d4950a0f3b08c2bc |
@linter.register <NEW_LINE> @with_matched_tokens(start=match_regex("^using$"), end=match_regex("^=$"), length=3) <NEW_LINE> def alias_names(source, *, match): <NEW_LINE> <INDENT> alias_token = match[1] <NEW_LINE> alias = alias_token.value <NEW_LINE> if alias == "is_transparent": <NEW_LINE> <INDENT> return <NEW_LINE> <D... | Flag type aliases that don't adhere to the naming conventions. | 625941c015fb5d323cde0a78 |
def can_nodes_fuse(v1, v2, glycan1, glycan2): <NEW_LINE> <INDENT> if v1 * v2 < 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif v1 == -1 and v2 == -1: <NEW_LINE> <INDENT> root_sugar1, root_bond1 = get_root_bond(glycan1) <NEW_LINE> root_sugar2, root_bond2 = get_root_bond(glycan2) <NEW_LINE> same_root_bond = ... | Checks immediate neighbors of v1 in glycan1 and v2 in glycan2
to verify they can fuse. O(1) run time, since maximum degree
is limited by sugar carbon count. | 625941c0d7e4931a7ee9de88 |
def new_model(self): <NEW_LINE> <INDENT> BASE_PATH = reduce(lambda l, r: l + os.path.sep + r, os.path.dirname(os.path.realpath(__file__)).split(os.path.sep)[:-1]) <NEW_LINE> dataPath = os.path.join(BASE_PATH, "data") | Just calls load_model without a filename
to create a new model. | 625941c0d486a94d0b98e0b0 |
def __init__( self, cursor: SnowflakeCursor, rows: list[bytes], stream_buffer_size: int = 1024 * 1024 * 10, ): <NEW_LINE> <INDENT> self.cursor = cursor <NEW_LINE> self.rows = rows <NEW_LINE> self._stream_buffer_size = stream_buffer_size <NEW_LINE> self.stage_path = f"@{self._STAGE_NAME}/{uuid.uuid4().hex}" | Construct an agent that uploads binding parameters as CSV files to a temporary stage.
Args:
cursor: The cursor object.
rows: Rows of binding parameters in CSV format.
stream_buffer_size: Size of each file, default to 10MB. | 625941c0293b9510aa2c3203 |
def adapt_datetime(ts): <NEW_LINE> <INDENT> return time.mktime(ts.timetuple()) | Internet says I need dis | 625941c0d6c5a10208143fb4 |
def cleanup(self): <NEW_LINE> <INDENT> if self._temp_dir: <NEW_LINE> <INDENT> self.logger.debug("Deleting temporary directory '%s'" % self._temp_dir) <NEW_LINE> shutil.rmtree(path=self._temp_dir, ignore_errors=True) <NEW_LINE> self._temp_dir = None | Cleanup any resources used by this command. | 625941c0167d2b6e31218b01 |
def __repr__(self): <NEW_LINE> <INDENT> out = "<%s(" % (self.__class__.__name__) <NEW_LINE> fields = [] <NEW_LINE> fields.append("filename=%r" % (self.filename)) <NEW_LINE> fields.append("auto_remove=%r" % (self.auto_remove)) <NEW_LINE> fields.append("appname=%r" % (self.appname)) <NEW_LINE> fields.append("verbose=%r" ... | Typecasting into a string for reproduction. | 625941c05fcc89381b1e1628 |
def browse(self, destination_name, cnt=100, jms_correlation_id=None, jms_type=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msg = 'destination_name:{0}, count:{1}, jms_correlation_id:{2}, jms_type:{3}'.format( destination_name, cnt, jms_correlation_id, jms_type) <NEW_LINE> self._mh.demsg('htk_on_debug_info', self... | Method browses queue
Args:
destination_name (str): queue name
cnt (int): count of messages
jms_correlation_id (str): requested JMSCorrelationID
jms_type (str): requested JMSType
Returns:
list: messages as dictionary {'message', JMS headers}
Raises:
event: jms_before_browse
event: jms_after_brows... | 625941c056ac1b37e626413f |
def get_player_ids(self) -> List[str]: <NEW_LINE> <INDENT> return [x.player_id for x in self.player_list] | Collect user ids from a list of players | 625941c05fdd1c0f98dc019e |
def test_new_user_email_normalized(self): <NEW_LINE> <INDENT> email = '[email protected]' <NEW_LINE> user = get_user_model().objects.create_user(email, 'test123') <NEW_LINE> self.assertEqual(user.email, email.lower()) | Test the email for a new user is normalized | 625941c030c21e258bdfa407 |
def forward(self, context, h, x): <NEW_LINE> <INDENT> x = self.embeds(x) <NEW_LINE> context = context.squeeze() <NEW_LINE> prob = self.p_gen(torch.cat((context, h[-1], x), dim=1)) <NEW_LINE> return F.sigmoid(prob) | :param context: (batch, hidden_size) attention vector
:param h: (n_layer, batch, hidden_size) decoder state
:param x: (batch, embedding_size) decoder input
:return: generation probability | 625941c04527f215b584c3c5 |
def get_available_letters(letters_guessed): <NEW_LINE> <INDENT> choices_left = list("abcdefghijklmnopqrstuvwxyz") <NEW_LINE> for letter in letters_guessed: <NEW_LINE> <INDENT> if letter in choices_left: <NEW_LINE> <INDENT> choices_left.remove(letter) <NEW_LINE> <DEDENT> <DEDENT> return choices_left | lettersGuessed: list of letters that have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed. | 625941c023849d37ff7b2ffc |
def delete_by_id(model, value): <NEW_LINE> <INDENT> session = get_session() <NEW_LINE> session.delete(session.query(model).filter_by(ID=value).first()) <NEW_LINE> session.commit() <NEW_LINE> session.close() <NEW_LINE> pass | 根据条件删除记录
:param model:
:param value:
:return: | 625941c01f5feb6acb0c4abf |
def update(self, x=None, update_model=False): <NEW_LINE> <INDENT> if update_model: <NEW_LINE> <INDENT> self.model.update() <NEW_LINE> <DEDENT> if self.is_stack_of_tasks(): <NEW_LINE> <INDENT> for hard_task in self.tasks: <NEW_LINE> <INDENT> for soft_task in hard_task: <NEW_LINE> <INDENT> soft_task.update(x=x, update_mo... | Compute the A matrix and b vector that will be used by the task solver.
Args:
x (np.array[float], None): variables that are being optimized.
update_model (bool): if True, it will update the model before updating each task. | 625941c060cbc95b062c64ae |
def goal_pose_cb(self, msg_curr_pose, msg_goal_pose: PoseStamped): <NEW_LINE> <INDENT> with self.lock: <NEW_LINE> <INDENT> if self.graph is None: <NEW_LINE> <INDENT> self.get_logger().warn( 'Got goal pose, but the map was not received yet!') <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> self.lock.acquire() <NEW_LINE> ... | Given a the robot current and target/goal poses, compute the path from
the starting pose to the goal pose. We are only considering positions. | 625941c021a7993f00bc7c58 |
def __init__(self, error=None, metadata=None, orders=None, success=None, warning=None): <NEW_LINE> <INDENT> self._error = None <NEW_LINE> self._metadata = None <NEW_LINE> self._orders = None <NEW_LINE> self._success = None <NEW_LINE> self._warning = None <NEW_LINE> self.discriminator = None <NEW_LINE> if error is not N... | EmailOrdersResponse - a model defined in Swagger | 625941c0d268445f265b4dda |
def can_support_nonorthogonal_axes(self) -> bool: <NEW_LINE> <INDENT> return self._nonorthogonal_axes_supported | Return boolean indicating if the current slice selection can support nonorthogonal viewing.
Both display axes must be spatial for this to be supported. | 625941c08c3a873295158323 |
def add_tempo(self, track, time, tempo): <NEW_LINE> <INDENT> self.tracks[track].addTempo(time, tempo) | Add a tempo event.
Use:
MyMIDI.addTempo(track, time, tempo)
Arguments:
track: The track to which the event is added. [Integer, 0-127].
time: The time at which the event is added, in beats. [Float].
tempo: The tempo, in Beats per Minute. [Integer] | 625941c0d486a94d0b98e0b1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.