_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q256100
watermark
validation
def watermark(im, mark, position, opacity=1): """Adds a watermark to an image.""" if opacity < 1: mark = reduce_opacity(mark, opacity) if im.mode != 'RGBA': im = im.convert('RGBA') # create a transparent layer the size of the image and draw the # watermark in that layer. layer = ...
python
{ "resource": "" }
q256101
check_subprocess
validation
def check_subprocess(cmd, source, outname): """Run the command to resize the video and remove the output file if the processing fails. """ logger = logging.getLogger(__name__) try: res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) exc...
python
{ "resource": "" }
q256102
video_size
validation
def video_size(source, converter='ffmpeg'): """Returns the dimensions of the video.""" res = subprocess.run([converter, '-i', source], stderr=subprocess.PIPE) stderr = res.stderr.decode('utf8') pattern = re.compile(r'Stream.*Video.* ([0-9]+)x([0-9]+)') match = pattern.search(stderr) rot_pattern...
python
{ "resource": "" }
q256103
generate_video
validation
def generate_video(source, outname, settings, options=None): """Video processor. :param source: path to a video :param outname: path to the generated video :param settings: settings dict :param options: array of options passed to ffmpeg """ logger = logging.getLogger(__name__) # Don't...
python
{ "resource": "" }
q256104
generate_thumbnail
validation
def generate_thumbnail(source, outname, box, delay, fit=True, options=None, converter='ffmpeg'): """Create a thumbnail image for the video source, based on ffmpeg.""" logger = logging.getLogger(__name__) tmpfile = outname + ".tmp.jpg" # dump an image of the video cmd = [conv...
python
{ "resource": "" }
q256105
AbstractWriter.generate_context
validation
def generate_context(self, album): """Generate the context dict for the given path.""" from . import __url__ as sigal_link self.logger.info("Output album : %r", album) return { 'album': album, 'index_title': self.index_title, 'settings': self.settings...
python
{ "resource": "" }
q256106
AbstractWriter.write
validation
def write(self, album): """Generate the HTML page and save it.""" page = self.template.render(**self.generate_context(album)) output_file = os.path.join(album.dst_path, album.output_file) with open(output_file, 'w', encoding='utf-8') as f: f.write(page)
python
{ "resource": "" }
q256107
get_thumb
validation
def get_thumb(settings, filename): """Return the path to the thumb. examples: >>> default_settings = create_settings() >>> get_thumb(default_settings, "bar/foo.jpg") "bar/thumbnails/foo.jpg" >>> get_thumb(default_settings, "bar/foo.png") "bar/thumbnails/foo.png" for videos, it returns ...
python
{ "resource": "" }
q256108
read_settings
validation
def read_settings(filename=None): """Read settings from a config file in the source_dir root.""" logger = logging.getLogger(__name__) logger.info("Reading settings ...") settings = _DEFAULT_CONFIG.copy() if filename: logger.debug("Settings file: %s", filename) settings_path = os.pa...
python
{ "resource": "" }
q256109
generate_media_pages
validation
def generate_media_pages(gallery): '''Generates and writes the media pages for all media in the gallery''' writer = PageWriter(gallery.settings, index_title=gallery.title) for album in gallery.albums.values(): medias = album.medias next_medias = medias[1:] + [None] previous_medias ...
python
{ "resource": "" }
q256110
PageWriter.write
validation
def write(self, album, media_group): ''' Generate the media page and save it ''' from sigal import __url__ as sigal_link file_path = os.path.join(album.dst_path, media_group[0].filename) page = self.template.render({ 'album': album, 'media': media_group[0], ...
python
{ "resource": "" }
q256111
cleanup_directory
validation
def cleanup_directory(config_data): """ Asks user for removal of project directory and eventually removes it """ if os.path.exists(config_data.project_directory): choice = False if config_data.noinput is False and not config_data.verbose: choice = query_yes_no( ...
python
{ "resource": "" }
q256112
validate_project
validation
def validate_project(project_name): """ Check the defined project name against keywords, builtins and existing modules to avoid name clashing """ if '-' in project_name: return None if keyword.iskeyword(project_name): return None if project_name in dir(__builtins__): ...
python
{ "resource": "" }
q256113
_manage_args
validation
def _manage_args(parser, args): """ Checks and validate provided input """ for item in data.CONFIGURABLE_OPTIONS: action = parser._option_string_actions[item] choices = default = '' input_value = getattr(args, action.dest) new_val = None # cannot count this until...
python
{ "resource": "" }
q256114
supported_versions
validation
def supported_versions(django, cms): """ Convert numeric and literal version information to numeric format """ cms_version = None django_version = None try: cms_version = Decimal(cms) except (ValueError, InvalidOperation): try: cms_version = CMS_VERSION_MATRIX[st...
python
{ "resource": "" }
q256115
less_than_version
validation
def less_than_version(value): """ Converts the current version to the next one for inserting into requirements in the ' < version' format """ items = list(map(int, str(value).split('.'))) if len(items) == 1: items.append(0) items[1] += 1 if value == '1.11': return '2.0' ...
python
{ "resource": "" }
q256116
parse_config_file
validation
def parse_config_file(parser, stdin_args): """Parse config file. Returns a list of additional args. """ config_args = [] # Temporary switch required args and save them to restore. required_args = [] for action in parser._actions: if action.required: required_args.append...
python
{ "resource": "" }
q256117
dump_config_file
validation
def dump_config_file(filename, args, parser=None): """Dump args to config file.""" config = ConfigParser() config.add_section(SECTION) if parser is None: for attr in args: config.set(SECTION, attr, args.attr) else: keys_empty_values_not_pass = ( '--extra-setti...
python
{ "resource": "" }
q256118
_convert_config_to_stdin
validation
def _convert_config_to_stdin(config, parser): """Convert config options to stdin args. Especially boolean values, for more information @see https://docs.python.org/3.4/library/configparser.html#supported-datatypes """ keys_empty_values_not_pass = ( '--extra-settings', '--languages', '--requ...
python
{ "resource": "" }
q256119
create_project
validation
def create_project(config_data): """ Call django-admin to create the project structure :param config_data: configuration data """ env = deepcopy(dict(os.environ)) env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name)) env[str('PYTHONPATH')] = str(os.pathse...
python
{ "resource": "" }
q256120
_install_aldryn
validation
def _install_aldryn(config_data): # pragma: no cover """ Install aldryn boilerplate :param config_data: configuration data """ import requests media_project = os.path.join(config_data.project_directory, 'dist', 'media') static_main = False static_project = os.path.join(config_data.proj...
python
{ "resource": "" }
q256121
setup_database
validation
def setup_database(config_data): """ Run the migrate command to create the database schema :param config_data: configuration data """ with chdir(config_data.project_directory): env = deepcopy(dict(os.environ)) env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_dat...
python
{ "resource": "" }
q256122
create_user
validation
def create_user(config_data): """ Create admin user without user input :param config_data: configuration data """ with chdir(os.path.abspath(config_data.project_directory)): env = deepcopy(dict(os.environ)) env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.p...
python
{ "resource": "" }
q256123
sox
validation
def sox(args): '''Pass an argument list to SoX. Parameters ---------- args : iterable Argument list for SoX. The first item can, but does not need to, be 'sox'. Returns: -------- status : bool True on success. ''' if args[0].lower() != "sox": args.i...
python
{ "resource": "" }
q256124
_get_valid_formats
validation
def _get_valid_formats(): ''' Calls SoX help for a lists of audio formats available with the current install of SoX. Returns: -------- formats : list List of audio file extensions that SoX can process. ''' if NO_SOX: return [] so = subprocess.check_output(['sox', '-h']...
python
{ "resource": "" }
q256125
soxi
validation
def soxi(filepath, argument): ''' Base call to SoXI. Parameters ---------- filepath : str Path to audio file. argument : str Argument to pass to SoXI. Returns ------- shell_output : str Command line output of SoXI ''' if argument not in SOXI_ARGS: ...
python
{ "resource": "" }
q256126
play
validation
def play(args): '''Pass an argument list to play. Parameters ---------- args : iterable Argument list for play. The first item can, but does not need to, be 'play'. Returns: -------- status : bool True on success. ''' if args[0].lower() != "play": a...
python
{ "resource": "" }
q256127
_validate_file_formats
validation
def _validate_file_formats(input_filepath_list, combine_type): '''Validate that combine method can be performed with given files. Raises IOError if input file formats are incompatible. ''' _validate_sample_rates(input_filepath_list, combine_type) if combine_type == 'concatenate': _validate_...
python
{ "resource": "" }
q256128
_validate_sample_rates
validation
def _validate_sample_rates(input_filepath_list, combine_type): ''' Check if files in input file list have the same sample rate ''' sample_rates = [ file_info.sample_rate(f) for f in input_filepath_list ] if not core.all_equal(sample_rates): raise IOError( "Input files do ...
python
{ "resource": "" }
q256129
_validate_num_channels
validation
def _validate_num_channels(input_filepath_list, combine_type): ''' Check if files in input file list have the same number of channels ''' channels = [ file_info.channels(f) for f in input_filepath_list ] if not core.all_equal(channels): raise IOError( "Input files do not ...
python
{ "resource": "" }
q256130
_build_input_format_list
validation
def _build_input_format_list(input_filepath_list, input_volumes=None, input_format=None): '''Set input formats given input_volumes. Parameters ---------- input_filepath_list : list of str List of input files input_volumes : list of float, default=None Li...
python
{ "resource": "" }
q256131
_build_input_args
validation
def _build_input_args(input_filepath_list, input_format_list): ''' Builds input arguments by stitching input filepaths and input formats together. ''' if len(input_format_list) != len(input_filepath_list): raise ValueError( "input_format_list & input_filepath_list are not the same si...
python
{ "resource": "" }
q256132
_validate_volumes
validation
def _validate_volumes(input_volumes): '''Check input_volumes contains a valid list of volumes. Parameters ---------- input_volumes : list list of volume values. Castable to numbers. ''' if not (input_volumes is None or isinstance(input_volumes, list)): raise TypeError("input_vo...
python
{ "resource": "" }
q256133
silent
validation
def silent(input_filepath, threshold=0.001): ''' Determine if an input file is silent. Parameters ---------- input_filepath : str The input filepath. threshold : float Threshold for determining silence Returns ------- is_silent : bool True if file is determi...
python
{ "resource": "" }
q256134
validate_input_file
validation
def validate_input_file(input_filepath): '''Input file validation function. Checks that file exists and can be processed by SoX. Parameters ---------- input_filepath : str The input filepath. ''' if not os.path.exists(input_filepath): raise IOError( "input_filep...
python
{ "resource": "" }
q256135
validate_input_file_list
validation
def validate_input_file_list(input_filepath_list): '''Input file list validation function. Checks that object is a list and contains valid filepaths that can be processed by SoX. Parameters ---------- input_filepath_list : list A list of filepaths. ''' if not isinstance(input_filep...
python
{ "resource": "" }
q256136
validate_output_file
validation
def validate_output_file(output_filepath): '''Output file validation function. Checks that file can be written, and has a valid file extension. Throws a warning if the path already exists, as it will be overwritten on build. Parameters ---------- output_filepath : str The output filepat...
python
{ "resource": "" }
q256137
info
validation
def info(filepath): '''Get a dictionary of file information Parameters ---------- filepath : str File path. Returns: -------- info_dictionary : dict Dictionary of file information. Fields are: * channels * sample_rate * bitrate ...
python
{ "resource": "" }
q256138
_stat_call
validation
def _stat_call(filepath): '''Call sox's stat function. Parameters ---------- filepath : str File path. Returns ------- stat_output : str Sox output from stderr. ''' validate_input_file(filepath) args = ['sox', filepath, '-n', 'stat'] _, _, stat_output = sox(...
python
{ "resource": "" }
q256139
_parse_stat
validation
def _parse_stat(stat_output): '''Parse the string output from sox's stat function Parameters ---------- stat_output : str Sox output from stderr. Returns ------- stat_dictionary : dict Dictionary of audio statistics. ''' lines = stat_output.split('\n') stat_dict...
python
{ "resource": "" }
q256140
Transformer.set_globals
validation
def set_globals(self, dither=False, guard=False, multithread=False, replay_gain=False, verbosity=2): '''Sets SoX's global arguments. Overwrites any previously set global arguments. If this function is not explicity called, globals are set to this function's defaults. ...
python
{ "resource": "" }
q256141
Transformer.biquad
validation
def biquad(self, b, a): '''Apply a biquad IIR filter with the given coefficients. Parameters ---------- b : list of floats Numerator coefficients. Must be length 3 a : list of floats Denominator coefficients. Must be length 3 See Also ---...
python
{ "resource": "" }
q256142
Transformer.channels
validation
def channels(self, n_channels): '''Change the number of channels in the audio signal. If decreasing the number of channels it mixes channels together, if increasing the number of channels it duplicates. Note: This overrides arguments used in the convert effect! Parameters ...
python
{ "resource": "" }
q256143
Transformer.contrast
validation
def contrast(self, amount=75): '''Comparable with compression, this effect modifies an audio signal to make it sound louder. Parameters ---------- amount : float Amount of enhancement between 0 and 100. See Also -------- compand, mcompand ...
python
{ "resource": "" }
q256144
Transformer.convert
validation
def convert(self, samplerate=None, n_channels=None, bitdepth=None): '''Converts output audio to the specified format. Parameters ---------- samplerate : float, default=None Desired samplerate. If None, defaults to the same as input. n_channels : int, default=None ...
python
{ "resource": "" }
q256145
Transformer.dcshift
validation
def dcshift(self, shift=0.0): '''Apply a DC shift to the audio. Parameters ---------- shift : float Amount to shift audio between -2 and 2. (Audio is between -1 and 1) See Also -------- highpass ''' if not is_number(shift) or shift <...
python
{ "resource": "" }
q256146
Transformer.delay
validation
def delay(self, positions): '''Delay one or more audio channels such that they start at the given positions. Parameters ---------- positions: list of floats List of times (in seconds) to delay each audio channel. If fewer positions are given than the numb...
python
{ "resource": "" }
q256147
Transformer.downsample
validation
def downsample(self, factor=2): '''Downsample the signal by an integer factor. Only the first out of each factor samples is retained, the others are discarded. No decimation filter is applied. If the input is not a properly bandlimited baseband signal, aliasing will occur. This may be d...
python
{ "resource": "" }
q256148
Transformer.echo
validation
def echo(self, gain_in=0.8, gain_out=0.9, n_echos=1, delays=[60], decays=[0.4]): '''Add echoing to the audio. Echoes are reflected sound and can occur naturally amongst mountains (and sometimes large buildings) when talking or shouting; digital echo effects emulate this beh...
python
{ "resource": "" }
q256149
Transformer.flanger
validation
def flanger(self, delay=0, depth=2, regen=0, width=71, speed=0.5, shape='sine', phase=25, interp='linear'): '''Apply a flanging effect to the audio. Parameters ---------- delay : float, default=0 Base delay (in miliseconds) between 0 and 30. depth : f...
python
{ "resource": "" }
q256150
Transformer.gain
validation
def gain(self, gain_db=0.0, normalize=True, limiter=False, balance=None): '''Apply amplification or attenuation to the audio signal. Parameters ---------- gain_db : float, default=0.0 Gain adjustment in decibels (dB). normalize : bool, default=True If Tru...
python
{ "resource": "" }
q256151
Transformer.loudness
validation
def loudness(self, gain_db=-10.0, reference_level=65.0): '''Loudness control. Similar to the gain effect, but provides equalisation for the human auditory system. The gain is adjusted by gain_db and the signal is equalised according to ISO 226 w.r.t. reference_level. Parameters...
python
{ "resource": "" }
q256152
Transformer.noiseprof
validation
def noiseprof(self, input_filepath, profile_path): '''Calculate a profile of the audio for use in noise reduction. Running this command does not effect the Transformer effects chain. When this function is called, the calculated noise profile file is saved to the `profile_path`. ...
python
{ "resource": "" }
q256153
Transformer.noisered
validation
def noisered(self, profile_path, amount=0.5): '''Reduce noise in the audio signal by profiling and filtering. This effect is moderately effective at removing consistent background noise such as hiss or hum. Parameters ---------- profile_path : str Path to a n...
python
{ "resource": "" }
q256154
Transformer.norm
validation
def norm(self, db_level=-3.0): '''Normalize an audio file to a particular db level. This behaves identically to the gain effect with normalize=True. Parameters ---------- db_level : float, default=-3.0 Output volume (db) See Also -------- gai...
python
{ "resource": "" }
q256155
Transformer.oops
validation
def oops(self): '''Out Of Phase Stereo effect. Mixes stereo to twin-mono where each mono channel contains the difference between the left and right stereo channels. This is sometimes known as the 'karaoke' effect as it often has the effect of removing most or all of the vocals from a rec...
python
{ "resource": "" }
q256156
Transformer.overdrive
validation
def overdrive(self, gain_db=20.0, colour=20.0): '''Apply non-linear distortion. Parameters ---------- gain_db : float, default=20 Controls the amount of distortion (dB). colour : float, default=20 Controls the amount of even harmonic content in the output...
python
{ "resource": "" }
q256157
Transformer.pad
validation
def pad(self, start_duration=0.0, end_duration=0.0): '''Add silence to the beginning or end of a file. Calling this with the default arguments has no effect. Parameters ---------- start_duration : float Number of seconds of silence to add to beginning. end_du...
python
{ "resource": "" }
q256158
Transformer.phaser
validation
def phaser(self, gain_in=0.8, gain_out=0.74, delay=3, decay=0.4, speed=0.5, modulation_shape='sinusoidal'): '''Apply a phasing effect to the audio. Parameters ---------- gain_in : float, default=0.8 Input volume between 0 and 1 gain_out: float, default...
python
{ "resource": "" }
q256159
Transformer.pitch
validation
def pitch(self, n_semitones, quick=False): '''Pitch shift the audio without changing the tempo. This effect uses the WSOLA algorithm. The audio is chopped up into segments which are then shifted in the time domain and overlapped (cross-faded) at points where their waveforms are most sim...
python
{ "resource": "" }
q256160
Transformer.remix
validation
def remix(self, remix_dictionary=None, num_output_channels=None): '''Remix the channels of an audio file. Note: volume options are not yet implemented Parameters ---------- remix_dictionary : dict or None Dictionary mapping output channel to list of input channel(s)...
python
{ "resource": "" }
q256161
Transformer.repeat
validation
def repeat(self, count=1): '''Repeat the entire audio count times. Parameters ---------- count : int, default=1 The number of times to repeat the audio. ''' if not isinstance(count, int) or count < 1: raise ValueError("count must be a postive int...
python
{ "resource": "" }
q256162
Transformer.reverse
validation
def reverse(self): '''Reverse the audio completely ''' effect_args = ['reverse'] self.effects.extend(effect_args) self.effects_log.append('reverse') return self
python
{ "resource": "" }
q256163
Transformer.silence
validation
def silence(self, location=0, silence_threshold=0.1, min_silence_duration=0.1, buffer_around_silence=False): '''Removes silent regions from an audio file. Parameters ---------- location : int, default=0 Where to remove silence. One of: * 0 to rem...
python
{ "resource": "" }
q256164
Transformer.stat
validation
def stat(self, input_filepath, scale=None, rms=False): '''Display time and frequency domain statistical information about the audio. Audio is passed unmodified through the SoX processing chain. Unlike other Transformer methods, this does not modify the transformer effects chain. Instead...
python
{ "resource": "" }
q256165
Transformer.stats
validation
def stats(self, input_filepath): '''Display time domain statistical information about the audio channels. Audio is passed unmodified through the SoX processing chain. Statistics are calculated and displayed for each audio channel Unlike other Transformer methods, this does not modify th...
python
{ "resource": "" }
q256166
Transformer.swap
validation
def swap(self): '''Swap stereo channels. If the input is not stereo, pairs of channels are swapped, and a possible odd last channel passed through. E.g., for seven channels, the output order will be 2, 1, 4, 3, 6, 5, 7. See Also ---------- remix ''' eff...
python
{ "resource": "" }
q256167
Transformer.tempo
validation
def tempo(self, factor, audio_type=None, quick=False): '''Time stretch audio without changing pitch. This effect uses the WSOLA algorithm. The audio is chopped up into segments which are then shifted in the time domain and overlapped (cross-faded) at points where their waveforms are mos...
python
{ "resource": "" }
q256168
Transformer.trim
validation
def trim(self, start_time, end_time=None): '''Excerpt a clip from an audio file, given the start timestamp and end timestamp of the clip within the file, expressed in seconds. If the end timestamp is set to `None` or left unspecified, it defaults to the duration of the audio file. Parameters --...
python
{ "resource": "" }
q256169
Transformer.vad
validation
def vad(self, location=1, normalize=True, activity_threshold=7.0, min_activity_duration=0.25, initial_search_buffer=1.0, max_gap=0.25, initial_pad=0.0): '''Voice Activity Detector. Attempts to trim silence and quiet background sounds from the ends of recordings of speech. The alg...
python
{ "resource": "" }
q256170
Transformer.vol
validation
def vol(self, gain, gain_type='amplitude', limiter_gain=None): '''Apply an amplification or an attenuation to the audio signal. Parameters ---------- gain : float Interpreted according to the given `gain_type`. If `gain_type' = 'amplitude', `gain' is a positive a...
python
{ "resource": "" }
q256171
NamedUsersRoomsMixin.join
validation
def join(self, room): """Lets a user join a room on a specific Namespace.""" self.socket.rooms.add(self._get_room_name(room))
python
{ "resource": "" }
q256172
NamedUsersRoomsMixin.leave
validation
def leave(self, room): """Lets a user leave a room on a specific Namespace.""" self.socket.rooms.remove(self._get_room_name(room))
python
{ "resource": "" }
q256173
socketio_manage
validation
def socketio_manage(environ, namespaces, request=None, error_handler=None, json_loads=None, json_dumps=None): """Main SocketIO management function, call from within your Framework of choice's view. The ``environ`` variable is the WSGI ``environ``. It is used to extract Socket objec...
python
{ "resource": "" }
q256174
Socket._save_ack_callback
validation
def _save_ack_callback(self, msgid, callback): """Keep a reference of the callback on this socket.""" if msgid in self.ack_callbacks: return False self.ack_callbacks[msgid] = callback
python
{ "resource": "" }
q256175
Socket._pop_ack_callback
validation
def _pop_ack_callback(self, msgid): """Fetch the callback for a given msgid, if it exists, otherwise, return None""" if msgid not in self.ack_callbacks: return None return self.ack_callbacks.pop(msgid)
python
{ "resource": "" }
q256176
Socket.get_multiple_client_msgs
validation
def get_multiple_client_msgs(self, **kwargs): """Get multiple messages, in case we're going through the various XHR-polling methods, on which we can pack more than one message if the rate is high, and encode the payload for the HTTP channel.""" client_queue = self.client_queue ms...
python
{ "resource": "" }
q256177
Socket.remove_namespace
validation
def remove_namespace(self, namespace): """This removes a Namespace object from the socket. This is usually called by :meth:`~socketio.namespace.BaseNamespace.disconnect`. """ if namespace in self.active_ns: del self.active_ns[namespace] if len(self.active_n...
python
{ "resource": "" }
q256178
Socket.send_packet
validation
def send_packet(self, pkt): """Low-level interface to queue a packet on the wire (encoded as wire protocol""" self.put_client_msg(packet.encode(pkt, self.json_dumps))
python
{ "resource": "" }
q256179
Socket.spawn
validation
def spawn(self, fn, *args, **kwargs): """Spawn a new Greenlet, attached to this Socket instance. It will be monitored by the "watcher" method """ log.debug("Spawning sub-Socket Greenlet: %s" % fn.__name__) job = gevent.spawn(fn, *args, **kwargs) self.jobs.append(job) ...
python
{ "resource": "" }
q256180
Socket._receiver_loop
validation
def _receiver_loop(self): """This is the loop that takes messages from the queue for the server to consume, decodes them and dispatches them. It is the main loop for a socket. We join on this process before returning control to the web framework. This process is not tracked by...
python
{ "resource": "" }
q256181
Socket._watcher
validation
def _watcher(self): """Watch out if we've been disconnected, in that case, kill all the jobs. """ while True: gevent.sleep(1.0) if not self.connected: for ns_name, ns in list(six.iteritems(self.active_ns)): ns.recv_disconnect()...
python
{ "resource": "" }
q256182
Socket._heartbeat
validation
def _heartbeat(self): """Start the heartbeat Greenlet to check connection health.""" interval = self.config['heartbeat_interval'] while self.connected: gevent.sleep(interval) # TODO: this process could use a timeout object like the disconnect # timeout t...
python
{ "resource": "" }
q256183
Socket._spawn_heartbeat
validation
def _spawn_heartbeat(self): """This functions returns a list of jobs""" self.spawn(self._heartbeat) self.spawn(self._heartbeat_timeout)
python
{ "resource": "" }
q256184
encode
validation
def encode(data, json_dumps=default_json_dumps): """ Encode an attribute dict into a byte string. """ payload = '' msg = str(MSG_TYPES[data['type']]) if msg in ['0', '1']: # '1::' [path] [query] msg += '::' + data['endpoint'] if 'qs' in data and data['qs'] != '': ...
python
{ "resource": "" }
q256185
decode
validation
def decode(rawstr, json_loads=default_json_loads): """ Decode a rawstr packet arriving from the socket into a dict. """ decoded_msg = {} try: # Handle decoding in Python<3. rawstr = rawstr.decode('utf-8') except AttributeError: pass split_data = rawstr.split(":", 3) ...
python
{ "resource": "" }
q256186
BaseNamespace.process_event
validation
def process_event(self, packet): """This function dispatches ``event`` messages to the correct functions. You should override this method only if you are not satisfied with the automatic dispatching to ``on_``-prefixed methods. You could then implement your own dispatch. See the...
python
{ "resource": "" }
q256187
BaseNamespace.call_method_with_acl
validation
def call_method_with_acl(self, method_name, packet, *args): """You should always use this function to call the methods, as it checks if the user is allowed according to the ACLs. If you override :meth:`process_packet` or :meth:`process_event`, you should definitely want to use this ...
python
{ "resource": "" }
q256188
BaseNamespace.error
validation
def error(self, error_name, error_message, msg_id=None, quiet=False): """Use this to use the configured ``error_handler`` yield an error message to your application. :param error_name: is a short string, to associate messages to recovery methods :param error_m...
python
{ "resource": "" }
q256189
BaseNamespace.send
validation
def send(self, message, json=False, callback=None): """Use send to send a simple string message. If ``json`` is True, the message will be encoded as a JSON object on the wire, and decoded on the other side. This is mostly for backwards compatibility. ``emit()`` is more fun. :...
python
{ "resource": "" }
q256190
BaseNamespace.emit
validation
def emit(self, event, *args, **kwargs): """Use this to send a structured event, with a name and arguments, to the client. By default, it uses this namespace's endpoint. You can send messages on other endpoints with something like: ``self.socket['/other_endpoint'].emit()``. ...
python
{ "resource": "" }
q256191
BaseNamespace.spawn
validation
def spawn(self, fn, *args, **kwargs): """Spawn a new process, attached to this Namespace. It will be monitored by the "watcher" process in the Socket. If the socket disconnects, all these greenlets are going to be killed, after calling BaseNamespace.disconnect() This method use...
python
{ "resource": "" }
q256192
SocketIOServer.get_socket
validation
def get_socket(self, sessid=''): """Return an existing or new client Socket.""" socket = self.sockets.get(sessid) if sessid and not socket: return None # you ask for a session that doesn't exist! if socket is None: socket = Socket(self, self.config) ...
python
{ "resource": "" }
q256193
create
validation
def create(): """ Handles post from the "Add room" form on the homepage, and redirects to the new room. """ name = request.form.get("name") if name: room, created = get_or_create(ChatRoom, name=name) return redirect(url_for('room', slug=room.slug)) return redirect(url_for('ro...
python
{ "resource": "" }
q256194
XHRPollingTransport.get_messages_payload
validation
def get_messages_payload(self, socket, timeout=None): """This will fetch the messages from the Socket's queue, and if there are many messes, pack multiple messages in one payload and return """ try: msgs = socket.get_multiple_client_msgs(timeout=timeout) data = se...
python
{ "resource": "" }
q256195
XHRPollingTransport.encode_payload
validation
def encode_payload(self, messages): """Encode list of messages. Expects messages to be unicode. ``messages`` - List of raw messages to encode, if necessary """ if not messages or messages[0] is None: return '' if len(messages) == 1: return messages[0].e...
python
{ "resource": "" }
q256196
JSONPolling.write
validation
def write(self, data): """Just quote out stuff before sending it out""" args = parse_qs(self.handler.environ.get("QUERY_STRING")) if "i" in args: i = args["i"] else: i = "0" # TODO: don't we need to quote this data in here ? super(JSONPolling, self...
python
{ "resource": "" }
q256197
BroadcastMixin.broadcast_event
validation
def broadcast_event(self, event, *args): """ This is sent to all in the sockets in this particular Namespace, including itself. """ pkt = dict(type="event", name=event, args=args, endpoint=self.ns_name) for sessid,...
python
{ "resource": "" }
q256198
RoleMixin.add_parent
validation
def add_parent(self, parent): """Add a parent to this role, and add role itself to the parent's children set. you should override this function if neccessary. Example:: logged_user = RoleMixin('logged_user') student = RoleMixin('student') student.add...
python
{ "resource": "" }
q256199
AccessControlList.allow
validation
def allow(self, role, method, resource, with_children=True): """Add allowing rules. :param role: Role of this rule. :param method: Method to allow in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Allow role's children in ru...
python
{ "resource": "" }