_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q235500
WebSocketWSGIHandler.setup_environ
train
def setup_environ(self): """ Setup the environ dictionary and add the `'ws4py.socket'` key. Its associated value is the real socket underlying socket. """ SimpleHandler.setup_environ(self) self.environ['ws4py.socket'] = get_connection(self.environ['wsgi.input']) ...
python
{ "resource": "" }
q235501
WebSocketWSGIRequestHandler.handle
train
def handle(self): """ Unfortunately the base class forces us to override the whole method to actually provide our wsgi handler. """ self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return ...
python
{ "resource": "" }
q235502
INA219.configure
train
def configure(self, voltage_range=RANGE_32V, gain=GAIN_AUTO, bus_adc=ADC_12BIT, shunt_adc=ADC_12BIT): """ Configures and calibrates how the INA219 will take measurements. Arguments: voltage_range -- The full scale voltage range, this is either 16V or 32V represente...
python
{ "resource": "" }
q235503
INA219.wake
train
def wake(self): """ Wake the INA219 from power down mode """ configuration = self._read_configuration() self._configuration_register(configuration | 0x0007) # 40us delay to recover from powerdown (p14 of spec) time.sleep(0.00004)
python
{ "resource": "" }
q235504
_return_response_and_status_code
train
def _return_response_and_status_code(response, json_results=True): """ Output the requests response content or content as json and status code :rtype : dict :param response: requests response object :param json_results: Should return JSON or raw content :return: dict containing the response content...
python
{ "resource": "" }
q235505
PublicApi.put_comments
train
def put_comments(self, resource, comment, timeout=None): """ Post a comment on a file or URL. The initial idea of VirusTotal Community was that users should be able to make comments on files and URLs, the comments may be malware analyses, false positive flags, disinfection instructions, etc. ...
python
{ "resource": "" }
q235506
PublicApi.get_ip_report
train
def get_ip_report(self, this_ip, timeout=None): """ Get IP address reports. :param this_ip: a valid IPv4 address in dotted quad notation, for the time being only IPv4 addresses are supported. :param timeout: The amount of time in seconds the request should wait before ti...
python
{ "resource": "" }
q235507
PublicApi.get_domain_report
train
def get_domain_report(self, this_domain, timeout=None): """ Get information about a given domain. :param this_domain: a domain name. :param timeout: The amount of time in seconds the request should wait before timing out. :return: JSON response """ params = {'apikey': s...
python
{ "resource": "" }
q235508
PrivateApi.get_upload_url
train
def get_upload_url(self, timeout=None): """ Get a special URL for submitted files bigger than 32MB. In order to submit files bigger than 32MB you need to obtain a special upload URL to which you can POST files up to 200MB in size. This API generates such a URL. :param timeout: The amou...
python
{ "resource": "" }
q235509
PrivateApi.file_search
train
def file_search(self, query, offset=None, timeout=None): """ Search for samples. In addition to retrieving all information on a particular file, VirusTotal allows you to perform what we call "advanced reverse searches". Reverse searches take you from a file property to a list of files that ...
python
{ "resource": "" }
q235510
PrivateApi.get_file_clusters
train
def get_file_clusters(self, this_date, timeout=None): """ File similarity clusters for a given time frame. VirusTotal has built its own in-house file similarity clustering functionality. At present, this clustering works only on PE, PDF, DOC and RTF files and is based on a very simple structura...
python
{ "resource": "" }
q235511
PrivateApi.get_url_distribution
train
def get_url_distribution(self, after=None, reports='true', limit=1000, timeout=None): """ Get a live feed with the lastest URLs submitted to VirusTotal. Allows you to retrieve a live feed of URLs submitted to VirusTotal, along with their scan reports. This call enables you to stay synced with V...
python
{ "resource": "" }
q235512
PrivateApi.get_url_feed
train
def get_url_feed(self, package=None, timeout=None): """ Get a live file feed with the latest files submitted to VirusTotal. Allows you to retrieve a live feed of reports on absolutely all URLs scanned by VirusTotal. This API requires you to stay relatively synced with the live submissions as on...
python
{ "resource": "" }
q235513
IntelApi.get_intel_notifications_feed
train
def get_intel_notifications_feed(self, page=None, timeout=None): """ Get notification feed in JSON for further processing. :param page: the next_page property of the results of a previously issued query to this API. This parameter should not be provided if it is the very first query to the ...
python
{ "resource": "" }
q235514
IntelApi.delete_intel_notifications
train
def delete_intel_notifications(self, ids, timeout=None): """ Programmatically delete notifications via the Intel API. :param ids: A list of IDs to delete from the notification feed. :returns: The post response. """ if not isinstance(ids, list): raise TypeError("ids m...
python
{ "resource": "" }
q235515
Session.get_credentials
train
def get_credentials(self): """ Returns botocore.credential.Credential object. """ return Credentials(access_key=self.aws_access_key_id, secret_key=self.aws_secret_access_key, token=self.aws_session_token)
python
{ "resource": "" }
q235516
HostCreate.form_valid
train
def form_valid(self, form): """First call the parent's form valid then let the user know it worked.""" form_valid_from_parent = super(HostCreate, self).form_valid(form) messages.success(self.request, 'Host {} Successfully Created'.format(self.object)) return form_valid_from_parent
python
{ "resource": "" }
q235517
SSHKeys.post
train
def post(self, *args, **kwargs): """Create the SSH file & then return the normal get method...""" existing_ssh = models.SSHConfig.objects.all() if existing_ssh.exists(): return self.get_view() remote_user = self.request.POST.get('remote_user', 'root') create_ssh_c...
python
{ "resource": "" }
q235518
update_sandbox_site
train
def update_sandbox_site(comment_text): """put's a text file on the server""" file_to_deliver = NamedTemporaryFile(delete=False) file_text = "Deployed at: {} <br /> Comment: {}".format(datetime.datetime.now().strftime('%c'), cgi.escape(comment_text)) file_to_deliver.write(file_text) file_to_delive...
python
{ "resource": "" }
q235519
Project.web_hooks
train
def web_hooks(self, include_global=True): """Get all web hooks for this project. Includes global hooks.""" from fabric_bolt.web_hooks.models import Hook ors = [Q(project=self)] if include_global: ors.append(Q(project=None)) hooks = Hook.objects.filter(reduce(operato...
python
{ "resource": "" }
q235520
Project.get_deployment_count
train
def get_deployment_count(self): """Utility function to get the number of deployments a given project has""" ret = self.stage_set.annotate(num_deployments=Count('deployment')).aggregate(total_deployments=Sum('num_deployments')) return ret['total_deployments']
python
{ "resource": "" }
q235521
Stage.get_configurations
train
def get_configurations(self): """ Generates a dictionary that's made up of the configurations on the project. Any configurations on a project that are duplicated on a stage, the stage configuration will take precedence. """ project_configurations_dictionary = {} project_...
python
{ "resource": "" }
q235522
Configuration.get_absolute_url
train
def get_absolute_url(self): """Determine where I am coming from and where I am going""" # Determine if this configuration is on a stage if self.stage: # Stage specific configurations go back to the stage view url = reverse('projects_stage_view', args=(self.project.pk, se...
python
{ "resource": "" }
q235523
DeployUser.gravatar
train
def gravatar(self, size=20): """ Construct a gravatar image address for the user """ default = "mm" gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?" gravatar_url += urllib.urlencode({'d': default, 's': str(size)}) r...
python
{ "resource": "" }
q235524
HookManager.hooks
train
def hooks(self, project): """ Look up the urls we need to post to""" return self.get_queryset().filter( Q(project=None) | Q(project=project) ).distinct('url')
python
{ "resource": "" }
q235525
web_hook_receiver
train
def web_hook_receiver(sender, **kwargs): """Generic receiver for the web hook firing piece.""" deployment = Deployment.objects.get(pk=kwargs.get('deployment_id')) hooks = deployment.web_hooks if not hooks: return for hook in hooks: data = payload_generator(deployment) d...
python
{ "resource": "" }
q235526
PaginateTable.paginate
train
def paginate(self, klass=Paginator, per_page=None, page=1, *args, **kwargs): """ Paginates the table using a paginator and creates a ``page`` property containing information for the current page. :type klass: Paginator class :param klass: a paginator class to paginate the...
python
{ "resource": "" }
q235527
BaseTaskRunnerBackend.get_fabric_tasks
train
def get_fabric_tasks(self, project): """ Generate a list of fabric tasks that are available """ cache_key = 'project_{}_fabfile_tasks'.format(project.pk) cached_result = cache.get(cache_key) if cached_result: return cached_result try: fa...
python
{ "resource": "" }
q235528
ProjectCopy.get_initial
train
def get_initial(self): """ Returns the initial data to use for forms on this view. """ initial = super(ProjectCopy, self).get_initial() if self.copy_object: initial.update({'name': '%s copy' % self.copy_object.name, 'description': self.copy...
python
{ "resource": "" }
q235529
ProjectConfigurationDelete.get_success_url
train
def get_success_url(self): """Get the url depending on what type of configuration I deleted.""" if self.stage_id: url = reverse('projects_stage_view', args=(self.project_id, self.stage_id)) else: url = reverse('projects_project_view', args=(self.project_id,)) re...
python
{ "resource": "" }
q235530
create_ssh_config
train
def create_ssh_config(remote_user='root', name='Auto Generated SSH Key', file_name='fabricbolt_private.key', email='deployments@fabricbolt.io', public_key_text=None, private_key_text=None): """Create SSH Key""" if not private_key_text and not public_key_text: ...
python
{ "resource": "" }
q235531
Json2Html.convert
train
def convert(self, json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True): """ Convert JSON to HTML Table format """ # table attributes such as class, id, data-attr-*, etc. # eg: table_attributes = 'class = "table table-bordered sortable"' se...
python
{ "resource": "" }
q235532
Json2Html.column_headers_from_list_of_dicts
train
def column_headers_from_list_of_dicts(self, json_input): """ This method is required to implement clubbing. It tries to come up with column headers for your input """ if not json_input \ or not hasattr(json_input, '__getitem__') \ or not hasattr(json_input...
python
{ "resource": "" }
q235533
Json2Html.convert_list
train
def convert_list(self, list_input): """ Iterate over the JSON list and process it to generate either an HTML table or a HTML list, depending on what's inside. If suppose some key has array of objects and all the keys are same, instead of creating a new row for eac...
python
{ "resource": "" }
q235534
Json2Html.convert_object
train
def convert_object(self, json_input): """ Iterate over the JSON object and process it to generate the super awesome HTML Table format """ if not json_input: return "" #avoid empty tables converted_output = self.table_init_markup + "<tr>" conver...
python
{ "resource": "" }
q235535
HomeData.personsAtHome
train
def personsAtHome(self, home=None): """ Return the list of known persons who are currently at home """ if not home: home = self.default_home home_data = self.homeByName(home) atHome = [] for p in home_data['persons']: #Only check known persons ...
python
{ "resource": "" }
q235536
HomeData.getProfileImage
train
def getProfileImage(self, name): """ Retrieve the face of a given person """ for p in self.persons: if 'pseudo' in self.persons[p]: if name == self.persons[p]['pseudo']: image_id = self.persons[p]['face']['id'] key = sel...
python
{ "resource": "" }
q235537
HomeData.updateEvent
train
def updateEvent(self, event=None, home=None): """ Update the list of event with the latest ones """ if not home: home=self.default_home if not event: #If not event is provided we need to retrieve the oldest of the last event seen by each camera listEvent =...
python
{ "resource": "" }
q235538
HomeData.personSeenByCamera
train
def personSeenByCamera(self, name, home=None, camera=None): """ Return True if a specific person has been seen by a camera """ try: cam_id = self.cameraByName(camera=camera, home=home)['id'] except TypeError: logger.warning("personSeenByCamera: Camera name...
python
{ "resource": "" }
q235539
HomeData.someoneKnownSeen
train
def someoneKnownSeen(self, home=None, camera=None): """ Return True if someone known has been seen """ try: cam_id = self.cameraByName(camera=camera, home=home)['id'] except TypeError: logger.warning("personSeenByCamera: Camera name or home is unknown") ...
python
{ "resource": "" }
q235540
HomeData.motionDetected
train
def motionDetected(self, home=None, camera=None): """ Return True if movement has been detected """ try: cam_id = self.cameraByName(camera=camera, home=home)['id'] except TypeError: logger.warning("personSeenByCamera: Camera name or home is unknown") ...
python
{ "resource": "" }
q235541
batch
train
def batch(sequence, callback, size=100, **kwargs): """Helper to setup batch requests. There are endpoints which support updating multiple resources at once, but they are often limited to 100 updates per request. This function helps with splitting bigger requests into sequence of smaller ones. ...
python
{ "resource": "" }
q235542
Zendesk._handle_retry
train
def _handle_retry(self, resp): """Handle any exceptions during API request or parsing its response status code. Parameters: resp: requests.Response instance obtained during concerning request or None, when request failed Returns: True if should retry our request or ...
python
{ "resource": "" }
q235543
notification_redirect
train
def notification_redirect(request, ctx): """ Helper to handle HTTP response after an action is performed on notification :param request: HTTP request context of the notification :param ctx: context to be returned when a AJAX call is made. :returns: Either JSON for AJAX or redirects to the calcula...
python
{ "resource": "" }
q235544
mark
train
def mark(request): """ Handles marking of individual notifications as read or unread. Takes ``notification id`` and mark ``action`` as POST data. :param request: HTTP request context. :returns: Response to mark action of supplied notification ID. """ notification_id = request.POST.get('id'...
python
{ "resource": "" }
q235545
mark_all
train
def mark_all(request): """ Marks notifications as either read or unread depending of POST parameters. Takes ``action`` as POST data, it can either be ``read`` or ``unread``. :param request: HTTP Request context. :return: Response to mark_all action. """ action = request.POST.get('action', ...
python
{ "resource": "" }
q235546
delete
train
def delete(request): """ Deletes notification of supplied notification ID. Depending on project settings, if ``NOTIFICATIONS_SOFT_DELETE`` is set to ``False``, the notifications will be deleted from DB. If not, a soft delete will be performed. By default, notifications are deleted softly. ...
python
{ "resource": "" }
q235547
notification_update
train
def notification_update(request): """ Handles live updating of notifications, follows ajax-polling approach. Read more: http://stackoverflow.com/a/12855533/4726598 Required URL parameters: ``flag``. Explanation: - The ``flag`` parameter carries the last notification ID \ received...
python
{ "resource": "" }
q235548
read_and_redirect
train
def read_and_redirect(request, notification_id): """ Marks the supplied notification as read and then redirects to the supplied URL from the ``next`` URL parameter. **IMPORTANT**: This is CSRF - unsafe method. Only use it if its okay for you to mark notifications \ as read without a robust chec...
python
{ "resource": "" }
q235549
HikCamera.get_motion_detection
train
def get_motion_detection(self): """Fetch current motion state from camera""" url = ('%s/ISAPI/System/Video/inputs/' 'channels/1/motionDetection') % self.root_url try: response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT) except (requests.exceptions.Req...
python
{ "resource": "" }
q235550
HikCamera._set_motion_detection
train
def _set_motion_detection(self, enable): """Set desired motion detection state on camera""" url = ('%s/ISAPI/System/Video/inputs/' 'channels/1/motionDetection') % self.root_url enabled = self._motion_detection_xml.find(self.element_query('enabled')) if enabled is None: ...
python
{ "resource": "" }
q235551
HikCamera.add_update_callback
train
def add_update_callback(self, callback, sensor): """Register as callback for when a matching device sensor changes.""" self._updateCallbacks.append([callback, sensor]) _LOGGING.debug('Added update callback to %s on %s', callback, sensor)
python
{ "resource": "" }
q235552
HikCamera.initialize
train
def initialize(self): """Initialize deviceInfo and available events.""" device_info = self.get_device_info() if device_info is None: self.name = None self.cam_id = None self.event_states = None return for key in device_info: i...
python
{ "resource": "" }
q235553
HikCamera.get_event_triggers
train
def get_event_triggers(self): """ Returns dict of supported events. Key = Event Type List = Channels that have that event activated """ events = {} nvrflag = False event_xml = [] url = '%s/ISAPI/Event/triggers' % self.root_url try: ...
python
{ "resource": "" }
q235554
HikCamera.get_device_info
train
def get_device_info(self): """Parse deviceInfo into dictionary.""" device_info = {} url = '%s/ISAPI/System/deviceInfo' % self.root_url using_digest = False try: response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT) if response.status_code == reque...
python
{ "resource": "" }
q235555
HikCamera.watchdog_handler
train
def watchdog_handler(self): """Take care of threads if wachdog expires.""" _LOGGING.debug('%s Watchdog expired. Resetting connection.', self.name) self.watchdog.stop() self.reset_thrd.set()
python
{ "resource": "" }
q235556
HikCamera.disconnect
train
def disconnect(self): """Disconnect from event stream.""" _LOGGING.debug('Disconnecting from stream: %s', self.name) self.kill_thrd.set() self.thrd.join() _LOGGING.debug('Event stream thread for %s is stopped', self.name) self.kill_thrd.clear()
python
{ "resource": "" }
q235557
HikCamera.alert_stream
train
def alert_stream(self, reset_event, kill_event): """Open event stream.""" _LOGGING.debug('Stream Thread Started: %s, %s', self.name, self.cam_id) start_event = False parse_string = "" fail_count = 0 url = '%s/ISAPI/Event/notification/alertStream' % self.root_url ...
python
{ "resource": "" }
q235558
HikCamera.process_stream
train
def process_stream(self, tree): """Process incoming event stream packets.""" try: etype = SENSOR_MAP[tree.find( self.element_query('eventType')).text.lower()] estate = tree.find( self.element_query('eventState')).text echid = tree.find(...
python
{ "resource": "" }
q235559
HikCamera.update_stale
train
def update_stale(self): """Update stale active statuses""" # Some events don't post an inactive XML, only active. # If we don't get an active update for 5 seconds we can # assume the event is no longer active and update accordingly. for etype, echannels in self.event_states.items...
python
{ "resource": "" }
q235560
HikCamera.publish_changes
train
def publish_changes(self, etype, echid): """Post updates for specified event type.""" _LOGGING.debug('%s Update: %s, %s', self.name, etype, self.fetch_attributes(etype, echid)) signal = 'ValueChanged.{}'.format(self.cam_id) sender = '{}.{}'.format(etype, echid) ...
python
{ "resource": "" }
q235561
Watchdog.start
train
def start(self): """ Starts the watchdog timer. """ self._timer = Timer(self.time, self.handler) self._timer.daemon = True self._timer.start() return
python
{ "resource": "" }
q235562
HikCamObject.flip_motion
train
def flip_motion(self, value): """Toggle motion detection""" if value: self.cam.enable_motion_detection() else: self.cam.disable_motion_detection()
python
{ "resource": "" }
q235563
HikSensor.update_callback
train
def update_callback(self, msg): """ get updates. """ print('Callback: {}'.format(msg)) print('{}:{} @ {}'.format(self.name, self._sensor_state(), self._sensor_last_update()))
python
{ "resource": "" }
q235564
NavigationItem.render
train
def render(self, renderer=None, **kwargs): """Render the navigational item using a renderer. :param renderer: An object implementing the :class:`~.Renderer` interface. :return: A markupsafe string with the rendered result. """ return Markup(get_renderer(...
python
{ "resource": "" }
q235565
Renderer.visit_object
train
def visit_object(self, node): """Fallback rendering for objects. If the current application is in debug-mode (``flask.current_app.debug`` is ``True``), an ``<!-- HTML comment -->`` will be rendered, indicating which class is missing a visitation function. Outside of deb...
python
{ "resource": "" }
q235566
register_renderer
train
def register_renderer(app, id, renderer, force=True): """Registers a renderer on the application. :param app: The :class:`~flask.Flask` application to register the renderer on :param id: Internal id-string for the renderer :param renderer: Renderer to register :param force: Whether ...
python
{ "resource": "" }
q235567
get_renderer
train
def get_renderer(app, id): """Retrieve a renderer. :param app: :class:`~flask.Flask` application to look ``id`` up on :param id: Internal renderer id-string to look up """ renderer = app.extensions.get('nav_renderers', {})[id] if isinstance(renderer, tuple): mod_name, cls_name = render...
python
{ "resource": "" }
q235568
Nav.init_app
train
def init_app(self, app): """Initialize an application. :param app: A :class:`~flask.Flask` app. """ if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['nav'] = self app.add_template_global(self.elems, 'nav') # register some render...
python
{ "resource": "" }
q235569
Nav.navigation
train
def navigation(self, id=None): """Function decorator for navbar registration. Convenience function, calls :meth:`.register_element` with ``id`` and the decorated function as ``elem``. :param id: ID to pass on. If ``None``, uses the decorated functions name. "...
python
{ "resource": "" }
q235570
Nav.renderer
train
def renderer(self, id=None, force=True): """Class decorator for Renderers. The decorated class will be added to the list of renderers kept by this instance that will be registered on the app upon app initialization. :param id: Id for the renderer, defaults to the class name in snake ...
python
{ "resource": "" }
q235571
parse_time
train
def parse_time(time): """Parses date and time from input string in OpenVPN logging format.""" if isinstance(time, datetime.datetime): return time return datetime.datetime.strptime(time, DATETIME_FORMAT_OPENVPN)
python
{ "resource": "" }
q235572
LoRaPayload.decrypt
train
def decrypt(self, key, dev_addr): """ Decrypt the actual payload in this LoraPayload. key: 16-byte hex-encoded AES key. (i.e. AABBCCDDEEFFAABBCCDDEEFFAABBCCDD) dev_addr: 4-byte hex-encoded DevAddr (i.e. AABBCCDD) """ sequence_counter = int(self.FCntUp) return lo...
python
{ "resource": "" }
q235573
LogParser.parse
train
def parse(self): """Parses the status log. :raises ParsingError: if syntax error found in the log. :return: The :class:`.models.Status` with filled data. """ status = Status() self.expect_line(Status.client_list.label) status.updated_at = self.expect_tuple(Statu...
python
{ "resource": "" }
q235574
parse_status
train
def parse_status(status_log, encoding='utf-8'): """Parses the status log of OpenVPN. :param status_log: The content of status log. :type status_log: :class:`str` :param encoding: Optional. The encoding of status log. :type encoding: :class:`str` :return: The instance of :class:`.models.Status` ...
python
{ "resource": "" }
q235575
Datastream.version
train
def version(self): """Return version of the TR DWE.""" res = self.client.service.Version() return '.'.join([ustr(x) for x in res[0]])
python
{ "resource": "" }
q235576
Datastream.system_info
train
def system_info(self): """Return system information.""" res = self.client.service.SystemInfo() res = {ustr(x[0]): x[1] for x in res[0]} to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]]) res['OSVersion'] = to_str(res['OSVersion']) res['RuntimeVersion'] = to_str(res...
python
{ "resource": "" }
q235577
Datastream.sources
train
def sources(self): """Return available sources of data.""" res = self.client.service.Sources(self.userdata, 0) return [ustr(x[0]) for x in res[0]]
python
{ "resource": "" }
q235578
Datastream.status
train
def status(self, record=None): """Extract status from the retrieved data and save it as a property of an object. If record with data is not specified then the status of previous operation is returned. status - dictionary with data source, string with request and status type, ...
python
{ "resource": "" }
q235579
Datastream.construct_request
train
def construct_request(ticker, fields=None, date=None, date_from=None, date_to=None, freq=None): """Construct a request string for querying TR DWE. tickers - ticker or symbol fields - list of fields. date - date for a single-date query da...
python
{ "resource": "" }
q235580
Datastream.fetch
train
def fetch(self, tickers, fields=None, date=None, date_from=None, date_to=None, freq='D', only_data=True, static=False): """Fetch data from TR DWE. tickers - ticker or list of tickers fields - list of fields. date - date for a single-date query date_...
python
{ "resource": "" }
q235581
Datastream.get_OHLCV
train
def get_OHLCV(self, ticker, date=None, date_from=None, date_to=None): """Get Open, High, Low, Close prices and daily Volume for a given ticker. ticker - ticker or symbol date - date for a single-date query date_from, date_to - date range (used only if "date" is not specifie...
python
{ "resource": "" }
q235582
Datastream.get_constituents
train
def get_constituents(self, index_ticker, date=None, only_list=False): """ Get a list of all constituents of a given index. index_ticker - Datastream ticker for index date - date for which list should be retrieved (if None then list of present constitue...
python
{ "resource": "" }
q235583
check_encoding_chars
train
def check_encoding_chars(encoding_chars): """ Validate the given encoding chars :type encoding_chars: ``dict`` :param encoding_chars: the encoding chars (see :func:`hl7apy.set_default_encoding_chars`) :raises: :exc:`hl7apy.exceptions.InvalidEncodingChars` if the given encoding chars are not valid ...
python
{ "resource": "" }
q235584
check_validation_level
train
def check_validation_level(validation_level): """ Validate the given validation level :type validation_level: ``int`` :param validation_level: validation level (see :class:`hl7apy.consts.VALIDATION_LEVEL`) :raises: :exc:`hl7apy.exceptions.UnknownValidationLevel` if the given validation level is uns...
python
{ "resource": "" }
q235585
load_library
train
def load_library(version): """ Load the correct module according to the version :type version: ``str`` :param version: the version of the library to be loaded (e.g. '2.6') :rtype: module object """ check_version(version) module_name = SUPPORTED_LIBRARIES[version] lib = sys.modules.g...
python
{ "resource": "" }
q235586
load_reference
train
def load_reference(name, element_type, version): """ Look for an element of the given type, name and version and return its reference structure :type element_type: ``str`` :param element_type: the element type to look for (e.g. 'Segment') :type name: ``str`` :param name: the element name to loo...
python
{ "resource": "" }
q235587
find_reference
train
def find_reference(name, element_types, version): """ Look for an element of the given name and version into the given types and return its reference structure :type name: ``str`` :param name: the element name to look for (e.g. 'MSH') :type types: ``list`` or ``tuple`` :param types: the element...
python
{ "resource": "" }
q235588
get_date_info
train
def get_date_info(value): """ Returns the datetime object and the format of the date in input :type value: `str` """ fmt = _get_date_format(value) dt_value = _datetime_obj_factory(value, fmt) return dt_value, fmt
python
{ "resource": "" }
q235589
get_timestamp_info
train
def get_timestamp_info(value): """ Returns the datetime object, the format, the offset and the microsecond of the timestamp in input :type value: `str` """ value, offset = _split_offset(value) fmt, microsec = _get_timestamp_format(value) dt_value = _datetime_obj_factory(value, fmt) retu...
python
{ "resource": "" }
q235590
get_datetime_info
train
def get_datetime_info(value): """ Returns the datetime object, the format, the offset and the microsecond of the datetime in input :type value: `str` """ date_value, offset = _split_offset(value) date_format = _get_date_format(date_value[:8]) try: timestamp_form, microsec = _get_ti...
python
{ "resource": "" }
q235591
is_base_datatype
train
def is_base_datatype(datatype, version=None): """ Check if the given datatype is a base datatype of the specified version :type datatype: ``str`` :param datatype: the datatype (e.g. ST) :type version: ``str`` :param version: the HL7 version (e.g. 2.5) :return: ``True`` if it is a base dat...
python
{ "resource": "" }
q235592
ElementList.get_ordered_children
train
def get_ordered_children(self): """ Return the list of children ordered according to the element structure :return: a list of :class:`Element <hl7apy.core.Element>` """ ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else [] chil...
python
{ "resource": "" }
q235593
ElementList.insert
train
def insert(self, index, child, by_name_index=-1): """ Add the child at the given index :type index: ``int`` :param index: child position :type child: :class:`Element <hl7apy.core.Element>` :param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass ...
python
{ "resource": "" }
q235594
ElementList.append
train
def append(self, child): """ Append the given child :class:`Element <hl7apy.core.Element>` :param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass """ if self._can_add_child(child): if self.element == child.parent: self...
python
{ "resource": "" }
q235595
ElementList.set
train
def set(self, name, value, index=-1): """ Assign the ``value`` to the child having the given ``name`` at the ``index`` position :type name: ``str`` :param name: the child name (e.g. PID) :type value: an instance of :class:`Element <hl7apy.core.Element>`, a `str` or an instance ...
python
{ "resource": "" }
q235596
ElementList.remove
train
def remove(self, child): """ Remove the given child from both child list and child indexes :type child: :class:`Element <hl7apy.core.Element>` :param child: an instance of :class:`Element <hl7apy.core.Element>` subclass """ try: if self.element == child.trave...
python
{ "resource": "" }
q235597
ElementList.remove_by_name
train
def remove_by_name(self, name, index=0): """ Remove the child having the given name at the given position :type name: ``str`` :param name: child name (e.g. PID) :type index: ``int`` :param index: child index :return: an instance of :class:`Element <hl7apy.core....
python
{ "resource": "" }
q235598
ElementList.child_at_index
train
def child_at_index(self, name, index): """ Return the child named `name` at the given index :type name: ``str`` :param name: child name (e.g. PID) :type index: ``int`` :param index: child index :return: an instance of :class:`Element <hl7apy.core.Element>` subc...
python
{ "resource": "" }
q235599
ElementList.create_element
train
def create_element(self, name, traversal_parent=False, reference=None): """ Create an element having the given name :type name: ``str`` :param name: the name of the element to be created (e.g. PID) :type traversal_parent: ``bool`` :param traversal_parent: if ``True``, t...
python
{ "resource": "" }