_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q12500
rfftn
train
def rfftn(a, s=None, axes=None, norm=None): """ Compute the N-dimensional discrete Fourier Transform for real input. This function computes the N-dimensional discrete Fourier Transform over any number of axes in an M-dimensional real array by means of the Fast Fourier Transform (FFT). By default, ...
python
{ "resource": "" }
q12501
rfft2
train
def rfft2(a, s=None, axes=(-2, -1), norm=None): """ Compute the 2-dimensional FFT of a real array. Parameters ---------- a : array Input array, taken to be real. s : sequence of ints, optional Shape of the FFT. axes : sequence of ints, optional Axes over which to com...
python
{ "resource": "" }
q12502
irfftn
train
def irfftn(a, s=None, axes=None, norm=None): """ Compute the inverse of the N-dimensional FFT of real input. This function computes the inverse of the N-dimensional discrete Fourier Transform for real input over any number of axes in an M-dimensional array by means of the Fast Fourier Transform (FF...
python
{ "resource": "" }
q12503
irfft2
train
def irfft2(a, s=None, axes=(-2, -1), norm=None): """ Compute the 2-dimensional inverse FFT of a real array. Parameters ---------- a : array_like The input array s : sequence of ints, optional Shape of the inverse FFT. axes : sequence of ints, optional The axes over w...
python
{ "resource": "" }
q12504
cli
train
def cli(obj, environment, service, resource, event, group, tags, customer, start, duration, text, delete): """Suppress alerts for specified duration based on alert attributes.""" client = obj['client'] if delete: client.delete_blackout(delete) else: if not environment: raise ...
python
{ "resource": "" }
q12505
cli
train
def cli(obj, username, scopes, duration, text, customer, delete): """Create or delete an API key.""" client = obj['client'] if delete: client.delete_key(delete) else: try: expires = datetime.utcnow() + timedelta(seconds=duration) if duration else None key = client...
python
{ "resource": "" }
q12506
cli
train
def cli(obj, id, name, email, password, status, roles, text, email_verified, delete): """Create user or update user details, including password reset.""" client = obj['client'] if delete: client.delete_user(delete) elif id: if not any([name, email, password, status, roles, text, email_ve...
python
{ "resource": "" }
q12507
cli
train
def cli(ctx, obj): """Show Alerta server and client versions.""" client = obj['client'] click.echo('alerta {}'.format(client.mgmt_status()['version'])) click.echo('alerta client {}'.format(client_version)) click.echo('requests {}'.format(requests_version)) click.echo('click {}'.format(click.__ve...
python
{ "resource": "" }
q12508
cli
train
def cli(obj, show_userinfo): """Display logged in user or full userinfo.""" client = obj['client'] userinfo = client.userinfo() if show_userinfo: for k, v in userinfo.items(): if isinstance(v, list): v = ', '.join(v) click.echo('{:20}: {}'.format(k, v)) ...
python
{ "resource": "" }
q12509
cli
train
def cli(obj): """Display client config downloaded from API server.""" for k, v in obj.items(): if isinstance(v, list): v = ', '.join(v) click.echo('{:20}: {}'.format(k, v))
python
{ "resource": "" }
q12510
cli
train
def cli(obj, ids, query, filters): """Delete alerts.""" client = obj['client'] if ids: total = len(ids) else: if not (query or filters): click.confirm('Deleting all alerts. Do you want to continue?', abort=True) if query: query = [('q', query)] els...
python
{ "resource": "" }
q12511
cli
train
def cli(obj): """Display API server uptime in days, hours.""" client = obj['client'] status = client.mgmt_status() now = datetime.fromtimestamp(int(status['time']) / 1000.0) uptime = datetime(1, 1, 1) + timedelta(seconds=int(status['uptime']) / 1000.0) click.echo('{} up {} days {:02d}:{:02d}'....
python
{ "resource": "" }
q12512
cli
train
def cli(obj, ids, query, filters, tags): """Remove tags from alerts.""" client = obj['client'] if ids: total = len(ids) else: if query: query = [('q', query)] else: query = build_query(filters) total, _, _ = client.get_count(query) ids = [a...
python
{ "resource": "" }
q12513
cli
train
def cli(ctx, ids, query, filters, details, interval): """Watch for new alerts.""" if details: display = 'details' else: display = 'compact' from_date = None auto_refresh = True while auto_refresh: try: auto_refresh, from_date = ctx.invoke(query_cmd, ids=ids, ...
python
{ "resource": "" }
q12514
cli
train
def cli(obj): """Display API server switch status and usage metrics.""" client = obj['client'] metrics = client.mgmt_status()['metrics'] headers = {'title': 'METRIC', 'type': 'TYPE', 'name': 'NAME', 'value': 'VALUE', 'average': 'AVERAGE'} click.echo(tabulate([{ 'title': m['title'], '...
python
{ "resource": "" }
q12515
cli
train
def cli(obj, ids, query, filters, attributes): """Update alert attributes.""" client = obj['client'] if ids: total = len(ids) else: if query: query = [('q', query)] else: query = build_query(filters) total, _, _ = client.get_count(query) id...
python
{ "resource": "" }
q12516
cli
train
def cli(obj, origin, tags, timeout, customer, delete): """Send or delete a heartbeat.""" client = obj['client'] if delete: client.delete_heartbeat(delete) else: try: heartbeat = client.heartbeat(origin=origin, tags=tags, timeout=timeout, customer=customer) except Exce...
python
{ "resource": "" }
q12517
cli
train
def cli(obj): """List customer lookups.""" client = obj['client'] if obj['output'] == 'json': r = client.http.get('/customers') click.echo(json.dumps(r['customers'], sort_keys=True, indent=4, ensure_ascii=False)) else: headers = {'id': 'ID', 'customer': 'CUSTOMER', 'match': 'GRO...
python
{ "resource": "" }
q12518
cli
train
def cli(obj): """List API keys.""" client = obj['client'] if obj['output'] == 'json': r = client.http.get('/keys') click.echo(json.dumps(r['keys'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezone'] headers = { 'id': 'ID', 'key': ...
python
{ "resource": "" }
q12519
cli
train
def cli(obj, role, scopes, delete): """Add or delete role-to-permission lookup entry.""" client = obj['client'] if delete: client.delete_perm(delete) else: if not role: raise click.UsageError('Missing option "--role".') if not scopes: raise click.UsageErro...
python
{ "resource": "" }
q12520
cli
train
def cli(obj): """Display alerts like unix "top" command.""" client = obj['client'] timezone = obj['timezone'] screen = Screen(client, timezone) screen.run()
python
{ "resource": "" }
q12521
cli
train
def cli(obj, expired=None, info=None): """Trigger the expiration and deletion of alerts.""" client = obj['client'] client.housekeeping(expired_delete_hours=expired, info_delete_hours=info)
python
{ "resource": "" }
q12522
cli
train
def cli(obj, purge): """List alert suppressions.""" client = obj['client'] if obj['output'] == 'json': r = client.http.get('/blackouts') click.echo(json.dumps(r['blackouts'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timezone'] headers = { ...
python
{ "resource": "" }
q12523
cli
train
def cli(obj, name, email, password, status, text): """Create new Basic Auth user.""" client = obj['client'] if not email: raise click.UsageError('Need "--email" to sign-up new user.') if not password: raise click.UsageError('Need "--password" to sign-up new user.') try: r = c...
python
{ "resource": "" }
q12524
cli
train
def cli(ctx, config_file, profile, endpoint_url, output, color, debug): """ Alerta client unified command-line tool. """ config = Config(config_file) config.get_config_for_profle(profile) config.get_remote_config(endpoint_url) ctx.obj = config.options # override current options with co...
python
{ "resource": "" }
q12525
cli
train
def cli(obj, ids, query, filters): """Show raw data for alerts.""" client = obj['client'] if ids: query = [('id', x) for x in ids] elif query: query = [('q', query)] else: query = build_query(filters) alerts = client.search(query) headers = {'id': 'ID', 'rawData': 'R...
python
{ "resource": "" }
q12526
cli
train
def cli(obj, name, email, password, status, text): """Update current user details, including password reset.""" if not any([name, email, password, status, text]): click.echo('Nothing to update.') sys.exit(1) client = obj['client'] try: r = client.update_me(name=name, email=email...
python
{ "resource": "" }
q12527
cli
train
def cli(obj, ids, query, filters): """Show status and severity changes for alerts.""" client = obj['client'] if obj['output'] == 'json': r = client.http.get('/alerts/history') click.echo(json.dumps(r['history'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj...
python
{ "resource": "" }
q12528
transcribe
train
def transcribe(files=[], pre=10, post=50): '''Uses pocketsphinx to transcribe audio files''' total = len(files) for i, f in enumerate(files): filename = f.replace('.temp.wav', '') + '.transcription.txt' if os.path.exists(filename) is False: print(str(i+1) + '/' + str(total) + ...
python
{ "resource": "" }
q12529
convert_timestamps
train
def convert_timestamps(files): '''Converts pocketsphinx transcriptions to usable timestamps''' sentences = [] for f in files: if not f.endswith('.transcription.txt'): f = f + '.transcription.txt' if os.path.exists(f) is False: continue with open(f, 'r') a...
python
{ "resource": "" }
q12530
text
train
def text(files): '''Returns the whole transcribed text''' sentences = convert_timestamps(files) out = [] for s in sentences: out.append(' '.join([w[0] for w in s['words']])) return '\n'.join(out)
python
{ "resource": "" }
q12531
search
train
def search(query, files, mode='sentence', regex=False): '''Searches for words or sentences containing a search phrase''' out = [] sentences = convert_timestamps(files) if mode == 'fragment': out = fragment_search(query, sentences, regex) elif mode == 'word': out = word_search(query,...
python
{ "resource": "" }
q12532
extract_words
train
def extract_words(files): ''' Extracts individual words form files and exports them to individual files. ''' output_directory = 'extracted_words' if not os.path.exists(output_directory): os.makedirs(output_directory) for f in files: file_format = None source_segment = None ...
python
{ "resource": "" }
q12533
compose
train
def compose(segments, out='out.mp3', padding=0, crossfade=0, layer=False): '''Stiches together a new audiotrack''' files = {} working_segments = [] audio = AudioSegment.empty() if layer: total_time = max([s['end'] - s['start'] for s in segments]) * 1000 audio = AudioSegment.silen...
python
{ "resource": "" }
q12534
load
train
def load(target, **namespace): """ Import a module or fetch an object from a module. * ``package.module`` returns `module` as a module object. * ``pack.mod:name`` returns the module variable `name` from `pack.mod`. * ``pack.mod:func()`` calls `pack.mod.func()` and returns the result. ...
python
{ "resource": "" }
q12535
Route.all_plugins
train
def all_plugins(self): ''' Yield all Plugins affecting this route. ''' unique = set() for p in reversed(self.app.plugins + self.plugins): if True in self.skiplist: break name = getattr(p, 'name', False) if name and (name in self.skiplist or name in unique): co...
python
{ "resource": "" }
q12536
BaseRequest.remote_route
train
def remote_route(self): """ A list of all IPs that were involved in this request, starting with the client IP and followed by zero or more proxies. This does only work if all proxies support the ```X-Forwarded-For`` header. Note that this information can be forged by maliciou...
python
{ "resource": "" }
q12537
BaseResponse.get_header
train
def get_header(self, name, default=None): ''' Return the value of a previously defined header. If there is no header with that name, return a default value. ''' return self._headers.get(_hkey(name), [default])[-1]
python
{ "resource": "" }
q12538
MultiDict.get
train
def get(self, key, default=None, index=-1, type=None): ''' Return the most recent value for a key. :param default: The default value to be returned if the key is not present or the type conversion fails. :param index: An index for the list of available values. ...
python
{ "resource": "" }
q12539
JSXTransformer.transform_string
train
def transform_string(self, jsx, harmony=False, strip_types=False): """ Transform ``jsx`` JSX string into javascript :param jsx: JSX source code :type jsx: basestring :keyword harmony: Transform ES6 code into ES3 (default: False) :type harmony: bool :keyword strip_types: ...
python
{ "resource": "" }
q12540
Leaderboard.pool
train
def pool(self, host, port, db, pools={}, **options): ''' Fetch a redis conenction pool for the unique combination of host and port. Will create a new one if there isn't one already. ''' key = (host, port, db) rval = pools.get(key) if not isinstance(rval, Connectio...
python
{ "resource": "" }
q12541
Leaderboard.rank_member
train
def rank_member(self, member, score, member_data=None): ''' Rank a member in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member data. ''' self.rank_member_in(self.leaderboard_name, m...
python
{ "resource": "" }
q12542
Leaderboard.rank_member_if
train
def rank_member_if( self, rank_conditional, member, score, member_data=None): ''' Rank a member in the leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed the following parameters: member: Member name. current_score: Current...
python
{ "resource": "" }
q12543
Leaderboard.rank_member_if_in
train
def rank_member_if_in( self, leaderboard_name, rank_conditional, member, score, member_data=None): ''' Rank a member in the named leaderboard based on execution of the +rank_conditional+. The +rank_conditional+ is passed th...
python
{ "resource": "" }
q12544
Leaderboard.member_data_for_in
train
def member_data_for_in(self, leaderboard_name, member): ''' Retrieve the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return String of optional member data. ...
python
{ "resource": "" }
q12545
Leaderboard.members_data_for_in
train
def members_data_for_in(self, leaderboard_name, members): ''' Retrieve the optional member data for a given list of members in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param members [Array] Member names. @return Array of strings of option...
python
{ "resource": "" }
q12546
Leaderboard.update_member_data
train
def update_member_data(self, member, member_data): ''' Update the optional member data for a given member in the leaderboard. @param member [String] Member name. @param member_data [String] Optional member data. ''' self.update_member_data_in(self.leaderboard_name, membe...
python
{ "resource": "" }
q12547
Leaderboard.update_member_data_in
train
def update_member_data_in(self, leaderboard_name, member, member_data): ''' Update the optional member data for a given member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param member_data [String] Opti...
python
{ "resource": "" }
q12548
Leaderboard.total_pages_in
train
def total_pages_in(self, leaderboard_name, page_size=None): ''' Retrieve the total number of pages in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param page_size [int, nil] Page size to be used when calculating the total number of pages. @re...
python
{ "resource": "" }
q12549
Leaderboard.total_members_in_score_range
train
def total_members_in_score_range(self, min_score, max_score): ''' Retrieve the total members in a given score range from the leaderboard. @param min_score [float] Minimum score. @param max_score [float] Maximum score. @return the total members in a given score range from the lea...
python
{ "resource": "" }
q12550
Leaderboard.total_members_in_score_range_in
train
def total_members_in_score_range_in( self, leaderboard_name, min_score, max_score): ''' Retrieve the total members in a given score range from the named leaderboard. @param leaderboard_name Name of the leaderboard. @param min_score [float] Minimum score. @param max_s...
python
{ "resource": "" }
q12551
Leaderboard.total_scores_in
train
def total_scores_in(self, leaderboard_name): ''' Sum of scores for all members in the named leaderboard. @param leaderboard_name Name of the leaderboard. @return Sum of scores for all members in the named leaderboard. ''' return sum([leader[self.SCORE_KEY] for leader in ...
python
{ "resource": "" }
q12552
Leaderboard.score_for_in
train
def score_for_in(self, leaderboard_name, member): ''' Retrieve the score for a member in the named leaderboard. @param leaderboard_name Name of the leaderboard. @param member [String] Member name. @return the score for a member in the leaderboard or +None+ if the member is not i...
python
{ "resource": "" }
q12553
Leaderboard.change_score_for
train
def change_score_for(self, member, delta, member_data=None): ''' Change the score for a member in the leaderboard by a score delta which can be positive or negative. @param member [String] Member name. @param delta [float] Score change. @param member_data [String] Optional membe...
python
{ "resource": "" }
q12554
Leaderboard.remove_members_in_score_range
train
def remove_members_in_score_range(self, min_score, max_score): ''' Remove members from the leaderboard in a given score range. @param min_score [float] Minimum score. @param max_score [float] Maximum score. ''' self.remove_members_in_score_range_in( self.lead...
python
{ "resource": "" }
q12555
Leaderboard.remove_members_outside_rank_in
train
def remove_members_outside_rank_in(self, leaderboard_name, rank): ''' Remove members from the named leaderboard in a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param rank [int] the rank (inclusive) which we should keep. @return the total member ...
python
{ "resource": "" }
q12556
Leaderboard.page_for
train
def page_for(self, member, page_size=DEFAULT_PAGE_SIZE): ''' Determine the page where a member falls in the leaderboard. @param member [String] Member name. @param page_size [int] Page size to be used in determining page location. @return the page where a member falls in the lea...
python
{ "resource": "" }
q12557
Leaderboard.page_for_in
train
def page_for_in(self, leaderboard_name, member, page_size=DEFAULT_PAGE_SIZE): ''' Determine the page where a member falls in the named leaderboard. @param leaderboard [String] Name of the leaderboard. @param member [String] Member name. @param page_size [int]...
python
{ "resource": "" }
q12558
Leaderboard.percentile_for_in
train
def percentile_for_in(self, leaderboard_name, member): ''' Retrieve the percentile for a member in the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @return the percentile for a member in the named leaderboard. ...
python
{ "resource": "" }
q12559
Leaderboard.score_for_percentile_in
train
def score_for_percentile_in(self, leaderboard_name, percentile): ''' Calculate the score for a given percentile value in the leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param percentile [float] Percentile value (0.0 to 100.0 inclusive). @return the sc...
python
{ "resource": "" }
q12560
Leaderboard.expire_leaderboard_for
train
def expire_leaderboard_for(self, leaderboard_name, seconds): ''' Expire the given leaderboard in a set number of seconds. Do not use this with leaderboards that utilize member data as there is no facility to cascade the expiration out to the keys for the member data. @param lead...
python
{ "resource": "" }
q12561
Leaderboard.leaders
train
def leaders(self, current_page, **options): ''' Retrieve a page of leaders from the leaderboard. @param current_page [int] Page to retrieve from the leaderboard. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders fro...
python
{ "resource": "" }
q12562
Leaderboard.leaders_in
train
def leaders_in(self, leaderboard_name, current_page, **options): ''' Retrieve a page of leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param current_page [int] Page to retrieve from the named leaderboard. @param options [Hash] Opti...
python
{ "resource": "" }
q12563
Leaderboard.all_leaders_from
train
def all_leaders_from(self, leaderboard_name, **options): ''' Retrieves all leaders from the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. @param options [Hash] Options to be used when retrieving the leaders from the named leaderboard. @return the n...
python
{ "resource": "" }
q12564
Leaderboard.members_from_score_range
train
def members_from_score_range( self, minimum_score, maximum_score, **options): ''' Retrieve members from the leaderboard within a given score range. @param minimum_score [float] Minimum score (inclusive). @param maximum_score [float] Maximum score (inclusive). @param ...
python
{ "resource": "" }
q12565
Leaderboard.members_from_score_range_in
train
def members_from_score_range_in( self, leaderboard_name, minimum_score, maximum_score, **options): ''' Retrieve members from the named leaderboard within a given score range. @param leaderboard_name [String] Name of the leaderboard. @param minimum_score [float] Minimum score...
python
{ "resource": "" }
q12566
Leaderboard.members_from_rank_range
train
def members_from_rank_range(self, starting_rank, ending_rank, **options): ''' Retrieve members from the leaderboard within a given rank range. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to...
python
{ "resource": "" }
q12567
Leaderboard.members_from_rank_range_in
train
def members_from_rank_range_in( self, leaderboard_name, starting_rank, ending_rank, **options): ''' Retrieve members from the named leaderboard within a given rank range. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (incl...
python
{ "resource": "" }
q12568
Leaderboard.top
train
def top(self, number, **options): ''' Retrieve members from the leaderboard within a range from 1 to the number given. @param ending_rank [int] Ending rank (inclusive). @param options [Hash] Options to be used when retrieving the data from the leaderboard. @return number from t...
python
{ "resource": "" }
q12569
Leaderboard.top_in
train
def top_in(self, leaderboard_name, number, **options): ''' Retrieve members from the named leaderboard within a range from 1 to the number given. @param leaderboard_name [String] Name of the leaderboard. @param starting_rank [int] Starting rank (inclusive). @param ending_rank [i...
python
{ "resource": "" }
q12570
Leaderboard.around_me
train
def around_me(self, member, **options): ''' Retrieve a page of leaders from the leaderboard around a given member. @param member [String] Member name. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders from the leade...
python
{ "resource": "" }
q12571
Leaderboard.around_me_in
train
def around_me_in(self, leaderboard_name, member, **options): ''' Retrieve a page of leaders from the named leaderboard around a given member. @param leaderboard_name [String] Name of the leaderboard. @param member [String] Member name. @param options [Hash] Options to be used wh...
python
{ "resource": "" }
q12572
Leaderboard.ranked_in_list
train
def ranked_in_list(self, members, **options): ''' Retrieve a page of leaders from the leaderboard for a given list of members. @param members [Array] Member names. @param options [Hash] Options to be used when retrieving the page from the leaderboard. @return a page of leaders f...
python
{ "resource": "" }
q12573
Leaderboard.ranked_in_list_in
train
def ranked_in_list_in(self, leaderboard_name, members, **options): ''' Retrieve a page of leaders from the named leaderboard for a given list of members. @param leaderboard_name [String] Name of the leaderboard. @param members [Array] Member names. @param options [Hash] Options ...
python
{ "resource": "" }
q12574
Leaderboard.merge_leaderboards
train
def merge_leaderboards(self, destination, keys, aggregate='SUM'): ''' Merge leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the current lea...
python
{ "resource": "" }
q12575
Leaderboard.intersect_leaderboards
train
def intersect_leaderboards(self, destination, keys, aggregate='SUM'): ''' Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard. @param destination [String] Destination leaderboard name. @param keys [Array] Leaderboards to be merged with the cur...
python
{ "resource": "" }
q12576
Leaderboard._member_data_key
train
def _member_data_key(self, leaderboard_name): ''' Key for retrieving optional member data. @param leaderboard_name [String] Name of the leaderboard. @return a key in the form of +leaderboard_name:member_data+ ''' if self.global_member_data is False: return '%...
python
{ "resource": "" }
q12577
Leaderboard._parse_raw_members
train
def _parse_raw_members( self, leaderboard_name, members, members_only=False, **options): ''' Parse the raw leaders data as returned from a given leader board query. Do associative lookups with the member to rank, score and potentially sort the results. @param leaderboard_nam...
python
{ "resource": "" }
q12578
TieRankingLeaderboard.delete_leaderboard_named
train
def delete_leaderboard_named(self, leaderboard_name): ''' Delete the named leaderboard. @param leaderboard_name [String] Name of the leaderboard. ''' pipeline = self.redis_connection.pipeline() pipeline.delete(leaderboard_name) pipeline.delete(self._member_data_k...
python
{ "resource": "" }
q12579
TieRankingLeaderboard.rank_member_across
train
def rank_member_across( self, leaderboards, member, score, member_data=None): ''' Rank a member across multiple leaderboards. @param leaderboards [Array] Leaderboard names. @param member [String] Member name. @param score [float] Member score. @param member_d...
python
{ "resource": "" }
q12580
TieRankingLeaderboard.expire_leaderboard_at_for
train
def expire_leaderboard_at_for(self, leaderboard_name, timestamp): ''' Expire the given leaderboard at a specific UNIX timestamp. Do not use this with leaderboards that utilize member data as there is no facility to cascade the expiration out to the keys for the member data. @par...
python
{ "resource": "" }
q12581
check_key
train
def check_key(key, allowed): """ Validate that the specified key is allowed according the provided list of patterns. """ if key in allowed: return True for pattern in allowed: if fnmatch(key, pattern): return True return False
python
{ "resource": "" }
q12582
cs_encode
train
def cs_encode(s): """Encode URI component like CloudStack would do before signing. java.net.URLEncoder.encode(s).replace('+', '%20') """ if PY2 and isinstance(s, text_type): s = s.encode("utf-8") return quote(s, safe="*")
python
{ "resource": "" }
q12583
transform
train
def transform(params): """ Transforms an heterogeneous map of params into a CloudStack ready mapping of parameter to values. It handles lists and dicts. >>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}} >>> transform(p) >>> print(p) {'a': '1', 'b': 'foo', 'c': ...
python
{ "resource": "" }
q12584
read_config
train
def read_config(ini_group=None): """ Read the configuration from the environment, or config. First it try to go for the environment, then it overrides those with the cloudstack.ini file. """ env_conf = dict(DEFAULT_CONFIG) for key in REQUIRED_CONFIG_KEYS.union(ALLOWED_CONFIG_KEYS): ...
python
{ "resource": "" }
q12585
CloudStack._response_value
train
def _response_value(self, response, json=True): """Parses the HTTP response as a the cloudstack value. It throws an exception if the server didn't answer with a 200. """ if json: contentType = response.headers.get("Content-Type", "") if not contentType.startswith...
python
{ "resource": "" }
q12586
CloudStack._jobresult
train
def _jobresult(self, jobid, json=True, headers=None): """Poll the async job result. To be run via in a Thread, the result is put within the result list which is a hack. """ failures = 0 total_time = self.job_timeout or 2**30 remaining = timedelta(seconds=total_t...
python
{ "resource": "" }
q12587
_format_json
train
def _format_json(data, theme): """Pretty print a dict as a JSON, with colors if pygments is present.""" output = json.dumps(data, indent=2, sort_keys=True) if pygments and sys.stdout.isatty(): style = get_style_by_name(theme) formatter = Terminal256Formatter(style=style) return pygm...
python
{ "resource": "" }
q12588
Parser.parse
train
def parse(self, data=b''): """ Parses the wire protocol from NATS for the client and dispatches the subscription callbacks. """ self.buf.extend(data) while self.buf: if self.state == AWAITING_CONTROL_LINE: msg = MSG_RE.match(self.buf) ...
python
{ "resource": "" }
q12589
Client._server_connect
train
def _server_connect(self, s): """ Sets up a TCP connection to the server. """ self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.setblocking(0) self._socket.settimeout(1.0) if self.options["tcp_nodelay"]: self._socket.setsoc...
python
{ "resource": "" }
q12590
Client.connect_command
train
def connect_command(self): ''' Generates a JSON string with the params to be used when sending CONNECT to the server. ->> CONNECT {"verbose": false, "pedantic": false, "lang": "python2" } ''' options = { "verbose": self.options["verbose"], "ped...
python
{ "resource": "" }
q12591
Client.send_command
train
def send_command(self, cmd, priority=False): """ Flushes a command to the server as a bytes payload. """ if priority: self._pending.insert(0, cmd) else: self._pending.append(cmd) self._pending_size += len(cmd) if self._pending_size > DEFAU...
python
{ "resource": "" }
q12592
Client._flush_timeout
train
def _flush_timeout(self, timeout): """ Takes a timeout and sets up a future which will return True once the server responds back otherwise raise a TimeoutError. """ future = tornado.concurrent.Future() yield self._send_ping(future) try: result = yield ...
python
{ "resource": "" }
q12593
Client.subscribe
train
def subscribe( self, subject="", queue="", cb=None, future=None, max_msgs=0, is_async=False, pending_msgs_limit=DEFAULT_SUB_PENDING_MSGS_LIMIT, pending_bytes_limit=DEFAULT_SUB_PENDING_BYTES_LIMIT, ): ...
python
{ "resource": "" }
q12594
Client.subscribe_async
train
def subscribe_async(self, subject, **kwargs): """ Schedules callback from subscription to be processed asynchronously in the next iteration of the loop. """ kwargs["is_async"] = True sid = yield self.subscribe(subject, **kwargs) raise tornado.gen.Return(sid)
python
{ "resource": "" }
q12595
Client.unsubscribe
train
def unsubscribe(self, ssid, max_msgs=0): """ Takes a subscription sequence id and removes the subscription from the client, optionally after receiving more than max_msgs, and unsubscribes immediatedly. """ if self.is_closed: raise ErrConnectionClosed ...
python
{ "resource": "" }
q12596
Client._process_ping
train
def _process_ping(self): """ The server will be periodically sending a PING, and if the the client does not reply a PONG back a number of times, it will close the connection sending an `-ERR 'Stale Connection'` error. """ yield self.send_command(PONG_PROTO) if sel...
python
{ "resource": "" }
q12597
Client._process_msg
train
def _process_msg(self, sid, subject, reply, data): """ Dispatches the received message to the stored subscription. It first tries to detect whether the message should be dispatched to a passed callback. In case there was not a callback, then it tries to set the message into a fu...
python
{ "resource": "" }
q12598
Client._process_info
train
def _process_info(self, info_line): """ Process INFO lines sent by the server to reconfigure client with latest updates from cluster to enable server discovery. """ info = tornado.escape.json_decode(info_line.decode()) if 'connect_urls' in info: if info['conn...
python
{ "resource": "" }
q12599
Client._next_server
train
def _next_server(self): """ Chooses next available server to connect. """ if self.options["dont_randomize"]: server = self._server_pool.pop(0) self._server_pool.append(server) else: shuffle(self._server_pool) s = None for serve...
python
{ "resource": "" }