code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def print_results(df): <NEW_LINE> <INDENT> missed = df.received.str.count('missed').sum() <NEW_LINE> superfluous = df.received.str.count('superfluous').sum() <NEW_LINE> print(' ... Total: ' + str(df.shape[0])) <NEW_LINE> print(' ... Sent: ' + str((df['TX'] > 0).sum())) <NEW_LINE> print(' ... Received: ' + str((df['R... | Print the final results dataframe. | 625941e84a966d76dd5514a2 |
def test_that_when_checking_if_a_bucket_exists_and_a_bucket_does_not_exist_the_bucket_exists_method_returns_false(self): <NEW_LINE> <INDENT> self.conn.head_bucket.side_effect = e404_error <NEW_LINE> result = boto_s3_bucket.exists(Bucket='mybucket', **conn_parameters) <NEW_LINE> self.assertFalse(result['exists']) | Tests checking s3 bucket existence when the s3 bucket does not exist | 625941e85fc7496912cc3e0b |
def clear_location_terms(self): <NEW_LINE> <INDENT> raise errors.Unimplemented() | Clears the location terms.
*compliance: mandatory -- This method must be implemented.* | 625941e876d4e153a657efc0 |
def _api_url(self, path): <NEW_LINE> <INDENT> if self.USE_SSL: <NEW_LINE> <INDENT> protocol = "https" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> protocol = "http" <NEW_LINE> <DEDENT> return "%s://%s/%s/" %(protocol, self.API_ENDPOINT, path) | Helper method for create request-url
:Parameters:
- `path` - api-method
:Returns:
The request url | 625941e857b8e32f5248392c |
def string_value(self, tree: "Tree") -> "SchemaNode": <NEW_LINE> <INDENT> return SchemaNode( type="string_value", value=lark_to_string_value_node(tree) ) | Creates and returns a SchemaNode instance of type "string_value" with a
StringValueNode instance as value (extracted from the parsing of the
tree instance).
:param tree: the Tree to parse in order to extract the proper node
:type tree: Tree
:return: a SchemaNode instance of type "string_value" with a
StringValueNode in... | 625941e8167d2b6e31219023 |
def reset(self): <NEW_LINE> <INDENT> subs_setinit.setinitdirs(self) <NEW_LINE> logger.warning('Beam ' + self.beam + ': Deleting all raw data and their directories.') <NEW_LINE> subs_managefiles.director(self, 'ch', self.basedir) <NEW_LINE> try: <NEW_LINE> <INDENT> subs_managefiles.director( self, 'rm', self.basedir + s... | Function to reset the current step and remove all generated data. Be careful! Deletes all data generated in
this step! | 625941e856ac1b37e6264654 |
def tearDown(self): <NEW_LINE> <INDENT> if self.inst_creator: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.inst_creator.clean() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error( 'Unexpected exception cleaning VM instance with message' ' - %s', e) <NEW_LINE> <DEDENT> <DEDENT> if self.netw... | Cleans the created object | 625941e83617ad0b5ed68384 |
def parse(item): <NEW_LINE> <INDENT> cleaned = (remove_comment(line) for line in item.split('\n')) <NEW_LINE> item = '\n'.join(line for line in cleaned if line != '') <NEW_LINE> stack = [] <NEW_LINE> depth = 0 <NEW_LINE> inner = '' <NEW_LINE> def add(item): <NEW_LINE> <INDENT> current = stack <NEW_LINE> for _ in range(... | item is the raw text of a q-lisp file
Comments are removed, and then the parentheses are parsed, i.e.
(if (= c0 1) (X 0) (X 1))
becomes the python list:
['if', ['=', 'c0', '1'], ['X', '0'], ['X', '1']] | 625941e8090684286d50f17a |
def plot_time_v_procs(df, out_dir, name): <NEW_LINE> <INDENT> for size, size_df in df.groupby('Size'): <NEW_LINE> <INDENT> fig, ax = plt.subplots(figsize=get_figsize(size_df, 'CommSize', 'Impl')) <NEW_LINE> sns.violinplot(x='CommSize', y='Time', hue='Impl', data=size_df, cut=0, inner='quartile', linewidth=0.25, ax=ax) ... | Plot time vs process count for a fixed operator. | 625941e826238365f5f0f303 |
def get_refs_by_direct_link(docLink): <NEW_LINE> <INDENT> linkParts = docLink.split('/') <NEW_LINE> RefsLink = docLink + '/references' <NEW_LINE> GetLink = 'https://ieeexplore.ieee.org/rest/document/' + linkParts[-1] + '/references' <NEW_LINE> Headers={'Referer':RefsLink + '#references'} <NEW_LINE> refReq = requests.ge... | !!!!better to use get_refs_by_doc_id()
Given the direct ieee link to a document as a string,
makes an http GET request to IEEE
recieves a json of the document's references
write now rights json to a file, but will likely change
Link must have the document id as the last parameter in the link
... | 625941e84428ac0f6e5bac84 |
def update_subnet(self, subnet, if_revision=None, **attrs): <NEW_LINE> <INDENT> return self._update(_subnet.Subnet, subnet, if_revision=if_revision, **attrs) | Update a subnet
:param subnet: Either the id of a subnet or a
:class:`~openstack.network.v2.subnet.Subnet` instance.
:param int if_revision: Revision to put in If-Match header of update
request to perform compare-and-swap update.
:param dict attrs: The attributes to update on the subnet represented
by ``su... | 625941e8287bf620b61d3eef |
def is_valid_image_extension(file_path): <NEW_LINE> <INDENT> valid_extensions = ['.jpeg', '.jpg', '.gif', '.png'] <NEW_LINE> _, extension = os.path.splitext(file_path) <NEW_LINE> return extension.lower() in valid_extensions | is_valid_image_extension. | 625941e891f36d47f21ac985 |
def argmax_list(seq, func): <NEW_LINE> <INDENT> return argmin_list(seq, lambda x: -func(x)) | Return a list of elements of seq[i] with the highest
func(seq[i]) scores.
>>> argmax_list(['one', 'three', 'seven'], len)
['three', 'seven'] | 625941e88a349b6b435e8601 |
def addMonFiles(self): <NEW_LINE> <INDENT> configtmp = tempfile.NamedTemporaryFile(delete=True) <NEW_LINE> configtmp.write(str(self.config)) <NEW_LINE> configtmp.flush() <NEW_LINE> psetfilename = getattr(self.config.JobType, 'psetName', None) <NEW_LINE> if not psetfilename == None: <NEW_LINE> <INDENT> self.tarfile.add(... | Add monitoring files the debug tarball. | 625941e8f8510a7c17cf9b8e |
def start(self): <NEW_LINE> <INDENT> self.profiler.start() <NEW_LINE> self.start = lambda: None | Starts profiling and disables restarts. | 625941e882261d6c526ab935 |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkNormalizedCorrelationImageFilterPython.itkNormalizedCorrelationImageFilterIUC3IUC3IUC3_GetPointer(self) | GetPointer(self) -> itkNormalizedCorrelationImageFilterIUC3IUC3IUC3 | 625941e8d4950a0f3b08c7d7 |
def __call__(self, msg): <NEW_LINE> <INDENT> self.log(msg) | Allows the Log instance to be called directly
| 625941e8a8ecb033257d355a |
def create_freq_dict(sents): <NEW_LINE> <INDENT> i=0 <NEW_LINE> freqDict_list=[] <NEW_LINE> for sent in sents: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> freq_dict= {} <NEW_LINE> words = word_tokensize(sent) <NEW_LINE> for word in words: <NEW_LINE> <INDENT> word=word.lower() <NEW_LINE> if word in freq_dict: <NEW_LINE> <INDE... | This function creates a frequency distribution dictionary for each word in each document | 625941e8e5267d203edce125 |
def test_create_failure_incompatible_key(self): <NEW_LINE> <INDENT> incompatible_key = '-----BEGIN PUBLIC KEY-----' <NEW_LINE> self.assertIn(EasyJWT.algorithm, {Algorithm.HS256, Algorithm.HS384, Algorithm.HS512}) <NEW_LINE> easyjwt = EasyJWT(incompatible_key) <NEW_LINE> with self.assertRaises(IncompatibleKeyError) as e... | Test creating a token using an incompatible key.
Expected Result: An `IncompatibleKeyError` error is raised. | 625941e8bf627c535bc1365d |
def pytest_sessionfinish(self, session, exitstatus): <NEW_LINE> <INDENT> suite_stop_time = time.time() <NEW_LINE> suite_time_delta = suite_stop_time - self.suite_start_time <NEW_LINE> self.logfile.write('<testsuite ') <NEW_LINE> self.logfile.write('errors="%i" ' % self.error_count) <NEW_LINE> self.logfile.write('failur... | Write the xml output | 625941e816aa5153ce362906 |
def curr_selection(self): <NEW_LINE> <INDENT> self.domain = self.row[0] <NEW_LINE> abstract = self.row[5] <NEW_LINE> self.data_type = self.row[1] <NEW_LINE> self.object_id = self.row[3] <NEW_LINE> self.service = self.row[2] <NEW_LINE> self.layer_title = self.row[4] <NEW_LINE> crs_options = self.row[6] <NEW_LINE> self.d... | On the tableviews currentRowChanged store the details of the current
record Also, update the abstract as shown in the UI | 625941e87c178a314d6ef8f5 |
def map_to_primitive_cell(self, x, y, z=None): <NEW_LINE> <INDENT> if z is not None and not np.allclose(np.nan_to_num(z), 0.0): <NEW_LINE> <INDENT> raise RuntimeError('The local z positions contain values z!=0.') <NEW_LINE> <DEDENT> x_mod, x_primitve_cell = np.divmod(x + self.x_extent()[0], self.column_size * 2.0) <NEW... | Primitve cell is a pixel. Every second column must be mirrored (avoiding primitive cell becoming 2x1 pixels).
| 625941e8bf627c535bc1365e |
def set_dbserver(self, value): <NEW_LINE> <INDENT> self.__dbserver = value | set dbservername
:param value:
:type value:
:return:
:rtype: | 625941e8377c676e91272635 |
def test_tls_all_keys_match_leaf(mgr, temp_chains, cleanup): <NEW_LINE> <INDENT> do_cert_test( mgr, temp_chains, client_ca_certs=[SERVER_INTR, SERVER_CA, CLIENT_INTR, CLIENT_CA], server_trusted_client_certs=[ { "^ks:name": "TrustedClientRootCA", "ks:certificate": read_pem_b64(CLIENT_CA), }, { "^ks:name": "TrustedClient... | Verify that when the cert-to-name fingerprint matches the
leaf client cert the connection is accepted | 625941e8c4546d3d9de72ec6 |
def setX(self, x: str) -> None: <NEW_LINE> <INDENT> parsed_x = self._parseFloat(x) <NEW_LINE> bounding_box = Selection.getBoundingBox() <NEW_LINE> if not Float.fuzzyCompare(parsed_x, float(bounding_box.center.x), DIMENSION_TOLERANCE): <NEW_LINE> <INDENT> selected_nodes = self._getSelectedObjectsWithoutSelectedAncestors... | Set the x-location of the selected object(s) by translating relative to
the selection bounding box center.
:param x: Location in mm. | 625941e8097d151d1a2232e6 |
@cache_control(no_cache=True) <NEW_LINE> @transaction.atomic() <NEW_LINE> @reversion.create_revision() <NEW_LINE> def add_update_geo_data(request, uuid): <NEW_LINE> <INDENT> item_geotime = ItemGeoTime(uuid, request) <NEW_LINE> if item_geotime.manifest is not False: <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_... | Handles POST requests to update an date ranges for an item | 625941e86fece00bbac2dbd3 |
def has_flush(self): <NEW_LINE> <INDENT> self.suit_hist() <NEW_LINE> for ranks in self.suits.values(): <NEW_LINE> <INDENT> if len(ranks) >= 5: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | Returns True if the hand has a flush, False otherwise.
Note that this works correctly for hands with more than 5 cards. | 625941e891f36d47f21ac986 |
def _iotool_enable_yellow_command(self): <NEW_LINE> <INDENT> return self._iotool.commands.set_low(self._spconfig.IOTOOL_GREEN_YELLOW_SWITCH_PIN) | Produce a command that switches the green/yellow paddle to the yellow filter position. | 625941e8d268445f265b52fd |
def herd(list_input): <NEW_LINE> <INDENT> ndim = len(list_input) <NEW_LINE> Parallel_cpu = mp.cpu_count() <NEW_LINE> print('# files: ', ndim) <NEW_LINE> print('# cores: ', Parallel_cpu) <NEW_LINE> pool = mp.ProcessingPool(Parallel_cpu) <NEW_LINE> with tqdm(total=ndim): <NEW_LINE> <INDENT> herd_outputs = pool.map(mm.SED... | Wrapper to parallelise MrMoose on samples | 625941e81f037a2d8b94668b |
def lex_break(self) -> None: <NEW_LINE> <INDENT> s = self.match(self.break_exp) <NEW_LINE> last_tok = self.tok[-1] if self.tok else None <NEW_LINE> if isinstance(last_tok, Break): <NEW_LINE> <INDENT> was_semicolon = last_tok.string == ';' <NEW_LINE> last_tok.string += self.pre_whitespace + s <NEW_LINE> self.i += len(s)... | Analyse a line break. | 625941e8c432627299f050d8 |
def copy_btree(src): <NEW_LINE> <INDENT> copy = d_btree() <NEW_LINE> for key, value in src.iteritems(): <NEW_LINE> <INDENT> if isinstance(value, s_btree): <NEW_LINE> <INDENT> value = copy_btree(value) <NEW_LINE> <DEDENT> copy[key] = value <NEW_LINE> <DEDENT> return copy | Used for copying indices structure. | 625941e89f2886367277ad18 |
def turn_titles_into_sentences(raw_text): <NEW_LINE> <INDENT> paragraphs = raw_text.split("\n") <NEW_LINE> i = 0 <NEW_LINE> while i < len(paragraphs) and not paragraphs[i].endswith("."): <NEW_LINE> <INDENT> if paragraphs[i]: <NEW_LINE> <INDENT> paragraphs[i] = paragraphs[i].strip() + "." <NEW_LINE> <DEDENT> i += 1 <NEW... | Spacy is not quite clever enough to separate the title of an article from the
first sentence. This seems to cause problems with the POS-tagging. This function
adds full stops at the end of title lines. | 625941e8d58c6744b42580ed |
def image_data(image): <NEW_LINE> <INDENT> data = image.tobytes() <NEW_LINE> components = len(data) // (image.size[0] * image.size[1]) <NEW_LINE> return components, data | Get components and bytes for an image | 625941e88c3a87329515884f |
def __init__(self): <NEW_LINE> <INDENT> self.immediate = 32 * '0' <NEW_LINE> self.offset = 16 * '0' <NEW_LINE> self.src = 4 * '0' <NEW_LINE> self.dst = 4 * '0' <NEW_LINE> self.opcode = 8 * '0' | Instruction class constructor method.
Args:
self
Returns:
None
Raises:
None | 625941e8d10714528d600177 |
def find_objects_dna(self, dnaspec, exactmatch=False): <NEW_LINE> <INDENT> if self.debug > 1: <NEW_LINE> <INDENT> method_name = inspect.currentframe().f_code.co_name <NEW_LINE> message = "METHOD {}().{}(dnaspec='{}') was called".format( self.__class__.__name__, method_name, dnaspec) <NEW_LINE> logger.info(message) <NEW... | Find all :class:`~models_cisco.IOSCfgLine` objects whose text
matches ``dnaspec`` and return the :class:`~models_cisco.IOSCfgLine`
objects in a python list.
Notes
-----
:func:`~ciscoconfparse.CiscoConfParse.find_objects_dna` requires the configuration to be parsed with factory=True
Parameters
----------
dnaspec : st... | 625941e856ac1b37e6264655 |
def _build_command(self, application): <NEW_LINE> <INDENT> if self._connection['spark_home']: <NEW_LINE> <INDENT> connection_cmd = [os.path.join(self._connection['spark_home'], 'bin', self._connection['spark_binary'])] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> connection_cmd = [self._connection['spark_binary']] <NE... | Construct the spark-submit command to execute.
:param application: command to append to the spark-submit command
:type application: str
:return: full command to be executed | 625941e86fb2d068a760f533 |
def test_02_search_and_soup(self): <NEW_LINE> <INDENT> nsoups = self.nsearch.by_keyword(self.keyword).to_soup_list() <NEW_LINE> for nsoup in nsoups: <NEW_LINE> <INDENT> if nsoup.contents() is None: <NEW_LINE> <INDENT> self.fail('內文不可為 None') | 測試自由時報搜尋+分解 | 625941e8462c4b4f79d1db5e |
def get_queryset(self): <NEW_LINE> <INDENT> return Question.objects.order_by('-pub_date')[:5] | Return the last five publushed question | 625941e8d6c5a102081444dd |
def update_vhost(self, vhost, target): <NEW_LINE> <INDENT> self.redis_connection.delete('frontend:' + vhost) <NEW_LINE> self.redis_connection.rpush('frontend:' + vhost, vhost) <NEW_LINE> self.redis_connection.rpush('frontend:' + vhost, target) <NEW_LINE> keys = self.redis_connection.keys('*') | Updates the reverse proxy configuration vhost to backend:port in redis. | 625941e8925a0f43d254a30a |
def curry_quadratic(A, B, C): <NEW_LINE> <INDENT> return lambda x: quadratic(x, A=A, B=B, C=C) | "curry" the quadratic function to "lock in" particular arguments | 625941e860cbc95b062c69d2 |
def mean_rcc(img, roi=None): <NEW_LINE> <INDENT> red, green, blue = util.get_image_bands(img, roi=roi) <NEW_LINE> red = np.ma.average(red) <NEW_LINE> green = np.ma.average(green) <NEW_LINE> blue = np.ma.average(blue) <NEW_LINE> gcc = red / (red + green + blue) <NEW_LINE> return gcc | Calculates mean gcc from an image represented by a nummpy array
Assumes array structured as [rows,cols,bands] where the first
three bands are RGB.
Mean Rcc = mean(red) / (mean(green)+mean(red)+mean(blue))
Parameters:
img - a PIL image object or numpy array of a PhenoCam image.
roi - (optional) a PIL image or n... | 625941e866673b3332b92520 |
def pathSum(self, nums): <NEW_LINE> <INDENT> arr = [-1] * 32 <NEW_LINE> for i in nums : <NEW_LINE> <INDENT> v = i % 10 <NEW_LINE> i = i / 10 <NEW_LINE> p = i % 10 <NEW_LINE> l = i / 10 <NEW_LINE> pos = 2 ** (l - 1) + p - 2 <NEW_LINE> arr[pos] = v <NEW_LINE> <DEDENT> Q = [[0, 0]] <NEW_LINE> s = 0 <NEW_LINE> while(Q) : <... | :type nums: List[int]
:rtype: int | 625941e80a50d4780f667325 |
def check_url(url: str): <NEW_LINE> <INDENT> if not urlparse(url).scheme: <NEW_LINE> <INDENT> return 'http://' + url <NEW_LINE> <DEDENT> return url | Check whether or not URL have a scheme
:url: URL that is to be checked | 625941e8f548e778e58cda0e |
def _make_uri(self, resource): <NEW_LINE> <INDENT> return '/'.join([self.base_uri, self.version, resource]) | Construct the URL for a resource based on the API class's parameters | 625941e8a219f33f34628df2 |
def zero_blocks(self, f): <NEW_LINE> <INDENT> f = Polynomial(f) <NEW_LINE> variables = f.vars_as_monomial() <NEW_LINE> space = variables.divisors() <NEW_LINE> variables = list(variables.variables()) <NEW_LINE> zeros = f.zeros_in(space) <NEW_LINE> rest = zeros <NEW_LINE> res = list() <NEW_LINE> def choose_old(s): <NEW_L... | divides the zero set of f into blocks
>>> from brial import *
>>> r = declare_ring(["x", "y", "z"], dict())
>>> e = CNFEncoder(r)
>>> e.zero_blocks(r.variable(0)*r.variable(1)*r.variable(2))
[{y: 0}, {z: 0}, {x: 0}] | 625941e8e5267d203edce126 |
def evaluate(self, batch, store=True): <NEW_LINE> <INDENT> if not isinstance(batch, Batch): <NEW_LINE> <INDENT> raise TypeError("Expecting the given 'batch' to be an instance of `Batch`, instead got: " "{}".format(type(batch))) <NEW_LINE> <DEDENT> output = self._evaluate(batch) <NEW_LINE> if store: <NEW_LINE> <INDENT> ... | Compute/evaluate the target on the given batch and insert the result in the given batch.
Args:
batch (Batch): batch containing the transitions / trajectories.
store (bool): If True, it will save the evaluation of the target in the given batch.
Returns:
torch.Tensor: evaluated targets. | 625941e8b57a9660fec33d19 |
def test_helloworld_logs_last_logins(self): <NEW_LINE> <INDENT> user = User.objects.create_user(username='bob', password='bob', email='bob@test.com') <NEW_LINE> UserVisit.objects.create(user=user, visits=1) <NEW_LINE> self.client.login(username='bob', password='bob') <NEW_LINE> response = self.client.get('/helloworld/'... | When we visit /helloworld/ as a logged-in user, then the system logs a UserVisit for us | 625941e8bd1bec0571d90abe |
def __init__(self, strategy): <NEW_LINE> <INDENT> self.strategy = strategy | Initialize. | 625941e860cbc95b062c69d3 |
def normalize(self,arr): <NEW_LINE> <INDENT> arr = arr/(arr.max()/255.0) <NEW_LINE> return arr | normalize the pixel intensity | 625941e86fb2d068a760f534 |
def set_alt(self, i, alt, break_alt=None, change_time=True): <NEW_LINE> <INDENT> if i < 1 or i > self.rally_count(): <NEW_LINE> <INDENT> print("Inavlid rally point number %u" % i) <NEW_LINE> return <NEW_LINE> <DEDENT> self.rally_points[i-1].alt = int(alt) <NEW_LINE> if (break_alt != None): <NEW_LINE> <INDENT> self.rall... | set rally point altitude(s) | 625941e8f548e778e58cda0f |
def get_account_info(env, app, swift_source=None): <NEW_LINE> <INDENT> (version, account, _junk, _junk) = split_path(env['PATH_INFO'], 2, 4, True) <NEW_LINE> info = get_info(app, env, account, ret_not_found=True, swift_source=swift_source) <NEW_LINE> if not info: <NEW_LINE> <INDENT> info = headers_to_account_inf... | Get the info structure for an account, based on env and app.
This is useful to middlewares.
Note: This call bypasses auth. Success does not imply that the
request has authorization to the container. | 625941e8d164cc61757831df |
def process_regional_coverage(country): <NEW_LINE> <INDENT> level = country['regional_level'] <NEW_LINE> iso3 = country['iso3'] <NEW_LINE> gid_level = 'GID_{}'.format(level) <NEW_LINE> filename = 'regions_{}_{}.shp'.format(level, iso3) <NEW_LINE> folder = os.path.join(DATA_INTERMEDIATE, iso3, 'regions') <NEW_LINE> path... | This functions estimates the area covered by each cellular
technology.
Parameters
----------
country : dict
Contains specific country parameters.
Returns
-------
output : dict
Results for cellular coverage by each technology for
each region. | 625941e8099cdd3c635f10e8 |
def prompt(message): <NEW_LINE> <INDENT> return _ask_until_valid( ask= lambda: _input(message), validate= lambda text: not text ) | Prompts the user to input some text | 625941e850485f2cf553d22b |
def SetTransient(self, mode, A, A_time_s, B, B_time_s, operation="continuous"): <NEW_LINE> <INDENT> if mode.lower() not in self.modes: <NEW_LINE> <INDENT> raise Exception("Unknown mode") <NEW_LINE> <DEDENT> opcodes = {"cc":0x32, "cv":0x34, "cw":0x36, "cr":0x38} <NEW_LINE> if mode.lower() == "cc": <NEW_LINE> <INDENT> co... | Sets up the transient operation mode. mode is one of
"CC", "CV", "CW", or "CR". | 625941e88a43f66fc4b544ef |
def CalcBestMove(board_node): <NEW_LINE> <INDENT> if board_node.state == None: <NEW_LINE> <INDENT> for child in board_node.children: <NEW_LINE> <INDENT> child.minmax, child.moves_to_state = CalcBestMove(child) <NEW_LINE> <DEDENT> board_node.children = sorted(board_node.children, key = lambda x: x.minmax) <NEW_LINE> if ... | updates this board_node with correct values for state, moves_to_state, and best_move
(This is the engine.) | 625941e857b8e32f5248392d |
def make_new_module(name: str, module_manager: 'ReferenceDict', compiler: 'ErrorHandler' = None): <NEW_LINE> <INDENT> env = ReferenceDict(default.default.copy(), module_manager=module_manager) <NEW_LINE> env.update( __name__=name, OperatorPriority=op_priority, __compiler__=compiler) <NEW_LINE> module_manager[name] = en... | make a new module
| 625941e863b5f9789fde7575 |
def make_guess(self): <NEW_LINE> <INDENT> raise NotImplemented() | :return: guess code | 625941e82c8b7c6e89b35c4c |
def test_three_users(self): <NEW_LINE> <INDENT> A = User(); B = User(); C = User() <NEW_LINE> B.add_coach(A) <NEW_LINE> infected = total_infection(A) <NEW_LINE> self.assertEqual(set([A, B]), infected) <NEW_LINE> infected = total_infection(C) <NEW_LINE> self.assertEqual(set([C]), infected) <NEW_LINE> C.add_coach(B) <NEW... | Total infection of three users behaves well with different limit requests | 625941e844b2445a33932522 |
def headers(self, collection): <NEW_LINE> <INDENT> HTTPResponse.headers(self, collection) <NEW_LINE> collection.add('connection', 'upgrade') <NEW_LINE> collection.set('upgrade', ', '.join(self.param['tokens'])) | Modify response headers | 625941e88e7ae83300e4b45d |
def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): <NEW_LINE> <INDENT> if headers is None: <NEW_LINE> <INDENT> headers = {} <NEW_LINE> <DEDENT> if method == 'PATCH': <NEW_LINE> <INDENT> if 'oauth_token' in headers.get('authorization', ''): <NE... | Modify the request headers to add the user-agent. | 625941e831939e2706e4d2f3 |
def dataconverter(datarange): <NEW_LINE> <INDENT> deccords = [] <NEW_LINE> distance = [] <NEW_LINE> lats = [] <NEW_LINE> lons = [] <NEW_LINE> uvelocs = [] <NEW_LINE> vvelocs = [] <NEW_LINE> maxveloc = 0 <NEW_LINE> for datanumber in datarange: <NEW_LINE> <INDENT> if datanumber == 40: <NEW_LINE> <INDENT> continue <NEW_LI... | Converts data from datareader into usable data for contourplot
Args: datarange: the indices from the data files wich data
is to be extracted | 625941e81d351010ab855faa |
def valores(a=-0.5, b=0.5): <NEW_LINE> <INDENT> x = np.arange(a, b, 0.02) <NEW_LINE> y = (np.tanh(3*x*2*pi) - np.cos(3*x*2*pi)/np.sin(3*x*2*pi)) / (((2*x)/5) - 3*x) <NEW_LINE> return {'x': x, 'y': y, 'puntos': b - a + 1} | Recibe el intervalo a evaluar, devuelve un diccionario
con los valores en arrays y el delta del rango. | 625941e8b57a9660fec33d1a |
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <... | Returns the model properties as a dict | 625941e88da39b475bd65409 |
def unicode_getcwd(): <NEW_LINE> <INDENT> return os.getcwdu() | :func:`os.getcwd` unicode wrapper
Returns:
str: current directory (PY2: type unicode) | 625941e829b78933be1e5b36 |
def __init__(self, data: dict, client_id: str = None): <NEW_LINE> <INDENT> self.avatar_url = data["avatar_url"] <NEW_LINE> self.city = data["city"] <NEW_LINE> self.country_code = data["country_code"] <NEW_LINE> with suppress(KeyError): <NEW_LINE> <INDENT> self.comments_count = data["comments_count"] <NEW_LINE> self.cre... | :param data: The json dict from the response
:param client_id: The ID of the client | 625941e84c3428357757c7b5 |
def plot_pdf(self, points, name="x", xlabel="x", bins=12, normed=True, replot=False, overplot=False, clearwindow=True): <NEW_LINE> <INDENT> if not sherpa.utils.bool_cast(replot): <NEW_LINE> <INDENT> self._pdfplot.prepare(points, bins, normed, xlabel, name) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> sherpa.plot.begin(... | Plot the probability density function of an array of values.
Create and plot the probability density function (PDF) of
the input array.
Parameters
----------
points : array
The values used to create the probability density function.
name : str, optional
The label to use as part of the plot title.
xlabel : str, ... | 625941e821a7993f00bc8187 |
def permuteUnique(self, nums): <NEW_LINE> <INDENT> if nums is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if nums is []: <NEW_LINE> <INDENT> return [[]] <NEW_LINE> <DEDENT> results = [] <NEW_LINE> permutation = [] <NEW_LINE> nums = sorted(nums) <NEW_LINE> visited = [0 for i in range(len(nums))] <NEW_LINE> s... | :type nums: List[int]
:rtype: List[List[int]] | 625941e863d6d428bbe44980 |
def get_data(self, certain_file): <NEW_LINE> <INDENT> if self.file_path == certain_file: <NEW_LINE> <INDENT> return pd.read_excel(certain_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return pd.read_excel(certain_file) | Read all data from excel.
:param certain_file: file path
:return: <class 'pandas.core.frame.DataFrame'> | 625941e8009cb60464c6383d |
def load_dotenvs(): <NEW_LINE> <INDENT> if not os.getenv('DOTENVS_LOADED'): <NEW_LINE> <INDENT> envs = ['.env', '.flaskenv'] <NEW_LINE> for env in envs: <NEW_LINE> <INDENT> path = os.path.join(os.getcwd(), env) <NEW_LINE> if os.path.isfile(path): <NEW_LINE> <INDENT> dotenvs(path) <NEW_LINE> <DEDENT> <DEDENT> os.environ... | Load dotenvs
Loads .env and .flaskenv files from project root directory.
:return: | 625941e85166f23b2e1a55e8 |
@pytest.fixture(scope="function") <NEW_LINE> def functional_transports(): <NEW_LINE> <INDENT> run = os.environ.get("PYPSRP_RUN_INTEGRATION", None) <NEW_LINE> if run is None: <NEW_LINE> <INDENT> pytest.skip("Skipping CI functional tests because PYPSRP_RUN_INTEGRATION has not been set") <NEW_LINE> <DEDENT> username = os.... | This runs the same test over multiple auth providers and on SSL/Without.
It requires a specific host configuration of the target endpoint and for
this config to be defined by the following environment varaibles;
PYPSRP_RUN_INTEGRATION: if set to anything then these tests will run
PYPSRP_SERVER: The hostname or IP of t... | 625941e8baa26c4b54cb15aa |
def force_out(self): <NEW_LINE> <INDENT> if self.state() != NodeState.INVALID: <NEW_LINE> <INDENT> raise Exception("Not allowed") <NEW_LINE> <DEDENT> print('Warning! Overwriting changes in %s' % self.file.path) <NEW_LINE> if(confirm('Proceed?')): <NEW_LINE> <INDENT> os.remove(self.file.path) <NEW_LINE> self.merge() | Safety checks | 625941e856b00c62f0f14aec |
def __init__(self, direction=DirectionCommandMixin.DEFAULT_DIRECTION, steps_per_sec=SpeedCommandMixin.MAX_VALUE): <NEW_LINE> <INDENT> DirectionCommandMixin.__init__(self, direction) <NEW_LINE> SpeedCommandMixin.__init__(self, steps_per_sec) | :param int direction: the move direction (default: DirectionCommandMixin.DEFAULT_DIRECTION)
:param int steps_per_sec: the move speed (default: MAX_SPEED) | 625941e8b545ff76a89142a5 |
def __eq__(self, other): <NEW_LINE> <INDENT> if other.__class__ is not self.__class__: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if set(self.keys()) != set(other.keys()): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for name, sheet in self.items(): <NEW_LINE> <INDENT> if not sheet == other[name]: <NE... | Compare two workbooks
Args:
other (:obj:`Workbook`): other workbook
Returns:
:obj:`bool`: true if workbooks are semantically equal | 625941e89c8ee82313fbbc06 |
def copy(self): <NEW_LINE> <INDENT> newArr = ArrayList() <NEW_LINE> for i in range(0, self.len): <NEW_LINE> <INDENT> newArr.append(self.data[i]) <NEW_LINE> <DEDENT> return newArr | Returns a new ArrayList instance (with a separate data store), that
contains the same values as this list. | 625941e87d847024c06be74f |
def to_dict(self): <NEW_LINE> <INDENT> return {'name': self.name, 'version': self.version, 'last_updated': self.last_updated.isoformat()} | Return this object as a dict. Helper function for serialization | 625941e89f2886367277ad19 |
def get_headers(self): <NEW_LINE> <INDENT> headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'accept-encoding': 'gzip, deflate, sdch, br', 'accept-language': 'en-GB,en;q=0.8,en-US;q=0.6,ml;q=0.4', 'cache-control': 'max-age=0', 'upgrade-insecure-requests': '1', 'user-agen... | Retreive headers as params for GET request. | 625941e8d99f1b3c44c67a16 |
@contextmanager <NEW_LINE> def measure(metric, measure_func=time.time, reverse=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> before = measure_func() <NEW_LINE> yield _module_client <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> if reverse: <NEW_LINE> <INDENT> value = before - measure_func() <NEW_LINE> <DEDENT>... | Function to allow usage of graphiteudp as both a context manager
and a decorator. Takes an optional measure_func argument which is
called before and after to obtain the `value` thats passed to
graphiteudp.send. Defaults to time.
Args:
metric: The metric path to use.
measure_func: The function thats called on ent... | 625941e88c3a873295158850 |
def is_preprocessor(lines, lineno): <NEW_LINE> <INDENT> regex = r'\#\s*((include)|(define)).*' <NEW_LINE> if re.search(regex, lines[lineno]): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | For this line to be a preprocessor, it has to follow the pattern:
>>> #include something
>>> #define something
or some other preprocessor | 625941e8293b9510aa2c3721 |
def get_change(amount, coins=eur_coins): <NEW_LINE> <INDENT> change = [] <NEW_LINE> for denomination in sorted(coins.keys(), reverse=True): <NEW_LINE> <INDENT> while denomination <= amount and coins[denomination] > 0: <NEW_LINE> <INDENT> amount -= denomination <NEW_LINE> coins[denomination] -= 1 <NEW_LINE> change.appen... | Takes the payment amount and returns the change
`amount` the amount of money that we need to provide change for
`coins` is the set of coins that we need to get change for (i.e. the set
of available coins)
Returns a list of coin values | 625941e892d797404e30461c |
@lru_cache() <NEW_LINE> def extract_departments_date_ranges(html: str): <NEW_LINE> <INDENT> date_ranges = defaultdict(lambda: dict(autumn=list(), spring=list())) <NEW_LINE> for match in re.finditer(DEPARTMENT_PATTERN, html): <NEW_LINE> <INDENT> department_id, season, first, second = match.groups() <NEW_LINE> season = '... | Extract information about date ranges of the departments' schedules
from the given html page.
Return a dict object of the following structure: ::
{
'<department_id>': {
'autumn': [DateRange(<first>, <second>), ...],
'spring': [DateRange(<first>, <second>), ...]
},
...
}
The lists of DateR... | 625941e8283ffb24f3c55d8c |
@task <NEW_LINE> def pydocstyle(context, netbox_ver=NETBOX_VER, python_ver=PYTHON_VER): <NEW_LINE> <INDENT> docker = f"docker-compose -f {COMPOSE_FILE} -p {BUILD_NAME} run --rm netbox" <NEW_LINE> context.run( f"{docker} sh -c \"cd /source && find . -name '*.py' -not -path '*/migrations/*' | xargs pydocstyle\"", env={"N... | Run pydocstyle to validate docstring formatting adheres to NTC defined standards.
Args:
context (obj): Used to run specific commands
netbox_ver (str): NetBox version to use to build the container
python_ver (str): Will use the Python version docker image to build from | 625941e8ff9c53063f47c681 |
def open_config_file(config_file): <NEW_LINE> <INDENT> dirname = os.path.dirname(config_file) <NEW_LINE> if not os.path.exists(dirname): <NEW_LINE> <INDENT> os.makedirs(dirname) <NEW_LINE> <DEDENT> if not os.path.exists(config_file): <NEW_LINE> <INDENT> open(config_file, "w").close() <NEW_LINE> <DEDENT> if not os.acces... | Opens config file and makes additional checks
Creates config file if it doesn't exist and makes sure it is readable and
writable by user. That prevents surprise when user is not able to save
configuration when exiting the app. | 625941e8d6c5a102081444de |
def decode_eeprom(self, raw_data, width, offset=0): <NEW_LINE> <INDENT> top_slice = raw_data[offset:offset+width] <NEW_LINE> unpacked = struct.unpack("d", top_slice) <NEW_LINE> log.debug("Unpacked str: %s ", unpacked) <NEW_LINE> return str(unpacked[0]) | Reorder, pad and decode the eeprom data to produce a string
representation of the value stored in the device memory. | 625941e8e8904600ed9f23c4 |
def GetEmojiID(record): <NEW_LINE> <INDENT> if "uni" in record and "data" in record: <NEW_LINE> <INDENT> data = record["data"] <NEW_LINE> for item in data: <NEW_LINE> <INDENT> match = _emoji_alias_re.match(item) <NEW_LINE> if match: <NEW_LINE> <INDENT> return match.group(1) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return ... | Gets the Emoji ID from a CHAR_ENTRY record.
During development of Unicode 6.0/ISO 10646 AMD8,
each Emoji symbol in the NamesList temporarily has an additional alias line
with its Emoji symbol ID.
Returns:
The Emoji symbol ID as a 3-hex-digit string, if present.
Otherwise None. | 625941e8956e5f7376d712fc |
@blueprint.route('/signup', methods=['GET','POST']) <NEW_LINE> def signup(): <NEW_LINE> <INDENT> if session.get('logged_in'): <NEW_LINE> <INDENT> return render_template('login.html') <NEW_LINE> <DEDENT> if request.method == 'POST': <NEW_LINE> <INDENT> if request.form['signup']: <NEW_LINE> <INDENT> firstname = request.f... | Signup a new user | 625941e8c432627299f050d9 |
def make_temp_file(testcase, name=None): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = make_string('file') <NEW_LINE> <DEDENT> directory = mkdtemp() <NEW_LINE> testcase.addCleanup(rmtree, directory, ignore_errors=False) <NEW_LINE> return os.path.join(directory, name) | Return a path for a temporary file.
:param testcase: The TestCase containing your test. It will be made to
clean up the file once done.
:param name: Optional name for the file. If omitted, I'll make one up. | 625941e8d8ef3951e32439cd |
def before_start(self): <NEW_LINE> <INDENT> pass | Prepares the test for starting. | 625941e8e1aae11d1e74a14c |
def test_build_season(self): <NEW_LINE> <INDENT> s = tracker.Season() <NEW_LINE> s.build_season(self.response) <NEW_LINE> self.assertEqual(s.episodes_this_season, 10) | Test that the construction of a season works as expected | 625941e87d43ff24873a3133 |
def traverse(self): <NEW_LINE> <INDENT> cur_node = self <NEW_LINE> while cur_node is not None: <NEW_LINE> <INDENT> print(cur_node._val) <NEW_LINE> cur_node = cur_node._next | Traverse the node list. | 625941e8ec188e330fd5ac25 |
def distract(self): <NEW_LINE> <INDENT> self.focused = False <NEW_LINE> self.repaint() | When the user stops to focus on this widget | 625941e8656771135c3ebd04 |
def total(self, total) -> 'MonthlyIncome': <NEW_LINE> <INDENT> self.remains = total <NEW_LINE> return self | Set the total after which the payment is stopped | 625941e87d847024c06be750 |
def setUp(self): <NEW_LINE> <INDENT> self.loop = asyncio.new_event_loop() <NEW_LINE> asyncio.set_event_loop(None) <NEW_LINE> self.options = KytosConfig().options['daemon'] <NEW_LINE> self.controller = Controller(self.options, loop=self.loop) <NEW_LINE> self.controller.log = Mock() <NEW_LINE> self.switch = self.create_s... | Instantiate a controller. | 625941e84527f215b584c8e2 |
def argument(self, *args, **kwargs): <NEW_LINE> <INDENT> arg = Argument(*args, **kwargs) <NEW_LINE> def decorator(f): <NEW_LINE> <INDENT> self._create_command(f) <NEW_LINE> f.__climb__.add_argument(arg) <NEW_LINE> return f <NEW_LINE> <DEDENT> return decorator | Specify an argument for a command.
Parameters
----------
Check climb.argument.Argument constructor. | 625941e84a966d76dd5514a4 |
def se_resnet50(**kwargs): <NEW_LINE> <INDENT> model = SEResNet(Bottleneck, [3, 4, 6, 3], **kwargs) <NEW_LINE> return model | Constructs a SE-ResNet-50 model.
Args:
num_classes = 1000 (default) | 625941e8a05bb46b383eccad |
def dumps(self) -> Any: <NEW_LINE> <INDENT> pass | Dumps all the information of attrs into a dict. | 625941e857b8e32f5248392e |
def __bytes__(self): <NEW_LINE> <INDENT> return bytes((self._red, self._green, self._blue)) | Convert to bytes
:return: Byte string
:rtype: bytearray | 625941e856ac1b37e6264656 |
def get_hw_version(self): <NEW_LINE> <INDENT> return float(self._get_property_single('device.hw_version')) | :return: Hardware version of connected Moku:Lab | 625941e8fb3f5b602dac3b28 |
def rpmlist(environ, type, buildrootID=None, imageID=None, start=None, order='nvr'): <NEW_LINE> <INDENT> values = _initValues(environ, 'RPM List', 'hosts') <NEW_LINE> server = _getServer(environ) <NEW_LINE> if buildrootID is not None: <NEW_LINE> <INDENT> buildrootID = int(buildrootID) <NEW_LINE> buildroot = server.getB... | rpmlist requires a buildrootID OR an imageID to be passed in. From one
of these values it will paginate a list of rpms included in the
corresponding object. (buildroot or image) | 625941e8046cf37aa974d1d3 |
def __getitem__(self, location): <NEW_LINE> <INDENT> bytestringlocation = self._logical2physical(location) <NEW_LINE> bytestringrepr = self._physical2bytes(bytestringlocation, self._content) <NEW_LINE> value = self._decode(bytestringrepr) <NEW_LINE> return value | :return A sub-sequence that @location refers to. | 625941e82ae34c7f2600d5c0 |
def add_plate_border(img, box_info): <NEW_LINE> <INDENT> if random.randint(0,1): <NEW_LINE> <INDENT> padding = random.randint(3,20) <NEW_LINE> shape = list(img.shape) <NEW_LINE> shape[1] += 2*padding <NEW_LINE> img_new = np.zeros(shape, img.dtype) <NEW_LINE> img_new[:, padding:padding+img.shape[1]] = img <NEW_LINE> for... | add horizontal padding to simulate plates with big space | 625941e81b99ca400220af43 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.