code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, pixel_count=1, port='/dev/ttyAMA0', baudrate=115200): <NEW_LINE> <INDENT> self._serial_port = port <NEW_LINE> self._serial = Serial(port, baudrate=baudrate) <NEW_LINE> Plasma.__init__(self, pixel_count)
Initialise Serial device. :param pixel_count: Number of individual RGB LEDs :param port: Serial port name/path :param baudrate: Serial baud rate
625941eb55399d3f05588bb2
def test_kmod_free(self): <NEW_LINE> <INDENT> h = jockey.handlers.KernelModuleHandler(self.backend, 'vanilla') <NEW_LINE> self.assertEqual(h.name(), sandbox.fake_modinfo['vanilla']['description']) <NEW_LINE> self.assertEqual(h.id(), 'kmod:vanilla') <NEW_LINE> self.assertEqual(str(h), 'kmod:vanilla([KernelModuleHandler,...
KernelModuleHandler: free, no description, used
625941eb1b99ca400220afae
def get_effect(self, label: str) -> Effect: <NEW_LINE> <INDENT> return self._get_resource(label, self._effects, "effect")
Get an effect instance by label Args: label (str): The label for the effect instance Returns: Effect class instance
625941eba8ecb033257d35c5
def getraw(self, section, option): <NEW_LINE> <INDENT> return self[section].getraw(option)
Get the raw (un-interpolated) value of an option
625941eb7cff6e4e81117e80
def show(self, prefix=''): <NEW_LINE> <INDENT> outstr = '' <NEW_LINE> outstr += prefix + 'match: \n' <NEW_LINE> self.match.show(prefix + ' ') <NEW_LINE> outstr += prefix + 'table_id: ' + str(self.table_id) + '\n' <NEW_LINE> outstr += prefix + 'out_port: ' + str(self.out_port) + '\n' <NEW_LINE> return outstr
Generate string showing basic members of structure
625941ebe76e3b2f99f3acfd
def __call__(self, value): <NEW_LINE> <INDENT> return value
Returns the same value
625941ebb5575c28eb68e4ff
def addTranslationFile(self, domain, path_en_EN, path_de_DE=None, path_ru_RU=None, path_fr_FR=None): <NEW_LINE> <INDENT> fb_en = gettext.translation( domain, localedir=path_en_EN, languages=["en_US"], fallback=True) <NEW_LINE> if path_de_DE != None: <NEW_LINE> <INDENT> fb_de = gettext.translation( domain, localedir=pat...
Adds the given translation files as fallback for the general translation files. If the path to a language is None, then the path to the english fallback translation file will be used as a fallback. At least a path to an english translation has to be given.
625941eb99cbb53fe67930df
def _group_normals(normals): <NEW_LINE> <INDENT> nset = set() <NEW_LINE> unique_normals = [] <NEW_LINE> unique_map = [] <NEW_LINE> unique_i = -1 <NEW_LINE> for i in range(len(normals)): <NEW_LINE> <INDENT> normal = normals[i] <NEW_LINE> ntuple = (normal[0], normal[1], normal[2]) <NEW_LINE> if ntuple not in nset: <NEW_L...
Identify equal normals so that those can be shared by faces. This reduces storage space in obj-files and accelerates raytracing.
625941eb5f7d997b87174f97
def test_cast_vdata_reg_expand_sz(self): <NEW_LINE> <INDENT> vdata = salt.utils.stringutils.to_str("test data") <NEW_LINE> result = win_reg.cast_vdata(vdata=vdata, vtype="REG_EXPAND_SZ") <NEW_LINE> self.assertTrue(isinstance(result, six.text_type)) <NEW_LINE> vdata = salt.utils.stringutils.to_bytes("test data") <NEW_LI...
Test the cast_vdata function with REG_EXPAND_SZ Should always return unicode
625941eb4c3428357757c81f
def test_log_transform(): <NEW_LINE> <INDENT> def fn(module): <NEW_LINE> <INDENT> module.operation.value = cellprofiler.modules.imagemath.O_LOG_TRANSFORM <NEW_LINE> module.truncate_low.value = False <NEW_LINE> <DEDENT> numpy.random.seed(0) <NEW_LINE> image = numpy.random.uniform(size=(10, 10)).astype(numpy.float32) <NE...
Test log transform of an image
625941ebd164cc6175783249
def functions(macke_directory): <NEW_LINE> <INDENT> clg = CallGraph(path.join(macke_directory, "bitcode", "program.bc")) <NEW_LINE> totalfunccount = sum(1 for _, info in clg.graph.items() if not info["isexternal"]) <NEW_LINE> symenccount = sum(1 for func in clg.graph if clg.is_symbolic_encapsulable(func)) <NEW_LINE> re...
Extract all informations about the functions of a program as an OrderedDict
625941eb44b2445a3393258c
def _get_counts(self, dir_info): <NEW_LINE> <INDENT> file_count = dir_info['file_count'] <NEW_LINE> dir_count = len(dir_info['dirs']) <NEW_LINE> for subdir_info in dir_info['dirs'].values(): <NEW_LINE> <INDENT> sub_file_count, sub_dir_count = self._get_counts(subdir_info) <NEW_LINE> file_count += sub_file_count <NEW_LI...
Determines the total numbers of directories and files in the directory hierarchy below the directory of the specified info object. I.e. requires the info object to be filled with analysis results. @param dir_info - DirInfo, info object (with subdir info) @retval file_count, dir_count - (int, int) tuple, total number o...
625941eb796e427e537b0ac5
def connect_sftp(self): <NEW_LINE> <INDENT> print('Start to SFTP:') <NEW_LINE> sftp = paramiko.SFTPClient.from_transport(self.sf) <NEW_LINE> return sftp
建立sftp链接 :return:
625941ebf7d966606f6aa504
def register_contributors(self): <NEW_LINE> <INDENT> extension_points = PluginManager._extension_points <NEW_LINE> for name, attr in self.__class__.__dict__.iteritems(): <NEW_LINE> <INDENT> if callable(attr) and hasattr(attr, '_extension_point'): <NEW_LINE> <INDENT> if not attr._extension_point in extension_points: <NE...
Called by the plugin manager to register all contributor method of this plugin. This method is called after all extension points have been registered. If an extension point doesn't exist, an exception (PluginError) will be raised.
625941eb4e4d5625662d48cb
def clearProgramLogFile(): <NEW_LINE> <INDENT> tag = "{:23s} PROGRAM: pid:{:d} ########### {:s} ".format(longstime(), os.getpid(), "GeigerLog {} -- mit no meh pfupf underm füdli !".format(gglobs.__version__)) <NEW_LINE> line = tag + "#" * 30 <NEW_LINE> if gglobs.redirect: <NEW_LINE> <INDENT> sys.stdout = open...
To clear the debug file at the beginning of each run
625941eb956e5f7376d71366
def partial_transform(self, sequence): <NEW_LINE> <INDENT> return super(MultiSequenceDecompositionMixin, self).transform(sequence)
Apply dimensionality reduction to single sequence Parameters ---------- sequence: array like, shape (n_samples, n_features) A single sequence to transform Returns ------- out : array like, shape (n_samples, n_features)
625941eb627d3e7fe0d6934c
def posts_by_date(request, template="blogs/all_posts_list.html"): <NEW_LINE> <INDENT> posts = Document.objects.safe_for_user(request.user).filter( type="post" ) <NEW_LINE> context = _paginate(request, posts) <NEW_LINE> pnum = context['page'].number <NEW_LINE> context.update(get_nav_context()) <NEW_LINE> context['relate...
Show a list of posts by date
625941ebd99f1b3c44c67a80
def get_raw(self,reg_name=None): <NEW_LINE> <INDENT> assert len(self._data_reg) > 0,"No data register(s) implemented!" <NEW_LINE> if reg_name == None: <NEW_LINE> <INDENT> assert len(self._data_reg) == 1,"Need to specify data register!" <NEW_LINE> reg_name = self._data_reg[0] <NEW_LINE> <DEDENT> data = self.read(ctrl=se...
Read from a data register specified in 'self._data_reg'. Returns the value returned by self.read as a single (long) integer. Does not convert it according to e.g. two's compliment or a calibration. If only one register is defined in '_data_reg', 'reg_name' may be left empty.
625941eb92d797404e304687
def record(self): <NEW_LINE> <INDENT> if not os.path.exists(self.jobdir): <NEW_LINE> <INDENT> log_debug("creating '%s' folder for code pickling" % self.jobdir) <NEW_LINE> os.mkdir(self.jobdir) <NEW_LINE> <DEDENT> log_debug("writing '%s'" % self.filename) <NEW_LINE> if 'shared_data' in self.kwds: <NEW_LINE> <INDENT> del...
Records the job after evaluation on the disk.
625941eb435de62698dfe147
def is_climo(self): <NEW_LINE> <INDENT> if self.getCAxis() != 'T': <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return all((x == y for x,y in zip( sorted(self.getDate("m")), range(1, 13))))
Return True if the axis is a climatological time axis
625941ebf548e778e58cda7a
@pytest.fixture <NEW_LINE> def ok_provider(): <NEW_LINE> <INDENT> return 'odnoklassniki-oauth2'
Имя провайдера для социальной сети Одноклассники.
625941eba05bb46b383ecd17
def median_string(dnas, k): <NEW_LINE> <INDENT> assert (all(is_dna(dna) for dna in dnas)) <NEW_LINE> all_kmers = map(''.join, itertools.product('ACTG', repeat=k)) <NEW_LINE> return min(((kmer, dist(kmer, dnas)) for kmer in all_kmers), key=operator.itemgetter(1))
Find a median string (2B in BA_AALA) Median string is a kmer that minimizes d(pattern, dnas) among all possible kmers :param dnas: list of ACTG strings :param k: length of kmer :return: tuple(median_string, dist_median_dnas)
625941eba8370b7717052d98
def add(self, i, j): <NEW_LINE> <INDENT> self.pixels.append((i,j))
add a pixel (i, j) to the blob
625941eb283ffb24f3c55df7
def writeDouble(self, f): <NEW_LINE> <INDENT> pass
void QDataStream.writeDouble(float f)
625941eb851cf427c661aa05
def compareSplitsAll(self, precision=3, linewidth=120): <NEW_LINE> <INDENT> tpp = [m.treePartitions for m in self.mm] <NEW_LINE> p4.func.compareSplitsBetweenTreePartitions(tpp, precision=precision, linewidth=linewidth)
Do func.compareSplitsBetweenTreePartitions() for all pairs Output is verbose. Shows - average standard deviation of split frequencies (or supports), like MrBayes - maximum difference between split supports from each pair of checkpoints, like PhyloBayes Returns: None
625941eb4428ac0f6e5bacf1
def get_poster(self, size='small'): <NEW_LINE> <INDENT> assert isinstance(size, str) <NEW_LINE> if self.poster: <NEW_LINE> <INDENT> return '{}/po{}.{}.jpg'.format(common.URL_CDN, self.poster, common.poster_sizes[size])
Returns absolute path of specified size poster. :param str size: poster size (see common.poster_sizes) :return: URL :rtype: str or None
625941eb009cb60464c638a8
@tunnel_blueprint.route("/tunnels/<int:tunnel_id>", methods=["GET"]) <NEW_LINE> @jwt_required <NEW_LINE> def get_tunnel(tunnel_id) -> Tuple[Response, int]: <NEW_LINE> <INDENT> current_user = User.query.filter_by(uuid=get_jwt_identity()).first_or_404() <NEW_LINE> tunnel = Tunnel.query.filter_by(user=current_user, id=tun...
Retrieve Tunnel Resource
625941eba219f33f34628e5d
def plot_vs_bounds(df, validation_cases): <NEW_LINE> <INDENT> for args in validation_cases: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> vs_bounds(df, **args) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> logger.error(str(e)) <NEW_LINE> warnings.warn("ERROR: Validation Failed") <NEW_LINE> <DEDENT> bou...
Run through a data validation based on absolute bounds.
625941eb16aa5153ce362973
def in_order_traverse(self): <NEW_LINE> <INDENT> tree_nodes = [] <NEW_LINE> self.__root.in_order_traverse(tree_nodes) <NEW_LINE> tree_string = ' '.join(list(map(str, tree_nodes))) <NEW_LINE> return tree_string
traverses the tree in IN_ORDER and generates the parsed tree string
625941eb66673b3332b9258c
def _start_new_experiments(self, experiment_cls=Experiment): <NEW_LINE> <INDENT> for i in range(self._max_experiments - len(self._experiments)): <NEW_LINE> <INDENT> job = self._workqueue.assign_next_job(self.id) <NEW_LINE> if job is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> experiment = experiment_cls( job, s...
If not the max concurrent number of experiments is reached, starta new experiment.
625941eb6aa9bd52df0372a2
def osd_blacklist_ls(self, body='json', timeout=None): <NEW_LINE> <INDENT> return self._request('osd blacklist ls', body=body, timeout=timeout)
show blacklisted clients
625941eba17c0f6771cbe54a
def on_tab_selected(): <NEW_LINE> <INDENT> for i in range(self.ui.tabs.count()): <NEW_LINE> <INDENT> button = self.ui.tabs.itemAt(i).widget() <NEW_LINE> button.setProperty("active", button == tab_button) <NEW_LINE> button.style().unpolish(button) <NEW_LINE> button.style().polish(button) <NEW_LINE> <DEDENT> self.ui.tab_...
Event fired when a tab is selected by the user
625941eb9c8ee82313fbbc72
def render_first_look(dataframe): <NEW_LINE> <INDENT> number_of_rows = st.sidebar.slider('Number of rows', 1, 150, 10) <NEW_LINE> st.markdown("## **Exploring the dataset :mag:** ##") <NEW_LINE> if st.sidebar.checkbox("Color NaN values in red", value=True): <NEW_LINE> <INDENT> st.dataframe(dataframe.head(number_of_rows)...
Renders the head of the dataset (with nan values colored in red), and comments regarding instances, columns, and missing values.
625941eb3317a56b8693a147
def get_match_pick_bans(self, match): <NEW_LINE> <INDENT> fields = ['is_pick', 'hero_id', 'team', 'order'] <NEW_LINE> objectives = [] <NEW_LINE> if match['picks_bans']: <NEW_LINE> <INDENT> for item in match['picks_bans']: <NEW_LINE> <INDENT> obj = {'match_id': match['match_id']} <NEW_LINE> for field in fields: <NEW_LIN...
Get game objectives like Roshan and towers and append to self.objectives dataframe.
625941eb4f6381625f114f36
def get_station_licenses(self, station): <NEW_LINE> <INDENT> station = clean.station(station) <NEW_LINE> path = f"/station/{station}/licenses" <NEW_LINE> return self.request_json("GET", path)
Station licenses for disease models or forecast
625941eb8c0ade5d55d3eeba
@stack_deletion.declare_default_behavior <NEW_LINE> def default_delete_behavior(collection, request, stack_name, stack_id): <NEW_LINE> <INDENT> stack = collection.stack_by_id(stack_id) <NEW_LINE> if stack is None: <NEW_LINE> <INDENT> request.setResponseCode(404) <NEW_LINE> return b'' <NEW_LINE> <DEDENT> stack.update_ac...
Successfully delete a stack as long as it exists. Updates the stacks status.
625941eb15baa723493c4475
def graficar_exp(mediciones, label_mediciones, label_cota): <NEW_LINE> <INDENT> n = mediciones.n.unique() <NEW_LINE> ax1 = sns.lineplot(x="n", y="Tiempo", data=mediciones) <NEW_LINE> ax1 = sns.lineplot(x="n", y="cota", data=mediciones) <NEW_LINE> plt.xlim([min(n), max(n)]) <NEW_LINE> plt.ticklabel_format(style='sci', a...
Dibuja un grafico de lineas para Tiempo y cota, segun n
625941eb45492302aab5e7c4
def reraise(err, msg, *args): <NEW_LINE> <INDENT> err.args = (msg.format(*args),) <NEW_LINE> raise
Short-hand for overriding Exception message. It replaces exception original arguments by the passed message, and re-raise it without lossing the original traceback. Parameters ---------- err : Exception object A raised Exception object. msg : str Exception message to replace with. *args If given, ``str.fo...
625941ebab23a570cc250682
def get_means(self, iterations): <NEW_LINE> <INDENT> self.full_status = self.build_full_status(iterations) <NEW_LINE> means = self.get_mean_data(self.full_status, 'status') <NEW_LINE> return means
Create a full status and get the mean data for the status key :param iterations: iterations output from iteration_bunch :return: Dictionary containing all statuses as keys, and as value a list of the average value over all nodes for that state per iteration
625941eb4c3428357757c820
def char2pinyin(var_str, style=Style.FINALS_TONE3): <NEW_LINE> <INDENT> if isinstance(var_str, str): <NEW_LINE> <INDENT> if var_str == 'None': <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tmp = pinyin(var_str, style) <NEW_LINE> return " ".join(flatten(tmp)) <NEW_LINE> <DEDENT> <DEDENT> el...
将汉字(串)转为拼音(串) :param style: 该包内指定的返回拼音格式 :param var_str: str 类型的字符串 :return: 汉字转小写拼音
625941ebd6c5a1020814454a
def __get__(self, instance, owner): <NEW_LINE> <INDENT> if instance not in self.ds_references: <NEW_LINE> <INDENT> self.ds_references[instance] = self.data_structure( self.redis, self.get_key_name(instance), pickling=self.pickling, ) <NEW_LINE> <DEDENT> return self.ds_references[instance]
Return the attribute value.
625941eb925a0f43d254a377
def serialize(self, root: TreeNode) -> str: <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> left = self.serialize(root.left) <NEW_LINE> right = self.serialize(root.right) <NEW_LINE> return str(root.val) + "-" + str(len(left)) + "#" + left + "#" + right
Encodes a tree to a single string.
625941ebaad79263cf390f44
def l2normalize(self, docVectors): <NEW_LINE> <INDENT> norm = self.calculate_vector_norm(docVectors) <NEW_LINE> for key, value in docVectors.items(): <NEW_LINE> <INDENT> docVectors[key] = value / norm <NEW_LINE> <DEDENT> return docVectors
Uses the l2norm to normalize the given vectors by dividing each vector by the l2Norm :param docVectors: Document vector to normalize :return: the normalized vector
625941ebbe7bc26dc91cdaf1
def find(self): <NEW_LINE> <INDENT> pattern_checksum = self.checksum(self._pattern) <NEW_LINE> self.precompute_hashes() <NEW_LINE> results = [] <NEW_LINE> for i in range(self._scan_bound): <NEW_LINE> <INDENT> if pattern_checksum == self._checksums[i]: <NEW_LINE> <INDENT> if self._pattern == self._text[i:i + self._windo...
Returns all occurrences of pattern in the text.
625941eb167d2b6e31219090
def Rear(self): <NEW_LINE> <INDENT> return self.tail.pre.val
Get the last item from the queue. :rtype: int
625941eba934411ee3751b90
def error(status, *args, **kwargs): <NEW_LINE> <INDENT> return json({}, status)
A shortcut for empty json result.
625941eb8c0ade5d55d3eebb
def __init__(self, inFile = None): <NEW_LINE> <INDENT> self.__inFile = inFile <NEW_LINE> self.__extractedData = [] <NEW_LINE> if inFile == None: <NEW_LINE> <INDENT> return RuntimeError("An input file name must be specified.")
GammaView file printout conversion handler. Can create monogDB data or files. inFile = Input file. If not specified this will crash.
625941eb4a966d76dd551510
def package_point_match_data_into_json(dataarray, tileId, local_or_world='local'): <NEW_LINE> <INDENT> dlist = [] <NEW_LINE> for i in range(dataarray.shape[0]): <NEW_LINE> <INDENT> d = {} <NEW_LINE> d['tileId'] = tileId <NEW_LINE> d[local_or_world] = [dataarray[i, 0], dataarray[i, 1]] <NEW_LINE> dlist.append(d) <NEW_LI...
Convert a set of points defined by a numpy array and a tileId to a json for use in the renderapi Parameters ---------- dataarray : numpy.array a Nx2 array of points tileId : str a tileId to package them into local_or_world : whether this should be represented as a local or world coordinate (Default v...
625941eb71ff763f4b549b90
def validate_output(self): <NEW_LINE> <INDENT> for item in self.__get_output_elements(): <NEW_LINE> <INDENT> self.assertTrue(item.is_enabled())
Assert each element in output_list is enabled
625941eb5fcc89381b1e1bbe
def compute_w_backup(obj, cache_fn, func, args = (), refresh_cache = False, load_only = False, load_existing = False, continue_existing = False, **kwargs): <NEW_LINE> <INDENT> assert not (load_existing and continue_existing), "Both cannot be true." <NEW_LINE> if cache_fn is not None and os.path.exists(cache_fn): <NEW_L...
1.) Calls obj.load(cache_fn) if cache_fn exists and returns obj. 2.) Executes a function with parameters args. 3.) Calls obj.save(cache_fn) after execution. Parameters ---------- obj : object an object providing a save() and load() function cache_fn : str file name to load the computed value `func`(*`args`) ...
625941eb8e71fb1e9831dca3
def mu_mat(self, dim): <NEW_LINE> <INDENT> class _Mu(LinearOperator): <NEW_LINE> <INDENT> def __init__(self, diag_mu): <NEW_LINE> <INDENT> self._diag = diag_mu <NEW_LINE> shape = [len(diag_mu)] * 2 <NEW_LINE> super(_Mu, self).__init__('d', shape) <NEW_LINE> <DEDENT> def _matvec(self, vec): <NEW_LINE> <INDENT> return se...
Return the dipole moment matrix in DVR at direction ``dim``. Parameters ---------- dim : int Returns ------- (N, N) LinearOperator Notes ----- Suppose dim 0, 1, 2 correspond to x, y, z. Ignore constant factor.
625941eb442bda511e8be90c
def calibrate(rate): <NEW_LINE> <INDENT> print("Calibrating..") <NEW_LINE> average = 0 <NEW_LINE> for i in range(0, rate): <NEW_LINE> <INDENT> gyro = altimu.get_gyroscope_cal() <NEW_LINE> average += gyro[2] <NEW_LINE> <DEDENT> average = average/rate <NEW_LINE> last_sample = gyro[2] <NEW_LINE> print("Done calibrating") ...
This method performs an average of "rate" values to bring a bias that will aid to get the point of reference of the gyroscope. rate(int): This value determines the number values obtained from the gyroscope to perform the average.
625941eb7b25080760e39951
def list_service_certificates(kwargs=None, conn=None, call=None): <NEW_LINE> <INDENT> if call != 'function': <NEW_LINE> <INDENT> raise SaltCloudSystemExit( 'The list_service_certificates function must be called with -f or --function.' ) <NEW_LINE> <DEDENT> if kwargs is None: <NEW_LINE> <INDENT> kwargs = {} <NEW_LINE> <...
.. versionadded:: 2015.8.0 List certificates associated with the service CLI Example: .. code-block:: bash salt-cloud -f list_service_certificates my-azure name=my_service
625941eba17c0f6771cbe54b
def resetTable(self, cur): <NEW_LINE> <INDENT> self.deleteTable(cur) <NEW_LINE> self.setupTable(cur)
Deletes table and recreates it. Args: cur: Cursor of table
625941ebdd821e528d63b6a0
def p_root(t): <NEW_LINE> <INDENT> t[0] = Node("root", None, None, [t[1]])
root : import_main
625941eb66673b3332b9258d
def parse_args(): <NEW_LINE> <INDENT> desc = """send emails using csv input""" <NEW_LINE> parser = argparse.ArgumentParser(description=desc) <NEW_LINE> parser.add_argument("-i", "--input", help="""csv input data of attendees""", type=str, metavar="INPUT_DATA") <NEW_LINE> parser.add_argument("-d", "--delay", help="""del...
parse CLI args
625941eb656771135c3ebd70
def print_from_tail_to_head(self): <NEW_LINE> <INDENT> if not self.tail: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> nodes = [] <NEW_LINE> node = self.tail <NEW_LINE> while node: <NEW_LINE> <INDENT> nodes.append(str(node.value)) <NEW_LINE> node = node.previous_node <NEW_LINE> <DEDENT> print(', '.join(nodes))
>>> DoublyLinkedList().print_from_tail_to_head() >>> DoublyLinkedList(range(1)).print_from_tail_to_head() 0 >>> DoublyLinkedList(range(2)).print_from_tail_to_head() 1, 0 >>> DoublyLinkedList(range(3)).print_from_tail_to_head() 2, 1, 0
625941eba8370b7717052d99
def draw_solution(self, color='m'): <NEW_LINE> <INDENT> if self.capture_pb is None or self.solution is None: <NEW_LINE> <INDENT> pymanoid.warn("no solution to draw") <NEW_LINE> return [] <NEW_LINE> <DEDENT> if self.solution.lambda_ is None: <NEW_LINE> <INDENT> self.solution.compute_lambda() <NEW_LINE> <DEDENT> if self....
Draw the solution trajectory. Returns ------- handles : list of openravepy.GraphHandle OpenRAVE graphical handles. Must be stored in some variable, otherwise the drawn object will vanish instantly.
625941ebeab8aa0e5d26e056
def __init__(self, kernel): <NEW_LINE> <INDENT> self.kernel = kernel <NEW_LINE> super(Convolution, self).__init__( domain=kernel.space, range=kernel.space, linear=True)
Initialize a convolution operator with a known kernel.
625941eb26238365f5f0f371
def SeperateRadiomicsFeatures(feature_name): <NEW_LINE> <INDENT> sub_feature_name = [] <NEW_LINE> group = [] <NEW_LINE> group_name = [] <NEW_LINE> seq_group = [] <NEW_LINE> seq_count = 0 <NEW_LINE> image_class_group = [] <NEW_LINE> image_class_count = 0 <NEW_LINE> feature_class_group = [] <NEW_LINE> feature_class_count...
Generate the feature name, group, and group cound according to radiomics features. :param feature_name: The generated radiomis featues. which should including sequence_name, image_class, feature_class, and the feature_name, like T2_origin_glszm_ZonePercentage :return: Apr-29-18 Yang SONG [yang.song.91@foxmail.com]
625941ebe8904600ed9f2431
def get_total_assets_value(rh: Robinhood) -> float: <NEW_LINE> <INDENT> stocks_value = _get_stock_assets_value(rh) <NEW_LINE> crypto_value = _get_crypto_assets_value(rh) <NEW_LINE> return crypto_value + stocks_value
:param rh: The logged-in robinhood object :return: $ in stocks, $ not allocated (Cash)
625941eb046cf37aa974d23e
def test_fobj(): <NEW_LINE> <INDENT> Level3File(get_test_data('nids/Level3_FFC_N0Q_20140407_1805.nids'))
Test reading a specific NEXRAD NIDS files from a file object
625941eb99fddb7c1c9de88a
def auto_delete_comment(self, uin, mood_id, comment_id, reply_id, comment_uin, reply_uin): <NEW_LINE> <INDENT> url = "https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delreply_ugc" <NEW_LINE> params = { "qzreferrer": "https://qzs.qq.com/qzone/app/mood_v6/html/index.html", "uin": self.uin, "h...
自动删除评论。(这个没测试) :param int | uin: 好友账号 :param str | mood_id: 说说编号 :param int | comment_id: 评论编号 :param int | reply_id: 回复编号 :param int | comment_uin: 评论者账号 :param int | reply_uin: 回复者账号 :return: 删除结果信息对象。
625941eb7b180e01f3dc4cef
def start(self, num_instances): <NEW_LINE> <INDENT> log.info('Starting Tor swarm with %d instances...' % num_instances) <NEW_LINE> self._instances = list() <NEW_LINE> for i in range(num_instances): <NEW_LINE> <INDENT> tor = TorProcess('tor-%d' % i, self.base_socks_port + i, self.base_control_port + i, self.work_dir, so...
Start and return the Tor processes.
625941ebd6c5a1020814454b
def push_up (grid): <NEW_LINE> <INDENT> grid = grid <NEW_LINE> row=0 <NEW_LINE> for col in range(0,4): <NEW_LINE> <INDENT> if grid[row][col]!=0 or grid[row+1][col]!=0 or grid[row+2][col]!=0 or grid[row+3][col]!=0: <NEW_LINE> <INDENT> if grid[row][col]==0: <NEW_LINE> <INDENT> while grid[row][col]==0: <NEW_LINE> <INDENT>...
merge grid values upwards
625941ebb545ff76a8914311
def __init__(self, col, row): <NEW_LINE> <INDENT> pass
(Rectangular, int, int) -> NoneType Initializes a rectangular matrix
625941ebff9c53063f47c6ed
def _handle_leaflet_event(self, _, content, buffers): <NEW_LINE> <INDENT> if content.get('event', '') == 'popup: click': <NEW_LINE> <INDENT> self._popup_callbacks(**content)
Handle leaflet events trigged.
625941eba4f1c619b28b0529
def build_step(self): <NEW_LINE> <INDENT> cmd = ' '.join([ self.cfg['prebuildopts'], 'LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/lib', 'python external/scons/scons.py', 'mode=compile', '-j %s' % self.cfg['parallel'], self.cfg['buildopts'], ]) <NEW_LINE> run_cmd(cmd, log_all=True, simple=True)
Custom build procedure for Xmipp: call the scons wrapper with compile argument
625941eb442bda511e8be90d
def defaultKeywords(self, kwSet): <NEW_LINE> <INDENT> return QsciLexerPerl.keywords(self, kwSet)
Public method to get the default keywords. @param kwSet number of the keyword set (integer) @return string giving the keywords (string) or None
625941eb187af65679ca561c
def evoked_visual_potentials(raw, subject, event_dict, figdir="/tmp/"): <NEW_LINE> <INDENT> events = eventreader( raw=raw, subject=subject, outputdir=figdir, event_dict=event_dict ) <NEW_LINE> visual_epochs = epoch_data( raw=raw, events=events, event_dict=event_dict, subject=subject, conditionname=["visualfirst"], sens...
Function to plot visual potentials from the first visual option (left) as a sanity check
625941eb3cc13d1c6d3c7874
def create_superuser(self, email, name, password): <NEW_LINE> <INDENT> user = self.create_user(email, name, password) <NEW_LINE> user.is_superuser = True <NEW_LINE> user.is_staff = True <NEW_LINE> user.save(using=self._db) <NEW_LINE> return user
Creates and saves a new superuser profile object
625941eb50485f2cf553d298
def summary(match_result, stat, storage): <NEW_LINE> <INDENT> storage.clear() <NEW_LINE> return None
一局对局总结函数 若该函数未声明将不执行 该函数报错将跳过 params: match_result - 对局结果 stat - 游戏数据 storage - 游戏存储
625941eb01c39578d7e75337
def test_delete(self): <NEW_LINE> <INDENT> path = posixpath.join(self.test_dir, u"d\xe9lfoo.txt") <NEW_LINE> self.upload_file(self.foo, path) <NEW_LINE> metadata = self.client.metadata(path) <NEW_LINE> self.assert_file(metadata, self.foo, path = path) <NEW_LINE> self.client.file_delete(path) <NEW_LINE> metadata = self....
Tests if deleting a file really makes it disappear
625941eb55399d3f05588bb4
def get_child_ids(self): <NEW_LINE> <INDENT> id_list = [] <NEW_LINE> from ..id.objects import IdList <NEW_LINE> for child_node in self._my_map['childNodes']: <NEW_LINE> <INDENT> id_list.append(child_node['id']) <NEW_LINE> <DEDENT> return IdList(id_list)
Gets the children of this node. return: (osid.id.IdList) - the children of this node *compliance: mandatory -- This method must be implemented.*
625941eb3539df3088e2e848
def __str__(self): <NEW_LINE> <INDENT> return 'config_opts'
Returns the configration element defined by this object
625941eb8e7ae83300e4b4cb
def serial_main(SEQ): <NEW_LINE> <INDENT> count = sum(SEQ) <NEW_LINE> return count
Does the main without any parallel overhead :returns: the sum over the array
625941eb7cff6e4e81117e82
def set_log_file(filename, mask=None): <NEW_LINE> <INDENT> file_handler = logging.FileHandler(filename, 'w') <NEW_LINE> file_handler.setFormatter(logging.Formatter( '%(asctime)s %(name)-18s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')) <NEW_LINE> root = logging.getLogger() <NEW_LINE> root.addHandler(file_...
Set the filename used for logging. :param filename: :param mask: optional
625941eba219f33f34628e5e
def __ge_incompatible_build_types_with_http_info(self, agent_locator, **kwargs): <NEW_LINE> <INDENT> all_params = ['agent_locator', 'fields'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_r...
ge_incompatible_build_types # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.__ge_incompatible_build_types_with_http_info(agent_locator, async_req=True) >>> result = thread.get() :param async_req bool :param str ag...
625941ebe5267d203edce193
def test_console_stream_kwarg(self): <NEW_LINE> <INDENT> s = StringIO() <NEW_LINE> connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s) <NEW_LINE> send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection) <NEW_LINE> message = force_bytes(s.get...
Test that the console backend can be pointed at an arbitrary stream.
625941ebab23a570cc250683
def get_ad_title(Beautiful_Soup_object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> a_tag_data = Beautiful_Soup_object.a.text <NEW_LINE> ad_title_property = a_tag_data.strip().split(",") <NEW_LINE> ad_title_property = " -- ".join(ad_title_property) <NEW_LINE> return ad_title_property <NEW_LINE> <DEDENT> except: <NEW_...
This function extracts the title of the ad from the BeautifulSoup object provided. Daft.ie uses the address of the property as the ad title. The function accepts a BeautifulSoup object parsed as html, as a parameter.
625941ebb545ff76a8914312
def _tensor(self, parent): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sub_el = self._xpath('tensor', parent)[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> obj = Tensor() <NEW_LINE> obj.m_rr, obj.m_rr_errors = self._float_value(sub_el, 'Mrr') <NEW_LINE> obj.m_tt, obj.m_t...
Converts an etree.Element into an Tensor object. :type parent: :class:`~lxml.etree._Element` :rtype: :class:`~obspy.core.event.source.Tensor`
625941eb627d3e7fe0d6934e
def __init__(self,nb_arms=10,epsilon=0.01): <NEW_LINE> <INDENT> self.epsilon=epsilon <NEW_LINE> self.n=nb_arms <NEW_LINE> self.Q_a=[10+np.random.rand()]*nb_arms <NEW_LINE> self.N_a=np.ones(nb_arms) <NEW_LINE> self.counter=0
Init a new agent
625941ebbde94217f36832e9
def setUp(self): <NEW_LINE> <INDENT> app.flask_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + BASE_DIR + '/bucket_list_test.db' <NEW_LINE> app.db.session.close() <NEW_LINE> app.db.drop_all() <NEW_LINE> app.db.create_all() <NEW_LINE> self.client = app.flask_app.test_client()
setting up the test database
625941eb44b2445a3393258f
def _make_values_table(self, caption, tag, values_list, header_name = None, header_values = None, flip=True, numsigfigs=None): <NEW_LINE> <INDENT> if numsigfigs == None: <NEW_LINE> <INDENT> numsigfigs = self._config.numsigfigs <NEW_LINE> <DEDENT> header = ["Count", "Mean", "Std Dev", "Min", "Max"] <NEW_LINE> if header_...
Makes a table describing the values given, by providing the mean, standard deviation, minimum, maximum, and count.
625941eb435de62698dfe149
@defer.inlineCallbacks <NEW_LINE> def test_renaming_ancestor(udf_name, sd1, sd2, sd3, prefix): <NEW_LINE> <INDENT> folder1 = os.path.join(sd1.homedir, udf_name) <NEW_LINE> folder2 = os.path.join(folder1, "udf_parent_dir") <NEW_LINE> folder3 = os.path.join(folder2, "udf_dir") <NEW_LINE> debug(prefix, 'test_create_folder...
Test 6: Assert correct unsubscription when an ancestor is renamed.
625941eb66656f66f7cbc6a9
def test_node_max_connections(self): <NEW_LINE> <INDENT> global message <NEW_LINE> message = [] <NEW_LINE> def node_callback(event, main_node, connected_node, data): <NEW_LINE> <INDENT> global message <NEW_LINE> message.append(event + ":" + main_node.id) <NEW_LINE> <DEDENT> node_0 = Node(host='127.0.0.1', port=10000, c...
Testing the maximum connections of the node.
625941ebd10714528d6001e6
def parse_strip_setting(self, msg: bytes) -> LEDENETAddressableDeviceConfiguration: <NEW_LINE> <INDENT> high_byte = msg[1] <NEW_LINE> low_byte = msg[2] <NEW_LINE> pixels_per_segment = (high_byte << 8) + low_byte <NEW_LINE> _LOGGER.debug( "Pixel count (high: %s, low: %s) is: %s", hex(high_byte), hex(low_byte), pixels_pe...
Parse a strip settings message.
625941ebd164cc617578324c
def make_google_blueprint( client_id=None, client_secret=None, scope=None, offline=False, reprompt_consent=False, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None): <NEW_LINE> <INDENT> scope = scope or ["profile"] <NEW_LINE> authorization_url_params = {} <NEW_LI...
Make a blueprint for authenticating with Google using OAuth 2. This requires a client ID and client secret from Google. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET. Args: cli...
625941eb99fddb7c1c9de88b
def setMatrix(self, QMatrix4x4): <NEW_LINE> <INDENT> pass
setMatrix(self, QMatrix4x4)
625941eb29b78933be1e5ba2
def set_setting(self, name, value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._settings[name].set(value) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> _logger.error("in set_setting(%s):" % (name), exc_info=err) <NEW_LINE> raise
Set a setting.
625941eb5fc7496912cc3e7a
def __init__(self, mid, node_name, start_node, end_node, slurm_resources, work_dir, governor_address, aux_dir, config): <NEW_LINE> <INDENT> self.mid = mid <NEW_LINE> self.node_name = node_name <NEW_LINE> self.start_node = start_node <NEW_LINE> self.end_node = end_node <NEW_LINE> self.slurm_resources = slurm_resources <...
Initialize partition manager. Args: mid (str): partition manager identifier node_name (str): the node where partition manager should be launched start_node (int): the start node of the allocation the manager should control end_node (int): the end node of the allocation the manager should control sl...
625941eb293b9510aa2c378d
def testMagicMock(self): <NEW_LINE> <INDENT> mock = MagicMock() <NEW_LINE> self.assertNotEqual(mock, 3) <NEW_LINE> mock.__eq__.return_value = True <NEW_LINE> self.assertEqual(mock, 3)
Mock konczy sie z informacja, ze nie posiada atrybutu __eq__
625941ebf548e778e58cda7c
def notifyFailure(self, relay, message): <NEW_LINE> <INDENT> if self.noisy: <NEW_LINE> <INDENT> log.msg("could not relay " + message) <NEW_LINE> <DEDENT> message = os.path.basename(message) <NEW_LINE> with self.manager.queue.getEnvelopeFile(message) as fp: <NEW_LINE> <INDENT> from_, to = pickle.load(fp) <NEW_LINE> <DED...
Generate a bounce message for a message which cannot be relayed. @type relay: L{SMTPManagedRelayerFactory} @param relay: The factory for the relayer responsible for the message. @type message: L{bytes} @param message: The path of the file holding the message.
625941eb6e29344779a62b0d
@types(x=int, y=int, _ret_type=int) <NEW_LINE> def add2(x, y): <NEW_LINE> <INDENT> return x+y
this is add2
625941ebf548e778e58cda7d
def _calculate_log_likelihood(self, data=None): <NEW_LINE> <INDENT> return ll.log_likelihood_pixel(self, data, self.params['MAX_PIXEL_VALUE'], self.params['LL_VARIANCE'])
Calculates log likelihood of hypothesis given data. Overrides the method from base Hypothesis class. Right now, we use a pixel based likelihood model that assumes Gaussian noise. Parameters: data (numpy.ndarray): Observed image Returns: float: log likelihood
625941ebadb09d7d5db6cc89
def put(self, tpl): <NEW_LINE> <INDENT> tpl = tuple(tuple(v) if isinstance(v, list) else v for v in tpl) <NEW_LINE> self._tuples[tpl] = self._tuples.get(tpl, 0) + 1
put the given tuple into the tuple space.
625941eb507cdc57c63071e3
def create_mlb_coach_dict(): <NEW_LINE> <INDENT> url = "https://en.wikipedia.org/wiki/List_of_Major_League_Baseball_managers" <NEW_LINE> USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0" <NEW_LINE> MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90...
Source: https://en.wikipedia.org/wiki/List_of_nicknames_used_in_basketball :return: Nickname dict format: { nickname: Player Name The King: Lebron James }
625941eba8370b7717052d9a
def get_handle(self, mode="rb"): <NEW_LINE> <INDENT> return open(self.filename, mode)
Returns a handle to this file with the given mode
625941ebf8510a7c17cf9bfd
def train_distillation(data, file_name, params, num_epochs=50, batch_size=128, train_temp=1): <NEW_LINE> <INDENT> if not os.path.exists(file_name+"_init"): <NEW_LINE> <INDENT> train(data, file_name+"_init", params, 1, batch_size) <NEW_LINE> <DEDENT> teacher = train(data, file_name+"_teacher", params, num_epochs, batch_...
Train a network using defensive distillation. Distillation as a Defense to Adversarial Perturbations against Deep Neural Networks Nicolas Papernot, Patrick McDaniel, Xi Wu, Somesh Jha, Ananthram Swami IEEE S&P, 2016.
625941eb94891a1f4081bfa8
@ndb.toplevel <NEW_LINE> def test_ndb_future_executor_concurrency_top_level(testbed): <NEW_LINE> <INDENT> query = 'query Concurrent { a }' <NEW_LINE> class Lock(ndb.Model): <NEW_LINE> <INDENT> locked = ndb.BooleanProperty() <NEW_LINE> <DEDENT> lock_a_key = Lock(locked=True, id='a').put() <NEW_LINE> lock_b_key = Lock(lo...
This test illustrates a full query is an async process that can run concurrently with other async processes that may occur in a request-response cycle.
625941eb009cb60464c638aa