_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q271500
QueueProcessor._handle_auth
test
def _handle_auth(self, dtype, data, ts): """Handles authentication responses. :param dtype: :param data: :param ts: :return: """ # Contains keys status, chanId, userId, caps if dtype == 'unauth': raise NotImplementedError channel_id = ...
python
{ "resource": "" }
q271501
QueueProcessor._handle_conf
test
def _handle_conf(self, dtype, data, ts): """Handles configuration messages. :param dtype: :param data: :param ts: :return: """ self.log.debug("_handle_conf: %s - %s - %s", dtype, data, ts) self.log.info("Configuration accepted: %s", dtype) return
python
{ "resource": "" }
q271502
QueueProcessor.update_timestamps
test
def update_timestamps(self, chan_id, ts): """Updates the timestamp for the given channel id. :param chan_id: :param ts: :return: """ try: self.last_update[chan_id] = ts except KeyError: self.log.warning("Attempted ts update of channel %s, ...
python
{ "resource": "" }
q271503
BtfxWss.reset
test
def reset(self): """Reset the client. :return: """ self.conn.reconnect() while not self.conn.connected.is_set(): log.info("reset(): Waiting for connection to be set up..") time.sleep(1) for key in self.channel_configs: self.conn.send(...
python
{ "resource": "" }
q271504
BtfxWss.candles
test
def candles(self, pair, timeframe=None): """Return a queue containing all received candles data. :param pair: str, Symbol pair to request data for :param timeframe: str :return: Queue() """ timeframe = '1m' if not timeframe else timeframe key = ('candles', pair, ...
python
{ "resource": "" }
q271505
BtfxWss.config
test
def config(self, decimals_as_strings=True, ts_as_dates=False, sequencing=False, ts=False, **kwargs): """Send configuration to websocket server :param decimals_as_strings: bool, turn on/off decimals as strings :param ts_as_dates: bool, decide to request timestamps as dates instead...
python
{ "resource": "" }
q271506
BtfxWss.subscribe_to_ticker
test
def subscribe_to_ticker(self, pair, **kwargs): """Subscribe to the passed pair's ticker channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('ticker', pair) self._subscribe('ticker', identifier, symbol=pair, **kwarg...
python
{ "resource": "" }
q271507
BtfxWss.unsubscribe_from_ticker
test
def unsubscribe_from_ticker(self, pair, **kwargs): """Unsubscribe to the passed pair's ticker channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('ticker', pair) self._unsubscribe('ticker', identifier, symbol=pair,...
python
{ "resource": "" }
q271508
BtfxWss.subscribe_to_order_book
test
def subscribe_to_order_book(self, pair, **kwargs): """Subscribe to the passed pair's order book channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('book', pair) self._subscribe('book', identifier, symbol=pair, **k...
python
{ "resource": "" }
q271509
BtfxWss.unsubscribe_from_order_book
test
def unsubscribe_from_order_book(self, pair, **kwargs): """Unsubscribe to the passed pair's order book channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('book', pair) self._unsubscribe('book', identifier, symbol=p...
python
{ "resource": "" }
q271510
BtfxWss.subscribe_to_raw_order_book
test
def subscribe_to_raw_order_book(self, pair, prec=None, **kwargs): """Subscribe to the passed pair's raw order book channel. :param pair: str, Symbol pair to request data for :param prec: :param kwargs: :return: """ identifier = ('raw_book', pair) prec = '...
python
{ "resource": "" }
q271511
BtfxWss.unsubscribe_from_raw_order_book
test
def unsubscribe_from_raw_order_book(self, pair, prec=None, **kwargs): """Unsubscribe to the passed pair's raw order book channel. :param pair: str, Symbol pair to request data for :param prec: :param kwargs: :return: """ identifier = ('raw_book', pair) pr...
python
{ "resource": "" }
q271512
BtfxWss.subscribe_to_trades
test
def subscribe_to_trades(self, pair, **kwargs): """Subscribe to the passed pair's trades channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('trades', pair) self._subscribe('trades', identifier, symbol=pair, **kwarg...
python
{ "resource": "" }
q271513
BtfxWss.unsubscribe_from_trades
test
def unsubscribe_from_trades(self, pair, **kwargs): """Unsubscribe to the passed pair's trades channel. :param pair: str, Symbol pair to request data for :param kwargs: :return: """ identifier = ('trades', pair) self._unsubscribe('trades', identifier, symbol=pair,...
python
{ "resource": "" }
q271514
BtfxWss.subscribe_to_candles
test
def subscribe_to_candles(self, pair, timeframe=None, **kwargs): """Subscribe to the passed pair's OHLC data channel. :param pair: str, Symbol pair to request data for :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwarg...
python
{ "resource": "" }
q271515
BtfxWss.unsubscribe_from_candles
test
def unsubscribe_from_candles(self, pair, timeframe=None, **kwargs): """Unsubscribe to the passed pair's OHLC data channel. :param timeframe: str, {1m, 5m, 15m, 30m, 1h, 3h, 6h, 12h, 1D, 7D, 14D, 1M} :param kwargs: :return: """ valid_tfs =...
python
{ "resource": "" }
q271516
BtfxWss.authenticate
test
def authenticate(self): """Authenticate with the Bitfinex API. :return: """ if not self.key and not self.secret: raise ValueError("Must supply both key and secret key for API!") self.channel_configs['auth'] = {'api_key': self.key, 'secret': self.secret} self....
python
{ "resource": "" }
q271517
BtfxWss.cancel_order
test
def cancel_order(self, multi=False, **order_identifiers): """Cancel one or multiple orders via Websocket. :param multi: bool, whether order_settings contains settings for one, or multiples orders :param order_identifiers: Identifiers for the order(s) you with to cancel ...
python
{ "resource": "" }
q271518
GatewayClient._onCommand
test
def _onCommand(self, client, userdata, pahoMessage): """ Internal callback for device command messages, parses source device from topic string and passes the information on to the registered device command callback """ try: command = Command(pahoMessage, self._message...
python
{ "resource": "" }
q271519
GatewayClient._onDeviceCommand
test
def _onDeviceCommand(self, client, userdata, pahoMessage): """ Internal callback for gateway command messages, parses source device from topic string and passes the information on to the registered device command callback """ try: command = Command(pahoMessage, self._...
python
{ "resource": "" }
q271520
GatewayClient._onMessageNotification
test
def _onMessageNotification(self, client, userdata, pahoMessage): """ Internal callback for gateway notification messages, parses source device from topic string and passes the information on to the registered device command callback """ try: note = Notification(pahoMe...
python
{ "resource": "" }
q271521
DeviceTypes.create
test
def create(self, deviceType): """ Register one or more new device types, each request can contain a maximum of 512KB. """ r = self._apiClient.post("api/v0002/device/types", deviceType) if r.status_code == 201: return DeviceType(apiClient=self._apiClient, **r.json())...
python
{ "resource": "" }
q271522
DeviceClient.publishEvent
test
def publishEvent(self, event, msgFormat, data, qos=0, on_publish=None): """ Publish an event to Watson IoT Platform. # Parameters event (string): Name of this event msgFormat (string): Format of the data for this event data (dict): Data for this event qos (int): ...
python
{ "resource": "" }
q271523
Devices.update
test
def update(self, deviceUid, metadata=None, deviceInfo=None, status=None): """ Update an existing device """ if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict): deviceUid = DeviceUid(**deviceUid) deviceUrl = "api/v0002/device/types/%s/devices/%s"...
python
{ "resource": "" }
q271524
ConnectionStatus.find
test
def find(self, status=None, connectedAfter=None): """ Iterate through all Connectors """ queryParms = {} if status: queryParms["status"] = status if connectedAfter: queryParms["connectedAfter"] = connectedAfter return IterableClientStatusL...
python
{ "resource": "" }
q271525
MgmtExtensions.list
test
def list(self): """ List all device management extension packages """ url = "api/v0002/mgmt/custom/bundle" r = self._apiClient.get(url) if r.status_code == 200: return r.json() else: raise ApiException(r)
python
{ "resource": "" }
q271526
MgmtExtensions.create
test
def create(self, dmeData): """ Create a new device management extension package In case of failure it throws APIException """ url = "api/v0002/mgmt/custom/bundle" r = self._apiClient.post(url, dmeData) if r.status_code == 201: return r.json() ...
python
{ "resource": "" }
q271527
updateSchema
test
def updateSchema(self, schemaId, schemaDefinition): """ Update a schema. Throws APIException on failure. """ req = ApiClient.oneSchemaUrl % (self.host, "/draft", schemaId) body = {"schemaDefinition": schemaDefinition} resp = requests.put(req, auth=self.credentials, header...
python
{ "resource": "" }
q271528
AbstractClient.disconnect
test
def disconnect(self): """ Disconnect the client from IBM Watson IoT Platform """ # self.logger.info("Closing connection to the IBM Watson IoT Platform") self.client.disconnect() # If we don't call loop_stop() it appears we end up with a zombie thread which continues to pr...
python
{ "resource": "" }
q271529
AbstractClient._onConnect
test
def _onConnect(self, mqttc, userdata, flags, rc): """ Called when the broker responds to our connection request. The value of rc determines success or not: 0: Connection successful 1: Connection refused - incorrect protocol version 2: Connection refused - inv...
python
{ "resource": "" }
q271530
ApplicationClient.subscribeToDeviceEvents
test
def subscribeToDeviceEvents(self, typeId="+", deviceId="+", eventId="+", msgFormat="+", qos=0): """ Subscribe to device event messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): device...
python
{ "resource": "" }
q271531
ApplicationClient.subscribeToDeviceStatus
test
def subscribeToDeviceStatus(self, typeId="+", deviceId="+"): """ Subscribe to device status messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceId for the subscription, optional....
python
{ "resource": "" }
q271532
ApplicationClient.subscribeToDeviceCommands
test
def subscribeToDeviceCommands(self, typeId="+", deviceId="+", commandId="+", msgFormat="+"): """ Subscribe to device command messages # Parameters typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard) deviceId (string): deviceI...
python
{ "resource": "" }
q271533
ApplicationClient.publishCommand
test
def publishCommand(self, typeId, deviceId, commandId, msgFormat, data=None, qos=0, on_publish=None): """ Publish a command to a device # Parameters typeId (string) : The type of the device this command is to be published to deviceId (string): The id of the device this command is...
python
{ "resource": "" }
q271534
ApplicationClient._onUnsupportedMessage
test
def _onUnsupportedMessage(self, client, userdata, message): """ Internal callback for messages that have not been handled by any of the specific internal callbacks, these messages are not passed on to any user provided callback """ self.logger.warning( "Received messa...
python
{ "resource": "" }
q271535
ApplicationClient._onDeviceEvent
test
def _onDeviceEvent(self, client, userdata, pahoMessage): """ Internal callback for device event messages, parses source device from topic string and passes the information on to the registerd device event callback """ try: event = Event(pahoMessage, self._messageCodec...
python
{ "resource": "" }
q271536
ApplicationClient._onDeviceStatus
test
def _onDeviceStatus(self, client, userdata, pahoMessage): """ Internal callback for device status messages, parses source device from topic string and passes the information on to the registerd device status callback """ try: status = Status(pahoMessage) s...
python
{ "resource": "" }
q271537
ApplicationClient._onAppStatus
test
def _onAppStatus(self, client, userdata, pahoMessage): """ Internal callback for application command messages, parses source application from topic string and passes the information on to the registerd applicaion status callback """ try: status = Status(pahoMessage) ...
python
{ "resource": "" }
q271538
LEC.get
test
def get(self, deviceUid, eventId): """ Retrieves the last cached message for specified event from a specific device. """ if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict): deviceUid = DeviceUid(**deviceUid) url = "api/v0002/device/types/%s/devi...
python
{ "resource": "" }
q271539
LEC.getAll
test
def getAll(self, deviceUid): """ Retrieves a list of the last cached message for all events from a specific device. """ if not isinstance(deviceUid, DeviceUid) and isinstance(deviceUid, dict): deviceUid = DeviceUid(**deviceUid) url = "api/v0002/device/types/%s/devic...
python
{ "resource": "" }
q271540
IterableList._makeApiCall
test
def _makeApiCall(self, parameters=None): """ Retrieve bulk devices It accepts accepts a list of parameters In case of failure it throws Exception """ r = self._apiClient.get(self._url, parameters) if r.status_code == 200: return r.json() else: ...
python
{ "resource": "" }
q271541
MgmtRequests.initiate
test
def initiate(self, request): """ Initiates a device management request, such as reboot. In case of failure it throws APIException """ url = MgmtRequests.mgmtRequests r = self._apiClient.post(url, request) if r.status_code == 202: return r.json() ...
python
{ "resource": "" }
q271542
MgmtRequests.getStatus
test
def getStatus(self, requestId, typeId=None, deviceId=None): """ Get a list of device management request device statuses. Get an individual device mangaement request device status. """ if typeId is None or deviceId is None: url = MgmtRequests.mgmtRequestStatus % (reque...
python
{ "resource": "" }
q271543
Index.close
test
def close(self): """Force a flush of the index to storage. Renders index inaccessible.""" if self.handle: self.handle.destroy() self.handle = None else: raise IOError("Unclosable index")
python
{ "resource": "" }
q271544
Index.count
test
def count(self, coordinates): """Return number of objects that intersect the given coordinates. :param coordinates: sequence or array This may be an object that satisfies the numpy array protocol, providing the index's dimension * 2 coordinate pairs representing the ...
python
{ "resource": "" }
q271545
Index.nearest
test
def nearest(self, coordinates, num_results=1, objects=False): """Returns the ``k``-nearest objects to the given coordinates. :param coordinates: sequence or array This may be an object that satisfies the numpy array protocol, providing the index's dimension * 2 coordinate ...
python
{ "resource": "" }
q271546
Index.get_bounds
test
def get_bounds(self, coordinate_interleaved=None): """Returns the bounds of the index :param coordinate_interleaved: If True, the coordinates are turned in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax], otherwise they are returned as [xmin, xmax, ymin, ymax...
python
{ "resource": "" }
q271547
Index.delete
test
def delete(self, id, coordinates): """Deletes items from the index with the given ``'id'`` within the specified coordinates. :param id: long integer A long integer that is the identifier for this index entry. IDs need not be unique to be inserted into the index, and it ...
python
{ "resource": "" }
q271548
Index._create_idx_from_stream
test
def _create_idx_from_stream(self, stream): """This function is used to instantiate the index given an iterable stream of data.""" stream_iter = iter(stream) dimension = self.properties.dimension darray = ctypes.c_double * dimension mins = darray() maxs = darray()...
python
{ "resource": "" }
q271549
CustomStorage.loadByteArray
test
def loadByteArray(self, page, returnError): """Must be overridden. Must return a string with the loaded data.""" returnError.contents.value = self.IllegalStateError raise NotImplementedError("You must override this method.") return ''
python
{ "resource": "" }
q271550
RtreeContainer.delete
test
def delete(self, obj, coordinates): """Deletes the item from the container within the specified coordinates. :param obj: object Any object. :param coordinates: sequence or array Dimension * 2 coordinate pairs, representing the min and max coordinates...
python
{ "resource": "" }
q271551
check_return
test
def check_return(result, func, cargs): "Error checking for Error calls" if result != 0: s = rt.Error_GetLastErrorMsg().decode() msg = 'LASError in "%s": %s' % \ (func.__name__, s) rt.Error_Reset() raise RTreeError(msg) return True
python
{ "resource": "" }
q271552
WSGIApp.load
test
def load(self): """ Attempt an import of the specified application """ if isinstance(self.application, str): return util.import_app(self.application) else: return self.application
python
{ "resource": "" }
q271553
Common.init_app
test
def init_app(self, app): """Initializes the Flask application with Common.""" if not hasattr(app, 'extensions'): app.extensions = {} if 'common' in app.extensions: raise RuntimeError("Flask-Common extension already initialized") app.extensions['common'] = self ...
python
{ "resource": "" }
q271554
Common.serve
test
def serve(self, workers=None, **kwargs): """Serves the Flask application.""" if self.app.debug: print(crayons.yellow('Booting Flask development server...')) self.app.run() else: print(crayons.yellow('Booting Gunicorn...')) # Start the web server....
python
{ "resource": "" }
q271555
VersatileImageFieldSerializer.to_native
test
def to_native(self, value): """For djangorestframework <=2.3.14""" context_request = None if self.context: context_request = self.context.get('request', None) return build_versatileimagefield_url_set( value, self.sizes, request=context_requ...
python
{ "resource": "" }
q271556
CroppedImage.crop_on_centerpoint
test
def crop_on_centerpoint(self, image, width, height, ppoi=(0.5, 0.5)): """ Return a PIL Image instance cropped from `image`. Image has an aspect ratio provided by dividing `width` / `height`), sized down to `width`x`height`. Any 'excess pixels' are trimmed away in respect to the ...
python
{ "resource": "" }
q271557
CroppedImage.process_image
test
def process_image(self, image, image_format, save_kwargs, width, height): """ Return a BytesIO instance of `image` cropped to `width` and `height`. Cropping will first reduce an image down to its longest side and then crop inwards centered on the Primary Point of I...
python
{ "resource": "" }
q271558
ThumbnailImage.process_image
test
def process_image(self, image, image_format, save_kwargs, width, height): """ Return a BytesIO instance of `image` that fits in a bounding box. Bounding box dimensions are `width`x`height`. """ imagefile = BytesIO() image.thumbnail( (wid...
python
{ "resource": "" }
q271559
InvertImage.process_image
test
def process_image(self, image, image_format, save_kwargs={}): """Return a BytesIO instance of `image` with inverted colors.""" imagefile = BytesIO() inv_image = ImageOps.invert(image) inv_image.save( imagefile, **save_kwargs ) return imagefile
python
{ "resource": "" }
q271560
VersatileImageFormField.to_python
test
def to_python(self, data): """Ensure data is prepped properly before handing off to ImageField.""" if data is not None: if hasattr(data, 'open'): data.open() return super(VersatileImageFormField, self).to_python(data)
python
{ "resource": "" }
q271561
VersatileImageField.process_placeholder_image
test
def process_placeholder_image(self): """ Process the field's placeholder image. Ensures the placeholder image has been saved to the same storage class as the field in a top level folder with a name specified by settings.VERSATILEIMAGEFIELD_SETTINGS['placeholder_directory_name'] ...
python
{ "resource": "" }
q271562
VersatileImageField.pre_save
test
def pre_save(self, model_instance, add): """Return field's value just before saving.""" file = super(VersatileImageField, self).pre_save(model_instance, add) self.update_ppoi_field(model_instance) return file
python
{ "resource": "" }
q271563
VersatileImageField.update_ppoi_field
test
def update_ppoi_field(self, instance, *args, **kwargs): """ Update field's ppoi field, if defined. This method is hooked up this field's pre_save method to update the ppoi immediately before the model instance (`instance`) it is associated with is saved. This field's pp...
python
{ "resource": "" }
q271564
VersatileImageField.save_form_data
test
def save_form_data(self, instance, data): """ Handle data sent from MultiValueField forms that set ppoi values. `instance`: The model instance that is being altered via a form `data`: The data sent from the form to this field which can be either: * `None`: This is unset data fro...
python
{ "resource": "" }
q271565
VersatileImageField.formfield
test
def formfield(self, **kwargs): """Return a formfield.""" # This is a fairly standard way to set up some defaults # while letting the caller override them. defaults = {} if self.ppoi_field: defaults['form_class'] = SizedImageCenterpointClickDjangoAdminField if ...
python
{ "resource": "" }
q271566
PPOIField.value_to_string
test
def value_to_string(self, obj): """Prepare field for serialization.""" if DJANGO_VERSION > (1, 9): value = self.value_from_object(obj) else: value = self._get_val_from_obj(obj) return self.get_prep_value(value)
python
{ "resource": "" }
q271567
autodiscover
test
def autodiscover(): """ Discover versatileimagefield.py modules. Iterate over django.apps.get_app_configs() and discover versatileimagefield.py modules. """ from importlib import import_module from django.apps import apps from django.utils.module_loading import module_has_submodule ...
python
{ "resource": "" }
q271568
VersatileImageFieldRegistry.unregister_sizer
test
def unregister_sizer(self, attr_name): """ Unregister the SizedImage subclass currently assigned to `attr_name`. If a SizedImage subclass isn't already registered to `attr_name` NotRegistered will raise. """ if attr_name not in self._sizedimage_registry: rais...
python
{ "resource": "" }
q271569
VersatileImageFieldRegistry.unregister_filter
test
def unregister_filter(self, attr_name): """ Unregister the FilteredImage subclass currently assigned to attr_name. If a FilteredImage subclass isn't already registered to filters. `attr_name` NotRegistered will raise. """ if attr_name not in self._filter_registry: ...
python
{ "resource": "" }
q271570
VersatileImageMixIn.url
test
def url(self): """ Return the appropriate URL. URL is constructed based on these field conditions: * If empty (not `self.name`) and a placeholder is defined, the URL to the placeholder is returned. * Otherwise, defaults to vanilla ImageFieldFile behavior. ...
python
{ "resource": "" }
q271571
VersatileImageMixIn.build_filters_and_sizers
test
def build_filters_and_sizers(self, ppoi_value, create_on_demand): """Build the filters and sizers for a field.""" name = self.name if not name and self.field.placeholder_image_name: name = self.field.placeholder_image_name self.filters = FilterLibrary( name, ...
python
{ "resource": "" }
q271572
VersatileImageMixIn.get_filtered_root_folder
test
def get_filtered_root_folder(self): """Return the location where filtered images are stored.""" folder, filename = os.path.split(self.name) return os.path.join(folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME, '')
python
{ "resource": "" }
q271573
VersatileImageMixIn.get_sized_root_folder
test
def get_sized_root_folder(self): """Return the location where sized images are stored.""" folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '')
python
{ "resource": "" }
q271574
VersatileImageMixIn.get_filtered_sized_root_folder
test
def get_filtered_sized_root_folder(self): """Return the location where filtered + sized images are stored.""" sized_root_folder = self.get_sized_root_folder() return os.path.join( sized_root_folder, VERSATILEIMAGEFIELD_FILTERED_DIRNAME )
python
{ "resource": "" }
q271575
VersatileImageMixIn.delete_matching_files_from_storage
test
def delete_matching_files_from_storage(self, root_folder, regex): """ Delete files in `root_folder` which match `regex` before file ext. Example values: * root_folder = 'foo/' * self.name = 'bar.jpg' * regex = re.compile('-baz') Result: ...
python
{ "resource": "" }
q271576
ProcessedImage.preprocess
test
def preprocess(self, image, image_format): """ Preprocess an image. An API hook for image pre-processing. Calls any image format specific pre-processors (if defined). I.E. If `image_format` is 'JPEG', this method will look for a method named `preprocess_JPEG`, if found `...
python
{ "resource": "" }
q271577
ProcessedImage.preprocess_GIF
test
def preprocess_GIF(self, image, **kwargs): """ Receive a PIL Image instance of a GIF and return 2-tuple. Args: * [0]: Original Image instance (passed to `image`) * [1]: Dict with a transparency key (to GIF transparency layer) """ if 'transparency' in imag...
python
{ "resource": "" }
q271578
ProcessedImage.preprocess_JPEG
test
def preprocess_JPEG(self, image, **kwargs): """ Receive a PIL Image instance of a JPEG and returns 2-tuple. Args: * [0]: Image instance, converted to RGB * [1]: Dict with a quality key (mapped to the value of `QUAL` as defined by the `VERSATILEIMAGEFIE...
python
{ "resource": "" }
q271579
ProcessedImage.retrieve_image
test
def retrieve_image(self, path_to_image): """Return a PIL Image instance stored at `path_to_image`.""" image = self.storage.open(path_to_image, 'rb') file_ext = path_to_image.rsplit('.')[-1] image_format, mime_type = get_image_metadata_from_file_ext(file_ext) return ( ...
python
{ "resource": "" }
q271580
ProcessedImage.save_image
test
def save_image(self, imagefile, save_path, file_ext, mime_type): """ Save an image to self.storage at `save_path`. Arguments: `imagefile`: Raw image data, typically a BytesIO instance. `save_path`: The path within self.storage where the image should ...
python
{ "resource": "" }
q271581
SizedImage.ppoi_as_str
test
def ppoi_as_str(self): """Return PPOI value as a string.""" return "%s__%s" % ( str(self.ppoi[0]).replace('.', '-'), str(self.ppoi[1]).replace('.', '-') )
python
{ "resource": "" }
q271582
SizedImage.create_resized_image
test
def create_resized_image(self, path_to_image, save_path_on_storage, width, height): """ Create a resized image. `path_to_image`: The path to the image with the media directory to resize. If `None`, the VERSATILEIMAGE...
python
{ "resource": "" }
q271583
ClearableFileInputWithImagePreview.render
test
def render(self, name, value, attrs=None, renderer=None): """ Render the widget as an HTML string. Overridden here to support Django < 1.11. """ if self.has_template_widget_rendering: return super(ClearableFileInputWithImagePreview, self).render( name...
python
{ "resource": "" }
q271584
ClearableFileInputWithImagePreview.get_context
test
def get_context(self, name, value, attrs): """Get the context to render this widget with.""" if self.has_template_widget_rendering: context = super(ClearableFileInputWithImagePreview, self).get_context(name, value, attrs) else: # Build the context manually. co...
python
{ "resource": "" }
q271585
ClearableFileInputWithImagePreview.build_attrs
test
def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" attrs = base_attrs.copy() if extra_attrs is not None: attrs.update(extra_attrs) return attrs
python
{ "resource": "" }
q271586
get_resized_path
test
def get_resized_path(path_to_image, width, height, filename_key, storage): """ Return a `path_to_image` location on `storage` as dictated by `width`, `height` and `filename_key` """ containing_folder, filename = os.path.split(path_to_image) resized_filename = get_resized_fi...
python
{ "resource": "" }
q271587
get_filtered_path
test
def get_filtered_path(path_to_image, filename_key, storage): """ Return the 'filtered path' """ containing_folder, filename = os.path.split(path_to_image) filtered_filename = get_filtered_filename(filename, filename_key) path_to_return = os.path.join(*[ containing_folder, VERSAT...
python
{ "resource": "" }
q271588
validate_versatileimagefield_sizekey_list
test
def validate_versatileimagefield_sizekey_list(sizes): """ Validate a list of size keys. `sizes`: An iterable of 2-tuples, both strings. Example: [ ('large', 'url'), ('medium', 'crop__400x400'), ('small', 'thumbnail__100x100') ] """ try: for key, size_key in s...
python
{ "resource": "" }
q271589
get_url_from_image_key
test
def get_url_from_image_key(image_instance, image_key): """Build a URL from `image_key`.""" img_key_split = image_key.split('__') if 'x' in img_key_split[-1]: size_key = img_key_split.pop(-1) else: size_key = None img_url = reduce(getattr, img_key_split, image_instance) if size_ke...
python
{ "resource": "" }
q271590
get_rendition_key_set
test
def get_rendition_key_set(key): """ Retrieve a validated and prepped Rendition Key Set from settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS """ try: rendition_key_set = IMAGE_SETS[key] except KeyError: raise ImproperlyConfigured( "No Rendition Key Set exists at " ...
python
{ "resource": "" }
q271591
format_instruction
test
def format_instruction(insn): """ Takes a raw `Instruction` and translates it into a human readable text representation. As of writing, the text representation for WASM is not yet standardized, so we just emit some generic format. """ text = insn.op.mnemonic if not insn.imm: return ...
python
{ "resource": "" }
q271592
format_function
test
def format_function( func_body, func_type=None, indent=2, format_locals=True, ): """ Takes a `FunctionBody` and optionally a `FunctionType`, yielding the string representation of the function line by line. The function type is required for formatting function parameter and return value ...
python
{ "resource": "" }
q271593
decode_bytecode
test
def decode_bytecode(bytecode): """Decodes raw bytecode, yielding `Instruction`s.""" bytecode_wnd = memoryview(bytecode) while bytecode_wnd: opcode_id = byte2int(bytecode_wnd[0]) opcode = OPCODE_MAP[opcode_id] if opcode.imm_struct is not None: offs, imm, _ = opcode.imm_st...
python
{ "resource": "" }
q271594
decode_module
test
def decode_module(module, decode_name_subsections=False): """Decodes raw WASM modules, yielding `ModuleFragment`s.""" module_wnd = memoryview(module) # Read & yield module header. hdr = ModuleHeader() hdr_len, hdr_data, _ = hdr.from_raw(None, module_wnd) yield ModuleFragment(hdr, hdr_data) ...
python
{ "resource": "" }
q271595
deprecated_func
test
def deprecated_func(func): """Deprecates a function, printing a warning on the first usage.""" # We use a mutable container here to work around Py2's lack of # the `nonlocal` keyword. first_usage = [True] @functools.wraps(func) def wrapper(*args, **kwargs): if first_usage[0]: ...
python
{ "resource": "" }
q271596
Manager.connect
test
def connect(self): """connect to the server""" if self.loop is None: # pragma: no cover self.loop = asyncio.get_event_loop() t = asyncio.Task( self.loop.create_connection( self.config['protocol_factory'], self.config['host'], self.config['...
python
{ "resource": "" }
q271597
Manager.close
test
def close(self): """Close the connection""" if self.pinger: self.pinger.cancel() self.pinger = None if getattr(self, 'protocol', None): self.protocol.close()
python
{ "resource": "" }
q271598
Request._read_result
test
def _read_result(self): """Parse read a response from the AGI and parse it. :return dict: The AGI response parsed into a dict. """ response = yield from self.reader.readline() return parse_agi_result(response.decode(self.encoding)[:-1])
python
{ "resource": "" }
q271599
Application.handler
test
def handler(self, reader, writer): """AsyncIO coroutine handler to launch socket listening. :Example: :: @asyncio.coroutine def start(request): print('Receive a FastAGI request') print(['AGI variables:', request.headers]) fa...
python
{ "resource": "" }