code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def counting_sort(array, max_value): <NEW_LINE> <INDENT> b = [0] * len(array) <NEW_LINE> count_array = [0] * (max_value + 1) <NEW_LINE> count_occurences(array, count_array) <NEW_LINE> for i in range(len(array) - 1, -1, -1): <NEW_LINE> <INDENT> b[count_array[array[i]] - 1] = array[i] <NEW_LINE> count_array[array[i]] -= ...
:param array: Iterable of elements :param max_value: Maximum value in array :return: Sorted array
625941c915fb5d323cde0b9d
def betterEvaluationFunction(currentGameState): <NEW_LINE> <INDENT> new_Pos = currentGameState.getPacmanPosition() <NEW_LINE> new_Food = currentGameState.getFood() <NEW_LINE> new_Ghost_States = currentGameState.getGhostStates() <NEW_LINE> legalMoves = currentGameState.getLegalActions() <NEW_LINE> new_Scared_Times = [gh...
Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> 1. Die, Mahdis to ghost == 0 2. Food, i. Get food succ in food is True ii. Nearby food 2*2 grid from succ iii. Di...
625941c9442bda511e8be4a8
def image(url, alt, width=None, height=None, path=None, use_pil=False, **attrs): <NEW_LINE> <INDENT> if not alt: <NEW_LINE> <INDENT> alt = "" <NEW_LINE> <DEDENT> if width is not None or height is not None: <NEW_LINE> <INDENT> attrs['width'] = width <NEW_LINE> attrs['height'] = height <NEW_LINE> if path: <NEW_LINE> <IND...
Return an image tag for the specified ``source``. ``url`` The URL of the image. (This must be the exact URL desired. A previous version of this helper added magic prefixes; this is no longer the case.) ``alt`` The img's alt tag. Non-graphical browsers and screen readers will output this instead ...
625941c90a50d4780f666f20
def delete_challenge_tasks(self, challenge_id, status_filters=""): <NEW_LINE> <INDENT> query_params = { "statusFilters": str(status_filters) } <NEW_LINE> response = self.delete( endpoint=f"/challenge/{challenge_id}/tasks", params=query_params ) <NEW_LINE> return response
Method to delete all existing tasks within a challenge, optionally filtering on current task status :param challenge_id: the ID corresponding to the challenge :param status_filters: a comma separate list of status ID's: 0 = Created, 1 = Fixed, 2 = False Positive, 3 = Skipped, 4 = Deleted, 5 = Already Fixed, 6 = To...
625941c9711fe17d825423fb
def flush(self, lsn): <NEW_LINE> <INDENT> if lsn >= self.__current_lsn(): <NEW_LINE> <INDENT> self.__flush()
Ensures that the log records corresponding to the specified LSN has been written to disk. All earlier log records will also be written to disk. :param lsn: the LSN of a log record
625941c9ab23a570cc250211
def _createModuleObj(self): <NEW_LINE> <INDENT> raise NotImplementedError("Implement in child class.")
Create handle to corresponding C++ object.
625941c93317a56b86939ce8
def _get_feed_dict(self, iteration, batch): <NEW_LINE> <INDENT> obv_actor = self._duplicate_observations(batch['observations'], 1) <NEW_LINE> log_integral_pi_q = self._calc_log_integral_pi_q_bounded(obv_actor) <NEW_LINE> feed_dict = { self._observations_critic_ph: batch['observations'], self._observations_actor_ph: obv...
Construct TensorFlow feed_dict from sample batch.
625941c94f6381625f114aca
def get_groups(server): <NEW_LINE> <INDENT> return RequestData( service_url= API_URL.format(server, 'group'), data={} )
GET request for retrieving all groups that are visiable to the auth user.
625941c9be7bc26dc91cd690
def __init__(self, zuora_settings): <NEW_LINE> <INDENT> self.username = zuora_settings["username"] <NEW_LINE> self.password = zuora_settings["password"] <NEW_LINE> self.wsdl_file = zuora_settings["wsdl_file"] <NEW_LINE> self.base_dir = path.dirname(__file__) <NEW_LINE> self.authorize_gateway = zuora_settings.get("gatew...
Usage example: Required dictionary settings for zuora client: username : str : username for logging into Zuora password : str : password for logging into Zuora wsdl_file : str : path to local wsdl file used for suds library Optional dictionary settings: gateway_name : str : The name of the gateway used for payment ...
625941c926238365f5f0eefc
def displayer(location, dimension): <NEW_LINE> <INDENT> self.plot(location, dimension) <NEW_LINE> display(self.fig)
Update and display the plot with given arguments
625941c9dd821e528d63b238
def _pivot_relations(relset, keymap, db): <NEW_LINE> <INDENT> edges = [] <NEW_LINE> nodes = set() <NEW_LINE> def add_edges(keys): <NEW_LINE> <INDENT> for i in range(len(keys) - 1): <NEW_LINE> <INDENT> for j in range(i + 1, len(keys)): <NEW_LINE> <INDENT> edges.append((keys[i], keys[j])) <NEW_LINE> <DEDENT> <DEDENT> <DE...
Search to find a relation that can join two disjoint relations. Note: If disjoint relation sets cannot be conjoined with a single other relation, a TSQLError is raised.
625941c921a7993f00bc7d7d
def make_tuple(*pobjects, **options): <NEW_LINE> <INDENT> for pobj in pobjects: <NEW_LINE> <INDENT> assert isinstance(pobj, pobject.PObject) <NEW_LINE> <DEDENT> result = cartesian.cartesian(*pobjects, **options) <NEW_LINE> return pobject.PObject(result.node(), result.pipeline())
make tuple of pobjects
625941c9fbf16365ca6f6252
def store(self): <NEW_LINE> <INDENT> if self._loading: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> chain = self.chainbuilder.primary_block_chain <NEW_LINE> trans = self.chainbuilder.unconfirmed_transactions.copy() <NEW_LINE> peers = [list(peer.peer_addr) for peer in self.proto.peers if peer.is_connected and peer.pee...
Asynchronously stores current data to disk. Used as an event handler in the chainbuilder.
625941c94d74a7450ccd4253
def peel_raster(raster, catchment_mask): <NEW_LINE> <INDENT> conv_double = np.array([[0,1,1,1,0], [1,1,1,1,1], [1,1,0,1,1], [1,1,1,1,1], [0,1,1,1,0]]) <NEW_LINE> bound_double = scipy.signal.convolve2d(catchment_mask, conv_double, boundary='fill', fillvalue=False) <NEW_LINE> peeling_mask = np.ones(shape=catchment_mask.s...
Given a raster and a mask, gets the "peeling" or "shell" of the raster. (Peeling here are points within the raster) Input: - raster: 2dimensional nparray. Raster to be peeled. The peeling is part of the raster. - catchment_mask: 2dim nparray of same size as raster. This is the fruit in the peeling. Output: ...
625941c9d164cc6175782ddc
def _rss_start(self, bot, trigger, c): <NEW_LINE> <INDENT> bot.reply("Okay, I'll start fetching RSS feeds..." if not self.running else "Continuing to fetch RSS feeds.") <NEW_LINE> LOGGER.debug("RSS started.") <NEW_LINE> self.running = True
Start fetching feeds. Usage: !rss start
625941c991af0d3eaac9baa7
def sumListsForward(list1, list2): <NEW_LINE> <INDENT> padListZeroes(list1, list2) <NEW_LINE> ll = LinkedList.LinkedList() <NEW_LINE> sumListsForwardHelper(list1.head, list2.head, ll) <NEW_LINE> return ll
Recursive solution to forward variant of sum lists problem
625941c92c8b7c6e89b35850
def index_document(self, document): <NEW_LINE> <INDENT> from .models import Index <NEW_LINE> with transaction.atomic(): <NEW_LINE> <INDENT> self.remove_document(document) <NEW_LINE> for index in Index.objects.filter(enabled=True, document_types=document.document_type): <NEW_LINE> <INDENT> root_instance, created = self....
Update or create all the index instances related to a document
625941c97b25080760e394e8
def viewers_at_minimum(self): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if self._by_tid: <NEW_LINE> <INDENT> return self._by_tid.values()[0] <NEW_LINE> <DEDENT> return ()
Return all the viewers viewing the ``minimum_highest_visible_tid``. If that is None, this is the empty set.
625941c9b830903b967e999a
def shutdown(self, wait=True, shutdown_threadpool=True, close_jobstores=True): <NEW_LINE> <INDENT> if not self.running: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._stopped = True <NEW_LINE> self._wakeup.set() <NEW_LINE> if shutdown_threadpool: <NEW_LINE> <INDENT> self._threadpool.shutdown(wait) <NEW_LINE> <DED...
Shuts down the scheduler and terminates the thread. Does not interrupt any currently running jobs. :param wait: ``True`` to wait until all currently executing jobs have finished (if ``shutdown_threadpool`` is also ``True``) :param shutdown_threadpool: ``True`` to shut down the thread pool :param close_job...
625941c9460517430c394215
def make_matrix(num_rows, num_cols, entry_fn): <NEW_LINE> <INDENT> new_matrix = [[entry_fn(i, j) for j in range(num_cols)] for i in range(num_rows)] <NEW_LINE> valid_matrix, problems = valid.is_matrix(new_matrix) <NEW_LINE> if not valid_matrix: <NEW_LINE> <INDENT> raise IndexError(" ".join(problems)) <NEW_LINE> <DEDENT...
Create a matrix with num_rows rows and num_cols cols and populate the values of the matrix using entry_fn. Args: num_rows (Int): The number of rows in the output matrix. num_cols (Int): The number of columns in the output matrix. entry_fn (Function): A function to generate the values in the matrix. Return...
625941c926068e7796caed6d
def _progress_callback(self, size: float, speed: float, perc: float): <NEW_LINE> <INDENT> to_screen( f"\rSize: {to_MB(size)} MB Downloaded: {perc}% -- Speed: {speed} MB/s " ) <NEW_LINE> sys.stdout.flush()
Called Everytime the request receives a chunk of data and updates the screen Args: size (float): Current downloaded file size speed (float): Calculated speed of the download perc (float): Download Percentage
625941c99f2886367277a91c
def _parse(filename, regex=None): <NEW_LINE> <INDENT> if regex == None: <NEW_LINE> <INDENT> regex = re.compile(r"(\w+): (\w+)$", flags=re.MULTILINE) <NEW_LINE> <DEDENT> known = {} <NEW_LINE> with open(os.path.join(_self_path, filename)) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> m = regex.match(line) ...
Return a dict of known serial numbers : variable names (or specify)
625941c9be383301e01b5516
def check_protection(self, context, prep_info, target_attr=None): <NEW_LINE> <INDENT> if 'is_admin' in context and context['is_admin']: <NEW_LINE> <INDENT> LOG.warning(_('RBAC: Bypassing authorization')) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = 'identity:%s' % prep_info['f_name'] <NEW_LINE> creds = _build...
Provide call protection for complex target attributes. As well as including the standard parameters from the original API call (which is passed in prep_info), this call will add in any additional entities or attributes (passed in target_attr), so that they can be referenced by policy rules.
625941c963f4b57ef00011aa
def enabled(request): <NEW_LINE> <INDENT> return bool(settings.MDN_CONTRIBUTION)
Return True if contributions are enabled.
625941c966656f66f7cbc239
def execute_sql_script(self, sqlScriptFileName): <NEW_LINE> <INDENT> sqlScriptFile = open(sqlScriptFileName) <NEW_LINE> cur = None <NEW_LINE> try: <NEW_LINE> <INDENT> cur = self._dbconnection.cursor() <NEW_LINE> sqlStatement = '' <NEW_LINE> for line in sqlScriptFile: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> i...
Executes the content of the `sqlScriptFileName` as SQL commands. Useful for setting the database to a known state before running your tests, or clearing out your test data after running each a test. Sample usage : | Execute Sql Script | ${EXECDIR}${/}resources${/}DDL-setup.sql | | Execute Sql Script |...
625941c9be8e80087fb20cd3
def _make_zip_release(commit_date: object, filepath: str) -> None: <NEW_LINE> <INDENT> path = os.path.dirname(filepath) <NEW_LINE> if not os.path.exists(path): <NEW_LINE> <INDENT> os.makedirs(path) <NEW_LINE> <DEDENT> zip_file = zipfile.ZipFile(filepath, 'w', zipfile.ZIP_DEFLATED) <NEW_LINE> print("Adding files to ZIP ...
This routine handles copying files specified in FILE_LIST into a ZIP-file. Parameters ---------- commit_date: object The date of the commit the release is based on. This is only used to help notify the user of potentially stale library files. filepath : str Filename and path indicating where to write the Z...
625941c9bf627c535bc1325e
def jellyFor(self, jellier): <NEW_LINE> <INDENT> return "remote", jellier.invoker.registerReference(self)
(internal) Return a tuple which will be used as the s-expression to serialize this to a peer.
625941c9b830903b967e999b
def store_exposure_times(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.magnified["ExpTimes"] = self.norm_grp["ExpTimes"].value <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("\nExposure Times could NOT be extracted.\n")
Retrieving important data from Exposure Times
625941c94527f215b584c4e7
@login_required <NEW_LINE> def exam(request, exam_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exam = Exam.objects.get(pk=exam_id) <NEW_LINE> <DEDENT> except Exam.DoesNotExist: <NEW_LINE> <INDENT> raise Http404("This exam doesn't exist.") <NEW_LINE> <DEDENT> return render(request, 'exams/show.html', {'exam': exam}...
Show an exam details.
625941c901c39578d7e74eca
def field2property(spec: APISpec, field: fields.Field): <NEW_LINE> <INDENT> plugin = get_marshmallow_plugin(spec) <NEW_LINE> return plugin.converter.field2property(field)
Convert a marshmallow Field to OpenAPI dictionary We require an initialised APISpec object to use its converter function - in particular, this will depend on the OpenAPI version defined in `spec`. We also rely on the spec having a `MarshmallowPlugin` attached.
625941c9d58c6744b4257cef
def display_bar(self): <NEW_LINE> <INDENT> self.generate_text() <NEW_LINE> self.window_surface.blit(self.image, self.rect)
Display the information bar
625941c9d4950a0f3b08c3df
def parse(self, contents): <NEW_LINE> <INDENT> pass
Virtual method, parse DAT file contents.
625941c9d4950a0f3b08c3de
def test_status_code(self): <NEW_LINE> <INDENT> self.assertEquals(self.response.status_code, 200)
An invalid form sub should return to the same page
625941c97d847024c06be34a
def plot_basic_hist(samples, file_type, **plot_args): <NEW_LINE> <INDENT> sumy = sum([int(samples[sample]['data'][x][0]) for sample in samples for x in samples[sample]['data']]) <NEW_LINE> cutoff = sumy * 0.999 <NEW_LINE> all_x = set() <NEW_LINE> for item in sorted(chain(*[samples[sample]['data'].items() for sample in ...
Create line graph plot for basic histogram data for 'file_type'. The 'samples' parameter could be from the bbmap mod_data dictionary: samples = bbmap.MultiqcModule.mod_data[file_type]
625941c9baa26c4b54cb11af
def active(self, json): <NEW_LINE> <INDENT> self.send_active(json) <NEW_LINE> return self.recv_active()
Parameters: - json
625941c9460517430c394216
def get_max_it(x_max, wave_number_k=np.abs(WAVE_NUMBER)): <NEW_LINE> <INDENT> if np.isnan(x_max): <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> return int(np.ceil(wave_number_k * x_max + np.longdouble(4.05) * pow(wave_number_k * x_max, 1/3)) + 2)
Calculates stop iteration number
625941c9d8ef3951e32435cc
def test_showres_showres_2(): <NEW_LINE> <INDENT> args = """-x""" <NEW_LINE> exp_rs = 0 <NEW_LINE> user = pwd.getpwuid(os.getuid())[0] <NEW_LINE> _args = args.replace('<USER>',user) <NEW_LINE> results = testutils.run_cmd('showres.py',_args,None) <NEW_LINE> rs = results[0] <NEW_LINE> cmd_out = results[...
showres test run: showres_2 Command Output: Reservation Queue User Start Duration End Time Cycle Time Passthrough Partitions Project ResID CycleID Time Remaining ==================================================================...
625941c9462c4b4f79d1d760
def value(self, runde): <NEW_LINE> <INDENT> return self.lastValue - 10
Der Wert, den wir in Runde n als Preis nutzen.
625941c96aa9bd52df036e33
def testAmbiguousAlias(self): <NEW_LINE> <INDENT> sheet = self.doc.addObject("Spreadsheet::Sheet","Calc") <NEW_LINE> sheet.setAlias("A1","Test") <NEW_LINE> try: <NEW_LINE> <INDENT> sheet.setAlias("A2","Test") <NEW_LINE> self.fail("An ambiguous alias was set which shouldn't be allowed") <NEW_LINE> <DEDENT> except: <NEW_...
Try to set the same alias twice (bug #2402)
625941c97047854f462a149a
def dashboard_webinar_participants_qos(self, webinar_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.dashboard_webinar_participants_qos_with_http_info(webinar_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (da...
List Webinar Participant QOS # noqa: E501 Retrieve a list of participants from live or past webinars and the quality of service they received.<br>This data indicates the connection quality for sending/receiving video, audio, and shared content. If nothing is being sent or received at that time, no information will be...
625941c907f4c71912b11511
def Pai_DFS(Grafo,v,o): <NEW_LINE> <INDENT> with open("DFS.txt","r") as arvGer: <NEW_LINE> <INDENT> next(arvGer) <NEW_LINE> vertice = 1 <NEW_LINE> for linha in arvGer: <NEW_LINE> <INDENT> if vertice == v: <NEW_LINE> <INDENT> return int(linha.split()[0]) <NEW_LINE> <DEDENT> vertice += 1
Retorna o pai[v] na arvore induzida pela DFS quando iniciada no vertice 'o'.
625941c9b7558d58953c4fa5
def set_bootloader_mode(self, mode): <NEW_LINE> <INDENT> self.check_validity() <NEW_LINE> mode = int(mode) <NEW_LINE> return self.ipcon.send_request(self, BrickletEPaper296x128.FUNCTION_SET_BOOTLOADER_MODE, (mode,), 'B', 9, 'B')
Sets the bootloader mode and returns the status after the requested mode change was instigated. You can change from bootloader mode to firmware mode and vice versa. A change from bootloader mode to firmware mode will only take place if the entry function, device identifier and CRC are present and correct. This functi...
625941c95fc7496912cc3a0d
def import_various(context): <NEW_LINE> <INDENT> if context.readDataFile('agsci.atlas.marker.txt') is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> logger = context.getLogger('agsci.atlas') <NEW_LINE> site = context.getSite() <NEW_LINE> add_catalog_indexes(site, logger) <NEW_LINE> create_registry_keys(site, logg...
Import step for configuration that is not handled in xml files.
625941c9cb5e8a47e48b7b3a
def set_stroke_style(self, style): <NEW_LINE> <INDENT> self.client.send_si(self.handle, "setIndexOfStrokeStyle("+b2str(style)+")")
Set the stroke style of lines for the item. This is equivalent to setting the index of Apperance>Stroke>Style within a view item dialog in kst:: 0: SolidLine 1: DashLine 2: DotLine 3: DashDotLine 4: DashDotDotLine 5: CustomDashLine
625941c901c39578d7e74ecb
def __str__(self): <NEW_LINE> <INDENT> return json.dumps(self._to_dict(), indent=2)
Return a `str` version of this QueryResultResultMetadata object.
625941c950812a4eaa59c3b2
def update(self, state): <NEW_LINE> <INDENT> pass
Do nothing
625941c9498bea3a759b9b3e
def make_hazard(self, **kwargs): <NEW_LINE> <INDENT> pmf = self.make_pmf() <NEW_LINE> at_risk = self + pmf <NEW_LINE> haz = Hazard(pmf / at_risk, **kwargs) <NEW_LINE> haz.total = getattr(self, 'total', 1.0) <NEW_LINE> haz.name = self.name <NEW_LINE> return haz
Make a Hazard from the Surv. :return: Hazard
625941c9a8370b771705292f
def getCopyRef(self): <NEW_LINE> <INDENT> return self.base.get("copy_ref", [])
a reference to the copy
625941c966673b3332b92120
def immediate(self): <NEW_LINE> <INDENT> return lib.zsock_immediate(self._as_parameter_)
Get socket option `immediate`.
625941c91d351010ab855bab
def create_app(): <NEW_LINE> <INDENT> app = Flask('pikka_bird_server') <NEW_LINE> app.debug = (os.environ['LOG_LEVEL'] == 'DEBUG') <NEW_LINE> for r in [ 'collections', 'statics']: <NEW_LINE> <INDENT> app.register_blueprint( getattr(getattr(pikka_bird_server.routes, r), r)) <NEW_LINE> <DEDENT> for code in default_except...
Create application, using Flask. Payloads are in JSON.
625941c9097d151d1a222eea
def subscribe_eventgroup( self, eventgroup: someip.config.Eventgroup, endpoint: _T_SOCKADDR ) -> None: <NEW_LINE> <INDENT> self.subscribeentries.append((eventgroup, endpoint)) <NEW_LINE> if self.alive: <NEW_LINE> <INDENT> asyncio.get_event_loop().call_soon( self._send_start_subscribe, endpoint, [eventgroup] )
eventgroup: someip.config.Eventgroup that describes the eventgroup to subscribe to and the local endpoint that accepts the notifications endpoint: remote SD endpoint that will receive the subscription messages
625941c9099cdd3c635f0cea
def irfft3d(input, fft_length, Treal=_dtypes.float32, name=None): <NEW_LINE> <INDENT> _ctx = _context._context or _context.context() <NEW_LINE> tld = _ctx._thread_local_data <NEW_LINE> if tld.is_eager: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _result = pywrap_tfe.TFE_Py_FastPathExecute( _ctx._context_handle, tld.de...
Inverse 3D real-valued fast Fourier transform. Computes the inverse 3-dimensional discrete Fourier transform of a real-valued signal over the inner-most 3 dimensions of `input`. The inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`: The inner-most dimension contains the `fft_length / 2 + 1` ...
625941c994891a1f4081bb39
def getHlim(self, MinDistancesMap, percentile, T, n_traces): <NEW_LINE> <INDENT> De = np.percentile(MinDistancesMap, percentile, axis=1).tolist() <NEW_LINE> Dr = self.getDr(T) <NEW_LINE> Hlim = [] <NEW_LINE> for i in range(len(Dr)): <NEW_LINE> <INDENT> if Dr[i] > De[i]: <NEW_LINE> <INDENT> Hlim.append((De[i] + (Dr[i] -...
Return Hlim. the limit distances in the m dimensions from which traces quickly decrease their effect on the state space
625941c967a9b606de4a7f4a
def list_tags_for_resource(ResourceArn=None): <NEW_LINE> <INDENT> pass
Retrieve a list of the tags (keys and values) that are associated with a specified resource. A tag is a label that you optionally define and associate with a resource. Each tag consists of a required tag key and an optional associated tag value . A tag key is a general label that acts as a category for more specifi...
625941c96e29344779a626a2
@pytest.fixture(scope='function') <NEW_LINE> def routeapp(request, testapp): <NEW_LINE> <INDENT> url, url2, url3, url4 = '/lorem', '/life', '/world', '/echo' <NEW_LINE> testapp.routes = [url, url2, url3, url4] <NEW_LINE> @testapp.route(url, methods=['GET']) <NEW_LINE> def lorem(): <NEW_LINE> <INDENT> return jsonify(tit...
Returns Flask app with established app context and registered routes.
625941c921a7993f00bc7d7e
def recognize(self, frame): <NEW_LINE> <INDENT> _, res = ai.recognize(frame) <NEW_LINE> print('recognize result:', res) <NEW_LINE> if res in _wakeup_words: <NEW_LINE> <INDENT> pivot.emit('angelia:wakeup')
recognize
625941c991af0d3eaac9baa8
def write_preds_to_file(embeddings_dict, classfier, outfile_name): <NEW_LINE> <INDENT> results_dir = save_results_to_dir + '/predictions/' <NEW_LINE> create_dir_if_not_exists(results_dir) <NEW_LINE> xs, ys, ys_pred = get_xs_ys_predictions(embeddings_dict, classfier) <NEW_LINE> with open('%s%s' % (results_dir, outfile_n...
Write predictions made by 'classifier' and gold standard labels to file. Files can be used for further processing -- e.g. to compare predictions made by different classifiers.
625941c9167d2b6e31218c26
def make_gen(size, vector, start=0, length=1): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> len(vector) <NEW_LINE> end = start + size <NEW_LINE> if length > 1: <NEW_LINE> <INDENT> return (vector [i:i+length] for i in range(start, end)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (vector[i] for i in range(start...
Return a generator that is either a sliding slice of vector if length > 1 or a value if length = 1 or a repeated constant
625941c963b5f9789fde7175
def local_to_world(self, point): <NEW_LINE> <INDENT> pass
Return the position of point relative to the body in world space.
625941c9baa26c4b54cb11b0
def fermat_spiral(a,n): <NEW_LINE> <INDENT> dmax = 2*a*np.sqrt( n / np.pi ) <NEW_LINE> print( "Generating Fermat spiral with dmax: " + str(dmax) ) <NEW_LINE> c = 0.5*dmax/np.sqrt(n) <NEW_LINE> vr,vt = [],[] <NEW_LINE> t = 0.4 <NEW_LINE> goldenAngle = np.pi*(3-np.sqrt(5)) <NEW_LINE> while t < n: <NEW_LINE> <INDENT> vr.a...
Creates a Fermat spiral with n points distributed in a circular area with diamter<= dmax. Returns the x,y coordinates of the spiral points. The average distance between points can be roughly estimated as 0.5*dmax/(sqrt(n/pi)) RAM comment: setting it to an overlap distance would be more helpful, so that the input par...
625941c95f7d997b87174b27
def specify_stack(self, stack): <NEW_LINE> <INDENT> self.stack = stack
Specify the stack this task belongs to
625941c9a8ecb033257d315d
def min(self): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise Empty("Priority queue is empty.") <NEW_LINE> <DEDENT> pos = self._data.first() <NEW_LINE> item = pos.element() <NEW_LINE> return (item._key, item._value)
Return but don't remove (k, v) tuple with minimum key.
625941c930dc7b76659019f7
def timer_clear (self, xmpp_message, room, nick, args): <NEW_LINE> <INDENT> atname = self.bot.api.user_nick2at(nick) <NEW_LINE> if not self.timers.has_key(nick) or not self.timers[nick]: <NEW_LINE> <INDENT> return "%s%s has no active timers." % (EMOTICON, atname) <NEW_LINE> <DEDENT> room_id, expiration, message = self....
Clear the last set timer for the user. Usage: .clear_timer
625941c929b78933be1e573d
def __repr__(self): <NEW_LINE> <INDENT> return "<ToDoItem {}, {}>".format(self.title, self.duedate.strftime('%Y/%m/%d %H:%M'))
ToDo項目の表示形式文字列を作る
625941c99b70327d1c4e0e64
def split(file, n): <NEW_LINE> <INDENT> with open(file, mode="r", encoding="utf8") as read_file: <NEW_LINE> <INDENT> total_line = 0 <NEW_LINE> for line in read_file: <NEW_LINE> <INDENT> total_line += 1 <NEW_LINE> <DEDENT> line_count = math.ceil(total_line / n) <NEW_LINE> name, ext = os.path.splitext(os.path.basename(fi...
指定したファイルを行単位でN分割する :param str file: 対象ファイルパス :param int n: 分割数
625941c9f8510a7c17cf978c
@counselor.route('/_update_editor_contents', methods=['POST']) <NEW_LINE> @login_required <NEW_LINE> @counselor_required <NEW_LINE> def update_editor_contents(): <NEW_LINE> <INDENT> edit_data = request.form.get('edit_data') <NEW_LINE> editor_name = request.form.get('editor_name') <NEW_LINE> editor_contents = EditableHT...
Update the contents of an editor.
625941c95510c4643540f476
def graph_intersect(self, other_graph): <NEW_LINE> <INDENT> for node in self.nodes.values(): <NEW_LINE> <INDENT> if not other_graph.find_node("id", node.id): <NEW_LINE> <INDENT> self.del_node(node.id) <NEW_LINE> <DEDENT> <DEDENT> for edge in self.edges.values(): <NEW_LINE> <INDENT> if not other_graph.find_edge("id", ed...
:param other_graph: :return:
625941c93c8af77a43ae3830
def num_trees_with_degrees(arr): <NEW_LINE> <INDENT> return
The number of labeled trees with vertices of the degree [d1, d2, ..., dn] https://www.coursera.org/learn/teoriya-grafov/lecture/fX8HH/dieriev-ia-s-zadannoi-posliedovatiel-nost-iu-stiepieniei rac{(n-2)!}{\prod_{i=1}^{n}(d_i-1)!} if the vertex has degree D, it is clear that it will appear D-1 times in a pruffer code. S...
625941c95fcc89381b1e174e
def operations(self,color): <NEW_LINE> <INDENT> command = '' <NEW_LINE> direction=self.direction <NEW_LINE> color_c = (-2*color[0] + 3*color[1] + color[2])%11 <NEW_LINE> bf = '><+-.,[]' <NEW_LINE> if color_c < 8: <NEW_LINE> <INDENT> command = bf[color_c] <NEW_LINE> <DEDENT> if color_c == 8: <NEW_LINE> <INDENT> directio...
Interprets BrainCopter code.
625941c9fbf16365ca6f6253
def nginx_user(): <NEW_LINE> <INDENT> return 'www-data'
Returns the correct apache user for the environment
625941c9507cdc57c6306d69
def inputMemberDefaultPassword(self): <NEW_LINE> <INDENT> logger.info("Input 默认密码 begin") <NEW_LINE> API().inputStringByResourceId(self.testcase, self.driver, self.logger, DLPC.resource_id_pass_word, DLPC.member_password, DLPC.assert_timeout) <NEW_LINE> logger.info("Input 默认密码 end")
usage: 输入默认密码
625941c94a966d76dd55109f
def json_zip2str(json_data): <NEW_LINE> <INDENT> return base64.b64encode( zlib.compress( json.dumps(json_data).encode('utf-8') ) ).decode('ascii')
Return a string of compressed JSON data, suitable for transmission back to a client.
625941c9442bda511e8be4a9
def loadData(self, name="dataset"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.dataQuantification = "-".join(name.split("-")[1:]) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> print("数据集需要数据量化方式") <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> path = os.path.join(dataset, "DeepLearningDateSet", name) <NEW_L...
3个数据集:训练集60%,交叉验证集合20%,测试集20% :param name: :return:
625941c9ff9c53063f47c284
def remove(self, event, subscriber): <NEW_LINE> <INDENT> subs = self._subscribers <NEW_LINE> if event not in subs: <NEW_LINE> <INDENT> raise ValueError('No subscribers: %r' % event) <NEW_LINE> <DEDENT> subs[event].remove(subscriber)
Remove a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be removed.
625941c9287bf620b61d3af4
def some(): <NEW_LINE> <INDENT> full = A + B <NEW_LINE> for one in full: <NEW_LINE> <INDENT> yield one
:rtype: generator
625941c976e4537e8c351702
def nextFilename(self, num): <NEW_LINE> <INDENT> fTempl = "frame{0:04d}.jpg" <NEW_LINE> fileName = fTempl.format(num) <NEW_LINE> return fileName
This function is a helper function for the writeData() function. It gives writeData() the next file name.
625941c982261d6c526ab52e
def load(fileName): <NEW_LINE> <INDENT> return load_stream(open(fileName))
Loads an SVG image from a file.
625941c90a366e3fb873e8aa
def plot_loss(self): <NEW_LINE> <INDENT> plt.subplot(2, 2, 1) <NEW_LINE> plt.plot(self.winrates, label="winrate") <NEW_LINE> plt.xlabel("n") <NEW_LINE> plt.ylabel("winrate") <NEW_LINE> plt.legend() <NEW_LINE> plt.subplot(2, 2, 2) <NEW_LINE> plt.plot(- np.diff(np.array(self.winrates)), label="gain") <NEW_LINE> plt.xlabe...
display winrate evolution
625941c9090684286d50ed75
def rmse(self, y_pred, t): <NEW_LINE> <INDENT> fct_t = np.concatenate((self.t0[:, np.newaxis], self.t1[:, np.newaxis]), 1)[range(len(self.t0)), self.a[:, 0]] <NEW_LINE> cfct_t = np.concatenate((self.t0[:, np.newaxis], self.t1[:, np.newaxis]), 1)[range(len(self.t0)), 1-self.a[:, 0]] <NEW_LINE> fct_idx = (2*self.a[:, 0] ...
rmse of all intervention values, which include factual values
625941c93539df3088e2e3db
def undetermine(self, event): <NEW_LINE> <INDENT> option_id = event.GetId() <NEW_LINE> self.parent.undetermine_grid(option_id) <NEW_LINE> cell_id = option_id % 10 <NEW_LINE> self.undetermine_cell(cell_id)
Colling undetermine functions
625941c96aa9bd52df036e34
def is_congruent_base(self, integer): <NEW_LINE> <INDENT> tmp_min, tmp_max = -(abs(integer) + 1), abs(integer) + 1 <NEW_LINE> return integer in self.get_congruent_bases(tmp_min, tmp_max)
Is true when `integer` is congruent to base in sieve. Otherwise false. :: >>> sieve = ResidueClass(3, 0) | ResidueClass(2, 0) >>> sieve.get_congruent_bases(6) [0, 2, 3, 4, 6] >>> sieve.is_congruent_base(12) True Otherwise false: :: >>> sieve.is_congruent_base...
625941c955399d3f05588744
def errorlist(self, name): <NEW_LINE> <INDENT> name = self._get_name(name) <NEW_LINE> errors = self.errors_for(name) <NEW_LINE> if not errors: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> content = "\n".join(HTML.tag("li", error) for error in errors) <NEW_LINE> return HTML.tag("ul", tags.literal(content), class_='...
Return a list of errors for the given field as a ``ul`` tag.
625941c9ab23a570cc250212
@fn(BUILTINS, "h") <NEW_LINE> def heading(): <NEW_LINE> <INDENT> FN_TYPE = type_parser.parse_fn("(λ ...inline . block)") <NEW_LINE> def from_int(n: e.Integer): <NEW_LINE> <INDENT> def from_inline(*args): <NEW_LINE> <INDENT> return e.BlockTag(f"h{n.value}", "", args) <NEW_LINE> <DEDENT> return e.Function({FN_TYPE: from_...
Heading. Represents the %%(tt "<h1>..<h6>")%% HTML tags.
625941c9e8904600ed9f1fbc
@evaluator_method_cache() <NEW_LINE> def infer_param(execution_context, param): <NEW_LINE> <INDENT> annotation = param.annotation <NEW_LINE> if annotation is None: <NEW_LINE> <INDENT> all_params = [child for child in param.parent.children if child.type == 'param'] <NEW_LINE> node = param.parent.parent <NEW_LINE> commen...
Infers the type of a function parameter, using type annotations.
625941c96e29344779a626a3
def flow_has_out_port(flow, port, groups): <NEW_LINE> <INDENT> if port == ofp.OFPP_ANY or port == ofp.OFPP_ALL: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for inst in flow.flow_mod.instructions: <NEW_LINE> <INDENT> if inst.__class__ == instruction.instruction_write_actions or inst.__class__ == i...
Return boolean indicating if the flow has a set output port action for the given port. Assumes port is not OFPP_ANY. NOTE: All groups and all group buckets are searched, not just active buckets.
625941c924f1403a92600bf7
def register(self, job): <NEW_LINE> <INDENT> job = inspect.isclass(job) and job() or job <NEW_LINE> name = job.name <NEW_LINE> self[name] = job
Register a job in the job registry. The task will be automatically instantiated if not already an instance.
625941c97cff6e4e81117a16
def apply_driver_hacks(self, app, info, options): <NEW_LINE> <INDENT> if "convert_unicode" in options: <NEW_LINE> <INDENT> del options["convert_unicode"] <NEW_LINE> <DEDENT> super().apply_driver_hacks(app, info, options)
SQLAlchemy now gives SADeprecationWarnings for the "convert_unicode" parameter that Flask-SQLAlchemy injects. We avoid the warnings by not passing that parameter.
625941c907d97122c417891b
def mti(self): <NEW_LINE> <INDENT> return self.header() & 0b00000011
Description ----------- Returns bits 0 and 1 of the header They give the type of PDU message
625941c9fb3f5b602dac3723
def parametrize(metafunc, argnames, argvalues, *args, **kwargs): <NEW_LINE> <INDENT> kwargs.pop('selector') <NEW_LINE> if _param_check(metafunc, argnames, argvalues): <NEW_LINE> <INDENT> metafunc.parametrize(argnames, argvalues, *args, **kwargs) <NEW_LINE> <DEDENT> elif 'provider' in metafunc.fixturenames: <NEW_LINE> <...
parametrize wrapper that calls :py:func:`_param_check`, and only parametrizes when needed This can be used in any place where conditional parametrization is used.
625941c982261d6c526ab52f
def setup(self): <NEW_LINE> <INDENT> for i in range(0, 2, 1): <NEW_LINE> <INDENT> print('1: Human\n2: Super AI\n3: Better AI\n4: Best AI') <NEW_LINE> intAI = int(input('Enter AI Option: ')) <NEW_LINE> strName = '' <NEW_LINE> if i == 0: <NEW_LINE> <INDENT> if intAI == 1: <NEW_LINE> <INDENT> strName = 'Human' <NEW_LINE> ...
Setups player one and two
625941c9f7d966606f6aa094
def intersections_for(self, ix): <NEW_LINE> <INDENT> start, end = self.sphere_indexes_for(ix) <NEW_LINE> this_ixr = self.adj[start:end] <NEW_LINE> sphere_ix, inters_ix = np.where(this_ixr == True) <NEW_LINE> inters_inputs = np.array([self.sphere_to_input(x) for x in inters_ix]) <NEW_LINE> not_self_inters = np.where(int...
ix : (int) input index how to store this this:others sphere_this : sphere_others this : this_end : other : other_end Returns: --------- index of this sphere np.array(num_candidates) index of other input np.array(num_candidates) index of other sphere np.array(num_candidates)
625941c95e10d32532c5efb8
def tensorIntersect(ref, rem): <NEW_LINE> <INDENT> finalTensor = np.zeros(ref.shape[0]) <NEW_LINE> i = 1; <NEW_LINE> for j in range(ref.shape[0]): <NEW_LINE> <INDENT> found = 0; <NEW_LINE> for k in range(rem.shape[0]): <NEW_LINE> <INDENT> if (rem[k] == ref[j]): <NEW_LINE> <INDENT> found = 1 <NEW_LINE> <DEDENT> <DEDENT>...
Returns the intersection between two tensors
625941c94f6381625f114acb
def test_amenity_str_method(self): <NEW_LINE> <INDENT> amenity = Amenity() <NEW_LINE> amenity_str = amenity.__str__() <NEW_LINE> self.assertIsInstance(amenity_str, str) <NEW_LINE> self.assertEqual(amenity_str[:9], '[Amenity]') <NEW_LINE> self.assertEqual(amenity_str[10:48], '({})'.format(amenity.id)) <NEW_LINE> self.as...
Amenity str method creates accurate representation
625941c9a17c0f6771cbe0e1
def largestIsland(self, grid): <NEW_LINE> <INDENT> N = len(grid) <NEW_LINE> area = dict() <NEW_LINE> def dfs(r, c, index): <NEW_LINE> <INDENT> area = 0 <NEW_LINE> for dr, dc in ((1,0),(0,1),(-1,0),(0,-1)): <NEW_LINE> <INDENT> newR, newC = r+dr, c+dc <NEW_LINE> if 0<=newR<N and 0<=newC<N and grid[newR][newC] == 1: <NEW_...
:type grid: List[List[int]] :rtype: int
625941c90c0af96317bb8279
def to_dataflow_graph(self): <NEW_LINE> <INDENT> graph = DataflowGraph(self.identifier) <NEW_LINE> tasks = [] <NEW_LINE> channels = [] <NEW_LINE> for task in self.tasks: <NEW_LINE> <INDENT> task = DataflowProcess(task) <NEW_LINE> tasks.append(task) <NEW_LINE> <DEDENT> for key, properties in self.channels.items(): <NEW_...
Transfers the the tgff graph into a dataflow graph :returns: the equivalent dataflow graph representation :rtype: DataflowGraph
625941c9c4546d3d9de72ac4
def _trampoline(initial_state: FsmGenFunc, args, kwargs) -> FsmGen: <NEW_LINE> <INDENT> state_generator: FsmGen = initial_state(*args, **kwargs) <NEW_LINE> while True: <NEW_LINE> <INDENT> state_func, args, kwargs = (yield from state_generator) <NEW_LINE> if state_func is None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDE...
Tie multiple subgenerators into one generator that passes control between them. The trampoline generator starts by yielding from the first subgenerator; when that subgenerator is done, it `return`s the next generator function to yield from. This lets you write a multi-state process as multiple subgenerators, one per s...
625941c9a17c0f6771cbe0e2
def SetOutputVTKType(self, value): <NEW_LINE> <INDENT> if value not in Converter.MetaImageType_to_vtkType.values(): <NEW_LINE> <INDENT> raise ValueError("Unexpected Type: {}".format(value)) <NEW_LINE> <DEDENT> self._OutputVTKType = value
Sets the VTK type the produced vtkImageData will be. Parameters ---------- value: must be one of the values in this list: [vtk.VTK_SIGNED_CHAR,vtk.VTK_UNSIGNED_CHAR, vtk.VTK_SHORT, vtk.VTK_UNSIGNED_SHORT, vtk.VTK_INT, vtk.VTK_UNSIGNED_INT, vtk.VTK_FLOAT, vtk.VTK_DOUBLE]
625941c94e4d5625662d4469
def clearacc(irc, source, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> chanpair = args[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> error(irc, "Invalid arguments given. Needs 1: channel.") <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ircobj, channel = _get_channel_pair(irc, so...
<channel> Removes all Automode entries for the given channel.
625941c9460517430c394217
def list_inactive_vms(): <NEW_LINE> <INDENT> vmadm = _check_vmadm() <NEW_LINE> cmd = '{0} lookup state=stopped'.format(vmadm) <NEW_LINE> vms = [] <NEW_LINE> res = __salt__['cmd.run_all'](cmd) <NEW_LINE> retcode = res['retcode'] <NEW_LINE> if retcode != 0: <NEW_LINE> <INDENT> raise CommandExecutionError(_exit_status(ret...
Return a list of uuids for inactive virtual machine on the minion CLI Example:: salt '*' virt.list_inactive_vms
625941c997e22403b379d02a
def plot_algo(algo, dataset_id, title, algo_args=[]): <NEW_LINE> <INDENT> pl.title(title) <NEW_LINE> result = algo(npoints[dataset_id], *algo_args) <NEW_LINE> pl.plot(zip(*result)[0], zip(*result)[1], 'o-') <NEW_LINE> return pl
Plots a line simplification algorithm. :param algo: algorithm to plot :type algo: function :param dataset_ids: list of datasets to plot :type dataset_ids: list of integers :param title: title of the plot :type title: string :param algo_args: arguments to pass to the algorithm :type algo_args: list of arguments
625941c9a05bb46b383ec8b3