code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_test_config(): <NEW_LINE> <INDENT> dirname = os.path.dirname(__file__) <NEW_LINE> conf_file = dirname + "/test.conf" <NEW_LINE> if os.path.exists(conf_file): <NEW_LINE> <INDENT> config = ConfigParser.ConfigParser() <NEW_LINE> config.read(conf_file) <NEW_LINE> return config <NEW_LINE> <DEDENT> return None | Reads test.conf config file which contains configurable options
to run functional tests.
:returns: ConfigParser instance if test.conf found, None otherwise. | 625941f3656771135c3ebe6b |
def confusion_matrix(y_true,y_predict): <NEW_LINE> <INDENT> return np.array([ [TN(y_true,y_predict), FP(y_true,y_predict)], [FN(y_true, y_predict), TP(y_true, y_predict)] ]) | 实现混淆矩阵 | 625941f3a8ecb033257d36bf |
def write_cobra_model_to_sbml_file(cobra_model, sbml_filename, sbml_level=2, sbml_version=1, print_time=False, use_fbc_package=True): <NEW_LINE> <INDENT> if not libsbml: <NEW_LINE> <INDENT> raise ImportError('write_cobra_model_to_sbml_file ' 'requires python-libsbml') <NEW_LINE> <DEDENT> sbml_doc = get_libsbml_document... | Write a cobra.Model object to an SBML XML file.
Parameters
----------
cobra_model : cobra.core.Model.Model
The model object to write
sbml_filename : string
The file to write the SBML XML to.
sbml_level : int
2 is the only supported level.
sbml_version : int
1 is the only supported version.
print_time :... | 625941f356ac1b37e62647b7 |
def image_repository(self): <NEW_LINE> <INDENT> code, fam = self.shared_image_repository() <NEW_LINE> if bool(code or fam): <NEW_LINE> <INDENT> return pywikibot.Site(code, fam, self.username()) | Return Site object for image repository e.g. commons. | 625941f33317a56b8693a23d |
def __init__(self, handler, iri, subordinate, included_by=None, context=None, wildcard_counter=0): <NEW_LINE> <INDENT> self._prefixes = {} <NEW_LINE> self._wc2identity = {} <NEW_LINE> self._maphandler = handler <NEW_LINE> self.base = iri <NEW_LINE> self.wildcard_counter = wildcard_counter <NEW_LINE> self._subordinate =... | `handler`
A IMapHandler instance.
`iri`
The document / base IRI used to resolve identifiers / IRIs against
`subordinate`
Indicates if the topic map was included / merged by another topic map.
`included_by`
Either ``None`` or a list of document IRIs from which the topic map
was included by.
`context`... | 625941f356b00c62f0f14c52 |
def sanitize(file_path, mention_set, output_file_path, label_set): <NEW_LINE> <INDENT> file_p_new_json = open(output_file_path, 'w') <NEW_LINE> used_mentions = set() <NEW_LINE> with open(file_path, 'r') as file_p: <NEW_LINE> <INDENT> for row in file_p: <NEW_LINE> <INDENT> data = json.loads(row) <NEW_LINE> new_mentions ... | Sanitize data. | 625941f3d99f1b3c44c67b78 |
def copy_s3_file(source, destination, aws_access_key_id=None, aws_secret_access_key=None): <NEW_LINE> <INDENT> dest_bucket, dest_key = parse_s3_uri(destination) <NEW_LINE> source_bucket, source_key = parse_s3_uri(source) <NEW_LINE> conn = get_conn(aws_access_key_id, aws_secret_access_key) <NEW_LINE> logger.info("Copyin... | Copy an S3 object from one location to another
| 625941f34a966d76dd55160b |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'XYECOS.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure ... | Run administrative tasks. | 625941f316aa5153ce362a6e |
def locale_org_assign(handle, locale_name, name, org_dn="org-root", descr=None, **kwargs): <NEW_LINE> <INDENT> from ucsmsdk.mometa.aaa.AaaOrg import AaaOrg <NEW_LINE> locale = locale_get(handle, locale_name, caller="locale_org_assign") <NEW_LINE> if not handle.query_dn(org_dn): <NEW_LINE> <INDENT> raise UcsOperationErr... | assigns a locale to org
Args:
handle (UcsHandle)
locale_name(string): locale name
name (string): name for the org assignment
org_dn (string): org dn
descr (string): description
**kwargs: Any additional key-value pair of managed object(MO)'s
property and value, which are not part o... | 625941f366656f66f7cbc7a2 |
def read_file(self, full_path): <NEW_LINE> <INDENT> with open(full_path, 'r', encoding="ascii", errors="surrogateescape") as f: <NEW_LINE> <INDENT> return f.read() | Returns contents of file at [full_path].
Override if you expect binary data or want to preprocess with shell commands.
Ref: http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html#files-in-an-ascii-compatible-encoding-minimise-risk-of-data-corruption | 625941f3d4950a0f3b08c93b |
def set_text_channel(self, channel, need_req=True): <NEW_LINE> <INDENT> if not channel: <NEW_LINE> <INDENT> self.current_text = "0" <NEW_LINE> return <NEW_LINE> <DEDENT> if channel != self.current_text: <NEW_LINE> <INDENT> self.current_text = channel <NEW_LINE> log.info( "Changing text room: %s", channel) <NEW_LINE> if... | Set currently active text channel | 625941f373bcbd0ca4b2c66a |
def exchange(S, A, z): <NEW_LINE> <INDENT> W = S[:] <NEW_LINE> for v in A: <NEW_LINE> <INDENT> W.remove(v) <NEW_LINE> <DEDENT> S.append(z) <NEW_LINE> for w in W: <NEW_LINE> <INDENT> tmp = S[:] <NEW_LINE> tmp.remove(w) <NEW_LINE> if does_solution_exist(coldict2mat(tmp), w): <NEW_LINE> <INDENT> return w <NEW_LINE> <DEDEN... | Input:
- S: a list of vectors, as instances of your Vec class
- A: a list of vectors, each of which are in S, with len(A) < len(S)
- z: an instance of Vec such that A+[z] is linearly independent
Output: a vector w in S but not in A such that Span S = Span ({z} U S - {w})
Example:
>>> S = [list2vec(v) fo... | 625941f39b70327d1c4e13cd |
def test_prediction_model_success(self): <NEW_LINE> <INDENT> data = self.data <NEW_LINE> keywords = data.drop('Price', axis=1) <NEW_LINE> keywords = keywords.drop('Date', axis=1) <NEW_LINE> price = data.Price.values.reshape(-1, 1) <NEW_LINE> scaler = StandardScaler() <NEW_LINE> price = scaler.fit_transform(price).ravel... | Testing for Prediction Model Success Case | 625941f3cad5886f8bd275cd |
def changeServer(self): <NEW_LINE> <INDENT> self._servers.pop() <NEW_LINE> self._servers.append("Server 5") | Change the server | 625941f3bd1bec0571d90c24 |
def box_reg_loss(self): <NEW_LINE> <INDENT> if self._no_instances: <NEW_LINE> <INDENT> return 0.0 * self.pred_proposal_deltas.sum() <NEW_LINE> <DEDENT> box_dim = self.proposals.tensor.size(1) <NEW_LINE> cls_agnostic_bbox_reg = self.pred_proposal_deltas.size(1) == box_dim <NEW_LINE> device = self.pred_proposal_deltas.de... | Deprecated | 625941f37c178a314d6efa5f |
def create_aliens(screen, game_settings, aliens, alien_number, row_number): <NEW_LINE> <INDENT> alien = Alien(screen, game_settings) <NEW_LINE> alien_width = alien.rect.width <NEW_LINE> alien_height = alien.rect.height <NEW_LINE> alien_x = alien_width + 2 * alien_width * alien_number <NEW_LINE> alien_y = alien_height +... | 创建一个外星人,并放在当前行 | 625941f3c432627299f0523f |
def translate_pitch_name(pitch_name, accidental, language="nederlands"): <NEW_LINE> <INDENT> if language not in lilypond_note_names.outbound: <NEW_LINE> <INDENT> raise exceptions.LilyPondError("Unrecognized language: '{}'".format(language)) <NEW_LINE> <DEDENT> language_dict = lilypond_note_names.outbound[language] <NEW... | Convert the English pair (name, accidental) to a pitch name in another language. | 625941f3eab8aa0e5d26e14f |
def check_modulo_one(j, number): <NEW_LINE> <INDENT> if number == 1: <NEW_LINE> <INDENT> j *= -1 <NEW_LINE> <DEDENT> return j | Checks if one of the ranges in sequence is 1
If true, returns inverted j
Else j | 625941f34e4d5625662d49c4 |
def _check_valid_circle_results(circle, num_points, circle_points): <NEW_LINE> <INDENT> assert all([len(point) == 2 for point in circle_points]) <NEW_LINE> assert len(circle_points) == num_points <NEW_LINE> center_x = circle.center_x <NEW_LINE> center_y = circle.center_y <NEW_LINE> radius = circle.radius <NEW_LINE> dis... | Check the randomly generated points for a valid 2D circle definition.
It is checked that num_points points are created and that each created point
lies on the defined 2D circle.
Args:
circle (Circle2D): A valid 2D circle definition
num_points (int): A valid number of random points to be created
circle_poi... | 625941f33d592f4c4ed1d651 |
def Release(self, targetname, timeout=10, **kwargs): <NEW_LINE> <INDENT> taskparameters = {'command': 'Release', 'targetname': targetname, } <NEW_LINE> taskparameters.update(kwargs) <NEW_LINE> return self.ExecuteCommand(taskparameters, timeout=timeout) | Releases a grabbed object.
:param targetname: Name of the object | 625941f321a7993f00bc82f1 |
def copy_password(number,count): <NEW_LINE> <INDENT> UserData.copy_password(number,count) | Function that copies the password to the clipboard | 625941f307f4c71912b11a7a |
def guassian(x, mu=0, sigma=1): <NEW_LINE> <INDENT> return np.exp(- (x - mu) ** 2 / (2 * sigma ** 2) ) / (np.sqrt(2 * np.pi) * sigma) | Compute normal function
Args:
x : vector
mu : vector | 625941f3d6c5a10208144645 |
def sortCreationDateFunction (page1, page2): <NEW_LINE> <INDENT> if page1.creationdatetime > page2.creationdatetime: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif page1.creationdatetime < page2.creationdatetime: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> return 0 | Функция для сортировки страниц по дате создания (первые - самые новые) | 625941f3e1aae11d1e74a2b2 |
def IPMT(*args) -> Function: <NEW_LINE> <INDENT> return Function("IPMT", args) | Calculates the payment on interest for an investment based on constant-amount
periodic payments and a constant interest rate.
Learn more: https//support.google.com/docs/answer/3093175 | 625941f357b8e32f52483a94 |
def scorers(self): <NEW_LINE> <INDENT> raise NotImplementedError("decoders method is not implemented") | Get scorers for `beam_search` (optional).
Returns:
dict[str, ScorerInterface]: dict of `ScorerInterface` objects | 625941f3aad79263cf39103f |
def handle_request(module, session, parameter): <NEW_LINE> <INDENT> func = module['func'] <NEW_LINE> signature = module['signature'] <NEW_LINE> try: <NEW_LINE> <INDENT> parameter = utils.validate_parameter(signature, parameter) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise ParametersInvalid(str(e... | This function handles the user request | 625941f3bde94217f36833e0 |
def _recv_tag_raw(sock): <NEW_LINE> <INDENT> s = sock.recv(4 * 4) <NEW_LINE> if len(s) != 16: <NEW_LINE> <INDENT> raise RuntimeError('Not enough bytes received, something is wrong. ' 'Make sure the mne_rt_server is running.') <NEW_LINE> <DEDENT> tag = Tag(*np.fromstring(s, '>i4')) <NEW_LINE> n_received = 0 <NEW_LINE> r... | Read a tag and the associated data from a socket
Parameters
----------
sock : socket.socket
The socket from which to read the tag.
Returns
-------
tag : instance of Tag
The tag.
buff : str
The raw data of the tag (including header). | 625941f371ff763f4b549c8c |
def task(self): <NEW_LINE> <INDENT> return { 'assignee': self.assignee, 'author': self.author, 'description': self.description, 'done': self.done, 'due': self.due, 'reminder': self.reminder, 'title': self.title, 'id': self.uid } | Return the task as dictionary.
The dictionary has the keys ``'assignee'``, ``'author'``,
``'description'``, ``'done'``, ``'due'``, ``'reminder'``, ``'title'``
and ``'id'`` | 625941f3b5575c28eb68e5fb |
def compress_pdf(filepath, output_path, ghostscript_binary): <NEW_LINE> <INDENT> if not filepath.endswith(PDF_EXTENSION): <NEW_LINE> <INDENT> raise ValueError("Filename must end with .pdf!\n%s does not." % filepath) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> file_size = os.stat(filepath).st_size <NEW_LINE> if file_si... | Compress a single PDF file.
Args:
filepath (str): Path to the PDF file.
output_path (str): Output path.
ghostscript_binary (str): Name/alias of the Ghostscript binary.
Raises:
ValueError
FileNotFoundError | 625941f321bff66bcd684f42 |
def lexical_scan(self, buffer): <NEW_LINE> <INDENT> c_definitions = open(HEADER_FILE,'w') <NEW_LINE> ignore = False <NEW_LINE> for line in buffer.split('\n'): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if line.startswith('#'): <NEW_LINE> <INDENT> ignore = self.is_system(line) <NEW_LINE> continue <NEW_LINE> <DED... | Iterate over buffer, and reduce to bare-minimal
header file | 625941f36fb2d068a760f69c |
def test_get_unique_keys(): <NEW_LINE> <INDENT> from knowviz.index import KeywordIndex <NEW_LINE> quantities = KeywordIndex("data/metadata/quantities.yml") <NEW_LINE> expected = ("q1", "q2", "q3") <NEW_LINE> count = 0 <NEW_LINE> for key in quantities.unique_keys(): <NEW_LINE> <INDENT> assert key in expected <NEW_LINE> ... | Test the unique_keys method of KeywordIndex | 625941f31b99ca400220b0a9 |
def VerifyProfile(self, profile_name): <NEW_LINE> <INDENT> profile = self.session.LoadProfile(profile_name) <NEW_LINE> if profile != None: <NEW_LINE> <INDENT> return self._ApplyFindDTB(self.find_dtb_impl, profile) | Check that the profile name is valid. | 625941f3379a373c97cfb13c |
def patch_syslog_servers( self, references=None, syslog_server=None, ids=None, names=None, async_req=False, _return_http_data_only=False, _preload_content=True, _request_timeout=None, ): <NEW_LINE> <INDENT> kwargs = dict( syslog_server=syslog_server, ids=ids, names=names, async_req=async_req, _return_http_data_only=_re... | Modify the URI of a configured syslog server.
Args:
references (list[FixedReference], optional):
A list of references to query for. Overrides ids and names keyword arguments.
syslog_server (SyslogServerPostOrPatch, required):
ids (list[str], optional):
A list of resource IDs. If after filt... | 625941f38e71fb1e9831dd9b |
def test__api_get_product_types_for_opus_id_no_request(self): <NEW_LINE> <INDENT> with self.assertRaisesRegex(Http404, r'Internal error \(No request was provided\) for /api/product_types/vg-iss-2-s-c4360845.json'): <NEW_LINE> <INDENT> api_get_product_types_for_opus_id(None, 'vg-iss-2-s-c4360845') | [test_results.py] api_get_product_types_for_opus_id: no request | 625941f3c432627299f05240 |
def test_post_me_not_allowed(self): <NEW_LINE> <INDENT> response = self.client.post(self.ME_URL, {}) <NEW_LINE> self.assertEqual( response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED, ) | Test that POST is not allowed in the me URL | 625941f3d7e4931a7ee9e515 |
def type_coerce(type_, value, fallback): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return type_(value) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return fallback | Return type_(value), on ValueError return fallback. | 625941f3a17c0f6771cbe644 |
def scraping_buysell(): <NEW_LINE> <INDENT> url = "https://navi.gaitame.com/v2/info/tools/buysell" <NEW_LINE> DATA_DIR = "buysell_gaitame" <NEW_LINE> now = datetime.now().strftime("%Y%m%d_%H%M") <NEW_LINE> nations = [ "eurjpy","usdjpy","eurusd","cadjpy", "chfjpy","usdchf","sekjpy","nokjpy", "tryjpy","zarjpy","mxnjpy","... | 売買比率を確認 | 625941f3187af65679ca5715 |
def scroll_to_selected(self, *args): <NEW_LINE> <INDENT> self.parent.scroll_to_index(self.sel_last) | Scrolls view to self.sel_last index | 625941f350812a4eaa59c910 |
def _build_data(random_id): <NEW_LINE> <INDENT> return { "id": random_id, "api_key": apikey, "method": method, "args": kw } | Builds API data with given random ID
:param random_id: | 625941f3167d2b6e3121918a |
def main(*args): <NEW_LINE> <INDENT> parser = OptionParser() <NEW_LINE> parser.add_option("-d", "--days", action="store", dest="days", type="int", default=None, help=_("Close events which are " "at least DAYS old. DAYS must be a positive non-zero integer.")) <NEW_LINE> parser.add_option("-u", "--up", action="store_true... | Point d'entrée du script qui ferme les événements en vert
dans le bac à événements (VigiBoard).
@note: Cette fonction ne rend pas la main, mais quitte
l'exécution de Python à la fin de sa propre exécution.
Les codes de retour possibles pour le script sont :
* 0 : pas d'erreur
* 1 : exception levée dura... | 625941f3046cf37aa974d336 |
def virtual_labels(self, z, method, p=None): <NEW_LINE> <INDENT> if method == 'binary': <NEW_LINE> <INDENT> v = binarizeWeakLabels(z, self.c).astype(float) <NEW_LINE> <DEDENT> elif method == 'quasi-IPL': <NEW_LINE> <INDENT> v = binarizeWeakLabels(z, self.c).astype(float) <NEW_LINE> for index in range(len(v)): <NEW_LINE... | Generate the set of virtual labels v for the (decimal) weak labels in
z, given a weak label model in variable method and, optionally, a
mixing matrix M, and a list of admissible decimal labels.
Warning: This method is deprecated. Use compute_virtual_labels instead
Parameters
----------
z : list
Weak labels. Each ... | 625941f3a05bb46b383ece11 |
def should_move_down(self, i): <NEW_LINE> <INDENT> child_index = self.get_top_child(i) <NEW_LINE> return (False if (child_index == None) else self.is_favoured(child_index, i)) | Return true if the element at index i needs to move down the tree | 625941f363b5f9789fde76db |
def testJoinCsv(): <NEW_LINE> <INDENT> with open('./mergedCurrency.csv', 'r') as f: <NEW_LINE> <INDENT> lastrow = deque(csv.reader(f), 1)[0] <NEW_LINE> <DEDENT> assert lastrow == ['243', 'Zimbabwe Dollar', 'ZWD', '0.002542', '396.647', 'Zimbabwe'] | test to assert if the join csv function is working correctly, by testing its output, mergedCurrency.csv | 625941f38e7ae83300e4b5c4 |
def handle_paste(self, text_field): <NEW_LINE> <INDENT> text_field.insert_text(self.clipboard) | Insert the contents of `self.clipboard` into the
text field that emitted a `paste_text` signal. | 625941f330dc7b7665901f54 |
def _get_referring_modules(self, obj): <NEW_LINE> <INDENT> for ref_obj in gc.get_referrers(obj): <NEW_LINE> <INDENT> if isinstance(ref_obj, dict) and '__name__' in ref_obj: <NEW_LINE> <INDENT> for mod in gc.get_referrers(ref_obj): <NEW_LINE> <INDENT> if isinstance(mod, types.ModuleType): <NEW_LINE> <INDENT> yield mod._... | Find all modules that *directly* refer to object `obj' | 625941f30383005118ecfbd6 |
def next_empty(board): <NEW_LINE> <INDENT> for row in range(len(board)): <NEW_LINE> <INDENT> for col in range(len(board)): <NEW_LINE> <INDENT> if board[row][col] == 0: <NEW_LINE> <INDENT> return (row, col) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None | Function which looks for the next empty square in the board.
Args:
board (list): The sudoku board
Returns:
tuple: Tuple with co-ordinates of the square, None if no empty squares remains | 625941f391af0d3eaac9c013 |
def colweight(self, i, weight): <NEW_LINE> <INDENT> self.frame.columnconfigure(i, weight=weight) | assign (weight) to column (i)
| 625941f3a8ecb033257d36c0 |
def printVarArgs( arg1, *vartuple ): <NEW_LINE> <INDENT> print ("Output is: ") <NEW_LINE> print (arg1) <NEW_LINE> print ("Variable arguments are") <NEW_LINE> for var in vartuple: <NEW_LINE> <INDENT> print (var) <NEW_LINE> <DEDENT> return; | This prints a variable passed arguments | 625941f3187af65679ca5716 |
def __init__(self, func, name=None, variables=None, extras=None, overflow=True, reqargs=None, evalinclude=False, memoize=None, memo=None, curried=None, funcstr=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> self.name = e.unusedarg() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.name = str(name) <N... | Creates A Callable Function. | 625941f315baa723493c4570 |
def checked_start(self): <NEW_LINE> <INDENT> self.running = True <NEW_LINE> if self.flush_interval: <NEW_LINE> <INDENT> self.flush_timer = Timer(self.flush_interval, self._flush) <NEW_LINE> <DEDENT> return True | Start the separate threads | 625941f3507cdc57c63072df |
def complete(self, task_id, success=True): <NEW_LINE> <INDENT> session = self.Session() <NEW_LINE> try: <NEW_LINE> <INDENT> task = session.query(Task).get(task_id) <NEW_LINE> <DEDENT> except SQLAlchemyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if success: <NEW_LINE> <INDENT> task.status = "success" <NE... | Mark a task as completed.
@param task_id: task id.
@param success: completed with status.
@return: operation status. | 625941f3aad79263cf391040 |
def write_complex(f, geot, band=1): <NEW_LINE> <INDENT> out.write('\t\t<ComplexSource>\n') <NEW_LINE> out.write('\t\t\t<SourceFilename relativeToVRT="0">{name}' '</SourceFilename>\n'.format(name=f.filename.replace('"', ''))) <NEW_LINE> out.write('\t\t\t<SourceBand>{nb}</SourceBand>\n'.format(nb=band)) <NEW_LINE> out.wr... | Write a complex source to VRT file | 625941f3d18da76e23532ad4 |
def get_page_boundaries(filename): <NEW_LINE> <INDENT> tree = ET.parse(filename) <NEW_LINE> minX = None <NEW_LINE> minY = None <NEW_LINE> maxX = None <NEW_LINE> maxY = None <NEW_LINE> def min(a, b): <NEW_LINE> <INDENT> if a == None: <NEW_LINE> <INDENT> return b <NEW_LINE> <DEDENT> if a < b: <NEW_LINE> <INDENT> return a... | get_page_boundaries determines page boundaries by looking at the
coordinates of the extracted text from a djvu XML file. | 625941f35f7d997b87175093 |
def cmd_get(self, msg_list): <NEW_LINE> <INDENT> if len(msg_list) >= 2: <NEW_LINE> <INDENT> filename = msg_list[1] <NEW_LINE> get_dic = { "action": "get", "filename": filename, } <NEW_LINE> self.ck.send(json.dumps(get_dic).encode()) <NEW_LINE> status,filesize = self.ck.recv(1024).decode().split(",") <NEW_LINE> if statu... | 文件下载 | 625941f36aa9bd52df03739e |
def maxDepth2(self, root, comp=lambda x,y: x if x>y else y): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> return comp(self.maxDepth2(root.left),self.maxDepth2(root.right)) + 1 | 递归 | 625941f3f8510a7c17cf9cf7 |
def test_copy_to_root_resource(): <NEW_LINE> <INDENT> arn_string = 'arn:aws:execute-api:us-east-1:1234567890:abcdefgh/latest/GET/some/path' <NEW_LINE> method = MethodArn.parse(arn_string) <NEW_LINE> updated = method.copy(resource='') <NEW_LINE> assert updated.resource == '' | test copying to a root resource | 625941f357b8e32f52483a95 |
def calculate(self): <NEW_LINE> <INDENT> result = set() <NEW_LINE> psscan = self.session.plugins.psscan() <NEW_LINE> pslist = self.session.plugins.pslist() <NEW_LINE> for _, physical_eprocess in psscan.scan_processes(): <NEW_LINE> <INDENT> eprocess = pslist.virtual_process_from_physical_offset( physical_eprocess) <NEW_... | Enumerate processes by scanning for _EPROCESS. | 625941f3d268445f265b5465 |
def hook_outgoing(self, packet, **kwargs): <NEW_LINE> <INDENT> return packet, kwargs | Method called by tcpsession just before a tcp packet is crafted and sent | 625941f3e76e3b2f99f3adf7 |
def test_buildProtocolOnce(self): <NEW_LINE> <INDENT> protocol = self.factory.buildProtocol(None) <NEW_LINE> self.assertIsInstance(protocol, ftp.DTP) <NEW_LINE> self.assertIdentical(self.factory.buildProtocol(None), None) | A L{ftp.DTPFactory} instance's C{buildProtocol} method can be used once
to create a L{ftp.DTP} instance. | 625941f37b180e01f3dc4de5 |
def load_dbip(): <NEW_LINE> <INDENT> with open("db-ip.txt", "r") as fin: <NEW_LINE> <INDENT> countries = [line.strip().split() for line in fin] <NEW_LINE> <DEDENT> return countries | Load IP to Country file into a list and return list | 625941f3711fe17d82542953 |
def __new__(cls, image_data, units=None, dtype=None, copy=True, t_start=0 * pq.s, spatial_scale=None, frame_duration=None, sampling_rate=None, name=None, description=None, file_origin=None, **annotations): <NEW_LINE> <INDENT> if spatial_scale is None: <NEW_LINE> <INDENT> raise ValueError("spatial_scale is required") <N... | Constructs new :class:`ImageSequence` from data.
This is called whenever a new class:`ImageSequence` is created from
the constructor, but not when slicing.
__array_finalize__ is called on the new object. | 625941f363d6d428bbe44ae7 |
def _calc_indendation(self, string): <NEW_LINE> <INDENT> number_whitespace = 0 <NEW_LINE> if type(string) is list: <NEW_LINE> <INDENT> for character in string[0]: <NEW_LINE> <INDENT> if character is " ": <NEW_LINE> <INDENT> number_whitespace += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <... | calculates the default indendation of the docustring
###
string - (list/string) the list of the individual lines of the method
###
RETURNS (int) | 625941f3097d151d1a22344c |
def intersects(self, other): <NEW_LINE> <INDENT> if self.right < other.left: return False <NEW_LINE> if other.right < self.left: return False <NEW_LINE> if self.top < other.bottom: return False <NEW_LINE> if other.top < self.bottom: return False <NEW_LINE> return True | Return boolean whether the "other" rect (an object with .x, .y,
.width and .height attributes) overlaps this Rect in any way. | 625941f3e64d504609d74e36 |
def forward(self, input_left, input_right): <NEW_LINE> <INDENT> left_size = input_left.size() <NEW_LINE> right_size = input_right.size() <NEW_LINE> assert left_size[:-1] == right_size[:-1], "batch size of left and right inputs mis-match: (%s, %s)" % (left_size[:-1], right_size[:-1]) <NEW_LINE> batch = int(np... | Args:
input_left: Tensor
the left input tensor with shape = [batch1, batch2, ..., left_features]
input_right: Tensor
the right input tensor with shape = [batch1, batch2, ..., right_features]
Returns: | 625941f3ad47b63b2c50a576 |
def is_relaunched(self, simulation_name): <NEW_LINE> <INDENT> return simulation_name in self.relaunched_simulation_names | This function ...
:param simulation_name:
:return: | 625941f3851cf427c661aaff |
def zero_state(self, batch_size, hiddennum, dtype): <NEW_LINE> <INDENT> shape = self.shape <NEW_LINE> num_features = self.num_features <NEW_LINE> zeros = tf.zeros([batch_size, shape[0], shape[1], num_features * hiddennum]) <NEW_LINE> return zeros | Return zero-filled state tensor(s).
Args:
batch_size: int, float, or unit Tensor representing the batch size.
dtype: the data type to use for the state.
Returns:
tensor of shape '[batch_size x shape[0] x shape[1] x num_features]
filled with zeros | 625941f344b2445a33932687 |
def threeSum(self, nums): <NEW_LINE> <INDENT> res = [] <NEW_LINE> nums.sort() <NEW_LINE> print(nums) <NEW_LINE> i = 0 <NEW_LINE> while i < len(nums): <NEW_LINE> <INDENT> target = -nums[i] <NEW_LINE> x, y = i + 1, len(nums) - 1 <NEW_LINE> while x < y: <NEW_LINE> <INDENT> if nums[x] + nums[y] < target: <NEW_LINE> <INDENT... | :type nums: List[int]
:rtype: List[List[int]] | 625941f391f36d47f21acaf0 |
def osa_distance(word1, word2, mem): <NEW_LINE> <INDENT> matrix = [[0 for i in range(0, len(word2) + 1)] for j in range(0, len(word1) + 1)] <NEW_LINE> for i in range(0, len(word1) + 1): <NEW_LINE> <INDENT> matrix[i][0] = i <NEW_LINE> <DEDENT> for j in range(0, len(word2) + 1): <NEW_LINE> <INDENT> matrix[0][j] = j <NEW_... | Returns OSA distance using insert, delete, substitute, and transpose | 625941f3d486a94d0b98e73d |
def get_course_interactions(self): <NEW_LINE> <INDENT> course_interations = np.zeros((self.size, self.size)) <NEW_LINE> for i in self.diners: <NEW_LINE> <INDENT> pos = self.get_positon(i) <NEW_LINE> for j in self.get_adjacents(pos): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> course_interations[i][j] = self.com["adjac... | This takes the state of the table and creates a numpy array of | 625941f3a4f1c619b28b0620 |
def multiply(self, vecs_in): <NEW_LINE> <INDENT> if type(vecs_in) is not superVector: <NEW_LINE> <INDENT> raise TypeError("Input variable is not a superVector") <NEW_LINE> <DEDENT> if not self.checkSame(vecs_in): <NEW_LINE> <INDENT> raise ValueError("ERROR! Dimensionality mismatching between given superVectors") <NEW_L... | Function to multiply element-wise two vectors | 625941f36fece00bbac2dd3c |
def resize_as_min_side(im, masks, mask, boxes, classes, min_side, max_side): <NEW_LINE> <INDENT> h, w, c = im.shape <NEW_LINE> n = classes.size <NEW_LINE> im_shape = im.shape <NEW_LINE> im_size_min = np.min(im_shape[0:2]) <NEW_LINE> im_size_max = np.max(im_shape[0:2]) <NEW_LINE> im_scale = float(min_side) / float(im_si... | resize image so that it may max-fix the canvas | 625941f3fff4ab517eb2fa36 |
def softmax(x): <NEW_LINE> <INDENT> e = np.exp(x) <NEW_LINE> dist = e / (np.sum(e) + 1e-8) <NEW_LINE> return dist | Compute softmax values for each sets of scores in x. | 625941f35e10d32532c5f51b |
def toggle_favorite(self, type, val, hm_token=None): <NEW_LINE> <INDENT> assert str(type) in ['item', 'site', 'user'], ('"type" must be item or' 'site or user') <NEW_LINE> payload = self._parse_payload(locals().copy(), []) <NEW_LINE> endpoint = '/me/favorites?' + self._param('hm_token', self.hm_token) <NEW_LINE> return... | Add to favorites
Returns 1 or 0, reflecting the final state of the item (1 is favorite,
0 is not)
POST method
Args:
REQUIRED:
- string type: type of resource to favorite
allowable values: item, site, user
- string val: id of resource to favorite, generally numerical
- string hm_token: user toke... | 625941f331939e2706e4d457 |
def mergeTwoLists2(self, l1, l2): <NEW_LINE> <INDENT> if not l1 or not l2: <NEW_LINE> <INDENT> return l1 or l2 <NEW_LINE> <DEDENT> dummyHead = ListNode(-1) <NEW_LINE> cur = dummyHead <NEW_LINE> while l1 and l2: <NEW_LINE> <INDENT> if l1.val < l2.val: <NEW_LINE> <INDENT> cur.next = l1 <NEW_LINE> l1 = l1.next <NEW_LINE> ... | non-recursive: 初始一个dummyHead,初始一个cur从dummyHead开始,当l1和l2都不为空时,用if-else确定将
谁加到cur的后面,加了之后后移相应对应链表的头,同时要后移cur到新加的节点上 | 625941f399fddb7c1c9de984 |
def addtd(val): <NEW_LINE> <INDENT> return '<td>{}</td>'.format(par._val_to_html(val)) | Use the parameter to convert to HTML | 625941f3a219f33f34628f57 |
def get_version(module='sewergraph'): <NEW_LINE> <INDENT> with open(os.path.join(HERE, module, '__init__.py'), 'r') as f: <NEW_LINE> <INDENT> data = f.read() <NEW_LINE> <DEDENT> lines = data.split('\n') <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> if line.startswith('VERSION_INFO'): <NEW_LINE> <INDENT> version_tup... | Get version. | 625941f39f2886367277ae7e |
def sample(self, inputs, states=None, max_len=20): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for i in range(max_len): <NEW_LINE> <INDENT> lstm_out, states = self.lstm(inputs, states) <NEW_LINE> outputs = self.hidden2out(lstm_out.squeeze(1)) <NEW_LINE> _, predicted = outputs.max(dim=1) <NEW_LINE> res.append(predicted.item... | Accepts pre-processed image tensor (inputs) and returns predicted sentence
(list of tensor ids of length max_len) | 625941f3442bda511e8bea05 |
def analyze(self, text): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> token_result = [] <NEW_LINE> result = 0 <NEW_LINE> pos_file = open(self.positives, encoding='utf-8') <NEW_LINE> neg_file = open(self.negatives, encoding='utf-8') <NEW_LINE> pos_string = pos_file.read() <NEW_LINE> neg_string = neg_file.read() <NEW_... | Analyze text for sentiment, returning its score. | 625941f38c3a8732951589b9 |
def setup_simulation(self): <NEW_LINE> <INDENT> self.config_dialog = ConfigureSimulationDialog(self.collection) | Shows the configure simulation dialog | 625941f3442bda511e8bea06 |
def leave(self, expected_state=None, timeout=None): <NEW_LINE> <INDENT> super(IxnPimV6JoinPruneListEmulation, self).call_operation('leave', expected_state, timeout) | Leave
For expected_state options see the class state variables | 625941f3293b9510aa2c3886 |
def test_cuda_mat_dot(self): <NEW_LINE> <INDENT> n = 1024 <NEW_LINE> m = 512 <NEW_LINE> a = np.random.randint(0, 10, size=n*m).reshape([n, m]) <NEW_LINE> b = np.random.randint(0, 10, size=n*m).reshape([m, n]) <NEW_LINE> actual = np.zeros([n, n]) <NEW_LINE> _test_mat_mul(a, b, actual) <NEW_LINE> expected = a @ b <NEW_LI... | Check whether CUDA kernel is invoked correctly for big matrices | 625941f38a349b6b435e8769 |
def download_asteroids(start_date, end_date, api_key): <NEW_LINE> <INDENT> base_uri = "https://api.nasa.gov/" <NEW_LINE> base_service_uri = "neo/rest/v1/feed" <NEW_LINE> query_string = f"?start_date={start_date}&end_date={end_date}&api_key={api_key}" <NEW_LINE> full_uri = f"{base_uri}{base_service_uri}{query_string}" <... | Download asteroid data from NASA | 625941f321bff66bcd684f43 |
def alphabet(self): <NEW_LINE> <INDENT> Sigma = set(['1', '0']) <NEW_LINE> return Sigma | Returns the NFA's input alphabet, generated on the fly. | 625941f376e4537e8c351c6f |
def _get_ellipse_bb(x, y, major, minor, angle_deg=0): <NEW_LINE> <INDENT> t = np.arctan(-minor / 2 * np.tan(np.radians(angle_deg)) / (major / 2)) <NEW_LINE> [max_x, min_x] = [x + major / 2 * np.cos(t) * np.cos(np.radians(angle_deg)) - minor / 2 * np.sin(t) * np.sin(np.radians(angle_deg)) for t in (t, t + np.pi)] <NEW_L... | Compute tight ellipse bounding box. | 625941f3c4546d3d9de73030 |
def openLock(self, deadends, target): <NEW_LINE> <INDENT> if "0000" in deadends: return -1 <NEW_LINE> queue = ["0000"] <NEW_LINE> visits = set(queue + deadends) <NEW_LINE> step = 0 <NEW_LINE> while queue: <NEW_LINE> <INDENT> queue0 = [] <NEW_LINE> for status in queue: <NEW_LINE> <INDENT> if status == target: return ste... | :type deadends: List[str]
:type target: str
:rtype: int | 625941f3d99f1b3c44c67b79 |
def identifyProtocols(pdml): <NEW_LINE> <INDENT> pass | Receives a file and returns a list of all identified protocols from it | 625941f338b623060ff0b3e3 |
def large_company(self): <NEW_LINE> <INDENT> return self.random_element(self.large_companies) | :example: 'SOCAR' | 625941f34e4d5625662d49c5 |
def model_test_both_score(self, data_name, cloze_path, choices_path, ans_path): <NEW_LINE> <INDENT> print(data_name) <NEW_LINE> near_line=0 <NEW_LINE> near_OK=0 <NEW_LINE> sent_line_one_word=0 <NEW_LINE> sent_OK_one_word=0 <NEW_LINE> sent_line=0 <NEW_LINE> sent_OK=0 <NEW_LINE> cloze_list=readCloze2(cloze_path) <NEW_LIN... | ファイル読み込み
モデル入力作成、1単語限定かどうかとか
スコア計算とか
選択肢のみ使用 | 625941f3d8ef3951e3243b34 |
def build_record(volumeId, result, record): <NEW_LINE> <INDENT> if 'publishDate' in result: <NEW_LINE> <INDENT> record['date'] = int(result['publishDate'][0]) <NEW_LINE> <DEDENT> if "callnumber" in result: <NEW_LINE> <INDENT> for callNumber in result['callnumber']: <NEW_LINE> <INDENT> classResponse = c.getClass(callNum... | Process Solr API results
results : JSON object of results from Solr
records : object of HATHI derived record information, to augment with Solr info and
write to jsoncatalog.txt | 625941f315fb5d323cde1110 |
@bottle.get('/firmware/<firmware_hash>/bin') <NEW_LINE> def download_firmware(firmware_hash): <NEW_LINE> <INDENT> filename = 'ledmacher.bin' <NEW_LINE> filepath = './build/{}/{}'.format(firmware_hash, filename) <NEW_LINE> if os.path.isfile(filepath): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> return bottle.static_fil... | Rertieve the binary file of a previous firmware build.
If there's a build directory with the given firmware hash, and a ledmacher.bin file exists in it,
the file is sent as binary octet-stream content.
If there's no such file, 404 response is sent instead. | 625941f3cad5886f8bd275cf |
def delete_rows(self, idx): <NEW_LINE> <INDENT> self_copy = deepcopy(self) <NEW_LINE> self_copy._data = np.delete(self_copy._data, idx, axis=0) <NEW_LINE> if self_copy.row_names is not None: <NEW_LINE> <INDENT> for i in sorted(_to_tuple(idx), reverse=True): <NEW_LINE> <INDENT> del self_copy.row_names[i] <NEW_LINE> <DED... | delete rows specified by idx
Parameters
----------
idx: single index or list of numeric row indices
Returns
------- | 625941f330c21e258bdfaa9b |
def data_generator(self): <NEW_LINE> <INDENT> while self.running: <NEW_LINE> <INDENT> chunk = self.buffer.get() <NEW_LINE> if chunk is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> data = [chunk] <NEW_LINE> while self.running: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chunk = self.buffer.get(block=False) <NEW... | A generator that yields all available data in the given buffer.
Yields:
bytes: A chunk of data that is the aggregate of all chunks of data in
`buff`. The function will block until at least one data chunk is
available. | 625941f3009cb60464c639a3 |
def createAsset(value, opt_path=None, opt_force=False, opt_properties=None): <NEW_LINE> <INDENT> if not isinstance(value, six.string_types): <NEW_LINE> <INDENT> value = json.dumps(value) <NEW_LINE> <DEDENT> args = {'value': value, 'json_format': 'v2'} <NEW_LINE> if opt_path is not None: <NEW_LINE> <INDENT> args['id'] =... | Creates an asset from a JSON value.
To create an empty image collection or folder, pass in a "value" object
with a "type" key whose value is "ImageCollection" or "Folder".
Args:
value: An object describing the asset to create or a JSON string
with the already-serialized value for the new asset.
opt_path: An... | 625941f36fece00bbac2dd3d |
def resource_handler(self, name, description=u"", siteresource=False): <NEW_LINE> <INDENT> def resource_auth_error(message): <NEW_LINE> <INDENT> return Response(message, 401, {'WWW-Authenticate': 'Bearer realm="Token Required" scope="%s"' % name}) <NEW_LINE> <DEDENT> def inner(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LIN... | Decorator for resource handlers. Verifies tokens and passes info on
the user and calling client. | 625941f3a05bb46b383ece12 |
def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> auth = tweepy.OAuthHandler(API_KEY, API_SECRET) <NEW_LINE> auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) <NEW_LINE> self.auth = auth <NEW_LINE> self.api = tweepy.API(auth) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise RuntimeError("Error. Authe... | Initializes the bot and handles authentication | 625941f3f548e778e58cdb77 |
def DECSCL(level, sevenBit=None): <NEW_LINE> <INDENT> if sevenBit is None: <NEW_LINE> <INDENT> params = [ level ] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> params = [ level, sevenBit ] <NEW_LINE> <DEDENT> escio.WriteCSI(params=params, intermediate='"', final="p") | Level should be one of 61, 62, 63, or 64. sevenBit can be 0 or 1, or not
specified. | 625941f330bbd722463cc3c0 |
def pointannot(jsn,label): <NEW_LINE> <INDENT> data = json.loads(jsn) <NEW_LINE> annotations = [] <NEW_LINE> for i in range(len(data)): <NEW_LINE> <INDENT> for j in range(len(data[i]["annotations"])): <NEW_LINE> <INDENT> data[i]["annotations"][j].update({"filename": data[i]["filename"][2:]}) <NEW_LINE> annotations.appe... | takes a json file and a point label. It returns the dictionary corresponding to label annotations).
label could be "head", "tail", "up_fin" or "low_fin". | 625941f396565a6dacc8fcc0 |
def get_diagram_type(self): <NEW_LINE> <INDENT> return self.diagram_type | Access the diagram type
Args: self method
Return: diagram type | 625941f323849d37ff7b3681 |
@register.filter(name='cut') <NEW_LINE> def cut(value, arg): <NEW_LINE> <INDENT> return value.replace(arg,'') | This cuts out all values of "arg" from the string! | 625941f321a7993f00bc82f3 |
def refreshAll(self): <NEW_LINE> <INDENT> if not self._active: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> log.debug("Refreshing device accessible tree: %s" % self.device) <NEW_LINE> self._manualSelect = True <NEW_LINE> self._treeWidget.clear() <NEW_LINE> self._view.clear() <NEW_LINE> path = accessible.Path() <NEW_L... | Refreshes all accessible trees. | 625941f301c39578d7e75432 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.