code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def buckets(context=None): <NEW_LINE> <INDENT> api = _create_api(context) <NEW_LINE> return _BucketList(api) | Retrieves a list of Storage buckets.
Args:
context: an optional Context object providing project_id and credentials.
Returns:
An iteratable list of buckets. | 625941ba5fc7496912cc3815 |
@register.simple_tag <NEW_LINE> def build(app_name): <NEW_LINE> <INDENT> url_link = f"http://localhost:3000/{app_name}" <NEW_LINE> file_name = f"dist/{app_name}" <NEW_LINE> try: <NEW_LINE> <INDENT> if requests.get(url_link).status_code == 200: <NEW_LINE> <INDENT> return url_link <NEW_LINE> <DEDENT> <DEDENT> except: <NE... | Connecting with the WebPackDev or Django Static
* First, checking the dev server & using it
* if status code is not 200, then using bundle file | 625941ba85dfad0860c3ace8 |
@pytest.mark.slow <NEW_LINE> def test_linemin(H2_ccecp_uhf): <NEW_LINE> <INDENT> mol, mf = H2_ccecp_uhf <NEW_LINE> wf, to_opt = generate_wf(mol, mf) <NEW_LINE> nconf = 100 <NEW_LINE> wf, dfgrad = line_minimization( wf, initial_guess(mol, nconf), gradient_generator(mol, wf, to_opt) ) <NEW_LINE> dfgrad = pd.DataFrame(dfg... | Optimize a Slater-Jastrow wave function and check that it's better than Hartree-Fock | 625941ba3eb6a72ae02ec364 |
def render(self): <NEW_LINE> <INDENT> return [ '%s%s' % (self.name()[0].upper(), self.name()[1:],), ['outputs=', self.outputs], ['inputs=', self.inputs], ['distargs=', self.get_distargs()], ['params=', self.get_params()], ['hypers=', self.get_hypers()], ['suffstats=', self.get_suffstats()], ] | Return an AST-like representation of the CGPM. | 625941ba63d6d428bbe4437f |
@register.simple_tag(takes_context=True) <NEW_LINE> def render_app_icon(context): <NEW_LINE> <INDENT> return AdminMenu.get_app_icon(context['app']['name']) | Render app icon | 625941ba66673b3332b91f26 |
def ReadMetrics( fileName ): <NEW_LINE> <INDENT> DataDF = pd.read_csv(fileName,header = 0, delimiter= ',', parse_dates=['Date']) <NEW_LINE> DataDF = DataDF.set_index('Date') <NEW_LINE> return( DataDF ) | This function takes a filename as input, and returns a dataframe with
the metrics from the assignment on descriptive statistics and
environmental metrics. Works for both annual and monthly metrics.
Date column should be used as the index for the new dataframe. Function
returns the completed DataFrame. | 625941baf548e778e58cd40c |
def check_fleet_edges(ai_settings, monsters): <NEW_LINE> <INDENT> for monster in monsters.sprites(): <NEW_LINE> <INDENT> if monster.check_edges(): <NEW_LINE> <INDENT> change_fleet_direction(ai_settings, monsters) <NEW_LINE> break | Respond appropriately if any aliens have reached an edge. | 625941bae5267d203edcdb30 |
def dns_mx_add(self, client_id, params=None): <NEW_LINE> <INDENT> default = {"server_id": 1, "zone": 1, "name": "www", "data": "127.0.0.1", "aux": 10, "ttl": "3600", "type": "MX", "active": "y"} <NEW_LINE> if params['zone']: <NEW_LINE> <INDENT> server_id = self.dns_zone_get(params['zone']) <NEW_LINE> if server_id: <NEW... | Adds a new DNS MX record.
Param:
id -- Client's id
param -- Dictionary containing record's informations.
Output:
Returns the ID of the newly added record. | 625941bacc40096d615957e2 |
def plot_not_before(self, all_years, nice_years, width=0.35): <NEW_LINE> <INDENT> xaxis_ticks = [] <NEW_LINE> idx = 0 <NEW_LINE> for y in range(2012, 2018): <NEW_LINE> <INDENT> for m in range(1, 13): <NEW_LINE> <INDENT> xaxis_ticks.append('%4d-%02d' % (y, m)) <NEW_LINE> idx += 1 <NEW_LINE> <DEDENT> <DEDENT> xaxis = np.... | Plot not before
:param all_years:
:param nice_years:
:param width:
:return: | 625941ba97e22403b379ce29 |
def bytes_string(text, encode="utf-8"): <NEW_LINE> <INDENT> if not PY3: <NEW_LINE> <INDENT> if isinstance(text, unicode): <NEW_LINE> <INDENT> result = text.encode(encode) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = text <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(text, bytes): <NEW_L... | Return a bytes object on Python 3 and a str object on Python 2 | 625941ba8a43f66fc4b53ef9 |
def render(self, data, accepted_media_type=None, renderer_context=None): <NEW_LINE> <INDENT> renderer_context = renderer_context or {} <NEW_LINE> view = renderer_context['view'] <NEW_LINE> request = renderer_context['request'] <NEW_LINE> response = renderer_context['response'] <NEW_LINE> if response.exception: <NEW_LIN... | Renders data to HTML, using Django's standard template rendering.
The template name is determined by (in order of preference):
1. An explicit .template_name set on the response.
2. An explicit .template_name set on this class.
3. The return result of calling view.get_template_names(). | 625941ba4e4d5625662d426c |
def plot_task(task): <NEW_LINE> <INDENT> cmap = colors.ListedColormap( [ '#000000', '#0074D9', '#FF4136', '#2ECC40', '#FFDC00', '#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25' ] ) <NEW_LINE> norm = colors.Normalize(vmin=0, vmax=9) <NEW_LINE> fig, axs = plt.subplots(1, 4, figsize=(15, 15)) <NEW_LINE> axs[0].imshow... | Plots the first train and test pairs of a specified task,
using same color scheme as the ARC app | 625941bab545ff76a8913cae |
def __init__(self): <NEW_LINE> <INDENT> from gamestate import GameState <NEW_LINE> self.data_in_q = Queue(MAX_Q_SIZE) <NEW_LINE> self.commands_out_q = Queue(MAX_Q_SIZE) <NEW_LINE> self.gs = GameState() <NEW_LINE> self.logger = None <NEW_LINE> self.last_run_time = None <NEW_LINE> self.delta_time = 0 <NEW_LINE> self._own... | Sets up queues for reading data in and out of this provider | 625941ba9b70327d1c4e0c64 |
def read_all(self): <NEW_LINE> <INDENT> print("\nCRUD: Read (all) test case") <NEW_LINE> docs = self.organizers.read() <NEW_LINE> self.show_docs(docs, 5) | Run Read(all) test case | 625941ba01c39578d7e74cd3 |
def refresh(self, cycles_passed): <NEW_LINE> <INDENT> if not self.busy: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.time_left -= cycles_passed <NEW_LINE> if self.time_left <= 0: <NEW_LINE> <INDENT> self.busy = False <NEW_LINE> self.time_left = 0 <NEW_LINE> return (self.locked_mode, self.locked_range) <NEW_... | Called every VM step, if device is busy, refresh how many cycles it'll busy more | 625941ba498bea3a759b9940 |
def countPrimes(self, n): <NEW_LINE> <INDENT> if n < 3: return 0 <NEW_LINE> primes = [True] * (n+1) <NEW_LINE> res = 0 <NEW_LINE> for i in range(2,n): <NEW_LINE> <INDENT> if primes[i]: <NEW_LINE> <INDENT> res += 1 <NEW_LINE> for j in range(i,n,i): <NEW_LINE> <INDENT> primes[j] = False <NEW_LINE> <DEDENT> <DEDENT> <DEDE... | :type n: int
:rtype: int | 625941ba26238365f5f0ecfa |
def to_file(self, filename=None): <NEW_LINE> <INDENT> t = localtime() <NEW_LINE> size = len(self.a) <NEW_LINE> assumptions = ['Independent Observations'] <NEW_LINE> if self.alt_hyp == 'unequal': <NEW_LINE> <INDENT> alternative = "Mean 1 != " + str(self.popmean) <NEW_LINE> sided = "two-sided" <NEW_LINE> <DEDENT> else: <... | Summarizes the results of the t-test performed and saves the results
out into `filename`.
Parameters
----------
filename : string, optional
The location of the file where the results will be stored. If no
filename is provided, a default filename will be generated, and the
results will be stored there. | 625941bad10714528d5ffb6f |
def identification(self, birth_date, first_name, middle_name, last_name, passport, inn=None, snils=None, oms=None): <NEW_LINE> <INDENT> result_json = apihelper.identification(self.token, self.number, birth_date, first_name, middle_name, last_name, passport, inn, snils, oms, self.proxy) <NEW_LINE> result_json['base_inn'... | Идентификация пользователя
Данный запрос позволяет отправить данные для упрощенной идентификации своего QIWI кошелька.
Warnings
--------
Данный метод не тестируется, соответственно я не могу гарантировать того что он будет работать как должен.
Вы делаете это на свой страх и риск.
Parameters
----------
birth_date : s... | 625941ba96565a6dacc8f565 |
def read(*parts): <NEW_LINE> <INDENT> path = os.path.join(os.path.dirname(__file__), *parts) <NEW_LINE> with codecs.open(path, encoding='utf-8') as fobj: <NEW_LINE> <INDENT> return fobj.read() | Read file and return contents. | 625941bac432627299f04ad4 |
def maxCount(self, m, n, ops): <NEW_LINE> <INDENT> rmin = m <NEW_LINE> cmin = n <NEW_LINE> for i in ops: <NEW_LINE> <INDENT> rmin = min(i[0], rmin) <NEW_LINE> cmin = min(i[1], cmin) <NEW_LINE> <DEDENT> return rmin * cmin | :type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int | 625941ba091ae35668666df5 |
def set_space(self, space): <NEW_LINE> <INDENT> self.space = space | sets the space the robot keeps between himself and the carrot
:param space: space in meters | 625941ba94891a1f4081b938 |
def upgrade_lock(self, purpose=None, retry=None): <NEW_LINE> <INDENT> if purpose is not None: <NEW_LINE> <INDENT> self._purpose = purpose <NEW_LINE> <DEDENT> if retry is not None: <NEW_LINE> <INDENT> self._retry = retry <NEW_LINE> <DEDENT> if self.shared: <NEW_LINE> <INDENT> LOG.debug('Upgrading shared lock on node %(u... | Upgrade a shared lock to an exclusive lock.
Also reloads node object from the database.
If lock is already exclusive only changes the lock purpose
when provided with one.
:param purpose: optionally change the purpose of the lock
:param retry: whether to retry locking if it fails, the
class-level value is used by ... | 625941ba293b9510aa2c3129 |
def create_information(self): <NEW_LINE> <INDENT> return AnimalInfo(origin=self, contents=None) | Create a new Info.
transmit() -> _what() -> create_information(). | 625941ba32920d7e50b2805d |
def rdkit2amberpdb(mol_pdb_txt): <NEW_LINE> <INDENT> mol_new_lines = [] <NEW_LINE> atom_counts = {} <NEW_LINE> line_format = '{0[0]}{0[1]:>7}{0[2]:>4}{0[3]:>5}{0[4]:>6}{0[5]: 12.3f}{0[6]: 8.3f}{0[7]: 8.3f}{0[8]:>6}{0[9]:>6}{0[10]:>12}' <NEW_LINE> mol_txt_lines = mol_pdb_txt.split('\n') <NEW_LINE> for line in mol_txt_li... | Converts a PDB block from openbabel or rdkit like format to the PDB block in rism pdb format
:param mol_pdb_txt: pdb block with openbabel or rdkit like format
:return: string with a pdb block in rism pdb comparable format | 625941bad8ef3951e32433cd |
def get_results(self, **kwargs): <NEW_LINE> <INDENT> if self.returncode is None: <NEW_LINE> <INDENT> raise self.Error("return code is None, you should call wait, communicate or poll") <NEW_LINE> <DEDENT> if self.status is None or self.status < self.S_DONE: <NEW_LINE> <INDENT> raise self.Error("Task is not completed") <... | Returns :class:`NodeResults` instance.
Subclasses should extend this method (if needed) by adding
specialized code that performs some kind of post-processing. | 625941bae8904600ed9f1db9 |
def test_rule(): <NEW_LINE> <INDENT> from pica.cells import Cells <NEW_LINE> from pica.conditions import Equals <NEW_LINE> from pica.rules import Rule, Result <NEW_LINE> rule = Rule('from', 'to', Equals(1, 0, 'no match'), 0.5) <NEW_LINE> cells = Cells(2, 2, 'from') <NEW_LINE> cells.update(0, 0, 'no match') <NEW_LINE> c... | A Rule | 625941ba498bea3a759b9941 |
def addCategory(self, entry): <NEW_LINE> <INDENT> newID = random.randint(10000, 99999) <NEW_LINE> while newID in self.idList: <NEW_LINE> <INDENT> newID = random.randint(10000, 99999) <NEW_LINE> <DEDENT> entry.insert(0, newID) <NEW_LINE> self.idList.append(newID) <NEW_LINE> self.cursor.execute("INSERT INTO CATEGORIES VA... | Author: Alex Lambert
UW NetID: alamb25
Date: 3/7/17
Add Category to the Database | 625941ba090684286d50eb71 |
def list_user_profiles(nextToken=None, maxResults=None): <NEW_LINE> <INDENT> pass | Lists all the user profiles configured for your AWS account in AWS CodeStar.
See also: AWS API Documentation
Exceptions
:example: response = client.list_user_profiles(
nextToken='string',
maxResults=123
)
:type nextToken: string
:param nextToken: The conti... | 625941ba0a50d4780f666d1f |
def get_enclitic(self, pronoun): <NEW_LINE> <INDENT> return yaziji_const.ENCLITICS.get(pronoun,"") | Extract enclitic | 625941ba30dc7b76659017fa |
def add_artifact(self, pt_id, artifact_id, private_key, public_key, del_flag=False): <NEW_LINE> <INDENT> if del_flag: <NEW_LINE> <INDENT> response_bytes = self.retrieve_part(pt_id) <NEW_LINE> if response_bytes != None: <NEW_LINE> <INDENT> jresponse = json.loads(response_bytes.decode()) <NEW_LINE> if len(jresponse["arti... | Constructs the batch payload for the "AddArtifact" command.
Args:
pt_id (str): The uuid of the part
artifact_id (str): The uuid of the artifact
private_key (str): The private key of the user
public_key (str): The public key of the user
del_flag (bool): The flag for "--delete" option (default False)... | 625941ba377c676e9127203a |
def update_last_updated(self, commit = True): <NEW_LINE> <INDENT> assert 'person_id' in self <NEW_LINE> assert self.table_name <NEW_LINE> self.api.db.do("UPDATE %s SET last_updated = CURRENT_TIMESTAMP " % (self.table_name) + " where person_id = %d" % (self['person_id']) ) <NEW_LINE> self.sync(comm... | Update last_updated field with current time | 625941ba44b2445a33931f30 |
def mask_out(src): <NEW_LINE> <INDENT> mini = np.amin(src) <NEW_LINE> num = len(src) <NEW_LINE> for i in range(num): <NEW_LINE> <INDENT> for j in range(num): <NEW_LINE> <INDENT> if (i - num / 2) ** 2 + (j - num / 2) ** 2 > (0.3846 * num) ** 2: <NEW_LINE> <INDENT> src[i][j] = mini <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> a... | Mask the data outside of the disk. 0.3846 is a number calculated based on the structure
of the pic. Due to -inf, this is normally done after normalize
:param src: full disk data | 625941baa79ad161976cbfd6 |
def _unwrap_maps(self, name_maps, name, analysis=None, **inner_maps): <NEW_LINE> <INDENT> name = name_maps.get('name', name) <NEW_LINE> name = name_maps.get('prefix', '') + name <NEW_LINE> analysis = name_maps.get('analysis', analysis) <NEW_LINE> maps = {} <NEW_LINE> for mtype in ('input_map', 'output_map'): <NEW_LINE>... | Unwraps potentially nested name-mapping dictionaries to get values
for name, input_map, output_map and analysis. Unsed in __init__.
Parameters
----------
name_maps : dict
A dictionary containing the name_maps to apply to the values
name : str
Name passed from inner pipeline constructor
analysis : Analysis
... | 625941ba67a9b606de4a7d4d |
def sigmoid_output_to_derivative(output): <NEW_LINE> <INDENT> return output * (1-output) | Convert the sigmoid function's output to its derivative. | 625941ba4f88993c3716bf04 |
def _adaptive_step_size(f, f0=None, alpha=None, tau=2): <NEW_LINE> <INDENT> if alpha is None: <NEW_LINE> <INDENT> alpha = 1 <NEW_LINE> <DEDENT> if f0 is None: <NEW_LINE> <INDENT> f0, _ = f(0) <NEW_LINE> <DEDENT> f_alpha, x_alpha = f(alpha) <NEW_LINE> if f_alpha < f0: <NEW_LINE> <INDENT> f_alpha_up, x_alpha_up = f(alpha... | Parameters
----------
f : callable
Optimized function, take only the step size as argument
f0 : float
value of f at current point, i.e. step size = 0
alpha : float
Initial step size
tau : float
Multiplication factor of the step size during the adaptation | 625941bad7e4931a7ee9ddac |
def test_get_data_from_dataset_with_multiword_dimnames(self): <NEW_LINE> <INDENT> data_frame = knoema.get('FDI_FLOW_CTRY', **{'Reporting country': 'AUS', 'Partner country/territory': 'w0', 'Measurement principle': 'DI', 'Type of FDI': 'T_FA_F', 'Type of entity': 'ALL', 'Accounting entry': 'NET', 'Level of counterpart':... | The method is testing load data from regular dataset with dimenions that have multi word names | 625941bab7558d58953c4dab |
def gen_sinc_list(a, b, n=1000): <NEW_LINE> <INDENT> dx = (b-a)/(n-1) <NEW_LINE> x = np.arange(0, n) <NEW_LINE> generatedList = [a + kx * dx for kx in x] <NEW_LINE> sincList = [np.divide(np.sin(t), t, out=None, where=t!=0) for t in generatedList] <NEW_LINE> return (generatedList, sincList) | Generates a list based on the "sinc" function. Based on the template for the Gaussian function above.
Args:
a (float): Lower bound of domain
b (float): Uper bound of domain
n (int): number of points in the domain, with a default value of 1000.
Returns:
(generatedList, sincList):
generatedList [float] : [a,... | 625941ba30bbd722463cbc53 |
def __init__(self, path, xlim=(0, 1), ylim=(0, 1), *args, **kwargs): <NEW_LINE> <INDENT> self.name = os.path.splitext(os.path.basename(path))[0] <NEW_LINE> self.img_data = self._read_image(path, *args, **kwargs) <NEW_LINE> self.xlim = xlim <NEW_LINE> self.ylim = ylim <NEW_LINE> self._data = None | Create a graph object from image at path. Optionally pass the x
and y limits.
Args:
path (str): The path to the image of the graph.
xlim (tuple[float]): The range of the x axis.
ylim (tuple[float]): The range of the y axis. | 625941ba6e29344779a624a6 |
def tuned_frequency_encode(self, tuned_freq): <NEW_LINE> <INDENT> return MAVLink_tuned_frequency_message(tuned_freq) | Control the tuned frequency of an SDR
tuned_freq : Tuned Frequency (float) | 625941ba26068e7796caeb6a |
def merge_user_into_another_user_accounts(request_ctx, id, destination_account_id, destination_user_id, **request_kwargs): <NEW_LINE> <INDENT> path = '/v1/users/{id}/merge_into/accounts/{destination_account_id}/users/{destination_user_id}' <NEW_LINE> url = request_ctx.base_api_url + path.format(id=id, destination_accou... | Merge a user into another user.
To merge users, the caller must have permissions to manage both users.
When finding users by SIS ids in different accounts the
destination_account_id is required.
The account can also be identified by passing the domain in destination_account_id.
:param request_ctx: The request co... | 625941bad164cc6175782bde |
def get_power_type(self, region, namespace, power_type_id, **filters): <NEW_LINE> <INDENT> filters['namespace'] = namespace <NEW_LINE> return self.get_resource('data/wow/power-type/{0}', region, *[power_type_id], **filters) | Power Type API - get power type by id | 625941ba9c8ee82313fbb605 |
def _GetInstanceParameterFields(): <NEW_LINE> <INDENT> fields = [ (_MakeField("hvparams", "HypervisorParameters", QFT_OTHER, "Hypervisor parameters (merged)"), IQ_CONFIG, 0, lambda ctx, _: ctx.inst_hvparams), (_MakeField("beparams", "BackendParameters", QFT_OTHER, "Backend parameters (merged)"), IQ_CONFIG, 0, lambda ct... | Get instance fields involving parameters.
@return: List of field definitions used as input for L{_PrepareFieldList} | 625941bafff4ab517eb2f2ca |
@app.route("/objectBrowser") <NEW_LINE> @login_required <NEW_LINE> def object_browser(): <NEW_LINE> <INDENT> return render_template("dashboard/index.haml") | The object Browser page
| 625941ba50812a4eaa59c1b5 |
def update_planet_position(segment): <NEW_LINE> <INDENT> conditions = segment.state.conditions <NEW_LINE> V = conditions.freestream.velocity[:,0] <NEW_LINE> altitude = conditions.freestream.altitude[:,0] <NEW_LINE> phi = conditions.frames.body.inertial_rotations[:,0] <NEW_LINE> theta = conditions... | Updates the location of the vehicle relative to the Planet throughout the mission
Assumptions:
This is valid for small movements and times as it does not account for the rotation of the Planet beneath the vehicle
Inputs:
segment.state.conditions:
freestream.velocity [meters/second]
freest... | 625941ba925a0f43d2549d04 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.result = None <NEW_LINE> self.meta = None <NEW_LINE> replace_names = { "result": "result", "meta": "meta", } <NEW_LINE> if kwargs is not None: <NEW_LINE> <INDENT> for key in kwargs: <NEW_LINE> <INDENT> if key in replace_names: <NEW_LINE> <INDENT> setattr(self, repl... | Constructor for the GetProductsWrapper class
Args:
**kwargs: Keyword Arguments in order to initialise the
object. Any of the attributes in this object are able to
be set through the **kwargs of the constructor. The values
that can be supplied and their types are as follows::
re... | 625941badc8b845886cb53c5 |
def pcToToneRow(pcSet): <NEW_LINE> <INDENT> if len(pcSet) == 12: <NEW_LINE> <INDENT> a = TwelveToneRow() <NEW_LINE> for thisPc in pcSet: <NEW_LINE> <INDENT> p = music21.pitch.Pitch() <NEW_LINE> p.pitchClass = thisPc <NEW_LINE> a.append(p) <NEW_LINE> <DEDENT> return a <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a = To... | A convenience function that, given a list of pitch classes represented as integers
and turns it in to a serial.ToneRow object.
>>> from music21 import *
>>> a = serial.pcToToneRow(range(12))
>>> matrixObj = a.matrix()
>>> print matrixObj
0 1 2 3 4 5 6 7 8 9 A B
B 0 1 2 3 4 5 6 7 8 9 A
...
>>... | 625941ba3346ee7daa2b2bfa |
def _handle_chat_event(self, event: events.ChatMessageWasReceived) -> None: <NEW_LINE> <INDENT> for subscriber in self._chat_subscribers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subscriber(event) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.exception(self._prefix_log_message( f"failed to send chat... | Not thread-safe. | 625941ba66656f66f7cbc03b |
def GetFeatureImage(self): <NEW_LINE> <INDENT> return _itkBinaryStatisticsKeepNObjectsImageFilterPython.itkBinaryStatisticsKeepNObjectsImageFilterIUL3ID3_GetFeatureImage(self) | GetFeatureImage(self) -> itkImageD3 | 625941ba15fb5d323cde099b |
def read_wav(filename): <NEW_LINE> <INDENT> wave_read = wave.open(filename, 'r') <NEW_LINE> n_samples = wave_read.getnframes() <NEW_LINE> byte_data = wave_read.readframes(n_samples) <NEW_LINE> x = np.frombuffer(byte_data, dtype=np.short) <NEW_LINE> return x | Read a 16-bit wav file as an numpy array of shorts | 625941bad6c5a10208143ed8 |
def test_empty_info(self) -> None: <NEW_LINE> <INDENT> sample_gen = Foundset(i for i in [1, 2]) <NEW_LINE> self.assertEqual(sample_gen.info, {}) | Test that a foundset without 'dataInfo' section returns an empty info dictionary | 625941bafff4ab517eb2f2cb |
def ScrollPageLeft(self): <NEW_LINE> <INDENT> pass | ScrollPageLeft(self: DocumentViewer)
Scrolls left one viewport. | 625941bac432627299f04ad5 |
def resourcesPoissonPP(self, Nres, ri = 40.): <NEW_LINE> <INDENT> rmax = min(self.Lx, self.Ly)/2 <NEW_LINE> N = self.Lx * self.Ly <NEW_LINE> self.Resx = np.zeros((Nres)) <NEW_LINE> self.Resy = np.zeros((Nres)) <NEW_LINE> for j in range(Nres): <NEW_LINE> <INDENT> r = (rmax - ri)*random.random() + ri <NEW_LINE> theta = 2... | Spreads resources around the area for the bees to look for. It is
implemented as a Poisson Point process. | 625941ba16aa5153ce362309 |
def test_projector(): <NEW_LINE> <INDENT> gmm1 = GMM(number_of_gaussians=2) <NEW_LINE> gmm1.ubm = GMMMachine.from_hdf5( pkg_resources.resource_filename("bob.bio.gmm.test", "data/gmm_ubm.hdf5") ) <NEW_LINE> feature = utils.random_array((20, 45), -5.0, 5.0, seed=seed_value) <NEW_LINE> projected = gmm1.project(feature) <N... | Tests the projector. | 625941ba91f36d47f21ac387 |
def network_add_cl(self, nb_filter, filter_size, activation='relu', padding='same'): <NEW_LINE> <INDENT> if self.network is None: <NEW_LINE> <INDENT> print("Network not initialized. Initialize network first using the 'init_network' method!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.network = conv_2d(self.netw... | Adds a convolutional layer to the specified network.
:param nb_filter: (int) Specifying the number of convolution filters
:param filter_size: (int or list(int)) Specifying the size of the filters
:param activation: (str) Specifying which type of activation function should be applied to the weights in the
given layer. ... | 625941ba3317a56b86939afa |
def test_tc10(self): <NEW_LINE> <INDENT> tc = LargestWord(file_path="tests/input_files/data_tc10.txt") <NEW_LINE> self.assertEqual("File is corrupted", tc.load_file()) | Validate program against a corrupted file
Note:
Generated file using command: dd if=/dev/urandom of=data_tc10.txt bs=5000 count=1 | 625941bab57a9660fec33712 |
def weight(self, S_bar, psi, outlier): <NEW_LINE> <INDENT> psi_inliers = psi[np.invert(outlier), :] <NEW_LINE> psi_max = psi[np.argmax(np.sum(psi, 1)), :].reshape( (1, S_bar.shape[1])) <NEW_LINE> psi_inliers = psi_max <NEW_LINE> nx = S_bar.shape[0] - 1 <NEW_LINE> if psi_inliers.size > 0: <NEW_LINE> <INDENT> weights = n... | Weigh the particles according to the probabilities in psi. | 625941baa4f1c619b28afed2 |
def convert_to_csv(element: etree.Element, **kwargs) -> None: <NEW_LINE> <INDENT> row = [] <NEW_LINE> csv_file = kwargs.get('csv_file') <NEW_LINE> namespaces = kwargs.get('namespaces') <NEW_LINE> print(f'c1: {element.xpath("ns:c1/text()", namespaces=namespaces)}') <NEW_LINE> with open(csv_file, mode='a', encoding='utf-... | Write/append row to CSV file. | 625941bacb5e8a47e48b7940 |
def set_directories(self, directories, cache_folder): <NEW_LINE> <INDENT> if jinja2 is None: <NEW_LINE> <INDENT> req_missing(['jinja2'], 'use this theme') <NEW_LINE> <DEDENT> cache_folder = os.path.join(cache_folder, 'jinja') <NEW_LINE> makedirs(cache_folder) <NEW_LINE> cache = jinja2.FileSystemBytecodeCache(cache_fold... | Create a new template lookup with set directories. | 625941bab7558d58953c4dac |
@prof.log_call(trace_logger) <NEW_LINE> def dot_product_normalized(new_vector_set_1, new_vector_set_2, ord=2): <NEW_LINE> <INDENT> assert ord > 0 <NEW_LINE> if not issubclass(new_vector_set_1.dtype.type, numpy.floating): <NEW_LINE> <INDENT> new_vector_set_1 = new_vector_set_1.astype(numpy.float64) <NEW_LINE> <DEDENT> i... | Determines the dot product between a pair of vectors from each set and
divides them by the norm of the two.
Args:
new_vector_set_1(numpy.ndarray): first set of vectors.
new_vector_set_2(numpy.ndarray): second set of vectors.
ord(optional): basically the same arguments
... | 625941ba627d3e7fe0d68ce0 |
def copy(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bounds = [x for x in self.boundingbox] <NEW_LINE> return TextBlock(self.text,bounds) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise Exception("Unable to copy textbox") | Return a deep copy of TextBlock
Returns:
Copy TextBlock (TextBlock): New Copied TextBlock | 625941baec188e330fd5a637 |
def find_le(self, a, x): <NEW_LINE> <INDENT> i = bisect_right(a, x) <NEW_LINE> if i: <NEW_LINE> <INDENT> return a[i-1] <NEW_LINE> <DEDENT> raise ValueError | Find rightmost value less than or equal to x | 625941ba462c4b4f79d1d562 |
def __init__(self, images, labels, seed=None): <NEW_LINE> <INDENT> seed1, seed2 = random_seed.get_seed(seed) <NEW_LINE> np.random.seed(seed1 if seed is None else seed2) <NEW_LINE> assert images.shape[0] == labels.shape[0], ( 'images.shape: %s labels.shape: %s' % (images.shape, labels.shape)) <NEW_LINE> self._num_exampl... | Construct a DataSet.
one_hot arg is used only if fake_data is true. `dtype` can be either
`uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
`[0, 1]`. Seed arg provides for convenient deterministic testing. | 625941bad99f1b3c44c67427 |
@login_required <NEW_LINE> def change_profile(request): <NEW_LINE> <INDENT> profile = UserProfile.get_or_create_profile(request.user) <NEW_LINE> if request.method == "GET": <NEW_LINE> <INDENT> user_form = UserForm(instance=request.user) <NEW_LINE> pass_change_form = PasswordChangeForm(request.user) <NEW_LINE> if profil... | The view function to change profile information for a user or admin. | 625941ba090684286d50eb72 |
def merge(*iterables, **kwargs): <NEW_LINE> <INDENT> key = kwargs.pop('key', lambda a: a) <NEW_LINE> reverse = kwargs.pop('reverse', False) <NEW_LINE> min_or_max = max if reverse else min <NEW_LINE> peekables = [peekable(it) for it in iterables] <NEW_LINE> peekables = [p for p in peekables if p] <NEW_LINE> while peekab... | Return an iterable ordered merge of the already-sorted items
from each of `iterables`, compared by kwarg `key`.
If reverse=True is passed, iterables must return their results in
descending order rather than ascending. | 625941bab830903b967e97a8 |
def test_empty_with_metadata(): <NEW_LINE> <INDENT> dict_undict_loops({ 'contents': {}, 'metadata': 'Fake metadata', }) | Test empty tree with metadata. | 625941bae1aae11d1e749b46 |
def get_table_ovs_ports(self): <NEW_LINE> <INDENT> raise UIException("Method isn't implemented") | Get OvsPorts table.
Returns:
list[dict]: table (list of dictionaries))
Examples::
env.switch[1].ui.get_table_ovs_ports() | 625941ba0c0af96317bb807b |
def blink(self, device_uuid=None, app_id=None): <NEW_LINE> <INDENT> return self._do_command( '{0}/blink'.format(self.SUPERVISOR_API_VERSION), device_uuid=device_uuid, app_id=app_id, method='POST' ) | Start a blink pattern on a LED for 15 seconds. This is the same with `balena.models.device.identify()`.
No need to set device_uuid and app_id if command is sent to the API on device.
Args:
device_uuid (Optional[str]): device uuid.
app_id (Optional[str]): application id.
Raises:
InvalidOption: if the endpo... | 625941ba7b25080760e392ec |
def save(self): <NEW_LINE> <INDENT> if self.id is None: <NEW_LINE> <INDENT> raise ObjectHasNoId <NEW_LINE> <DEDENT> self._commit() <NEW_LINE> return self | Сохранить изменения | 625941ba1b99ca400220a942 |
def exception(self, msg, *args, exc_info=True, **kwargs): <NEW_LINE> <INDENT> self.error(msg, *args, exc_info=exc_info, **kwargs) | Convenience method for logging an ERROR with exception information. | 625941ba82261d6c526ab334 |
def execute(self): <NEW_LINE> <INDENT> configurator = get_configurator(self.params.config, storage_path=self.params.storage, include_config_dirs=True) <NEW_LINE> cluster_name = self.params.cluster <NEW_LINE> try: <NEW_LINE> <INDENT> cluster = configurator.load_cluster(cluster_name) <NEW_LINE> if self.params.update: <NE... | Lists all nodes within the specified cluster with certain
information like id and ip. | 625941ba5e10d32532c5edc0 |
def _get_provider_for_router(self, context, router_id): <NEW_LINE> <INDENT> driver_name = self._stm.get_provider_names_by_resource_ids( context, [router_id]).get(router_id) <NEW_LINE> if not driver_name: <NEW_LINE> <INDENT> router = self.l3_plugin.get_router(context, router_id) <NEW_LINE> driver = self._attrs_to_driver... | Return the provider driver handle for a router id. | 625941ba21bff66bcd6847e7 |
def SleepUntilHistogramHasEntry(self, histogram_name, sleep_intervals=10): <NEW_LINE> <INDENT> histogram = {} <NEW_LINE> while(not histogram and sleep_intervals > 0): <NEW_LINE> <INDENT> histogram = self.GetHistogram(histogram_name, 5) <NEW_LINE> if (not histogram): <NEW_LINE> <INDENT> time.sleep(1) <NEW_LINE> sleep_in... | Polls if a histogram exists in 1-6 second intervals for 10 intervals.
Allows script to run with a timeout of 5 seconds, so the default behavior
allows up to 60 seconds until timeout.
Args:
histogram_name: The name of the histogram to wait for
sleep_intervals: The number of polling intervals, each polling cycle tak... | 625941ba3539df3088e2e1dd |
def _build_class(class_name, classes): <NEW_LINE> <INDENT> if not isinstance(classes, (list, tuple)): <NEW_LINE> <INDENT> classes = (classes, ) <NEW_LINE> <DEDENT> return type(class_name, tuple(import_obj(c) for c in classes), {}) | Import all classes from the parameter and then build a new class with
the given name.
:param class_name: the name for the new class
:param classes: one ore more Classes to build the new class out of | 625941bafbf16365ca6f604f |
def resco_12_hrs(read_sheet, dummy1, row, col): <NEW_LINE> <INDENT> data = read_sheet.cell_value(row, col) <NEW_LINE> return data | This function returns an integer which aligns with the number of hours worked associated with the call.
:param read_sheet: The active .xlsx sheet defined by xlrd.
:type read_sheet: object
:param dummy1: Unused variable.
:type dummy1: null
:param row: The data row that is being scraped.
:type row: integer
:param col: T... | 625941ba9b70327d1c4e0c66 |
def gainFocus(self, previous, previous_name, text="", *args, **kwargs): <NEW_LINE> <INDENT> self.old_state = previous <NEW_LINE> self.old_state_name = previous_name <NEW_LINE> self.ui = ui.UI(96, 208) <NEW_LINE> self.txtbox = ui.ScrollText(16, 8, 256, 33, text, 0.15) <NEW_LINE> self.ui.add(self.txtbox) <NEW_LINE> self.... | What should be done when the state gets focus. Previous is the state that had focus before this one. | 625941bab545ff76a8913cb0 |
def get_all_conversations(self,messages_dir): <NEW_LINE> <INDENT> conversations=[] <NEW_LINE> dirs=[convo for convo in os.listdir(messages_dir) if os.path.isdir(messages_dir+"/"+convo)==True] <NEW_LINE> for d in dirs: <NEW_LINE> <INDENT> files=[x for x in os.listdir(messages_dir+"/"+d) if os.path.isfile(messages_dir+"/... | :params message_dir: The location of the directory
:returns: a list of all the directory i.e conversations
Returns a list of all the converstaion that has taken place. | 625941ba8a349b6b435e8006 |
def forward(self, x, mask_matrix): <NEW_LINE> <INDENT> B, L, C = x.shape <NEW_LINE> H, W = self.H, self.W <NEW_LINE> assert L == H * W, "input feature has wrong size" <NEW_LINE> shortcut = x <NEW_LINE> x = self.norm1(x) <NEW_LINE> x = x.view(B, H, W, C) <NEW_LINE> pad_l = pad_t = 0 <NEW_LINE> pad_r = (self.window_size ... | Forward function.
Args:
x: Input feature, tensor size (B, H*W, C).
H, W: Spatial resolution of the input feature.
mask_matrix: Attention mask for cyclic shift. | 625941ba66656f66f7cbc03c |
def numJewelsInStones(J, S): <NEW_LINE> <INDENT> d = Counter(J) <NEW_LINE> count = 0 <NEW_LINE> for char in S: <NEW_LINE> <INDENT> if char in d: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> <DEDENT> <DEDENT> return count | :type J: str
:type S: str
:rtype: int | 625941ba4a966d76dd550e9e |
def download_photo(): <NEW_LINE> <INDENT> return response.download(request, db) | This action downloads a photo to be shown on screen. | 625941ba57b8e32f52483332 |
def get_euclid_distance_to(self, atom): <NEW_LINE> <INDENT> return linalg.norm(self.get_coords() - atom.get_coords()) | Gets the euclid distance from this atom to the given atom.
Returns
-------
distance : float
the distance from this atom to the diven atom | 625941bad10714528d5ffb72 |
def test_norm_vector(self): <NEW_LINE> <INDENT> desc = CoulombMatrix(n_atoms_max=5, permutation="random", sigma=100, flatten=False) <NEW_LINE> cm = desc.create(H2O) <NEW_LINE> self.assertEqual(len(cm), 5) <NEW_LINE> self.assertEqual(len(desc._norm_vector), 3) <NEW_LINE> cm = desc.create(H2O) <NEW_LINE> self.assertEqual... | Tests if the attribute _norm_vector is written and used correctly
| 625941baa4f1c619b28afed3 |
def export_getOverallStatus( self ): <NEW_LINE> <INDENT> return InstallTools.getOverallStatus( getCSExtensions() ) | Get the complete status information for the components in the
given list | 625941ba293b9510aa2c312b |
def get_registry_value(self, registry_path): <NEW_LINE> <INDENT> self.ready_event.wait() <NEW_LINE> ret = self.__post_and_wait("reg query value", registry_path) <NEW_LINE> return ret.get('value', None) | Retrieve the data from a registry value. | 625941bad8ef3951e32433cf |
def test_exp_then_log_right(self): <NEW_LINE> <INDENT> for metric in [self.metrics['right_canonical'], self.metrics['right_diag']]: <NEW_LINE> <INDENT> for base_point_type in self.elements: <NEW_LINE> <INDENT> base_point = self.elements[base_point_type] <NEW_LINE> for element_type in self.elements: <NEW_LINE> <INDENT> ... | Test that the riemannian left exponential and the
riemannian left logarithm are inverse.
Expect their composition to give the identity function. | 625941ba498bea3a759b9943 |
def GetFriendlyName(self): <NEW_LINE> <INDENT> if hasattr(self, 'NAME'): <NEW_LINE> <INDENT> return self.NAME <NEW_LINE> <DEDENT> return 'unknown thread' | Returns a human-friendly description of the thread. | 625941ba0a50d4780f666d21 |
def _initialize(self, resource = None, id_query = False, reset = False, **keywargs): <NEW_LINE> <INDENT> super(toellner8840_50, self)._initialize(resource, id_query, reset, **keywargs) <NEW_LINE> if self._interface is not None: <NEW_LINE> <INDENT> if 'xonxoff' in self._interface.__dict__: <NEW_LINE> <INDENT> self._inte... | Opens an I/O session to the instrument. | 625941ba4428ac0f6e5ba684 |
def unsqueeze(input, axes, name=None): <NEW_LINE> <INDENT> helper = LayerHelper("unsqueeze", **locals()) <NEW_LINE> out = helper.create_variable_for_type_inference(dtype=input.dtype) <NEW_LINE> x_shape = helper.create_variable_for_type_inference(dtype=input.dtype) <NEW_LINE> helper.append_op( type="unsqueeze2", inputs=... | Insert single-dimensional entries to the shape of a tensor. Takes one
required argument axes, a list of dimensions that will be inserted.
Dimension indices in axes are as seen in the output tensor.
For example:
.. code-block:: text
Given a tensor such that tensor with shape [3, 4, 5],
then Unsqueezed tensor with... | 625941ba0fa83653e4656e4f |
def _do_delete(self, subject_id=None, object_id=None, predicate=None): <NEW_LINE> <INDENT> affected_rels = self._get_relationships_from_criteria(subject_id, object_id, predicate).all() <NEW_LINE> tables = [schema.ObjectFromSubject, schema.SubjectFromObject] <NEW_LINE> with BatchQuery() as batch: <NEW_LINE> <INDENT> for... | Given one or more criteria, delete all matching Relationships from the DAO's backend.
This does not affect records, data, etc. Only Relationships.
:raise ValueError: if no criteria are specified. | 625941baad47b63b2c509e1b |
def test_partial(partial_author): <NEW_LINE> <INDENT> assert partial_author.name == "John Doe" <NEW_LINE> assert partial_author.user.username == "[email protected]" | Test fixture partial specialization. | 625941ba30c21e258bdfa32d |
def default(self, obj): <NEW_LINE> <INDENT> if isinstance(obj, trans.app.model.HistoryDatasetAssociation): <NEW_LINE> <INDENT> rval = { "__HistoryDatasetAssociation__": True, "create_time": obj.create_time.__str__(), "update_time": obj.update_time.__str__(), "hid": obj.hid, "name": to_unicode(obj.name), "info": to_unic... | Encode an HDA, default encoding for everything else. | 625941ba8c0ade5d55d3e852 |
def iter_headers(self): <NEW_LINE> <INDENT> return self.headerlist | Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. | 625941bab5575c28eb68de90 |
def test_resources_attribute_is_not_list(self): <NEW_LINE> <INDENT> new_task = Task(**self.kwargs) <NEW_LINE> with pytest.raises(TypeError) as cm: <NEW_LINE> <INDENT> new_task.resources = "a resource" <NEW_LINE> <DEDENT> assert str(cm.value) == 'Incompatible collection type: str is not list-like' | testing if a TypeError will be raised when the resources attribute
is set to any other value then a list | 625941ba377c676e9127203d |
def load_config_from_file(self, config_path): <NEW_LINE> <INDENT> self._config_path = config_path <NEW_LINE> with open(r'{}'.format(self._config_path)) as file: <NEW_LINE> <INDENT> self._config = yaml.load(file, Loader=yaml.FullLoader) <NEW_LINE> <DEDENT> self._parse_params() <NEW_LINE> self._create_output_dirs() | Loads configuration from a file | 625941ba4f88993c3716bf06 |
def version_setter(self, new_version): <NEW_LINE> <INDENT> pass | You must implement this method in your class | 625941ba30bbd722463cbc55 |
def players_turn(): <NEW_LINE> <INDENT> return _gamestate.players_turn | This function returns True if it is the player's turn, Flase if its not. | 625941ba38b623060ff0ac81 |
def _import_record(self, record_id, **kwargs): <NEW_LINE> <INDENT> return super(SaleOrderBatchImport, self)._import_record( record_id, max_retries=0, priority=5) | Import the record directly | 625941baab23a570cc250012 |
def max(values): <NEW_LINE> <INDENT> return builtins.max(values) | Given a sequence of values, returns the greatest value in the
sequence, also known as the "max" value.
Returns NaN (Not a Number) if passed an empty sequence.
Args:
values: A Sequence of numerical values. Accepts both Integers
and Floats. The sequence may not contain None type values.
However, pas... | 625941ba8e7ae83300e4ae5e |
def findDuplicate3(self, nums): <NEW_LINE> <INDENT> slow = nums[0] <NEW_LINE> fast = nums[slow] <NEW_LINE> while fast != slow: <NEW_LINE> <INDENT> slow = nums[slow] <NEW_LINE> fast = nums[nums[fast]] <NEW_LINE> <DEDENT> fast = 0 <NEW_LINE> while fast != slow: <NEW_LINE> <INDENT> fast = nums[fast] <NEW_LINE> slow = nums... | :type nums: List[int]
:rtype: int | 625941ba6e29344779a624a8 |
def get_value(self, pos): <NEW_LINE> <INDENT> x, y = pos <NEW_LINE> return self.matrix[x][y] | 给出矩阵特定位置的值
:param pos: [x, y]
:return: [a, b, cn],其中,a表示格子产出,b表示各自是否有个体占据,cn定义同上 | 625941ba26068e7796caeb6c |
def create(self, transaction, prec, succs=(), flag=0, parents=None, date=None, metadata=None): <NEW_LINE> <INDENT> if metadata is None: <NEW_LINE> <INDENT> metadata = {} <NEW_LINE> <DEDENT> if date is None: <NEW_LINE> <INDENT> if 'date' in metadata: <NEW_LINE> <INDENT> date = util.parsedate(metadata.pop('date')) <NEW_L... | obsolete: add a new obsolete marker
* ensuring it is hashable
* check mandatory metadata
* encode metadata
If you are a human writing code creating marker you want to use the
`createmarkers` function in this module instead.
return True if a new marker have been added, False if the markers
already existed (no op). | 625941bafff4ab517eb2f2cc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.