code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def user_hold(job_id): <NEW_LINE> <INDENT> process = subprocess.run([QHOLD, str(job_id)]) <NEW_LINE> return process.returncode == 0
Calls qhold_ for the given job id, placing a *user hold* on the job. **NOTE:** Because it's a user hold being placed, it's possible that even an operator might get access denied trying to hold jobs owned by another user. This will have to be sussed out. .. _qhold: http://gridscheduler.sourceforge.net/htmlman/htmlman...
625941f2d99f1b3c44c67b4b
def _compress_files(dname, files, dry_run=True): <NEW_LINE> <INDENT> assert os.path.isdir(dname) <NEW_LINE> assert isinstance(files, types.GeneratorType) <NEW_LINE> with DirectoryLock(dname): <NEW_LINE> <INDENT> for fname in files: <NEW_LINE> <INDENT> log.info('Compressing %s', fname) <NEW_LINE> assert os.path.commonpr...
Compress the files passed as argument.
625941f231939e2706e4d429
def get_sonar_queries(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.get_sonar_queries_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_sonar_queries_with_http_info(**kwargs) <NEW...
Sonar Queries # noqa: E501 Returns all sonar queries. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_sonar_queries(async_req=True) >>> result = thread.get() :param async_req bool :return: ResourcesSonarQuery...
625941f24e4d5625662d4997
def pyez(self, command, **kwargs): <NEW_LINE> <INDENT> return_value = self.current_node.current_controller.pyez(command=command, **kwargs) <NEW_LINE> return return_value
Execute rpc command on device device_object.execute_pyez(command = 'get-software-information')
625941f2be7bc26dc91cdbbd
def columns(self, n): <NEW_LINE> <INDENT> self.restore() <NEW_LINE> for i in xrange(n): <NEW_LINE> <INDENT> self._plus(self.cur, 0) <NEW_LINE> yield ''.join(reversed(self.cur))
generator for excel columns :param n: decimal count for excel col :return:
625941f23317a56b8693a211
def conv_2d(sub_model, channels, kernel_size, activation='relu'): <NEW_LINE> <INDENT> sub_model.add(nn.Conv2D(channels=channels, kernel_size=kernel_size, strides=1, padding=int((kernel_size - 1) / 2), activation=None)) <NEW_LINE> sub_model.add(nn.BatchNorm()) <NEW_LINE> if activation is not None: <NEW_LINE> <INDENT> su...
定义一个用于实现same conv的helper function activation: 'relu' or None
625941f2ff9c53063f47c7b8
def delete_room(self, roomid): <NEW_LINE> <INDENT> rooms = self.office + self.lspace <NEW_LINE> returnmsg = [] <NEW_LINE> rooms_id = [room.room_id for room in rooms] <NEW_LINE> roomid = int(roomid) <NEW_LINE> if roomid not in rooms_id: <NEW_LINE> <INDENT> returnmsg.append(colored("Room ID does not exist!!", "yellow")) ...
deletes a room from the system
625941f2293b9510aa2c3858
def get_image(self, x, y): <NEW_LINE> <INDENT> image = pygame.Surface([self.tile_width, self.tile_height]).convert() <NEW_LINE> image.blit(self.sprite_sheet, (0, 0), (x*self.tile_width, y*self.tile_height, self.tile_width, self.tile_height)) <NEW_LINE> image.set_colorkey((0, 0, 0)) <NEW_LINE> return image
Grab a single image out of a larger spritesheet Pass in the x, y location of the sprite and the width and height of the sprite.
625941f299cbb53fe67931ac
def get_dict(self): <NEW_LINE> <INDENT> d = dict() <NEW_LINE> for key, value in self.__dict__.items(): <NEW_LINE> <INDENT> if isinstance(value, TypeBase): <NEW_LINE> <INDENT> value = value.get_dict() <NEW_LINE> <DEDENT> elif isinstance(value, list): <NEW_LINE> <INDENT> value_list = [] <NEW_LINE> for elem in value: <NEW...
Returns object as a dict that follows LB's REST format. Some subclasses override this method.
625941f20a366e3fb873ede8
def set_to_file(links, file_name): <NEW_LINE> <INDENT> delete_file_contents(file_name) <NEW_LINE> for link in sorted(links): <NEW_LINE> <INDENT> append_to_file(file_name, link)
:param links: links to be sent from the set data type to the file :param file_name: the file in which the data will be stored :return:
625941f2dd821e528d63b76c
def is_applicable(self, url: str) -> bool: <NEW_LINE> <INDENT> parsed_url = urlparse(url) <NEW_LINE> if ( parsed_url.hostname in ("www.youtube.com", "youtube.com") and parsed_url.path == "/watch" ): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Return whether this scraper is applicable to a particular url.
625941f24527f215b584ca1a
def reverse_vowels(s): <NEW_LINE> <INDENT> vowels = set("aeiou") <NEW_LINE> string = list(s) <NEW_LINE> i = 0 <NEW_LINE> j = len(s) - 1 <NEW_LINE> while i < j: <NEW_LINE> <INDENT> if string[i].lower() not in vowels: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> elif string[j].lower() not in vowels: <NEW_LINE> <INDENT>...
Reverse vowels in a string. Characters which re not vowels do not change position in string, but all vowels (y is not a vowel), should reverse their order. >>> reverse_vowels("Hello!") 'Holle!' >>> reverse_vowels("Tomatoes") 'Temotaos' >>> reverse_vowels("Reverse Vowels In A String") 'RivArsI Vewols en e Streng' r...
625941f2656771135c3ebe3e
def get_build_file_path(path): <NEW_LINE> <INDENT> if os.path.isdir(path): <NEW_LINE> <INDENT> directory = path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> directory = os.path.dirpath(path) <NEW_LINE> <DEDENT> build_file_path = os.path.join(directory, 'BUILD') <NEW_LINE> return build_file_path
Get path to a BUILD file next to a given path. Args: path (str): Path to a file or directory. Returns build_file_path (str): Path to the BUILD in the given directory or in the directory containing the given file.
625941f2442bda511e8be9d8
def _compute_theta_char_poly(char_dict, f): <NEW_LINE> <INDENT> return sum(_multiply_theta_char(list(l), f)*char_dict[l] for l in char_dict)
Return the coefficient at ``f`` of the Siegel modular form .. math: \sum_{l \in\text{char_dict}} \alpha[l] * \prod_i \theta_l[i](8Z). INPUT: - ``char_dict`` -- a dictionary whose keys are *tuples* of theta characteristics and whose values are in some ring. - ``f`` -- a triple `(a,b,c)` of rational numbers...
625941f2fb3f5b602dac3c62
def naar_lijst(geheime_boodschap: str, aantal_kolommen: int) -> list: <NEW_LINE> <INDENT> lijst = [] <NEW_LINE> for index, start in enumerate( range(0, len(geheime_boodschap), aantal_kolommen)): <NEW_LINE> <INDENT> rij = geheime_boodschap[start:start + aantal_kolommen] <NEW_LINE> if not is_even(index): <NEW_LINE> <INDE...
Verkrijg de geheime boodschap als lijst. :param geheime_boodschap: De geheime boodschap als string. :param aantal_kolommen: Het aantal kolommen als integer. :return: De geheime boodschap als lijst.
625941f2a8370b7717052e65
def check_pos_player(player_name: str, season=CURR_SEASON) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return statsapi.lookup_player(player_name, season=season)[0]['primaryPosition']['abbreviation'] != "P" <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return False
A function that returns a bool indicating whether or not the player is a position player (as opposed to a pitcher). Parameters -----–----------- player_name: str The name of a player as a string (i.e. "Buster Posey")
625941f2ad47b63b2c50a548
def join(self): <NEW_LINE> <INDENT> self._is_thread_joined = True <NEW_LINE> self._thread.join() <NEW_LINE> if self._exception is not None: <NEW_LINE> <INDENT> self._testcase.fail("Error in checkedThread: %s" % str(self._exception))
Blocks until the thread terminates. Raises: self._testcase.failureException: If the thread terminates with due to an exception.
625941f2a8ecb033257d3693
def must_authenticate(): <NEW_LINE> <INDENT> return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
Sends a 401 response that enables basic auth
625941f23d592f4c4ed1d625
def find_tweet(self): <NEW_LINE> <INDENT> return self.browser.find_element_by_id("tweetmsg")
KRAV 4: Ett meddelande som är publicerat skall visas i kronologiskt fallande (senast först) ordning nedanför textfältet.
625941f21f5feb6acb0c5111
def _get_unique_name(name): <NEW_LINE> <INDENT> with ops.init_scope(): <NEW_LINE> <INDENT> return ops.get_default_graph().unique_name(name)
Returns a name that is unique in the root graph of `func_graph`. Args: name: String to uniquify. Returns: A string.
625941f2cb5e8a47e48b8068
def pop(self): <NEW_LINE> <INDENT> return heapq.heappop(self.elements)[1]
Returns item with highest priority (i.e. lowest priority value) and removes it from the queue.
625941f27c178a314d6efa32
def mon_status(self): <NEW_LINE> <INDENT> cmd = {'prefix': 'mon_status'} <NEW_LINE> return run_ceph_command(self.rados_config_file, cmd, inbuf='')
report status of monitors :return: (string outbuf, string outs) :raise CephError: Raises CephError on command execution errors :raise rados.Error: Raises on rados errors
625941f25510c4643540f99d
@app.errorhandler(400) <NEW_LINE> def handle_error2(err): <NEW_LINE> <INDENT> messages = err.data.get("messages", ["Invalid request."]) <NEW_LINE> return jsonify({"_0": "Internal data mismatch", "errors": messages}), 400
Flask error handler.
625941f25e10d32532c5f4ed
def SA_DiffCoeff(T,P): <NEW_LINE> <INDENT> Dref=0.0786 <NEW_LINE> Patm=1013.25 <NEW_LINE> Tref=298. <NEW_LINE> D=Dref*(Patm/P)*(T/Tref)**1.75 <NEW_LINE> return D
This function scales sulfuric acid diffusion coefficient to the real sampling temperature and pressure. This script is based on Hanson and Eisele 2000. Input: P in hPa T in Kelvin Output: D in cm2/s
625941f231939e2706e4d42a
def testAccordionItem3(self): <NEW_LINE> <INDENT> self.driver.get('https://willwile4.github.io') <NEW_LINE> self.driver.find_element(By.ID, 'portfolio-3').click() <NEW_LINE> return (EC.invisibility_of_element_located((By.ID, 'p2-p')) and EC.invisibility_of_element_located((By.ID, 'p2-links')) and EC.presence_of_element...
tests portfolio-2 item closes and portfolio-3 item opens on click
625941f263f4b57ef00016d0
def coeffs2vals(coeffs): <NEW_LINE> <INDENT> n = len(coeffs) <NEW_LINE> coeffs2 = coeffs.copy() <NEW_LINE> coeffs2[1:n-2] = 1/2*coeffs2[1:n-2] <NEW_LINE> tmp = np.concatenate((coeffs2, coeffs2[-2:0:-1])) <NEW_LINE> values = np.fft.fft(tmp, axis=0) <NEW_LINE> values = np.real(values[n-1::-1]) <NEW_LINE> return values
Convert Chebyshev coefficients to values at Chebyshev points.
625941f273bcbd0ca4b2c63e
def testSendSMS(self): <NEW_LINE> <INDENT> commands.getoutput('adb shell am start ' + self.runComponent) <NEW_LINE> assert d(text = 'Messaging').wait.exists(), 'Message launch failed' <NEW_LINE> self._clearMessage() <NEW_LINE> commands.getoutput('adb shell am start -a android.intent.action.SEND --es address ' + MESSAG...
Summary:testSendSMS: Send a SMS. #Init condition:Clear up all messagebox Steps:1. Open Messages app 2. Touch Compose button 3. Input deliver number and content 4. Touch Send button 5. Delete all messages 6. Exit Messages app
625941f266656f66f7cbc775
def intersection(self, end1, start2, end2, height=None, wrap=False): <NEW_LINE> <INDENT> return intersection(self, end1, start2, end2, height=height, wrap=wrap, LatLon=self.classof)
Locate the intersection point of two paths both defined by two points or a start point and bearing from North. @param end1: End point of the first path (L{LatLon}) or the initial bearing at this point (compass C{degrees360}). @param start2: Start point of the second path (L{LatLon}). @param e...
625941f22eb69b55b151ce81
def findFrequentTreeSum(self, root): <NEW_LINE> <INDENT> sum = [] <NEW_LINE> sumTree(root,sum) <NEW_LINE> counter = collections.Counter(sum) <NEW_LINE> most_common = counter.most_common() <NEW_LINE> if len(most_common) == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = [] <NEW_LINE>...
:type root: TreeNode :rtype: List[int]
625941f2460517430c39473d
def show_top_values(self, df, column, n=5, group='15min'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> values=df[column].value_counts()[:n] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> values=df[column].value_counts()[:] <NEW_LINE> <DEDENT> value_list = list(values.index) <NEW_LINE> if type(value_list)!=list: <NEW_...
Displays a chart with the top values for the specified column, very similar to count_top_values() but plots the results as well Call it as show_top_values(DataFrame, column, [n=5], [group=15min])
625941f29b70327d1c4e13a1
def setWord(self, key, value): <NEW_LINE> <INDENT> if not isinstance(key, (str)) or not isinstance(value, (str)): <NEW_LINE> <INDENT> raise ValueError("key或value必须为str类型") <NEW_LINE> <DEDENT> self.redis.set(key, value)
设置chenzhe的语录,将会持久化保存 params: key 键 value 值
625941f25fc7496912cc3f46
def densenet161(pretrained, **kwargs): <NEW_LINE> <INDENT> return _densenet(48, (6, 12, 36, 24), 96, pretrained, **kwargs)
Densenet-161 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr memory_efficient (bool) - If True, uses checkpoi...
625941f2ac7a0e7691ed4689
def _try_cwd(ftp, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ftp.cwd(item) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False
purpose: Determine if item is an ftp folder. Try to cwd into the item. If you can cwd it's a folder, if not, it's a file. arguments: ftp: ftplib.FTP an authenticated ftp connection item: string the name of the folder you are trying to cwd into return value: boolean True if the it...
625941f2ec188e330fd5ad5b
def test_array___delattr__(self): <NEW_LINE> <INDENT> pass
TODO
625941f24c3428357757c8ed
def pca_scatter( adata, color=None, use_raw=True, sort_order=True, alpha=None, groups=None, components=None, projection='2d', legend_loc='right margin', legend_fontsize=None, legend_fontweight=None, color_map=None, palette=None, right_margin=None, size=None, title=None, show=None, save=None, ax=None): <NEW_LINE> <INDEN...
Scatter plot in PCA coordinates. Parameters ---------- adata : :class:`~scanpy.api.AnnData` Annotated data matrix. color : string or list of strings, optional (default: None) Keys for observation/cell annotation either as list `["ann1", "ann2"]` or string `"ann1,ann2,..."`. use_raw : `bool`, optional (defa...
625941f2cb5e8a47e48b8069
def __init__(self, project, gui, cb_on_finish, cb_acq_error, cb_image_capture_done) : <NEW_LINE> <INDENT> self.project = project <NEW_LINE> self.gui = gui <NEW_LINE> self._cb_on_finish = cb_on_finish <NEW_LINE> self._cb_acq_error = cb_acq_error <NEW_LINE> self._cb_image_capture_done = cb_image_capture_done <NEW_LINE> s...
Init Thread, init gobject timer and clear progressbar
625941f25fcc89381b1e1c8d
def stat_mtime(stat): <NEW_LINE> <INDENT> return stat[8]
Returns the mtime field from the results returned by os.stat().
625941f21f037a2d8b9467c5
def get_available_name(self, name, max_length=None): <NEW_LINE> <INDENT> self.delete(name) <NEW_LINE> return name
Returns a filename that's free on the target storage system, and available for new content to be written to. Found at http://djangosnippets.org/snippets/976/ This file storage solves overwrite on upload problem. Another proposed solution was to override the save method on the model like so (from https://code.djangopr...
625941f2f548e778e58cdb49
def hasSpatialIndex(self): <NEW_LINE> <INDENT> return False
PulseWaves does not have a spatial index
625941f2091ae3566866751d
@pytest.mark.parametrize('x', ['foo', 1, True, False, 0, '', 2.3]) <NEW_LINE> def test_optional_with_value(x): <NEW_LINE> <INDENT> fn = mod.optional() <NEW_LINE> assert fn(x) == x
When optional() is called, it returns a function that does not raise for none-None values, and returns the value it was passed..
625941f2cc40096d61595f17
def export(plot, filename, width=800, height=600): <NEW_LINE> <INDENT> import signal <NEW_LINE> import uuid <NEW_LINE> from selenium.webdriver import PhantomJS <NEW_LINE> global __templates__, __cwd__ <NEW_LINE> phantom = PhantomJS(service_log_path=os.path.devnull) <NEW_LINE> tmpl = os.path.join(__templates__, 'export....
Export plot to file. Args: plot (quorra.Plot): Quorra plot object to export. width (int): Width for plot (pixels). height (int): Height for plot (pixels). filename (str): Filename to export to.
625941f250485f2cf553d365
def global_open_items(a_items=None, a_reset_scrollbar=False): <NEW_LINE> <INDENT> if ITEM_EDITOR.items or a_items: <NEW_LINE> <INDENT> ITEM_EDITOR.enabled = True <NEW_LINE> <DEDENT> global OPEN_ITEM_NAMES, OPEN_ITEM_UIDS, LAST_OPEN_ITEM_UIDS, LAST_OPEN_ITEM_NAMES <NEW_LINE> if a_items is not None: <NEW_LINE> <IN...
a_items is a list of str, which are the names of the items. Leave blank to open the existing list
625941f238b623060ff0b3b6
def minDepth(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if not root.left: <NEW_LINE> <INDENT> return self.minDepth(root.right) + 1 <NEW_LINE> <DEDENT> elif not root.right: <NEW_LINE> <INDENT> return self.minDepth(root.left) + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN...
:type root: TreeNode :rtype: int
625941f257b8e32f52483a68
def index(self, value): <NEW_LINE> <INDENT> for index in range(len(self)): <NEW_LINE> <INDENT> if self[index] == value: <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> <DEDENT> raise ValueError('Value not in array')
Returns first index of given value. Raises ValueError if value is not in this SparseArray. O(n) Args: value (int) : value to search for Returns: int : first index of value
625941f2e8904600ed9f2500
def _tree_load_link(self, new_traj_node, load_data, traj, as_new, hdf5_soft_link): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> linked_group = hdf5_soft_link() <NEW_LINE> link_name = hdf5_soft_link._v_name <NEW_LINE> if (not link_name in new_traj_node._links or load_data==pypetconstants.OVERWRITE_DATA): <NEW_LINE> <IND...
Loads a link :param new_traj_node: Node in traj containing link :param load_data: How to load data in the linked node :param traj: The trajectory :param as_new: If data in linked node should be loaded as new :param hdf5_soft_link: The hdf5 soft link
625941f2be383301e01b5a43
def _pre_condition(self): <NEW_LINE> <INDENT> self.logger.info("Checking precondition for MakeMasterSky") <NEW_LINE> suffix = self.action.args.new_type.lower() <NEW_LINE> ofn = self.action.args.name <NEW_LINE> rdir = self.config.instrument.output_directory <NEW_LINE> skyfile = None <NEW_LINE> skymask = None <NEW_LINE> ...
Checks if we can create a master sky :return:
625941f2167d2b6e3121915d
def as_dict(self) -> OrderedDictType[str, Any]: <NEW_LINE> <INDENT> context_dict: OrderedDict[str, Any] = OrderedDict() <NEW_LINE> context_dict[HELP] = self.help <NEW_LINE> if len(self.aliases) != 0: <NEW_LINE> <INDENT> context_dict[ALIASES] = self.aliases <NEW_LINE> <DEDENT> if self.parent is not None: <NEW_LINE> <IND...
Encode context as a dictionary. This is used in order to serialize the context in a configuration file. :return: Serialized representation dictionary :rtype: OrderedDict[str, Any]
625941f2167d2b6e3121915e
def test_sparse(self): <NEW_LINE> <INDENT> conversors = [ConversorStub(str if arff.PY3 else unicode), ConversorStub(float), ConversorStub(int), ConversorStub(str if arff.PY3 else unicode), ConversorStub(float), ConversorStub(int)] <NEW_LINE> fixture = u'{0 Iris,1 3.4, 2 2}' <NEW_LINE> self.data.decode_data(fixture, con...
Basic data instances.
625941f2925a0f43d254a446
def parse_events(data): <NEW_LINE> <INDENT> for event in data: <NEW_LINE> <INDENT> ingest(event)
:param data: given and array of nested json objects, separate each event 'type' to it's own dictionary. :return: Nothing
625941f27cff6e4e81117f4e
def __init__(self, zenpack, ): <NEW_LINE> <INDENT> super(ImpactPy, self).__init__(zenpack) <NEW_LINE> self.source_template = 'impact.tmpl' <NEW_LINE> self.zenpack = zenpack <NEW_LINE> self.components = zenpack.components <NEW_LINE> self.dest_file = "%s/impact.py" % zpDir(zenpack) <NEW_LINE> self.imports = defaults.get(...
Args: zenpack: ZenPack class instance
625941f2bd1bec0571d90bf8
def findMedianSortedArrays(self, nums1, nums2): <NEW_LINE> <INDENT> new_nums = nums1 + nums2 <NEW_LINE> new_nums = sorted(new_nums) <NEW_LINE> key = int(len(new_nums)/2) <NEW_LINE> if len(new_nums) % 2 == 0: <NEW_LINE> <INDENT> return float((new_nums[key] + new_nums[key-1])/2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE...
:type nums1: List[int] :type nums2: List[int] :rtype: float 取巧行为
625941f20383005118ecfba9
def getHighDataSeries(self): <NEW_LINE> <INDENT> return BarValueDataSeries(self, bar.Bar.getHigh)
Returns a :class:`DataSeries` with the high prices.
625941f22c8b7c6e89b35d85
def grid(): <NEW_LINE> <INDENT> action, table, id=request.args(0), request.args(1), request.args(2) <NEW_LINE> if action in ["new", "edit"]: <NEW_LINE> <INDENT> request.args=[id] <NEW_LINE> response.view='plugin_dialog/edit.html' <NEW_LINE> return edit() <NEW_LINE> <DEDENT> grid = SQLFORM.grid(query=db.plugin_dialog_cu...
loads grid via ajax so it can be refreshed when it changes
625941f292d797404e304756
def sinkhole(self, peer, query): <NEW_LINE> <INDENT> logger = self.foghorn.logging.debug <NEW_LINE> logger("sinkhole: %s - %s" % (peer, query))
A query will be sinkholed
625941f23617ad0b5ed684bf
def is_connected(self, i, j): <NEW_LINE> <INDENT> if i >= self.N or j >= self.N: return False <NEW_LINE> else: return j in self.G[i]
checks if i and j are connected
625941f2d164cc6175783318
def get_ka_learn_menu_topics(lang, curriculum=None): <NEW_LINE> <INDENT> post_data = { "operationName": "learnMenuTopicsQuery", "variables": {}, "query":"query learnMenuTopicsQuery($curriculum: String) {\n learnMenuTopics(curriculum: $curriculum) {\n slug\n translatedTitle\n href\n children {\n slug\n...
Obtain the custom menu from the Khan Academy website for language `lang` and `curriculum`, see for example https://es.khanacademy.org/?curriculum=pe-pe .
625941f23c8af77a43ae3d71
def _build_cache_names(self): <NEW_LINE> <INDENT> cache_basename = os.path.basename(os.path.normpath(self.dataset_root)) <NEW_LINE> if self.options['data_aug']: <NEW_LINE> <INDENT> cache_basename = cache_basename + '_aug' <NEW_LINE> <DEDENT> self.videos_train_cache = os.path.join(self.dataset_root, cache_basename + '_v...
Construct the list of file names for the cache
625941f29c8ee82313fbbd41
def replace_latex(s, escape_slash=False): <NEW_LINE> <INDENT> any_math_char = 'A-Za-z0-9{}\[\],;|\(\)=./\/+-_^\'' <NEW_LINE> pattern_1 = '\$(['+any_math_char+']['+any_math_char+' ]*['+any_math_char+']+)\$' <NEW_LINE> pattern_2 = '\$(['+any_math_char+'])\$' <NEW_LINE> text=re.sub('\$'+pattern_1+'\$', r'\n\n.. math::\n\t...
replace $XX X$ by :math:`XX X` $$X XX$$ by .. math: X XX .. [[ XXX]] by :ref:` XXX`
625941f2377c676e91272770
def test_bigger_than_infinity(self): <NEW_LINE> <INDENT> h3 = _create_host("h3") <NEW_LINE> self.router.table.update({ h3: TableEntry( dst=h3, port=1, latency=INFINITY+1, expire_time=FOREVER, ) }) <NEW_LINE> packet = Packet(dst=h3, src=_create_host("hz")) <NEW_LINE> with self._ensure_no_send(all_ports={1, 2, 3}): <NEW_...
Ensures packets for destinations of latency larger than infinity are dropped.
625941f294891a1f4081c075
def test_LinearDiscriminantAnalysis_solver(*data): <NEW_LINE> <INDENT> X_train,X_test,y_train,y_test=data <NEW_LINE> solvers=['svd','lsqr','eigen'] <NEW_LINE> for solver in solvers: <NEW_LINE> <INDENT> if(solver=='svd'): <NEW_LINE> <INDENT> lda = discriminant_analysis.LinearDiscriminantAnalysis(solver=solver) <NEW_LINE...
测试 LinearDiscriminantAnalysis 的预测性能随 solver 参数的影响 :param data: 可变参数。它是一个元组,这里要求其元素依次为:训练样本集、测试样本集、训练样本的标记、测试样本的标记 :return: None
625941f2b830903b967e9ece
def get_raw_image(self, image_id): <NEW_LINE> <INDENT> return self.compute_connection.get_image(image_id)
Find image by id
625941f2b7558d58953c54d0
def updateSelectedEntryRow(self, entryDict): <NEW_LINE> <INDENT> return self.entryList.updateSelectedEntryRow(entryDict)
See L{EntryList.updateSelectedEntryRow}.
625941f221a7993f00bc82c4
def auth_header(token): <NEW_LINE> <INDENT> return {'Authorization': f'Bearer {token}'}
Auth header object for Density API
625941f20fa83653e4657580
def test_get_date_list_staff(self): <NEW_LINE> <INDENT> self.article1.status = Article.STATUS.draft <NEW_LINE> self.article1.save() <NEW_LINE> user = User.objects.create_user('john.doe', 'john.doe@example.com', 'secret') <NEW_LINE> user.is_staff = True <NEW_LINE> user.save() <NEW_LINE> self.assertTrue(self.client.login...
Archive view has a list of years for which we have articles - staff will see all articles. This behaviour is a result of us overriding the get_queryset() method in the view.
625941f2c432627299f05214
def get_root(self): <NEW_LINE> <INDENT> temp = self <NEW_LINE> while not temp.is_root(): <NEW_LINE> <INDENT> temp = temp.get_ancestor() <NEW_LINE> <DEDENT> return temp
Returns root ancestor for given CascaDict.
625941f23617ad0b5ed684c0
def successors(self): <NEW_LINE> <INDENT> return [(move, self.make_move(move)) for move in self.legal_moves()]
Returns a list of legal (move, state) pairs
625941f226068e7796caf2b1
def connect(path,name=None, provider_name=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from os.path import splitext <NEW_LINE> if not provider_name: <NEW_LINE> <INDENT> ext = splitext(path)[-1] <NEW_LINE> ext = ext[1:4].lower() <NEW_LINE> p_map = {"mtd":"SPSS MTD File" , "xml":"Tabs ML" , "xls":"Excel 2007/2010 ...
uses the matrix handler to create a connection to a file based datasource
625941f223849d37ff7b3654
def to_string(self): <NEW_LINE> <INDENT> node = quote_if_necessary(self.obj_dict['name']) <NEW_LINE> node_attr = list() <NEW_LINE> for attr in self.obj_dict['attributes']: <NEW_LINE> <INDENT> value = self.obj_dict['attributes'][attr] <NEW_LINE> if value is not None: <NEW_LINE> <INDENT> node_attr.append( '%s=%s' % (attr...
Returns a string representation of the node in dot language.
625941f2de87d2750b860363
def object_map(api): <NEW_LINE> <INDENT> uid_mapping = {} <NEW_LINE> params1 = {'paging': False} <NEW_LINE> resp1 = api.get(endpoint='indicatorTypes', params=params1).json() <NEW_LINE> for elem in resp1['indicatorTypes']: <NEW_LINE> <INDENT> uid_mapping[elem['id']] = {u'desc': u"{}".format(elem['displayName'])} <NEW_LI...
get all relevant objects from the server and put it in a single dictionary
625941f26fb2d068a760f670
def GetDomains(self): <NEW_LINE> <INDENT> url = "http://" + HOST + PATH <NEW_LINE> url = url.replace(' ', '%20') <NEW_LINE> token = self.op.token_of_request(url) <NEW_LINE> header = {'Authorization': 'QBox %s' % token} <NEW_LINE> try: <NEW_LINE> <INDENT> re = requests.get(url, headers=header) <NEW_LINE> info = {'code':...
marker=None,limit=None,domainPrefix=None,sourceType=None,sourceQiniuBucket=None :param kwargs: :return:
625941f2498bea3a759ba077
def interface_tengigabitethernet_ip_pim_intf_phy_cont_pim_int_cmd_mcast_bdry_prefix_list(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete_interface', False) is True: <NE...
Auto Generated Code
625941f230bbd722463cc393
def plotter(density, image_name, default_cm=None, pixels=2000, pad_inches=None): <NEW_LINE> <INDENT> specialmaps1 = ['plasma', 'cool'] <NEW_LINE> specialmaps2 = ['spring', 'cool_r', 'spring_r'] <NEW_LINE> n_grid = density.shape[0] <NEW_LINE> (rows,cols) = np.nonzero(density) <NEW_LINE> vals = np.log(density[(rows,cols)...
Plot in a specific way and save
625941f263f4b57ef00016d1
def get_lunacode(name: str, is_clean_globals=True) -> LunaCode: <NEW_LINE> <INDENT> filename = os.path.join(DIR_PATTERNS, name + '.lua') <NEW_LINE> with open(filename) as f: <NEW_LINE> <INDENT> lua_code = f.read() <NEW_LINE> <DEDENT> return LunaCode(name, lua_code, is_clean_globals)
Фабрика по созданию объектов LunaCode :param name: Имя паттерна :param is_clean_globals: :return: объект
625941f2462c4b4f79d1dc99
def is_mounted(mount_point): <NEW_LINE> <INDENT> return get_mount(mount_point) is not None
Check if mount point is mounted. :param mount_point: Name of mount point :return bool:
625941f2460517430c39473e
@main.route('/my_story') <NEW_LINE> def my_story(): <NEW_LINE> <INDENT> title = "Blogers' Life Story." <NEW_LINE> return render_template('my_story.html',title = title)
view root page function that returns the my_story page and its data
625941f273bcbd0ca4b2c63f
def __init__(self, k, nums): <NEW_LINE> <INDENT> nums.sort() <NEW_LINE> self.heap = nums[-k:] <NEW_LINE> self.k = k <NEW_LINE> heapq.heapify(self.heap)
:type k: int :type nums: list[int]
625941f27d43ff24873a326f
@reg.register_compute("nn.conv2d") <NEW_LINE> def compute_conv2d(attrs, inputs, out_type, target): <NEW_LINE> <INDENT> padding = get_const_tuple(attrs.padding) <NEW_LINE> strides = get_const_tuple(attrs.strides) <NEW_LINE> dilation = get_const_tuple(attrs.dilation) <NEW_LINE> groups = attrs.groups <NEW_LINE> layout = a...
Compute definition of conv2d
625941f20a50d4780f667461
def enableProtocolOnPort(self, protocol, portName, enable=True): <NEW_LINE> <INDENT> vport = self.portMgmtObj.getVportObjectByName(portName) <NEW_LINE> if vport == None: <NEW_LINE> <INDENT> raise IxNetRestApiException('PortName {0} not connected to chassis'.format(portName)) <NEW_LINE> <DEDENT> RouterInstanceList = sel...
Description Enable protocol on a speficied port Parameters protocol: <str>: Protocol to start portName: <str>: Name of the port eg: '1/1/11' enable: <bool> enable or disable specified protocol. default is True Syntax PATCH: /api/v1/sessions/{id}/ixnetwork/vport/{id}/protocols/<protocol>/router/{id}...
625941f2e1aae11d1e74a287
def timedelta_2_str(td): <NEW_LINE> <INDENT> if isinstance(td, pd.Timedelta): <NEW_LINE> <INDENT> ret = str(td).split()[-1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret = td <NEW_LINE> <DEDENT> return ret
用于将 pd.Timedelta 类型转换为 str 类型 :param td: :return:
625941f28e05c05ec3eea943
def test_errs(): <NEW_LINE> <INDENT> default_map_dir = os.path.join( __rlpy_location__, "Domains", "SystemAdministratorMaps") <NEW_LINE> domain = SystemAdministrator(networkmapname=os.path.join( default_map_dir, "20MachTutorial.txt"))
Ensure that we can call custom methods without error
625941f2ec188e330fd5ad5c
def ReadChiProfileCSV(DataDirectory, fname_prefix): <NEW_LINE> <INDENT> import os <NEW_LINE> profile_suffix = '_burned_movern.csv' <NEW_LINE> fname = fname_prefix+profile_suffix <NEW_LINE> if not os.path.isfile(DataDirectory+fname): <NEW_LINE> <INDENT> print ("Reading the csv...") <NEW_LINE> fname = fname_prefix+'_move...
This function reads in the file with the suffix '_movern.csv', which contains the data for the full chi profiles, to a pandas dataframe. Args: DataDirectory: the data directory fname_prefix: the file name prefix Returns: pandas dataframe with the csv file Author: FJC
625941f2fbf16365ca6f679a
def test_execute(self): <NEW_LINE> <INDENT> class DummyError(Exception): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class DummyCursor(object): <NEW_LINE> <INDENT> def __init__(self, conn): <NEW_LINE> <INDENT> self.conn = conn <NEW_LINE> <DEDENT> def execute(self, query, args): <NEW_LINE> <INDENT> if query == 'execute...
Test Database._execute method
625941f2b545ff76a89143df
def drop_tenant_schema(tenant, using=None): <NEW_LINE> <INDENT> using = using or router.db_for_write(tenant.__class__, instance=tenant) <NEW_LINE> connection = connections[using] <NEW_LINE> quote_name = connection.ops.quote_name <NEW_LINE> pre_tenant_schema_deletion.send( sender=tenant.__class__, tenant=tenant, using=u...
DROP the tables associated with a tenant's models.
625941f2bd1bec0571d90bf9
def anchorIndex(self, anchor): <NEW_LINE> <INDENT> return self._anchors.index(anchor)
Get the index for **anchor**.
625941f2a219f33f34628f2b
def get_page(self, title, follow_redirects=True): <NEW_LINE> <INDENT> page = self.site.Pages[title] <NEW_LINE> while follow_redirects and page.redirect: <NEW_LINE> <INDENT> page = next(page.links()) <NEW_LINE> <DEDENT> return page
Get a Page object.
625941f291f36d47f21acac3
def create_swing_strategies(env: ExecEnv) -> List['AbstractStrategy']: <NEW_LINE> <INDENT> return [ cls(env=env, symbols=['DUMMY']) for cls in SWING_STRATEGY_CLASSES ]
Creates AbstractStrategy objects for all available swing-trading strategies, and assigns them env objects.
625941f25fdd1c0f98dc07ff
def test_wf_lzoutall_1(plugin, tmpdir): <NEW_LINE> <INDENT> wf = Workflow(name="wf_2", input_spec=["x", "y"]) <NEW_LINE> wf.add(multiply(name="mult", x=wf.lzin.x, y=wf.lzin.y)) <NEW_LINE> wf.add(add2_sub2_res(name="add_sub", res=wf.mult.lzout.all_)) <NEW_LINE> wf.set_output([("out", wf.add_sub.lzout.out_add)]) <NEW_LIN...
workflow with 2 tasks, no splitter passing entire result object to add2_sub2_res function by using lzout.all syntax
625941f28a43f66fc4b54629
def set_sanitized_hostname(self): <NEW_LINE> <INDENT> self._sanitized_hostname = get_sanitized_hostname()
Get the sanitized hostname of the host This will lower it and keep only the part before the first dot
625941f2fff4ab517eb2fa0a
def find_eg(name): <NEW_LINE> <INDENT> global ap_examples <NEW_LINE> populate_examples() <NEW_LINE> for eg in ap_examples: <NEW_LINE> <INDENT> if eg.name.lower() == name.lower(): <NEW_LINE> <INDENT> return eg <NEW_LINE> <DEDENT> <DEDENT> return None
try to find a matching ap_examples instance consider things like: if failure, and if 'name' is substring of only 1 example, return it return None on failure
625941f2cad5886f8bd275a2
def generate(self, B, E): <NEW_LINE> <INDENT> self.e = int(E, 16) <NEW_LINE> (pubkey, prikey) = rsa.newkeys(B) <NEW_LINE> self.n = pubkey.n <NEW_LINE> self.e = pubkey.e <NEW_LINE> self.d = prikey.d <NEW_LINE> self.p = prikey.p <NEW_LINE> self.q = prikey.q <NEW_LINE> self.dmp1 = prikey.exp1 <NEW_LINE> self.dmq1 = prikey...
Generate a new random private key B bits long, using public expt E
625941f2e5267d203edce260
def _translateToLonghand(self): <NEW_LINE> <INDENT> oldNumbers = self.numbers <NEW_LINE> newNumbers = oldNumbers <NEW_LINE> oldModifierStrings = self.modifierStrings <NEW_LINE> newModifierStrings = oldModifierStrings <NEW_LINE> try: <NEW_LINE> <INDENT> newNumbers = shorthandNotation[oldNumbers] <NEW_LINE> newModifierSt...
Provided the numbers and modifierStrings of a parsed notation column, translates it to longhand. >>> from music21.figuredBass import notation as n >>> notation1 = n.Notation('#6,5') #__init__ method calls _parseNotationColumn() >>> str(notation1.origNumbers) + " -> " + str(notation1.numbers) '(6, 5) -> (6, 5, 3)' >>>...
625941f276d4e153a657f0fd
def get_red(pix): <NEW_LINE> <INDENT> return pix.get_red()
Return the red value of Pixel pix.
625941f2e64d504609d74e0a
def draw_time(self): <NEW_LINE> <INDENT> if self.wait_end: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> time_img = self.img_time.copy() <NEW_LINE> t = int(time.time() - self.start_time) <NEW_LINE> if t > MAX_TIME: <NEW_LINE> <INDENT> self.start_time = time.time() <NEW_LINE> t = 0 <NEW_LINE> self.timeout[self.turn] +=...
绘制双方剩余的时间。
625941f28e71fb1e9831dd71
def mean(self) -> Union[DataFrame, Series]: <NEW_LINE> <INDENT> return self._reduce_for_stat_function(F.mean, only_numeric=True)
Compute mean of groups, excluding missing values. Returns ------- koalas.Series or koalas.DataFrame See Also -------- pyspark.pandas.Series.groupby pyspark.pandas.DataFrame.groupby Examples -------- >>> df = ps.DataFrame({'A': [1, 1, 2, 1, 2], ... 'B': [np.nan, 2, 3, 4, 5], ... ...
625941f273bcbd0ca4b2c640
def second_menu_del(request, pk): <NEW_LINE> <INDENT> url = memory_reverse(request, 'rbac:menu_list') <NEW_LINE> if request.method == 'GET': <NEW_LINE> <INDENT> return render(request, 'rbac/delete.html', {'cancel': url}) <NEW_LINE> <DEDENT> models.Permission.objects.filter(id=pk).delete() <NEW_LINE> return redirect(url...
:param request: :param pk: :return:
625941f276e4537e8c351c42
def test_getPAZFromXSEED(self): <NEW_LINE> <INDENT> filename = os.path.join(self.path, 'dataless.seed.BW_FURT') <NEW_LINE> sp1 = Parser(filename) <NEW_LINE> sp2 = Parser(sp1.get_XSEED()) <NEW_LINE> paz = sp2.getPAZ('EHE') <NEW_LINE> result = {'gain': 1.00000e+00, 'zeros': [0j, 0j, 0j], 'poles': [(-4.44400e+00 + 4.44400...
Get PAZ from XSEED file, testcase for #146
625941f23346ee7daa2b333c
def allow_connection_pickling(): <NEW_LINE> <INDENT> from . import connection
Install support for sending connections and sockets between processes
625941f28a349b6b435e873d
@api_view(['POST']) <NEW_LINE> def save_scan_list(request: Request) -> Response: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with transaction.atomic(): <NEW_LINE> <INDENT> scan_list = ScanList.objects.create( name=request.data['listname'], description=request.data['description'], private=bool(request.data['isprivate']...
Save a new list.
625941f25f7d997b87175068
def build_model_rnn(n_hidden: int = DEFAULT_N_HIDDEN, n_units: int = DEFAULT_N_UNITS, lambda_: float = DEFAULT_LAMBDA, learning_rate: float = DEFAULT_LEARNING_RATE ) -> tf.keras.models.Sequential: <NEW_LINE> <INDENT> model = tf.keras.models.Sequential() <NEW_LINE> for layer in range(n_hidden): <NEW_LINE> <INDENT> model...
Function to build RNN model according to input parameters. :param n_hidden: number of hidden layers :param n_units: number of units in each hidden layer :param lambda_: L2 regularization parameter :param learning_rate: learning rate parameter :return: RNN model
625941f221bff66bcd684f17
def eopen(file, path=None): <NEW_LINE> <INDENT> path = path if path else os.getcwd() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(os.path.join(path, file), 'r') as gee: <NEW_LINE> <INDENT> thefile = json.load(gee) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> with open(os.path.join(path, file+'.gee'...
Opens a files saved with `esave` method :return: the EE object
625941f2a4f1c619b28b05f5