code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def largestValues(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> res = [] <NEW_LINE> self.level_visit([root],res) <NEW_LINE> return res | :type root: TreeNode
:rtype: List[int] | 625941f16aa9bd52df037365 |
def m_calendar1OnCalendar( self, event ): <NEW_LINE> <INDENT> event.Skip() | カレンダーで日付をダブルクリックした | 625941f18a349b6b435e8730 |
def create_directory(config) : <NEW_LINE> <INDENT> now = datetime.datetime.now() <NEW_LINE> year = now.year <NEW_LINE> month = now.month <NEW_LINE> day = now.day <NEW_LINE> if config is not None : <NEW_LINE> <INDENT> base_dir = config.basePath <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> base_dir = '.' <NEW_LINE> <DE... | :param config: Config() object
:return: | 625941f1462c4b4f79d1dc8d |
def get_timestamp(self) -> Optional[int]: <NEW_LINE> <INDENT> flags = decode_flags(VmbFrameFlags, self._frame.receiveFlags) <NEW_LINE> if VmbFrameFlags.Timestamp not in flags: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return self._frame.timestamp | Get Frame timestamp.
Returns:
Timestamp if provided by the camera.
None if timestamp is not provided by the camera. | 625941f17d43ff24873a3263 |
def get_poi(self, **kwargs): <NEW_LINE> <INDENT> params = { 'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'tipos': util.ints_to_string(kwargs.get('types')), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs.get('lang')) } <NEW_LINE> result = self.make_request('geo... | Obtain a list of POI in the given radius.
Args:
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal degrees.
types (list[int] | int): POI IDs (or empty list to get all).
radius (int): Radius (in meters) of the search.
lang (str): Language code (*es* or *en*).
R... | 625941f14f6381625f114ff8 |
def image_loader(image_name): <NEW_LINE> <INDENT> image = Image.open(image_name) <NEW_LINE> image = Variable(loader(image)) <NEW_LINE> image = image.unsqueeze(0) <NEW_LINE> return image | convert an image to a variable tensor | 625941f13346ee7daa2b332f |
def isPaused(self): <NEW_LINE> <INDENT> if not self.proxy: <NEW_LINE> <INDENT> self.proxy = ALProxy("ALVisionRecognition") <NEW_LINE> <DEDENT> return self.proxy.isPaused() | Gets extractor pause status
:returns bool: True if the extractor is paused, False if not | 625941f1e1aae11d1e74a27b |
@receiver(SignalHandler.course_published) <NEW_LINE> @helpers.disable_if_certs_feature_off <NEW_LINE> def enable_self_generated_certs(sender, course_key, **kwargs): <NEW_LINE> <INDENT> course = CourseOverview.get_from_id(course_key) <NEW_LINE> toggle_self_generated_certs.delay(unicode(course_key), course.self_paced) | Enable/disable the self-generated certificates according to course-pacing. | 625941f1f7d966606f6aa5c9 |
def page(page=1, per_page=20, sort=None): <NEW_LINE> <INDENT> def des(s): return "%s DESC" % s[1:] if s[0] == '-' else s <NEW_LINE> if sort: <NEW_LINE> <INDENT> order = ' ORDER BY %s' % ', '.join(des(s) for s in sort) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> order = '' <NEW_LINE> <DEDENT> if per_page: <NEW_LINE> <... | Translate pagination parameters to SQL. | 625941f1bd1bec0571d90bed |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkScalarToRGBColormapImageFilterPython.itkScalarToRGBColormapImageFilterID3IRGBAUS3_GetPointer(self) | GetPointer(self) -> itkScalarToRGBColormapImageFilterID3IRGBAUS3 | 625941f1b5575c28eb68e5c4 |
def administer (request): <NEW_LINE> <INDENT> pass | Provides administaration functions | 625941f110dbd63aa1bd3160 |
def invert(requestContext, seriesList): <NEW_LINE> <INDENT> for series in seriesList: <NEW_LINE> <INDENT> series.name = "invert(%s)" % (series.name) <NEW_LINE> for i,value in enumerate(series): <NEW_LINE> <INDENT> series[i] = safePow(value, -1) <NEW_LINE> <DEDENT> <DEDENT> return seriesList | Takes one metric or a wildcard seriesList, and inverts each datapoint (i.e. 1/x).
Example:
.. code-block:: none
&target=invert(Server.instance01.threads.busy) | 625941f1293b9510aa2c384e |
def calculate_checksum(self, **kwargs): <NEW_LINE> <INDENT> checksum = ESPLoader.ESP_CHECKSUM_MAGIC <NEW_LINE> for seg in self.segments: <NEW_LINE> <INDENT> if seg.include_in_checksum or kwargs["checksum_irom"]: <NEW_LINE> <INDENT> checksum = ESPLoader.checksum(seg.data, checksum) <NEW_LINE> <DEDENT> <DEDENT> return ch... | Calculate checksum of loaded image, based on segments in
segment array. | 625941f130c21e258bdfaa62 |
def _iter_signals_from_spheres(seeds, niimg, radius, allow_overlap, mask_img=None): <NEW_LINE> <INDENT> X, A = _apply_mask_and_get_affinity(seeds, niimg, radius, allow_overlap, mask_img=mask_img) <NEW_LINE> for i, row in enumerate(A.rows): <NEW_LINE> <INDENT> yield X[:, row] | Utility function to iterate over spheres.
Parameters
----------
seeds: List of triplets of coordinates in native space
Seed definitions. List of coordinates of the seeds in the same space
as the images (typically MNI or TAL).
imgs: 3D/4D Niimg-like object
See http://nilearn.github.io/manipulating_images/inp... | 625941f1187af65679ca56de |
def MySelectElectrodePairFunction(definedElectrodePairs, **flags): <NEW_LINE> <INDENT> selectedElectrodePairs = [] <NEW_LINE> for ePair in definedElectrodePairs.values(): <NEW_LINE> <INDENT> if ePair['ePair'] % 2 == 0: <NEW_LINE> <INDENT> selectedElectrodePairs.append(ePair) <NEW_LINE> <DEDENT> <DEDENT> selectedElectro... | user defined selection and sorting of previously defined electrode pairs
| 625941f1adb09d7d5db6cd4a |
def db_to_form_schema(data): <NEW_LINE> <INDENT> return {} | Returns the schema for mapping package data from the database into a
format suitable for the form (optional) | 625941f1e5267d203edce253 |
def _ensure_sparse_format(spmatrix, accept_sparse, dtype, copy, force_all_finite, accept_large_sparse): <NEW_LINE> <INDENT> if dtype is None: <NEW_LINE> <INDENT> dtype = spmatrix.dtype <NEW_LINE> <DEDENT> changed_format = False <NEW_LINE> if isinstance(accept_sparse, str): <NEW_LINE> <INDENT> accept_sparse = [accept_sp... | Convert a sparse matrix to a given format.
Checks the sparse format of spmatrix and converts if necessary.
Parameters
----------
spmatrix : sparse matrix
Input to validate and convert.
accept_sparse : str, bool or list/tuple of str
String[s] representing allowed sparse matrix formats ('csc',
'csr', 'coo'... | 625941f1aad79263cf391008 |
def create_providers_nis_item_with_http_info(self, providers_nis_item, **kwargs): <NEW_LINE> <INDENT> all_params = ['providers_nis_item'] <NEW_LINE> all_params.append('async') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_t... | create_providers_nis_item # noqa: E501
Create a new NIS provider. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_providers_nis_item_with_http_info(providers_nis_item, async=True)
>>> result = thread.get()
:pa... | 625941f1d268445f265b542d |
def print_goodbye(self): <NEW_LINE> <INDENT> print("Thanks for playing! Come back soon!\n") | This is a farewell print statement | 625941f199cbb53fe67931a3 |
def setup(self): <NEW_LINE> <INDENT> self.shotgun_data = [{'id':1, 'type':'Group'}, {'id':2, 'type':'Project'}] <NEW_LINE> self.session = MockShotgun(schema=[], data=self.shotgun_data) <NEW_LINE> self.translator = HumanUserTranslator(self.session) | Set up the unit test suite.
.. versionadded:: v00_04_00 | 625941f14527f215b584ca10 |
def _save_create(self, doc, force_insert, write_concern): <NEW_LINE> <INDENT> collection = self._get_collection() <NEW_LINE> with set_write_concern(collection, write_concern) as wc_collection: <NEW_LINE> <INDENT> if force_insert: <NEW_LINE> <INDENT> return wc_collection.insert_one(doc).inserted_id <NEW_LINE> <DEDENT> i... | Save a new document.
Helper method, should only be used inside save(). | 625941f1004d5f362079a8ed |
def mettreTresor(c,tresor): <NEW_LINE> <INDENT> res=c['tresor'] <NEW_LINE> c['tresor']=tresor <NEW_LINE> return res | met le trésor passé en paramètre sur la carte et retourne la valeur de l'ancien trésor
paramètres: c une carte
tresor un entier positif
résultat l'entier représentant le trésor qui était sur la carte | 625941f192d797404e30474b |
def test_sample_weight_elm(): <NEW_LINE> <INDENT> X = Xdigits_binary[:50] <NEW_LINE> y = ydigits_binary[:50] <NEW_LINE> elm = ELMClassifier(n_hidden=20) <NEW_LINE> clf = AdaBoostClassifier(n_estimators=3, base_estimator=elm) <NEW_LINE> clf.fit(X, y) <NEW_LINE> assert_greater(clf.score(X, y), 0.9) | Smoke test - AdaBoostClassifier should work with ELMClassifer. | 625941f1fbf16365ca6f678f |
def meth2(arg1): <NEW_LINE> <INDENT> pass | Method 2 | 625941f11f5feb6acb0c5107 |
def get_profile_compose_file(self, profile: dict): <NEW_LINE> <INDENT> content = self._compile(profile) <NEW_LINE> fh = tempfile.TemporaryFile(mode="w+") <NEW_LINE> try: <NEW_LINE> <INDENT> rendered = render(content, env=self.workflow.environment.data) <NEW_LINE> <DEDENT> except EnvError as exc: <NEW_LINE> <INDENT> if ... | Processes the profile to generate the compose file | 625941f17d847024c06be87f |
def compute(diction): <NEW_LINE> <INDENT> numerator = sum([i[0]*i[1] for i in diction.values()]) <NEW_LINE> denominator1 = math.sqrt(sum([i[0]**2 for i in diction.values()])) <NEW_LINE> denominator2 = math.sqrt(sum([i[1]**2 for i in diction.values()])) <NEW_LINE> return numerator/(denominator1*denominator2) | compute the diction. | 625941f144b2445a33932650 |
def viewContextMenuActions(self): <NEW_LINE> <INDENT> return [] | Important note:
In order to use view menus in scripted plugins, it needs to be registered differently,
so that the Python API can be fully built by the time this function is called.
The following changes are necessary:
1. Remove or comment out the following line from constructor
AbstractScriptedSubjectHierarchyPl... | 625941f11f5feb6acb0c5108 |
def sim_perf(dens0 = 6e19, Rmid=1.65, R0=2.22, Rant=2.32, m=13, n=4, npts=100): <NEW_LINE> <INDENT> r = np.linspace(Rmid, Rant, npts) <NEW_LINE> dens = np.zeros_like(r) <NEW_LINE> dens = dens0*( 1.0 - ((r-Rmid)/(R0-Rmid))**m)**n <NEW_LINE> rmask = r>R0 <NEW_LINE> dens[rmask] = 0.0 <NEW_LINE> return r, dens | Makes a LFS density profile
Parameters
-----------
dens0 : Density at Rmid point
Rmid : Mid-point of the plasma column (core):
R0 : Last plasma point
Rant : Radial location of antennas
m : Geometric parameter for density profile
n : Geometric parameter for density profile
npts : Number of points for the profile (goin... | 625941f1460517430c394733 |
def set_pass(client, user, passwd, check): <NEW_LINE> <INDENT> if not check: <NEW_LINE> <INDENT> client.set_user_password(user, passwd) | Set an existing users password | 625941f1851cf427c661aac8 |
def contains_key(self, location): <NEW_LINE> <INDENT> return dictfs.exists(self.data, location) | Check if the current object instance has data stored at location.
| 625941f1ec188e330fd5ad51 |
def forward(self, x, hidden): <NEW_LINE> <INDENT> batch_size = x.size(0) <NEW_LINE> embeds = self.embedding(x) <NEW_LINE> lstm_out, hidden = self.lstm(embeds, hidden) <NEW_LINE> lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim) <NEW_LINE> out = self.dropout(lstm_out) <NEW_LINE> out = self.fc(out) <NEW_LINE> ou... | Perform a forward pass of our model on some input and hidden state. | 625941f1596a89723608a077 |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, HTTPForbiddenError): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941f1507cdc57c63072a8 |
def print_success_or_failure_message(expected, actual, flush_time=0.2): <NEW_LINE> <INDENT> if expected == actual: <NEW_LINE> <INDENT> print(" Test passed SUCCESSFULLY!") <NEW_LINE> <DEDENT> elif actual == None: <NEW_LINE> <INDENT> print(' Test FAILED.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> time.sleep(flus... | Prints a message indicating success or failure of the test. | 625941f123e79379d52eeb1a |
def download_overlays(path, download_all=False, fail_at_lookup=False, fail_at_device_detection=False, cleanup=False): <NEW_LINE> <INDENT> logger = get_logger() <NEW_LINE> try: <NEW_LINE> <INDENT> devices = _detect_devices() <NEW_LINE> <DEDENT> except RuntimeError as e: <NEW_LINE> <INDENT> if fail_at_device_detection: <... | Download overlays for detected devices in destination path.
Resolve ``overlay_res.ext`` files from ``overlay_res.ext.link``
json files. Downloaded ``overlay_res.ext`` files are put in a
``overlay_res.ext.d`` directory, with the device name added to their
filename, as ``overlay_res.device_name.ext``.
If the detected d... | 625941f1d486a94d0b98e705 |
@cli.command('save') <NEW_LINE> @click.help_option('-h', '--help') <NEW_LINE> @click.argument( 'bibfile', default=lambda: config.get('default-save-bibfile', section='bibtex'), required=True, type=click.Path()) <NEW_LINE> @click.option('-f', '--force', default=False, is_flag=True) <NEW_LINE> @click.pass_context <NEW_LIN... | Save the documents imported in bibtex format | 625941f1d58c6744b425821c |
def test_03(): <NEW_LINE> <INDENT> input = (' _ _ _ _ _ _ _ _ _ \n' ' _| _| _| _| _| _| _| _| _|\n' ' _| _| _| _| _| _| _| _| _|\n' ' ') <NEW_LINE> expected_output = ('333333333\n') <NEW_LINE> expected_output = expected_output.replace('\n', os.linesep) <NEW_LINE> output = ocr1_adaptor.... | Test of reading 3 | 625941f121bff66bcd684f0b |
def _parseStatusString(self, statusstring): <NEW_LINE> <INDENT> self._status = int(statusstring[3:5], 16) <NEW_LINE> self._alarm = int(statusstring[5:7], 16) <NEW_LINE> self._outs = int(statusstring[9:11], 16) | 0 'U' answer string
1 '0' axis number
2 'n' status inqiry result
3+4 '07' hex value corresponding to status
5+6 '00' hex value corresponding to Alarm
7+8 '40' hex value corresponding to IN
9+10 '90' hex value corresponding to OUT | 625941f107f4c71912b11a44 |
def decode_identity(ts, content): <NEW_LINE> <INDENT> return content | Identity encoding, an encoding that doesn't change the content. | 625941f1d53ae8145f87a823 |
def heatmap(self, s_out, t_membership, max_clusters=20, max_members=10, max_nodes=50, S_label=None): <NEW_LINE> <INDENT> if not self.is_clustered(): <NEW_LINE> <INDENT> util.error_msg('golist_clsutered is not clustered yet!') <NEW_LINE> <DEDENT> s_out, s_ext=os.path.splitext(s_out) <NEW_LINE> S_col=[x for x in t_member... | t_membership is the membership table generated by golists | 625941f1cc40096d61595f0c |
def get_package_version(): <NEW_LINE> <INDENT> base = os.path.abspath(os.path.dirname(__file__)) <NEW_LINE> with open(os.path.join(base, "myext/__init__.py")) as initf: <NEW_LINE> <INDENT> for line in initf: <NEW_LINE> <INDENT> m = version.match(line.strip()) <NEW_LINE> if not m: <NEW_LINE> <INDENT> continue <NEW_LINE>... | returns package version without importing it | 625941f1cc40096d61595f0d |
def grid(self, questionid_data): <NEW_LINE> <INDENT> grid_group = questionid_data.groupby(['Variable ID']) <NEW_LINE> subqlist = {} <NEW_LINE> for name, question in grid_group: <NEW_LINE> <INDENT> subqlist[name] = self.singleselect(name, question) <NEW_LINE> <DEDENT> return subqlist | Analyzes 'grid' type questions. | 625941f1cad5886f8bd27597 |
def get_doc_list(path): <NEW_LINE> <INDENT> doc_list = [] <NEW_LINE> for doc in os.listdir(path): <NEW_LINE> <INDENT> doc_list.append(doc) <NEW_LINE> <DEDENT> return doc_list | Get the generated documentation files as a list
Keyword arguments:
directory -- the path to the directory containing generated doc files | 625941f157b8e32f52483a5e |
def get_input(self): <NEW_LINE> <INDENT> if self.decision is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> input = json.loads( self.decision["events"][0]["workflowExecutionStartedEventAttributes"][ "input" ] ) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> input = None <NE... | From the decision response, which is JSON data form SWF, get the
input data that started the workflow | 625941f1e8904600ed9f24f6 |
def unique_houses(filename): <NEW_LINE> <INDENT> file = open(filename) <NEW_LINE> house_set = set() <NEW_LINE> for line in file: <NEW_LINE> <INDENT> line = line.rstrip() <NEW_LINE> words_list = line.split("|") <NEW_LINE> if words_list[2] == "": <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hous... | TODO: Return a set of student houses.
Iterate over the cohort_data.txt file to look for all of the included house names
and create a set called "houses" that holds those names.
For example:
>>> sorted(unique_houses("cohort_data.txt"))
["Dumbledore's Army", 'Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'] | 625941f150485f2cf553d35b |
def set_headers(self, headers): <NEW_LINE> <INDENT> if isinstance(headers, httplib.HTTPMessage): <NEW_LINE> <INDENT> self._headers = Headers() <NEW_LINE> for header in headers.headers: <NEW_LINE> <INDENT> key, value = header.split(':', 1) <NEW_LINE> self._headers[key.strip()] = value.strip() <NEW_LINE> <DEDENT> <DEDENT... | Sets the headers and also analyzes them in order to get the response
mime type (text/html , application/pdf, etc).
:param headers: The headers dict. | 625941f12c8b7c6e89b35d7b |
def prefix(self, host): <NEW_LINE> <INDENT> if '://' not in host: <NEW_LINE> <INDENT> host = 'https://%s' % host.strip('/') <NEW_LINE> <DEDENT> return '%s/piwebapi/' % host.rstrip('/') | Return the appropriate URL prefix to prepend to requests,
based on the host provided in settings. | 625941f1287bf620b61d401f |
def __init__(self, att_hidden_units, activation='prelu'): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.attention_dense = [Dense(units=unit, activation=PReLU() if activation == 'prelu' else Dice()) for unit in att_hidden_units] <NEW_LINE> self.output_layer = Dense(units=1) | :param att_hidden_units:
:param activation: | 625941f1d7e4931a7ee9e4df |
def get_last_processed_id(connection): <NEW_LINE> <INDENT> query = 'select id from last_processed_id;' <NEW_LINE> res = connection.execute(text(query)).fetchall() <NEW_LINE> if res: <NEW_LINE> <INDENT> first_id = res[-1][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = 'select id from public.raw_data limit 1' <... | If no last id from last_processed_id, return first id from raw_data | 625941f1167d2b6e31219154 |
def matrix_divided(matrix, div): <NEW_LINE> <INDENT> err = "matrix must be a matrix (list of lists) of integers/floats" <NEW_LINE> list_length = [] <NEW_LINE> for i in range(len(matrix)): <NEW_LINE> <INDENT> if not isinstance(matrix[i], list): <NEW_LINE> <INDENT> raise TypeError(err) <NEW_LINE> <DEDENT> list_length.app... | [summary]
Args:
matrix (List): of integers and floats
div (int / float): the number to divide matrix with
Returns:
new list of lists | 625941f123849d37ff7b3649 |
def extract_error_bars(fitspath): <NEW_LINE> <INDENT> der_prop_err = np.load(fitspath + npz_filename_dict['der_prop_errors']) <NEW_LINE> der_prop_file = asc.read(fitspath + filename_dict['bin_derived_prop_rev'], format='fixed_width_two_line') <NEW_LINE> valid_tbl = asc.read(fitspath + filename_dict['bin_valid_rev'], fo... | Purpose:
This function reads in the error bar arrays and reorders the low and high error arrays to plot.
Params:
fitspath --> string of the file path where data files are located.
Returns:
err_dict --> a dictionary containing temperature and metallicity low and high errors. | 625941f17b180e01f3dc4daf |
def check_dynamic_fields(conn, concurrently, dataset_filter, excluded_field_names, fields, name, rebuild_indexes=False, rebuild_view=False): <NEW_LINE> <INDENT> composite_indexes = ( ('lat', 'lon', 'time'), ('time', 'lat', 'lon'), ('sat_path', 'sat_row', 'time') ) <NEW_LINE> all_exclusions = tuple(excluded_field_names)... | Check that we have expected indexes and views for the given fields | 625941f1d6c5a1020814460e |
def joined_read(self, joined, where = None, order = None, **kwargs): <NEW_LINE> <INDENT> super(Model, self).joined_read(joined=joined, where=where, order=order, **kwargs) <NEW_LINE> if(self.table is None): <NEW_LINE> <INDENT> raise DatabaseError(u'No se definió una tabla en el modelo') <NEW_LINE> <DEDENT> if(self.field... | Consulta los elementos de la tabla leyendo los valores de join y los devuelve como una lista | 625941f1462c4b4f79d1dc8e |
def row_width(self, row): <NEW_LINE> <INDENT> if app.config.strict_debug: <NEW_LINE> <INDENT> assert isinstance(row, int) <NEW_LINE> <DEDENT> if row < 0: <NEW_LINE> <INDENT> row = len(self.rows) + row <NEW_LINE> <DEDENT> self._fully_parse_to(row) <NEW_LINE> visual = self.parserNodes[self.rows[row]][kVisual] <NEW_LINE> ... | Get the visual/display column width of a row.
If the text is all ASCII then len(text) will equal the column width. If
there are double wide characters (e.g. Chinese or some emoji) the column
width may be larger than len(text).
Args:
row (int): the row index is zero based (so it's `line_number - 1`).
Returns:
... | 625941f129b78933be1e5c64 |
def get_citations_per_affiliation(self): <NEW_LINE> <INDENT> self.logger.info('Finding sum of citations per affiliation') <NEW_LINE> self.logger.debug('Counting citations per paper') <NEW_LINE> cit_per_paper = np.array(self.cit_net.get_total_citations()) <NEW_LINE> self.logger.debug('Copying paper-affiliation matrix') ... | :return: numpy.array | 625941f16e29344779a62bd0 |
def update_object(model_name, obj_id, field, value): <NEW_LINE> <INDENT> model_class = models_data[model_name].get('class', None) <NEW_LINE> if model_class: <NEW_LINE> <INDENT> object_upd = model_class.objects.get(pk=int(obj_id)) <NEW_LINE> setattr(object_upd, field, value) <NEW_LINE> object_upd.save() <NEW_LINE> retur... | Function update object field from table cell and return update status | 625941f1d164cc617578330e |
def join_open_hockey_group(self, join_group='Open Hockey'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> group = self.group_model.objects.get(name=join_group) <NEW_LINE> self.request.user.groups.add(group) <NEW_LINE> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return | Adds user to open hockey group "behind the scenes", for communication purposes. | 625941f13c8af77a43ae3d67 |
def run(self, input_files, metadata=None): <NEW_LINE> <INDENT> pass | Perform the required operations to achieve the functionality of the
Workflow. This usually involves:
0. Perform relevant checks on the input
1. Instantiate a Tool and run it using some input data
2. Add the Tool's output to the intermediates
3. Repeat from 1 as many times as required
4. Optionally edit the output metad... | 625941f10fa83653e4657576 |
def readPDFFile_old(inputFile): <NEW_LINE> <INDENT> doc = '' <NEW_LINE> with pdfplumber.open(inputFile) as source_file: <NEW_LINE> <INDENT> for page in source_file.pages: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> doc = doc + page.extract_text() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print('\tPDF is unreadab... | Old function to read PDF into strings.
This function uses pdfplumber which is easier to install than textract.
If textract cannot be install, use this instead | 625941f1ad47b63b2c50a53f |
def _features_to_str(features): <NEW_LINE> <INDENT> chrom, pos, alignstrand, pos_in_strand, readname, strand, k_mer, signal_means, signal_stds, signal_lens, cent_signals, methy_label = features <NEW_LINE> means_text = ','.join([str(x) for x in np.around(signal_means, decimals=6)]) <NEW_LINE> stds_text = ','.join... | :param features: a tuple
:return: | 625941f1b830903b967e9ec4 |
def body_insertion(content, insertion, end=False): <NEW_LINE> <INDENT> if not content.startswith('<body'): <NEW_LINE> <INDENT> content = '<body>%s</body>' % content <NEW_LINE> <DEDENT> soup = BeautifulSoup(content) <NEW_LINE> if end: <NEW_LINE> <INDENT> soup.body.append(insertion) <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | Insert an HTML content into the body HTML node | 625941f1b7558d58953c54c7 |
def test_draw_hires(self): <NEW_LINE> <INDENT> nside = 4096*2**5 <NEW_LINE> ra, dec = 45, -45 <NEW_LINE> radius = 0.05 <NEW_LINE> pixels = cartosky.healpix.ang2disc(nside, ra, dec, radius) <NEW_LINE> values = pixels <NEW_LINE> plt.figure() <NEW_LINE> m = Skymap(projection='cyl', celestial=False, gridlines=False) <NEW_L... | Draw a partial healpix map with very large nside | 625941f1a8ecb033257d368a |
def add_column(B, H_B, a, proof): <NEW_LINE> <INDENT> verbose('starting add_column') <NEW_LINE> if B.rank() < B.nrows(): <NEW_LINE> <INDENT> return add_column_fallback(B, a, proof) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> z = solve_system_with_difficult_last_row(B, a) <NEW_LINE> <DEDENT> zd, d = z._clear_denom() <... | The add column procedure.
INPUT:
- B -- a square matrix (may be singular)
- H_B -- the Hermite normal form of B
- a -- an n x 1 matrix, where B has n rows
- proof -- bool; whether to prove result correct, in case we use fallback method.
OUTPUT:
- x -- a vector such that H' = H_B.augment(x) is the HNF of A = B.a... | 625941f197e22403b379d55b |
def GetAllAnalysisWSs(self): <NEW_LINE> <INDENT> return set(self.lp.CurAnalysisWss.split()) | Returns a set of language tags for all analysis writing systems used
in this project. | 625941f163f4b57ef00016c7 |
def __init__(self, observations, ast_filename=None, abg_file=None): <NEW_LINE> <INDENT> __PATH__ = os.path.dirname(__file__) <NEW_LINE> __ORBFIT_LIB__ = glob.glob(os.path.join(__PATH__, '*orbit*.so'))[0] <NEW_LINE> is_64bits = ctypes.sizeof(ctypes.c_voidp) == 8 <NEW_LINE> bin_ephem = is_64bits and 'binEphem.405_64' or ... | Given a list of mpc.Observations, compute the orbit using fit_radec and provide methods for
accessing that orbit.
Requires at least 3 mpc.Observations in the list.
:rtype : Orbfit | 625941f196565a6dacc8fc88 |
def _static_rules(sentence: str) -> Optional[List[SingleResult]]: <NEW_LINE> <INDENT> errors_caught_with_static_rules = [] <NEW_LINE> words = word_tokenize(sentence) <NEW_LINE> if "peoples" in words: <NEW_LINE> <INDENT> context = _get_mistake_context(2, words, words.index("peoples")) <NEW_LINE> errors_caught_with_stati... | :param sentence: sentence from users text
:return: list of errors found with heuristic methods | 625941f1379a373c97cfb106 |
def restart_vm_instance( self, req: typing.Optional[dict] = None, **kwargs ) -> dict: <NEW_LINE> <INDENT> d = { "Region": self.config.region, } <NEW_LINE> req and d.update(req) <NEW_LINE> d = apis.RestartVMInstanceRequestSchema().dumps(d) <NEW_LINE> resp = self.invoke("RestartVMInstance", d, **kwargs) <NEW_LINE> return... | RestartVMInstance - 重启虚拟机
**Request**
- **Region** (str) - (Config) 地域。枚举值:cn,表示中国;
- **VMID** (str) - (Required) 虚拟机ID;
- **Zone** (str) - (Required) 可用区。枚举值:zone-01,表示中国;
**Response**
- **Message** (str) - 返回信息描述 | 625941f1c4546d3d9de72ff9 |
def vgg16(pretrained=False, **kwargs): <NEW_LINE> <INDENT> if pretrained: <NEW_LINE> <INDENT> kwargs['init_weights'] = False <NEW_LINE> <DEDENT> model = VGG(make_layers(cfg['D']), **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> model.load_state_dict(torch.load(os.path.join(models_dir, model_name['vgg16']))) <NE... | VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941f1fb3f5b602dac3c59 |
def save(self): <NEW_LINE> <INDENT> outfile = open(self.file_name, 'w') <NEW_LINE> self._internal_df.to_csv(outfile, index=False) <NEW_LINE> outfile.close() | Save the current Data Frame as a file. | 625941f199fddb7c1c9de94d |
def proxy_delete_namespaced_pod(self, namespace, name, **kwargs): <NEW_LINE> <INDENT> if namespace is None: <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `namespace` when calling `proxy_delete_namespaced_pod`") <NEW_LINE> <DEDENT> if name is None: <NEW_LINE> <INDENT> raise ValueError("Missing the... | proxy DELETE requests to Pod
This method makes a synchronous HTTP request by default.To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_delete_namespaced_pod(names... | 625941f18e7ae83300e4b58e |
def result_shape(self, input_shape): <NEW_LINE> <INDENT> result_shape = (input_shape[2], input_shape[2], input_shape[1], input_shape[3]) <NEW_LINE> return result_shape | Returns the shape of the main result of the NodeCovariance analysis. | 625941f17047854f462a19c2 |
def deprecated_rollout( env, agent, max_path_length=np.inf, render=False, render_kwargs=None, ): <NEW_LINE> <INDENT> if render_kwargs is None: <NEW_LINE> <INDENT> render_kwargs = {} <NEW_LINE> <DEDENT> observations = [] <NEW_LINE> actions = [] <NEW_LINE> rewards = [] <NEW_LINE> terminals = [] <NEW_LINE> agent_infos = [... | The following value for the following keys will be a 2D array, with the
first dimension corresponding to the time dimension.
- observations
- actions
- rewards
- next_observations
- terminals
The next two elements will be lists of dictionaries, with the index into
the list being the index into the time
- agent_i... | 625941f10383005118ecfba0 |
def p_ex_tick(p): <NEW_LINE> <INDENT> p[0] = p[1] // p[2] | ex : tick ex | 625941f1851cf427c661aac9 |
def get_quantity(self): <NEW_LINE> <INDENT> return self._quantity | :return: a Quantity | 625941f130bbd722463cc389 |
def _constraint_exists(self, constraintname, tablename=None): <NEW_LINE> <INDENT> if tablename: <NEW_LINE> <INDENT> cur = self._execute( SQL( "SELECT 1 from information_schema.table_constraints " "WHERE table_name=%s and constraint_name=%s" ), [tablename, constraintname], silent=True, ) <NEW_LINE> return cur.fetchone()... | Check whether the specified constraint exists
INPUT:
- ``constraintname`` -- a string, the name of the index
- ``tablename`` -- (optional) a string
OUTPUT:
If ``tablename`` specified, returns a boolean. If not, returns
``False`` if there is no constraint with this name, or the corresponding tablename
as a string i... | 625941f17d43ff24873a3265 |
def set_url_crawled(self, url): <NEW_LINE> <INDENT> TbUrl.update({'is_crawled': 1}, [TbUrl.id == url.id]) | 将url爬取状态置为已爬取. | 625941f124f1403a92601121 |
def addAttrSeparator(obj, name='Options'): <NEW_LINE> <INDENT> obj = various.checkObj(obj) <NEW_LINE> if obj: <NEW_LINE> <INDENT> ite = 0 <NEW_LINE> longName = '_' <NEW_LINE> while (ite<100): <NEW_LINE> <INDENT> if pmc.objExists( obj.name()+'.'+longName ): <NEW_LINE> <INDENT> longName += '_' <NEW_LINE> <DEDENT> else: <... | Add separator into attribut | 625941f15166f23b2e1a5719 |
def _parse_device_from_datagram( device_callback: Callable[[SwitcherBase], Any], datagram: bytes ) -> None: <NEW_LINE> <INDENT> parser = DatagramParser(datagram) <NEW_LINE> if not parser.is_switcher_originator(): <NEW_LINE> <INDENT> logger.debug("received datagram from an unknown source") <NEW_LINE> <DEDENT> else: <NEW... | Use as callback function to be called for every broadcast message.
Will create devices and send to the on_device callback.
Args:
device_callback: callable for sending SwitcherBase devices parsed from message.
broadcast_message: the bytes message to parse. | 625941f1bde94217f36833ab |
def get_stackframe(levels=1): <NEW_LINE> <INDENT> frame = inspect.currentframe() <NEW_LINE> for _i in range(0, levels): <NEW_LINE> <INDENT> frame = frame.f_back <NEW_LINE> <DEDENT> return frame | Get the specified stack frame | 625941f13eb6a72ae02ecaad |
def deprecated(func): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> warn('Func {} is now deprecated!'.format(func.__name__)) <NEW_LINE> return wrapper(*args, **kwargs) <NEW_LINE> <DEDENT> return wrapper | Show deprecation warning of a function. | 625941f1956e5f7376d7142b |
def _calculate_unscaled_profile(self, params_local, **kwargs): <NEW_LINE> <INDENT> self.liouv.update(params_local) <NEW_LINE> delays = dict(zip(self.delays, self.liouv.delays(self.delays))) <NEW_LINE> d_neg = delays[self.t_neg] <NEW_LINE> d_eq = delays[self.time_eq] <NEW_LINE> d_taucc = delays[self.taucc] <NEW_LINE> pu... | TODO: Write docstring | 625941f107d97122c4178e59 |
def __init__(self, renderTo, **kwargs): <NEW_LINE> <INDENT> if 'data' not in kwargs: <NEW_LINE> <INDENT> raise ValueError('"data" param must be supplied.') <NEW_LINE> <DEDENT> super(BarChart, self).__init__(renderTo, **kwargs) <NEW_LINE> self.kind = 'ColumnChart' <NEW_LINE> self.chart['defaultSeriesType'] = 'bar' <NEW_... | ``data``: [['Item 1', 10], ['Item 2', 20]]
``minPointLength``: 0
Indica a altura mínima em pixels (mesmo se for valor zero) | 625941f15fc7496912cc3f3d |
def settingsDelete(): <NEW_LINE> <INDENT> choice = False <NEW_LINE> while 'Delete': <NEW_LINE> <INDENT> choice = formating.settingsdeleteuserdata(choice) <NEW_LINE> if choice == 'DeLeTe': <NEW_LINE> <INDENT> for i in range(1,5): <NEW_LINE> <INDENT> loader.resetSaveGame(i) <NEW_LINE> <DEDENT> loader.resetSettings() <NE... | Logic for Menu-Settings-Delete | 625941f126068e7796caf2a8 |
def dtrajs_index_sync(self, index_cluster = None): <NEW_LINE> <INDENT> if index_cluster is None: <NEW_LINE> <INDENT> index_cluster = self.most_populated_cluster() <NEW_LINE> <DEDENT> indexes_sync = [] <NEW_LINE> for dtraj in self.dtrajs: <NEW_LINE> <INDENT> indexes = np.where(dtraj == index_cluster)[0] <NEW_LINE> if le... | Return a list with length equal to the number of dtrajs
The elements of the list are integers equal to:
- the first occurance of the cluster index_cluster in the corresponding discretized trajectory
- -1 if the cluster doesn't occur
If index_cluster is None the most populated one is used | 625941f1435de62698dfe20d |
def join(tokens, start, result, separator=' '): <NEW_LINE> <INDENT> texts = [] <NEW_LINE> if len(result) > 0: <NEW_LINE> <INDENT> for e in result: <NEW_LINE> <INDENT> for child in e.iter(): <NEW_LINE> <INDENT> if child.text is not None: <NEW_LINE> <INDENT> texts.append(child.text) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ... | Join tokens into a single string with spaces between. | 625941f1be7bc26dc91cdbb5 |
def SSHcmd(hostname,port,username,password,arg): <NEW_LINE> <INDENT> cl = paramiko.SSHClient() <NEW_LINE> cl.set_missing_host_key_policy(paramiko.AutoAddPolicy()) <NEW_LINE> cl.connect(hostname=hostname,port=port,username=username,password=password) <NEW_LINE> output = [] <NEW_LINE> stdin,stdout,stderr=cl.exec_command(... | Execute command over SSH and get reply.
Args: hostname(str),port(int),username(str),password(str):
parameters for SSH connection
arg(str): command to execute on remote server
Return: [stdout,stderr] list with results of command | 625941f14e696a04525c9a0e |
def _run_python(self, pyscript, py_version='python'): <NEW_LINE> <INDENT> return self.client_remote.run(args=[py_version, '-c', pyscript], wait=False, stdout=StringIO()) | Override this to remove the daemon-helper prefix that is used otherwise
to make the process killable. | 625941f107d97122c4178e5a |
def make_class_obj(json_file_path='servers.json'): <NEW_LINE> <INDENT> exists_check(json_file_path) <NEW_LINE> with open(json_file_path) as json_file: <NEW_LINE> <INDENT> ADDR_DICT = json.load(json_file) <NEW_LINE> <DEDENT> for server, contact in izip(ADDR_DICT, contacts): <NEW_LINE> <INDENT> receivers[contact].append(... | make a class objects using json file | 625941f130c21e258bdfaa64 |
def test_get_result(self): <NEW_LINE> <INDENT> conn_result = self.scan_task.connection_result <NEW_LINE> results = self.scan_task.get_result() <NEW_LINE> self.assertEqual(results, conn_result) | Test get result method when results exist. | 625941f1d99f1b3c44c67b44 |
def prepare_data(y, d, D, s): <NEW_LINE> <INDENT> n_obs, batch_size = y.shape <NEW_LINE> s1 = s if D else (1 if d else 0) <NEW_LINE> s2 = 1 if d + D == 2 else 0 <NEW_LINE> y_diff = np.zeros((n_obs - d - s * D, batch_size), dtype=y.dtype) <NEW_LINE> for i in range(batch_size): <NEW_LINE> <INDENT> temp = y[s1:, i] - y[:-... | Applies differencing and seasonal differencing to the data
| 625941f132920d7e50b28795 |
def _setar(self, area, **kws): <NEW_LINE> <INDENT> if not area in self.data: <NEW_LINE> <INDENT> self.data[area] = {} <NEW_LINE> <DEDENT> for k,v in kws.iteritems(): <NEW_LINE> <INDENT> self.data[area][k] = v | Seta valores para data, este método é usado por __init__, setup, cliente e item
Exemplo:
>>> carrinho = Pagseguro()
>>> carrinho._setar('area', teste='testando')
>>> carrinho.data['area']['teste']
'testando' | 625941f14527f215b584ca11 |
def list_param_groups(self) -> Iterator[str]: <NEW_LINE> <INDENT> paginator = self.elasticache.get_paginator( "describe_cache_parameter_groups" ) <NEW_LINE> for page in paginator.paginate(): <NEW_LINE> <INDENT> for param_group in page["CacheParameterGroups"]: <NEW_LINE> <INDENT> yield param_group["CacheParameterGroupNa... | Elasticache parameters group list function.
List elasticache param group names
:yield Iterator[str]:
Elasticache param group names | 625941f14527f215b584ca12 |
def unameAvailableCheck(request): <NEW_LINE> <INDENT> context = {} <NEW_LINE> getusername = request.POST.get('username') <NEW_LINE> user_obj = User.objects.filter(username = getusername) <NEW_LINE> if user_obj: <NEW_LINE> <INDENT> context['success'] = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> context['success'... | 检查注册新用户的用户名是否可用 | 625941f14d74a7450ccd4785 |
def convert_template(heat_template_data): <NEW_LINE> <INDENT> temp = template.Template(heat_template_data) <NEW_LINE> temp.validate() <NEW_LINE> ctx = test_utils.dummy_context() <NEW_LINE> heat_stack = stack.Stack(context=ctx, stack_name="Dummy", tmpl=temp) <NEW_LINE> temp.validate_resource_definitions(heat_stack) <NEW... | convert_template takes a heat template and converts it into an ARM
template. | 625941f1cad5886f8bd27598 |
def crawler(): <NEW_LINE> <INDENT> global count <NEW_LINE> url = "https://ontrava.com" <NEW_LINE> source_code = requests.get(url) <NEW_LINE> plain_text = source_code.text <NEW_LINE> soup = BeautifulSoup(plain_text , "html.parser") <NEW_LINE> count = 1 <NEW_LINE> for element in soup.findAll('img' , {'class' : 'img-respo... | :rtype: object | 625941f107f4c71912b11a45 |
def generate_pass(length, num_absent = 0, num_late = 0): <NEW_LINE> <INDENT> if length == 0: <NEW_LINE> <INDENT> return [''] <NEW_LINE> <DEDENT> combinations = [] <NEW_LINE> for c in generate_pass(length - 1, num_absent, 0): <NEW_LINE> <INDENT> combinations.append(OK + c) <NEW_LINE> <DEDENT> if num_absent == 0: <NEW_LI... | Time: O(3^n)
Space: O(n.3^n) | 625941f1cb5e8a47e48b8060 |
def quit(self, widget): <NEW_LINE> <INDENT> sensors.cleanup() <NEW_LINE> sys.exit(0) | Quits the program | 625941f18c3a873295158982 |
def init_ui(self): <NEW_LINE> <INDENT> self.panel_sizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> self.figure_bmp = wx.StaticBitmap(self, wx.ID_ANY, bitmap=self.controller.empty_bitmap(self.bitmap_width, self.bitmap_height), pos=wx.DefaultPosition, size=wx.DefaultSize) <NEW_LINE> self.panel_sizer.Add(self.figure_bmp, ui_de... | Builds the wx Panel | 625941f155399d3f05588c78 |
def __init__(self, config, uniqname, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() | access student files and prepare for grading | 625941f13317a56b8693a20a |
def GetNeighborhoodIndex(self, *args): <NEW_LINE> <INDENT> return _itkNeighborhoodPython.itkNeighborhoodD2_GetNeighborhoodIndex(self, *args) | GetNeighborhoodIndex(self, itkOffset2 arg0) -> unsigned int | 625941f1627d3e7fe0d69412 |
def ctime(self) -> int: <NEW_LINE> <INDENT> return self.code_source.ctime() | retrieve the creation timestamp in ns | 625941f1d164cc617578330f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.