code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def displayConfirmation(self): <NEW_LINE> <INDENT> if not self.validISO() or self.selectedPartition == '': <NEW_LINE> <INDENT> self.critMessageBox.setText(('You must select an ISO image AND ' 'partition before continuing')) <NEW_LINE> self.critMessageBox.exec() <NEW_LINE> return <NEW_LINE> <DEDENT> confirmationText = (... | checks if both iso and partition have been selected and displays confirmation dialogue
If the yes button is clicked, a BDCThread instance is created and the thread is started.
After the thread has started, the logging view is displayed. | 625941e47b25080760e39858 |
def evaluate(self, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None): <NEW_LINE> <INDENT> if batch_size is None and steps is None: <NEW_LINE> <INDENT> batch_size = 32 <NEW_LINE> <DEDENT> if x is None and y is None and steps is None: <NEW_LINE> <INDENT> raise ValueError('If evaluating from data... | Returns the loss value & metrics values for the model in test mode.
Computation is done in batches.
Arguments:
x: Numpy array of test data (if the model has a single input),
or list of Numpy arrays (if the model has multiple inputs).
If input layers in the model are named, you can also pass a
... | 625941e4851cf427c661a90d |
@bottle.route('/users/week') <NEW_LINE> def ranking_users_week_page(): <NEW_LINE> <INDENT> users = api.most_popular_users(days=7, limit=10) <NEW_LINE> return jinja2_template('html/users.html', {'type': 1, 'users':users}) | 今週の人気ユーザーを表示 | 625941e4004d5f362079a732 |
def substitute_hand(hand, letter): <NEW_LINE> <INDENT> letter = str.lower(letter) <NEW_LINE> substitute_hand = copy.deepcopy(hand) <NEW_LINE> new_letter = '' <NEW_LINE> available_vowels = [] <NEW_LINE> available_consonants = [] <NEW_LINE> for i in VOWELS: <NEW_LINE> <INDENT> if i not in substitute_hand: <NEW_LINE> <IND... | Allow the user to replace all copies of one letter in the hand (chosen by user)
with a new letter chosen from VOWELS if the user chooses a VOWEL and
CONSONANTS if the user chooses a CONSONANT). The new letter
should be different from user's choice, and should not be any of the letters
already in the hand.
You can assu... | 625941e48e05c05ec3eea779 |
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_current(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> get_media_detail = ET.Element("get_media_detail") <NEW_LINE> config = get_media_detail <NEW_LINE> if kwargs.pop('delete_get_media_detail', False) is True: <NEW_LINE>... | Auto Generated Code
| 625941e4046cf37aa974d145 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GenericThrottlePolicy10): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e4287bf620b61d3e62 |
def consume(self, char): <NEW_LINE> <INDENT> if char == b"d": <NEW_LINE> <INDENT> self.reward_this_turn += 1 <NEW_LINE> self.is_done = True <NEW_LINE> return b" " <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return char | Defines how an agent interacts with the char it is standing on | 625941e4187af65679ca5521 |
def OnClick(self, v): <NEW_LINE> <INDENT> p = v.CurDir + os.path.sep + self._name <NEW_LINE> book = Book(1, path=p, cur_page=0) <NEW_LINE> v.ViewMgr.OpenBook(book) | override this func | 625941e4be8e80087fb2103e |
def open(self, uri): <NEW_LINE> <INDENT> self._continue_stream = True <NEW_LINE> headers = { 'mobileUUID': self._user, 'mobileName': 'Wireless Audio', 'mobileVersion': '1.0', } <NEW_LINE> while self._continue_stream: <NEW_LINE> <INDENT> _LOGGER.debug('Opening new stream') <NEW_LINE> try: <NEW_LINE> <INDENT> parser = Ht... | Generator consuming events from speaker's main info stream.
Yields ApiResponse instance.
:param uri: URI to open for the stream e.g. /UIC?cmd=%3Cname%3EGetMainInfo%3C/name%3E | 625941e4f548e778e58cd980 |
def test_upload_login_prompt_disabled_no_user(self): <NEW_LINE> <INDENT> files = {"conanfile.py": GenConanfile("Hello0", "1.2.1")} <NEW_LINE> client = TestClient(default_server_user=True) <NEW_LINE> client.save(files) <NEW_LINE> client.run("config set general.non_interactive=True") <NEW_LINE> client.run("create . user/... | Without user info, uploads should fail when login prompt has been disabled.
| 625941e4a17c0f6771cbe451 |
def get_3d_backend(): <NEW_LINE> <INDENT> global MNE_3D_BACKEND <NEW_LINE> return MNE_3D_BACKEND | Return the backend currently used.
Returns
-------
backend_used : str
The 3d backend currently in use. | 625941e42eb69b55b151ccb6 |
def install_with_tasks(self): <NEW_LINE> <INDENT> return [] | Execute preparation and installation steps. | 625941e423849d37ff7b348d |
def file_validator(opt_dict, name, value): <NEW_LINE> <INDENT> return check_file(None, name, value) | validate and return a filepath for option of type 'file' | 625941e416aa5153ce362879 |
def tr(self, message): <NEW_LINE> <INDENT> return QCoreApplication.translate('LCPNetwork', message) | Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString | 625941e45fcc89381b1e1ac2 |
def load_flickr(data_dir=None): <NEW_LINE> <INDENT> return _load_asunetwork_dataset(data_dir, 80513, 5899882, weighted=False, directed=False, name='Flickr') | Loads the Flickr dataset (http://socialcomputing.asu.edu/datasets/Flickr).
:param data_dir: Directory containing nodes.csv, edges.csv, and group-edges.csv | 625941e4a219f33f34628d65 |
def cell(n): <NEW_LINE> <INDENT> return '{:3} {:5}'.format( n, 'SPACE' if n == 32 else 'DEL' if n == 127 else chr(n) if n >= 33 else 'NA') | Format a cell | 625941e4d99f1b3c44c67989 |
def build_dicts(): <NEW_LINE> <INDENT> feat_counts = {} <NEW_LINE> nr_pos = 0 <NEW_LINE> with codecs.open("positive.review", 'r', 'utf8') as pos_file: <NEW_LINE> <INDENT> for line in pos_file: <NEW_LINE> <INDENT> nr_pos += 1 <NEW_LINE> toks = line.split(" ") <NEW_LINE> for feat in toks[0:-1]: <NEW_LINE> <INDENT> name, ... | builds feature dictionaries | 625941e43539df3088e2e74c |
def _get_gearperf_fg_dict(self): <NEW_LINE> <INDENT> gvals = self._build_lookup_data('GEAR_PERFORMANCE', include_empty=False, values_in_text=False) <NEW_LINE> for g in gvals: <NEW_LINE> <INDENT> if g['value'] == '5': <NEW_LINE> <INDENT> g['text'] = 'Problem - Pot(s) or other gear lost' <NEW_LINE> break <NEW_LINE> <DEDE... | Build gear performance description dict for FG
NOTE The description for #5 is trawl based, so hardcoded the alternate text here
@return: dict of format {'1':'Description', ...} | 625941e4435de62698dfe04e |
def join(self, arg, *args): <NEW_LINE> <INDENT> raise NotImplementedError() | Joins two or more pathname components (see os.path.join)
:param str arg: path start
:param str args: other path parts
:return: str | 625941e4b545ff76a8914216 |
def make_games_df(self): <NEW_LINE> <INDENT> n = len(self.competitors) <NEW_LINE> pairs = permutations(self.competitors.values(), 2) <NEW_LINE> games = [Game(ident=i, black=t[0], white=t[1]) for i, t in enumerate(pairs)] <NEW_LINE> games_dict = {g.ident: [g.black, g.white, g.winner] for g in games} <NEW_LINE> games_df ... | return list of games
double round robin | 625941e4d18da76e235328dc |
def _wait_for_response(self, request_id, wait_time=None, _now=datetime.utcnow, _delta=timedelta, _sleep=sleep): <NEW_LINE> <INDENT> now = _now() <NEW_LINE> until = now + _delta(seconds=wait_time or self.config.wait_time) <NEW_LINE> while now < until: <NEW_LINE> <INDENT> response = self.responses_received.get(request_id... | Wait until a response arrives and return it
or return None if there is no response up to wait_time or self.config.wait_time. | 625941e482261d6c526ab8a7 |
def __init__(self): <NEW_LINE> <INDENT> self.TotalCount = None <NEW_LINE> self.GatewayFlowMonitorDetailSet = None <NEW_LINE> self.RequestId = None | :param TotalCount: The number of objects meeting the condition.
:type TotalCount: int
:param GatewayFlowMonitorDetailSet: The gateway traffic monitoring details.
:type GatewayFlowMonitorDetailSet: list of GatewayFlowMonitorDetail
:param RequestId: The unique request ID, which is returned for each request. RequestId is ... | 625941e4bde94217f36831ee |
def player_use(game, user_action): <NEW_LINE> <INDENT> player = game.player <NEW_LINE> inventory = ' '.join(player.inventory) <NEW_LINE> key_word = next((word for word in user_action if word in inventory), 'item') <NEW_LINE> if key_word in inventory: <NEW_LINE> <INDENT> direction = next_room(game) <NEW_LINE> unlock_roo... | Allows player to use items
Args:
game: The current game state.
user_action: The user's input to act on
Returns:
True: Upon successful execution | 625941e4293b9510aa2c3693 |
def batchnorm_backward(dout, cache): <NEW_LINE> <INDENT> num_train = dout.shape[0] <NEW_LINE> dx, dgamma, dbeta = None, None, None <NEW_LINE> gamma, x, mean, var, eps, xhat = cache <NEW_LINE> N = x.shape[0] <NEW_LINE> a = np.sqrt(var + eps) <NEW_LINE> dxhat = dout * gamma <NEW_LINE> dvar = np.sum((x - mean) * dxhat * -... | Backward pass for batch normalization.
For this implementation, you should write out a computation graph for
batch normalization on paper and propagate gradients backward through
intermediate nodes.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from batchnorm_forward.
Retur... | 625941e4462c4b4f79d1dad1 |
def is_positive(self): <NEW_LINE> <INDENT> return self._is_pos | Is the expression positive?
| 625941e43346ee7daa2b3170 |
def __generate_fragment_ids(self): <NEW_LINE> <INDENT> message = "Can't generate fragment IDs for malformed documents" <NEW_LINE> assert self.root is not None, message <NEW_LINE> allowed = self.doctype.elements_allowing_fragment_ids() <NEW_LINE> highest_fragment_id = self.highest_fragment_id <NEW_LINE> for node in self... | Make sure all of the elements which can have a cdr:id attribute get one
This time we assign directly to self._xml, because we know it will
match the `root` property we just finished manipulating. | 625941e4b7558d58953c530d |
def __init__(self, devices=None): <NEW_LINE> <INDENT> self._devices = None <NEW_LINE> self.discriminator = None <NEW_LINE> if devices is not None: <NEW_LINE> <INDENT> self.devices = devices | DeviceList - a model defined in Swagger | 625941e4ac7a0e7691ed44c6 |
def ctrlp_stl_left_prog(pl, progress): <NEW_LINE> <INDENT> return [ { 'contents': 'Loading...', 'highlight_groups': ['ctrlp:progress', 'file_name'], }, ] | Highlight groups used: ``ctrlp:progress`` or ``file_name``. | 625941e46e29344779a62a11 |
def get_table(url): <NEW_LINE> <INDENT> soup = get_page(url) <NEW_LINE> table = soup.find('table') <NEW_LINE> tr = table.find_all('tr') <NEW_LINE> table_stats = [] <NEW_LINE> for i in range(len(tr)): <NEW_LINE> <INDENT> td = tr[i].find_all('td') <NEW_LINE> if td: <NEW_LINE> <INDENT> row_dict = {'rank': tr[i].find('th')... | Grabs stats table from basketball-reference and converts to DataFrame.
:param url: url of page
:type url: string | 625941e4fbf16365ca6f65cd |
def getArticles(): <NEW_LINE> <INDENT> path = '/home/ubuntu/workspace/parse/primerTexts' <NEW_LINE> articles = [] <NEW_LINE> for filename in os.listdir(path): <NEW_LINE> <INDENT> articles.append(open("./primerTexts/" + filename, "r")) <NEW_LINE> <DEDENT> return articles | Open all files in the primer texts for training in looking for key indicators
of desired topic | 625941e497e22403b379d39d |
def detect_errors(self, print_msg=False): <NEW_LINE> <INDENT> self.error_list = [] <NEW_LINE> if not self.lp_lines: <NEW_LINE> <INDENT> raise EmptyLPException("Given LP is empty. Can't detect errors") <NEW_LINE> <DEDENT> if all(i not in self.lp_lines[0].lower() for i in ['min', 'max']): <NEW_LINE> <INDENT> self.error_l... | This function collects the many possible errors in the syntax
of the given LP.
It returns the error_list which contains
messages with the errors
An exception is thrown if the LP contains no lines
and a warning is raised if there are errors in the LP. | 625941e4be383301e01b587f |
def autoimport(): <NEW_LINE> <INDENT> global _libraries <NEW_LINE> _libraries = {} <NEW_LINE> for spec in _find_all_specs(sys.path): <NEW_LINE> <INDENT> lib = _parse_lib(spec) <NEW_LINE> if lib is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> versions = _libraries.setdefault((lib.name, lib.author), []) <NEW_LI... | Find all libs in the path and enable use of them.
You only need to call this if you've installed a package or
otherwise changed sys.path in the current run, and need to see the
changes. Otherwise libraries are found on first call of `use`. | 625941e4cdde0d52a9e53437 |
def refresh_window(tot_before, tot_after, pnic_before, pnic_after): <NEW_LINE> <INDENT> global lineno <NEW_LINE> printl("total bytes: sent: %-10s received: %s" % ( bytes2human(tot_after.bytes_sent), bytes2human(tot_after.bytes_recv)) ) <NEW_LINE> printl("total packets: sent: %-10s received: %s" % ... | Print stats on screen. | 625941e430bbd722463cc1c9 |
def __init__(__self__, *, security_group_ids: Sequence[str], subnet_ids: Sequence[str]): <NEW_LINE> <INDENT> pulumi.set(__self__, "security_group_ids", security_group_ids) <NEW_LINE> pulumi.set(__self__, "subnet_ids", subnet_ids) | :param Sequence[str] security_group_ids: Security groups IDs for the environment. At least one of the security group needs to allow MWAA resources to talk to each other, otherwise MWAA cannot be provisioned.
:param Sequence[str] subnet_ids: The private subnet IDs in which the environment should be created. MWAA require... | 625941e4d58c6744b4258060 |
def rename_location_group(self, old_name, new_name): <NEW_LINE> <INDENT> raise NotImplementedError("rename_location_group must be implemented " "in subclass") | Rename location group named old_name to new_name
Returns deferred
Fails if location group with name same as new_name already exists | 625941e43c8af77a43ae3ba6 |
def set_extraction_results_map(self, results_map): <NEW_LINE> <INDENT> self._extraction_results_map = results_map | Pass the result map to extractor. It contains the pure unmodified extraction results of the previous
extractors in a map which can be used to resolve those results as a dependencies to this extractor.
:param results_map:
:return: | 625941e4090684286d50f0ed |
def transmit(self, d_msg, **kwargs): <NEW_LINE> <INDENT> d_meta = d_msg['meta'] <NEW_LINE> str_action = d_msg['action'] <NEW_LINE> str_meta = json.dumps(d_meta) <NEW_LINE> if self.b_pycurl: <NEW_LINE> <INDENT> pyurl = purl.Purl( msg = args.msg, http = args.http, jsonwrapper = 'paylo... | Transmit dispatcher. | 625941e4e1aae11d1e74a0bd |
def _label(tree, node, fields): <NEW_LINE> <INDENT> label = tree.forms(node) <NEW_LINE> if 'lemma' in fields: <NEW_LINE> <INDENT> label += u'\n' + tree.lemmas(node) <NEW_LINE> <DEDENT> postags = [] <NEW_LINE> if 'cpostag' in fields: <NEW_LINE> <INDENT> postags.append(tree.cpostags(node)) <NEW_LINE> <DEDENT> if 'postag'... | Compose a label for i'th word of a tree, according to 'fields'.
Return a string (possibly multiline). | 625941e4aad79263cf390e49 |
def to_scanner(self): <NEW_LINE> <INDENT> if vj.core.transform._check_90deg(self.pd): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise(Exception('Only Euler angles of 0,90,180 are permitted.')) <NEW_LINE> <DEDENT> return vj.core.transform._to_scanner(self) | Transform data to scanner coordinate space by properly swapping axes
Standard vnmrj orientation - meaning rotations are 0,0,0 - is axial, with
x,y,z axes (as global gradient axes) corresponding to phase, readout, slice.
vnmrjpy defaults to handling numpy arrays of:
(readout, phase, slice/phase2, time*echo,... | 625941e423849d37ff7b348e |
def __call__(self, rec): <NEW_LINE> <INDENT> self._candidate= rec <NEW_LINE> self._warnings = NONE <NEW_LINE> if not self.isValid(self._candidate.flight): <NEW_LINE> <INDENT> if self.mode == INTERACTIVE or self.verbose > 1: <NEW_LINE> <INDENT> self.log("\nCandidate:\n {0}\nhas warnings:\n -> {1}\n" .format(rec, "\n ->... | Invoke conflict handler
Checks if the record is valid and if conflicts exist. Depending on the
mode settings conflicts are resolved.
Arguments:
rec: Rec to investigate | 625941e49b70327d1c4e11d9 |
def der_encode(r, s): <NEW_LINE> <INDENT> r_len = sizeof(r) <NEW_LINE> s_len = sizeof(s) <NEW_LINE> total_len = (4 + r_len + s_len) <NEW_LINE> return b'\x30' + total_len.to_bytes(sizeof(total_len), 'big') + b'\x02' + r_len.to_bytes(sizeof(r_len), 'big') + r.to_bytes(sizeof(r), 'big') + b'\x02' + s_len.to_byt... | DER-encodes a signed tx. https://bitcoin.stackexchange.com/questions/12554/why-the-signature-is-always-65-13232-bytes-long
https://github.com/bitcoin/bitcoin/blob/ce74799a3c21355b35fed923106d13a0f8133721/src/script/interpreter.cpp#L108 | 625941e4d486a94d0b98e548 |
def hocrToObject(self, input, width, scale_factor, station): <NEW_LINE> <INDENT> soup = BeautifulSoup(input) <NEW_LINE> linelist = [] <NEW_LINE> for line in soup.findAll("span", { "class" : "ocr_line" }): <NEW_LINE> <INDENT> wordlist = [] <NEW_LINE> not_empty = False <NEW_LINE> newline = OCRline(line['title'], width, s... | Converts HOCR HTML data from Tesseract OCR into easily usable objects. | 625941e4711fe17d82542764 |
def disable_dir_mode(): <NEW_LINE> <INDENT> GLOBALS["dir_mode"] = False | Disables directory mode. | 625941e43d592f4c4ed1d464 |
def run(self, *args): <NEW_LINE> <INDENT> params = self.parser.parse_args(args) <NEW_LINE> code = self.initialize(name=params.name, reuse=params.reuse) <NEW_LINE> return code | Initialize a registry.
Create and initialize an empty registry which its name is defined by
<name> parameter. Required tables will be also created. | 625941e445492302aab5e6c9 |
def __rdiv__(self, other): <NEW_LINE> <INDENT> if (isinstance(other, int) or isinstance(other, float) or isinstance(other, complex) or isinstance(other, Quaternion)): <NEW_LINE> <INDENT> other = Quaternion(other) <NEW_LINE> denominator = (self.a**2) + (self.b**2) + (self.c**2) + (self.d**2) <NEW_LINE> atotal = ((other.... | Quaternion division method
Args:
other -- Quaternion/int/float/complex to divide by Quaternion.
Returns:
Result of multiplication operation, as a Quaternion object. | 625941e45fc7496912cc3d80 |
def compute(self, prefixExtended, pssmOutNameRaw): <NEW_LINE> <INDENT> chainType, chainId= prefixExtended.split("_")[1:3] <NEW_LINE> seqStr, fastaFname= self.seqsManager.getSeq(chainType, chainId) <NEW_LINE> if self.checkAlreayComputed(prefixExtended): <NEW_LINE> <INDENT> print("spider2 already computed for %s"%prefix... | Computes spider2 for the sequence seqStr, whose pssm is contained at pssmOutNameRaw. This sequence is
associated with prefixExtended as an unambiguous id
@param prefixExtended: str. unambiguous id of the sequence that will be the prefix of output names
@param pssmOutNameRaw: str. Path to psiblast pssms results | 625941e49c8ee82313fbbb78 |
def start(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.pidfile, 'r') as fd: <NEW_LINE> <INDENT> pid = int(fd.read().strip()) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> pid = None <NEW_LINE> <DEDENT> if pid: <NEW_LINE> <INDENT> message = "pidfile %s already exist. Daemon alrea... | Start the daemon | 625941e4d53ae8145f87a66a |
def set_form(self): <NEW_LINE> <INDENT> form_frame = Frame(self.reg_frame, bg="lightblue") <NEW_LINE> form_frame.pack(fill=X, padx=20, pady=10) <NEW_LINE> Label(form_frame, text="username:", font=("Microsoft Yahei", 12), bg="lightblue", fg="black").grid(row=0, column=1, pady=20) <NEW_LINE> Label(form_frame, text="passw... | 放置注册表单 | 625941e45510c4643540f7dc |
def findall(self, pat: str, flags: int = 0) -> "ps.Series": <NEW_LINE> <INDENT> pudf = pandas_udf( lambda s, *_: s.str.findall(pat, flags), returnType=ArrayType(StringType(), containsNull=True), functionType=PandasUDFType.SCALAR, ) <NEW_LINE> return self._data._with_new_scol(scol=pudf(self._data.spark.column)) | Find all occurrences of pattern or regular expression in the Series.
Equivalent to applying :func:`re.findall` to all the elements in
the Series.
Parameters
----------
pat : str
Pattern or regular expression.
flags : int, default 0 (no flags)
`re` module flags, e.g. `re.IGNORECASE`.
Returns
-------
Series of... | 625941e4f8510a7c17cf9b01 |
def __init__(self, album_url): <NEW_LINE> <INDENT> self.album_url = album_url <NEW_LINE> self.image_callbacks = [] <NEW_LINE> self.complete_callbacks = [] <NEW_LINE> match = re.match('(https?)\:\/\/(www\.)?(?:m\.)?imgur\.com/a/([a-zA-Z0-9]+)(#[0-9]+)?', album_url) <NEW_LINE> if not match: <NEW_LINE> <INDENT> raise Imgu... | Constructor. Pass in the album_url that you want to download. | 625941e4bf627c535bc135d1 |
@keras_export('keras.backend.categorical_crossentropy') <NEW_LINE> def categorical_crossentropy(target, output, from_logits=False, axis=-1): <NEW_LINE> <INDENT> if not from_logits: <NEW_LINE> <INDENT> if (isinstance(output, (ops.EagerTensor, variables_module.Variable)) or output.op.type != 'Softmax'): <NEW_LINE> <INDEN... | Categorical crossentropy between an output tensor and a target tensor.
Arguments:
target: A tensor of the same shape as `output`.
output: A tensor resulting from a softmax
(unless `from_logits` is True, in which
case `output` is expected to be the logits).
from_logits: Boolean, whether `out... | 625941e4e76e3b2f99f3ac07 |
def __init__(self, iterator): <NEW_LINE> <INDENT> self.iterator = iterator <NEW_LINE> self.peek_elem = None | Initialize your data structure here.
:type iterator: Iterator | 625941e491af0d3eaac9be1e |
def calculate_impv( price: float, f: float, k: float, r: float, t: float, cp: int, n: int = DEFAULT_STEP ) -> float: <NEW_LINE> <INDENT> if price <= 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> meet = False <NEW_LINE> if cp == 1 and price > (f - k): <NEW_LINE> <INDENT> meet = True <NEW_LINE> <DEDENT> elif cp == ... | Calculate option implied volatility | 625941e4566aa707497f4965 |
def barycenter(points_list_in): <NEW_LINE> <INDENT> points_arr = np.array(points_list_in) <NEW_LINE> return np.mean(points_arr[:,-3:], axis=0) | Determines the barycenter of a list of points | 625941e47b180e01f3dc4bf7 |
def test_django_session_csrf(self): <NEW_LINE> <INDENT> ok_('session_csrf.context_processor' in settings.TEMPLATE_CONTEXT_PROCESSORS) <NEW_LINE> ok_('django.core.context_processors.csrf' not in settings.TEMPLATE_CONTEXT_PROCESSORS) <NEW_LINE> ok_('session_csrf.CsrfMiddleware' in settings.MIDDLEWARE_CLASSES) <NEW_LINE> ... | test that we're correctly using session CSRF tokens
(as opposed to cookies) | 625941e40a366e3fb873ec20 |
def endPath(self)->HS2Sensors: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._lock() <NEW_LINE> packet = self._makeS2Packet(161) <NEW_LINE> packet[1] = 0 <NEW_LINE> self._sendS2PathCommand(packet) <NEW_LINE> return self._getS2SensorsResponse() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT... | Finaliza el modo path. | 625941e48e7ae83300e4b3d0 |
def assertMessagePanel(self, message, content): <NEW_LINE> <INDENT> if message.get('clickable', False): <NEW_LINE> <INDENT> self.assertIn('js-inpagelink', content) <NEW_LINE> <DEDENT> for message_line in message['text'].split('\n'): <NEW_LINE> <INDENT> self.assertIn(message_line, content) <NEW_LINE> <DEDENT> self.asser... | Helper method for asserting the rendered content includes the required message panels.
:param message: message dict
:param content: rendered HTML str | 625941e473bcbd0ca4b2c477 |
def get_descriptive_name(self): <NEW_LINE> <INDENT> long_name = str(self.year) + ' ' + self.make + ' ' + self.model <NEW_LINE> return long_name.title() | Return a neately formatted descriptive name. | 625941e42ae34c7f2600d533 |
def transform_song(song: Song, number: int, authenticated: bool) -> Dict: <NEW_LINE> <INDENT> transformed = model_to_dict(song, ["id", "name", "capo", "author", "link"]) <NEW_LINE> transformed["number"] = number <NEW_LINE> if authenticated: <NEW_LINE> <INDENT> transformed['edit_url'] = reverse("chords:edit", kwargs={"p... | Transforms song into a dict representation | 625941e4d6c5a10208144450 |
def nth_prime(n): <NEW_LINE> <INDENT> if n <= 0: <NEW_LINE> <INDENT> raise ValueError("nth prime meaningless for non-positive n (=%s)" % n) <NEW_LINE> <DEDENT> return ZZ(pari.prime(n)) | Return the n-th prime number (1-indexed, so that 2 is the 1st prime.)
INPUT:
- ``n`` -- a positive integer
OUTPUT:
- the n-th prime number
EXAMPLES::
sage: nth_prime(3)
5
sage: nth_prime(10)
29
sage: nth_prime(10^7)
179424673
::
sage: nth_prime(0)
Traceback (most recent call las... | 625941e4be383301e01b5880 |
def curve_coordinates(f, x0, x1, points): <NEW_LINE> <INDENT> coordinates = [] <NEW_LINE> x = x0 <NEW_LINE> delta = (x1 - x0) / (points - 1) <NEW_LINE> while x <= x1: <NEW_LINE> <INDENT> coordinates += [[x, f(x)]] <NEW_LINE> x += delta <NEW_LINE> <DEDENT> return coordinates | Returns list of coordinates
Creates linear splines for this function f, from x0 to x1
Length of returned list == points. | 625941e455399d3f05588ab9 |
def test_states(self): <NEW_LINE> <INDENT> self._recommender = cf_recommender.CollabFilteringRecommender( self._config, model_ctor=functools.partial(MockModel, model_output={})) <NEW_LINE> init_state = self._recommender.initial_state() <NEW_LINE> mock_user_response = Value( choice=ed.Deterministic( loc=tf.constant([0, ... | Tests next state with a mock model. | 625941e45fdd1c0f98dc0637 |
def get_threshold(self): <NEW_LINE> <INDENT> value_map = dict() <NEW_LINE> for key, value in self.threshold_classes.items(): <NEW_LINE> <INDENT> value_map[key] = [ value[0].value(), value[1].value(), ] <NEW_LINE> <DEDENT> return value_map | Return threshold based on current state. | 625941e423e79379d52ee961 |
def sharpness_behavior(img, **kwargs): <NEW_LINE> <INDENT> if img is None: <NEW_LINE> <INDENT> return [-1] * 5 <NEW_LINE> <DEDENT> blurred = blur(img, (9, 9)) <NEW_LINE> g1 = two_neighbors_gradient(img) <NEW_LINE> g2 = two_neighbors_gradient(blurred) <NEW_LINE> m = mean(g2) <NEW_LINE> i1 = [x + m < y for x, y in zip(g2... | The sharpness behavior (SHB) function. It returns the 5-D feature vector
extracted from the given image.
The features are:
#. The sharpness score for the original image;
#. The sharpness score for the blurred image;
#. The mean gradient for the original image;
#. A score estimating how much of the shar... | 625941e4b830903b967e9d09 |
def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self._to_dict(), indent=2) | Return a `str` version of this PdfHeadingDetection object. | 625941e4eab8aa0e5d26df5c |
def getMimicFadeRateStr(self): <NEW_LINE> <INDENT> return getNamedNodeAttrText(self.dom, "MM", "fr") | Retrieve value controlling the rate at which a mimic changes between
low and high brightness levels, as a string. | 625941e48a349b6b435e8575 |
def free_to_snail(s): <NEW_LINE> <INDENT> return s.strip().lower().replace(' ', '_') | Convert Free Case to snail_case. | 625941e482261d6c526ab8a8 |
def apply_correction(self, data): <NEW_LINE> <INDENT> return (data * self._mask - self._dark) * self._gain_map | Applies the corrections to a detector data frame.
This function initially applies the mask, if provided, to the data frame. The
dark data, if provided, is then subtracted. Finally, the result is multiplied
by the gain map (if provided).
Arguments:
data (numpy.ndarray): the detector data frame on which the correc... | 625941e42c8b7c6e89b35bc0 |
def parse_cli(to_parse): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser() <NEW_LINE> parser.set_defaults(command=print_table) <NEW_LINE> commands = parser.add_argument_group('sub commands') .add_mutually_exclusive_group() <NEW_LINE> commands.add_argument( '-s', '--simple', dest='command', acti... | ! Parse the command line
@return Retrun a namespace that contains:
* command - python function to run
* skip_retarget - bool indicting to skip retargeting
* list_unmounted - list boards that are not mounted
* debug - turn on debug logging | 625941e476d4e153a657ef35 |
def snap2road(pts_lon_lat, timestamps=(), pause=False): <NEW_LINE> <INDENT> import mapbox as mp <NEW_LINE> from utils import even_chunks, work_every_sec <NEW_LINE> from constants import mapbox_access <NEW_LINE> service = mp.MapMatcher(access_token=mapbox_access) <NEW_LINE> snapped = [] <NEW_LINE> raw = [] <NEW_LINE> fo... | params:
pts_lon_lat: [[lon, lat], [], ...]
timestamps: ['2015-10-15T12:06:50Z', ...]
return:
new_gps: [[lon, lat], [], ...], len(new_gps) not necessarily equals to len(pts_lon_lat)
confidences: [ (which batch, # origin pts, # snapped pts, confidence), (), ..] | 625941e4046cf37aa974d146 |
def prepare_video_conversion_command( input_file: str, framerate: float, quality: int, sid: Optional[int], font: Optional[Font], ) -> Sequence[str]: <NEW_LINE> <INDENT> width, height = calculate_dimensions(input_file) <NEW_LINE> v_cmd = [ FFMPEG, "-hide_banner", "-i", input_file, "-f", "data", "-map", "0:v:0", "-r", "%... | Prepare the command for converting the video stream. | 625941e4d18da76e235328dd |
def ensure_commands_exist(commands, exit_code=1): <NEW_LINE> <INDENT> commands_exist = map(command_available, commands) <NEW_LINE> if not all(commands_exist): <NEW_LINE> <INDENT> sys.exit(exit_code) <NEW_LINE> <DEDENT> return None | Ensure that all commands given by an iterable exist, otherwise exit (with
exit_code that defaults to 1). | 625941e476e4537e8c351a78 |
def close( self ): <NEW_LINE> <INDENT> if not self._isValid : return <NEW_LINE> self._isValid = False <NEW_LINE> self._tkwin.destroy() <NEW_LINE> self._tkwin.update_idletasks() <NEW_LINE> self._tkwin.quit() | Closes and destroys the image window. | 625941e40fa83653e46573bb |
def zmatrix(file_name): <NEW_LINE> <INDENT> return _add_extension(file_name, Extension.ZMATRIX) | adds zmatrix extension, if missing
| 625941e41b99ca400220aeb5 |
def compute_pareto_metrics(population): <NEW_LINE> <INDENT> pareto = sort_non_dominated(population) <NEW_LINE> pareto = calculate_crowding_distance(pareto) <NEW_LINE> return pareto | Compute the pareto fronts using NSGA-II.
:param population: A population to be sorted into fronts using NSGA-II.
:return: The pareto fronts. | 625941e4be8e80087fb2103f |
def levenshtein_distance(first_string, second_string): <NEW_LINE> <INDENT> if len(first_string) > len(second_string): <NEW_LINE> <INDENT> first_string, second_string = second_string, first_string <NEW_LINE> <DEDENT> distances = range(len(first_string) + 1) <NEW_LINE> for index2, char2 in enumerate(second_string): <NEW_... | Function to find the Levenshtein distance between two words/sentences | 625941e4283ffb24f3c55d00 |
@check50.check() <NEW_LINE> def strings3_exists(): <NEW_LINE> <INDENT> check50.exists("strings3.c") <NEW_LINE> check50.include("strings3_soln") | strings3.c exists | 625941e48e05c05ec3eea77a |
def sort(L): <NEW_LINE> <INDENT> for i in range(1, len(L)): <NEW_LINE> <INDENT> val = L[i] <NEW_LINE> k = i <NEW_LINE> while k > 0 and val < L[k - 1]: <NEW_LINE> <INDENT> L[k] = L[k - 1] <NEW_LINE> k -= 1 <NEW_LINE> <DEDENT> L[k] = val <NEW_LINE> <DEDENT> return L | Insertion sort is a simple algorithm which builds the final sorted list 1
item at a time.
It compares the current element with it's neighbor to the left. If the
current element is smaller than the neighbor, it then compares with the
neighbor before that and so on until the beginning of the list is reached.
Performanc... | 625941e4e5267d203edce09a |
def get_smallest_divisible_number(max_factor): <NEW_LINE> <INDENT> res = 1 <NEW_LINE> for factor_i in range(1, max_factor + 1): <NEW_LINE> <INDENT> res = least_common_multiple(res, factor_i) <NEW_LINE> <DEDENT> return res | Get the smallest divisible number by all [1..max_factor] numbers by using the LCM (least common multiple). | 625941e4d164cc6175783152 |
def next(self, counter=None): <NEW_LINE> <INDENT> if not counter: <NEW_LINE> <INDENT> counter = self._defaultCounter <NEW_LINE> <DEDENT> return next(self._getCounter(counter)) | Retrieves the numeric value for the given counter, then
increments it by one. New counters start at one. | 625941e43eb6a72ae02ec8ea |
def draw_checkerboard_canvas(height=180, width=180, box_size=10): <NEW_LINE> <INDENT> i_max = math.ceil(height/box_size) <NEW_LINE> j_max = math.ceil(width/box_size) <NEW_LINE> canvas = np.zeros((i_max*box_size, j_max*box_size)) <NEW_LINE> for i in range(i_max): <NEW_LINE> <INDENT> is_gray = i % 2 == 0 <NEW_LINE> for j... | Draw a checkerboard_canvas like the classic transparency background. | 625941e4be7bc26dc91cd9fb |
def make_aggregate_result_file(output_directory, result_dict): <NEW_LINE> <INDENT> result_file = open(output_directory + "/elio_plasma_aggregate_results.csv", "w") <NEW_LINE> result_file.write("Sample," "Percent of Bases Mapped to Genome (%)," "Percent of Bases Mapped to ROI (%)," "Average High Quality Distinct Coverag... | Aggregate the desired metrics and output into a csv file
:param output_directory:
:param result_dict:
:return: | 625941e4851cf427c661a90e |
def stop_cpm(self): <NEW_LINE> <INDENT> self.on = False | Stop counter. | 625941e4dc8b845886cb5939 |
def __init__(self, dealer_card, player_card, is_terminal=False): <NEW_LINE> <INDENT> self.dealer = dealer_card.value <NEW_LINE> self.player = player_card.value <NEW_LINE> self.term = is_terminal <NEW_LINE> self.r = 0 | :type self.is_terminal: bool
:type self.dealer: int
:type self.player: int | 625941e4ff9c53063f47c5f4 |
def process(self, outputs, resolution_raw): <NEW_LINE> <INDENT> outputs_reshaped = list() <NEW_LINE> for output in outputs: <NEW_LINE> <INDENT> outputs_reshaped.append(self._reshape_output(output)) <NEW_LINE> <DEDENT> boxes, categories, confidences = self._process_yolo_output( outputs_reshaped, resolution_raw) <NEW_LIN... | Take the YOLOv3 outputs generated from a TensorRT forward pass, post-process them
and return a list of bounding boxes for detected object together with their category
and their confidences in separate lists.
Keyword arguments:
outputs -- outputs from a TensorRT engine in NCHW format
resolution_raw -- the original spat... | 625941e41d351010ab855f1e |
def test_reverse_delete_rule_cascade_and_nullify_complex_field(self): <NEW_LINE> <INDENT> class BlogPost(Document): <NEW_LINE> <INDENT> content = StringField() <NEW_LINE> authors = ListField( ReferenceField(self.Person, reverse_delete_rule=CASCADE) ) <NEW_LINE> reviewers = ListField( ReferenceField(self.Person, reverse... | Ensure that a referenced document is also deleted upon
deletion for complex fields. | 625941e4d99f1b3c44c6798a |
def run_test(self, redant): <NEW_LINE> <INDENT> replaced_bricks = [] <NEW_LINE> ret, pids = redant.get_self_heal_daemon_pid(self.server_list) <NEW_LINE> if not ret: <NEW_LINE> <INDENT> raise Exception("Either No self heal daemon process found or " "more than One self heal daemon process " f"found : {pids}") <NEW_LINE> ... | 1. Get the self head daemon pids.
2. Get all the brivks for the volume
3. Check if the bricks exist in the shd volfile
4. Get the sub volumes for the volume type
5. Replace a brick in all the subvols.
6. Check for the volume process to be online.
7. Get the selh heal daemon pids and compare the same
with the previou... | 625941e45166f23b2e1a555c |
def begin_site(self): <NEW_LINE> <INDENT> for node in self.site.content.walk(): <NEW_LINE> <INDENT> for resource in node.resources: <NEW_LINE> <INDENT> created = None <NEW_LINE> modified = None <NEW_LINE> try: <NEW_LINE> <INDENT> created = resource.meta.created <NEW_LINE> modified = resource.meta.modified <NEW_LINE> <D... | Initialize plugin. Retrieve dates from git | 625941e485dfad0860c3b25e |
def handle_payment_overdue(self, registration): <NEW_LINE> <INDENT> activity = Activity( actor=registration.event, verb=PaymentOverdueVerb, object=registration, target=registration.user, ) <NEW_LINE> self.manager.add_activity(activity, [registration.user_id], [NotificationFeed]) <NEW_LINE> notification = EventPaymentOv... | Notify about payment overdue, called from a celery task run by beat. | 625941e410dbd63aa1bd2fa5 |
def _get_argument_parcer(remove_only=False): <NEW_LINE> <INDENT> description = ("Utility that help to remove file. Use bucket. All " "operation(except autoclean) use Unix filemask " "to select targect. You can use all operration like if " "all files present in folder.") <NEW_LINE> parser = argparse.ArgumentParser(prog... | Возвращает настроееный парсер аргументов.
Непозиционные аргументы:
* remove_only -- короткая точка входа | 625941e463b5f9789fde74e9 |
def convert(img): <NEW_LINE> <INDENT> img_grey = img.convert('L') <NEW_LINE> threshold = 200 <NEW_LINE> table = [] <NEW_LINE> for i in range(256): <NEW_LINE> <INDENT> if i < threshold: <NEW_LINE> <INDENT> table.append(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> table.append(1) <NEW_LINE> <DEDENT> <DEDENT> out_img ... | 二值化图像
:param img:
:return: | 625941e496565a6dacc8facd |
def get_trip_by_trip_uuid(): <NEW_LINE> <INDENT> trip_uuid = connexion.request.args.get('tripUUID', None) <NEW_LINE> trip = mongodb_interface.get_trip_by_trip_uuid(trip_uuid) <NEW_LINE> if not trip: <NEW_LINE> <INDENT> return ApiResponse(code=400, message='trip not found'), 400 <NEW_LINE> <DEDENT> raw_points = mongodb_... | Gets a trip given a tripUUID
# noqa: E501
:param trip_uuid:
:type trip_uuid:
:rtype: Trip | 625941e4711fe17d82542765 |
def SetOutputMinimum(self, *args): <NEW_LINE> <INDENT> return _itkRescaleIntensityImageFilterPython.itkRescaleIntensityImageFilterID2IUC2_SetOutputMinimum(self, *args) | SetOutputMinimum(self, unsigned char _arg) | 625941e4851cf427c661a90f |
def _unitstep_builder(db, piece, xvar, usdb): <NEW_LINE> <INDENT> amt = db[piece](xvar) <NEW_LINE> return (amt * usdb[piece](xvar)) - (amt * usdb[piece+1](xvar)) | Implements unit step function logic.
AKA: calculate the vlaue, then subtract it by itself if its unitstep value
says it should not exist
IN:
db - curried function database to use
piece - piece to calculate
xvar - xvar the var to pass into all functions
usdb - unitstep databse to use
RETURNS a ... | 625941e47d847024c06be6c2 |
def generate_new(self, project_name: str, project_dir: str): <NEW_LINE> <INDENT> file_names = ('Dockerfile', '.dockerignore') <NEW_LINE> options = {'project_name': project_name} <NEW_LINE> for file_name in file_names: <NEW_LINE> <INDENT> template_path = os.path.join(self._get_template_folder_path(), file_name) <NEW_LIN... | Generate Dockerfile and .dockerignore.
Args:
project_name: The name of your Django project.
project_dir: The destination directory path to put Dockerfile. | 625941e430c21e258bdfa8a4 |
def normalize(url): <NEW_LINE> <INDENT> if url[:4] != 'http': <NEW_LINE> <INDENT> url = 'http://'+url <NEW_LINE> <DEDENT> url = url.lower() <NEW_LINE> url_parts = urlparse(url) <NEW_LINE> if url_parts.netloc: <NEW_LINE> <INDENT> url_obj = parse(url).defrag().abspath().canonical().punycode() <NEW_LINE> return url_obj.ut... | Uses the Moz URL library to normalise and strip the URLs of
extraneous information, and the urlparse library to ensure it
is not a blank URL. | 625941e44527f215b584c856 |
def testQuadrilateral(self): <NEW_LINE> <INDENT> pass | Test Quadrilateral | 625941e431939e2706e4d267 |
def check_drive_format(node, params): <NEW_LINE> <INDENT> expected = params.get('drive_format') <NEW_LINE> if expected == 'scsi': <NEW_LINE> <INDENT> if arch.ARCH in ('ppc64', 'ppc64le'): <NEW_LINE> <INDENT> expected = 'spapr-vscsi' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> expected = 'lsi53c895a' <NEW_LINE> <DEDEN... | checks the drive format according to qtree info | 625941e4046cf37aa974d147 |
def list( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable["_models.ExpressRouteCircuitListResult"]: <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('e... | Gets all the express route circuits in a resource group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ExpressRouteCircuitListResult or the ... | 625941e4187af65679ca5523 |
def process_response(self, request, response): <NEW_LINE> <INDENT> if settings.USE_ETAGS: <NEW_LINE> <INDENT> if response.has_header('ETag'): <NEW_LINE> <INDENT> etag = response['ETag'] <NEW_LINE> <DEDENT> elif response.streaming: <NEW_LINE> <INDENT> etag = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> etag = '"%s... | Calculate the ETag, if needed. | 625941e4a17c0f6771cbe452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.