desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'using direct download for depth <= 2 using proxy with probability 0.3'
def use_proxy(self, request):
if (('depth' in request.meta) and (int(request.meta['depth']) <= 2)): return False i = random.randint(1, 10) return (i <= 2)
'Calculate the depth of response, and call corresponding method or stop crawl.'
def _cal_depth(self, response):
url = response.url for (depth, depth_regexp) in enumerate(self.depth_class_list): if re.match(depth_regexp, url): return depth return (-1)
'Calculate the depth of response, and call corresponding method or stop crawl.'
def _cal_depth(self, response):
url = response.url for (depth, depth_regexp) in enumerate(self.depth_class_list): if re.match(depth_regexp, url): return depth return (-1)
'generator of all the documents in this collection'
def _walk(self):
skip = 0 limit = 1000 hasMore = True while hasMore: res = self.collection.find(skip=skip, limit=limit) hasMore = (res.count(with_limit_and_skip=True) == limit) for x in res: (yield x) skip += limit
'return all the documents in this collection'
def walk(self):
docs = [] for doc in self._walk(): docs.append(doc) return docs
''
def load_proxycn(self):
psource_template = 'http://www.proxycn.cn/html_proxy/port%s-%s.html' psource_ports = (8080, 80, 81, 3128, 8000, 1080, 444) p_nextpage = re.compile('<a href=[^>]*>\xe4\xb8\x8b\xe4\xb8\x80\xe9\xa1\xb5</a>') p_proxy = re.compile('<TR [^>]* onDblClick="clip\\(\'([\\d.]+):(\\d+)\'\\);alert\\(\'\xe5\...
'Put model into ProxyModel, return has_next_page.'
def __loadProxyFromURL(self, proxies, url, pattern):
p_nextpage = re.compile('<a href=[^>]*>\xe4\xb8\x8b\xe4\xb8\x80\xe9\xa1\xb5</a>') print ('---proxyloader---:load proxy from %s' % url) source = self.html_getter.getHtmlRetry(url, 3) source = unicode(source, 'gbk').encode('UTF-8') foundNextPage = p_nextpage.search(source) results = pa...
'Save list of ProxyModel in a file.'
def saveToFile(self, file_abspath, proxies):
if os.path.exists(file_abspath): os.remove(file_abspath) print ('$proxy/> remove %s.' % file_abspath) f = file(file_abspath, 'w') for proxyModel in proxies: f.write(proxyModel.to_line()) f.write('\n') f.close() print ('$proxy/> write proxies to %s.' ...
'default parse method, rule is not useful now'
def parse(self, response):
response = response.replace(url=HtmlParser.remove_url_parameter(response.url)) hxs = HtmlXPathSelector(response) index_level = self.determine_level(response) log.msg(('Parse: index level:' + str(index_level))) if (index_level in [1, 2, 3, 4]): self.save_to_file_system(index_level, resp...
'determine the index level of current response, so we can decide wether to continue crawl or not. level 1: people/[a-z].html level 2: people/[A-Z][\d+].html level 3: people/[a-zA-Z0-9-]+.html level 4: search page, pub/dir/.+ level 5: profile page'
def determine_level(self, response):
import re url = response.url if re.match('.+/[a-z]\\.html', url): return 1 elif re.match('.+/[A-Z]\\d+.html', url): return 2 elif re.match('.+/people-[a-zA-Z0-9-]+', url): return 3 elif re.match('.+/pub/dir/.+', url): return 4 elif re.match('.+/search/._', url...
'save the response to related folder'
def save_to_file_system(self, level, response):
if (level in [1, 2, 3, 4, 5]): fileName = self.get_clean_file_name(level, response) if (fileName is None): return fn = path.join(self.settings['DOWNLOAD_FILE_FOLDER'], str(level), fileName) self.create_path_if_not_exist(fn) if (not path.exists(fn)): wi...
'generate unique linkedin id, now use the url'
def get_clean_file_name(self, level, response):
url = response.url if (level in [1, 2, 3]): return url.split('/')[(-1)] linkedin_id = self.get_linkedin_id(url) if linkedin_id: return linkedin_id return None
'using direct download for depth <= 2 using proxy with probability 0.3'
def use_proxy(self, request):
if (('depth' in request.meta) and (int(request.meta['depth']) <= 2)): return False i = random.randint(1, 10) return (i <= 2)
'Iterate through sources. Delete database references to sources not existing, including its corresponding thumbnails (files and database references).'
def clean_up(self, dry_run=False, verbosity=1, last_n_days=0, cleanup_path=None, storage=None):
if dry_run: print 'Dry run...' if (not storage): storage = get_storage_class(settings.THUMBNAIL_DEFAULT_STORAGE)() sources_to_delete = [] time_start = time.time() query = Source.objects.all() if (last_n_days > 0): today = date.today() query = query.filter(modif...
'Print statistics about the cleanup performed.'
def print_stats(self):
print '{0:-<48}'.format(str(datetime.now().strftime('%Y-%m-%d %H:%M '))) print '{0:<40} {1:>7}'.format('Sources checked:', self.sources) print '{0:<40} {1:>7}'.format('Source references deleted from DB:', self.source_refs_deleted) print '{0:<40} {1:>7}'.format('Thumbnails ...
'Get a PIL Image instance of this file. The image is cached to avoid the file needing to be read again if the function is called again.'
def _get_image(self):
if (not hasattr(self, '_image_cache')): from easy_thumbnails.source_generators import pil_image self.image = pil_image(self) return self._image_cache
'Set the image for this file. This also caches the dimensions of the image.'
def _set_image(self, image):
if image: self._image_cache = image self._dimensions_cache = image.size else: if hasattr(self, '_image_cache'): del self._cached_image if hasattr(self, '_dimensions_cache'): del self._dimensions_cache
'Return a standard XHTML ``<img ... />`` tag for this field. :param alt: The ``alt=""`` text for the tag. Defaults to ``\'\'``. :param use_size: Whether to get the size of the thumbnail image for use in the tag attributes. If ``None`` (default), the size will only be used it if won\'t result in a remote file retrieval....
def tag(self, alt='', use_size=None, **attrs):
if (use_size is None): if getattr(self, '_dimensions_cache', None): use_size = True else: try: self.storage.path(self.name) use_size = True except NotImplementedError: use_size = False attrs['alt'] = alt attr...
'Set image dimensions from the cached dimensions of a ``Thumbnail`` model instance.'
def set_image_dimensions(self, thumbnail):
try: dimensions = getattr(thumbnail, 'dimensions', None) except models.ThumbnailDimensions.DoesNotExist: dimensions = None if (not dimensions): return False self._dimensions_cache = dimensions.size return self._dimensions_cache
'Retrieve a thumbnail matching the alias options (or raise a ``KeyError`` if no such alias exists).'
def __getitem__(self, alias):
options = aliases.get(alias, target=self.alias_target) if (not options): raise KeyError(alias) return self.get_thumbnail(options, silent_template_exception=True)
'Get the thumbnail options that includes the default options for this thumbnailer (and the project-wide default options).'
def get_options(self, thumbnail_options, **kwargs):
if isinstance(thumbnail_options, ThumbnailOptions): return thumbnail_options args = [] if (thumbnail_options is not None): args.append(thumbnail_options) opts = ThumbnailOptions(*args, **kwargs) if ('quality' not in thumbnail_options): opts['quality'] = self.thumbnail_quality...
'Return an unsaved ``ThumbnailFile`` containing a thumbnail image. The thumbnail image is generated using the ``thumbnail_options`` dictionary.'
def generate_thumbnail(self, thumbnail_options, high_resolution=False, silent_template_exception=False):
thumbnail_options = self.get_options(thumbnail_options) orig_size = thumbnail_options['size'] (min_dim, max_dim) = (0, 0) for dim in orig_size: try: dim = int(dim) except (TypeError, ValueError): continue (min_dim, max_dim) = (min(min_dim, dim), max(max_di...
'Return a thumbnail filename for the given ``thumbnail_options`` dictionary and ``source_name`` (which defaults to the File\'s ``name`` if not provided).'
def get_thumbnail_name(self, thumbnail_options, transparent=False, high_resolution=False):
thumbnail_options = self.get_options(thumbnail_options) (path, source_filename) = os.path.split(self.name) source_extension = os.path.splitext(source_filename)[1][1:] preserve_extensions = self.thumbnail_preserve_extensions if (preserve_extensions and ((preserve_extensions is True) or (source_extens...
'Return a ``ThumbnailFile`` containing an existing thumbnail for a set of thumbnail options, or ``None`` if not found.'
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False):
thumbnail_options = self.get_options(thumbnail_options) names = [self.get_thumbnail_name(thumbnail_options, transparent=False, high_resolution=high_resolution)] transparent_name = self.get_thumbnail_name(thumbnail_options, transparent=True, high_resolution=high_resolution) if (transparent_name not in na...
'Return a ``ThumbnailFile`` containing a thumbnail. If a matching thumbnail already exists, it will simply be returned. By default (unless the ``Thumbnailer`` was instanciated with ``generate=False``), thumbnails that don\'t exist are generated. Otherwise ``None`` is returned. Force the generation behaviour by setting ...
def get_thumbnail(self, thumbnail_options, save=True, generate=None, silent_template_exception=False):
thumbnail_options = self.get_options(thumbnail_options) if (generate is None): generate = self.generate thumbnail = self.get_existing_thumbnail(thumbnail_options) if (not thumbnail): if generate: thumbnail = self.generate_thumbnail(thumbnail_options, silent_template_exception...
'Save a thumbnail to the thumbnail_storage. Also triggers the ``thumbnail_created`` signal and caches the thumbnail values and dimensions for future lookups.'
def save_thumbnail(self, thumbnail):
filename = thumbnail.name try: self.thumbnail_storage.delete(filename) except Exception: pass self.thumbnail_storage.save(filename, thumbnail) thumb_cache = self.get_thumbnail_cache(thumbnail.name, create=True, update=True) if settings.THUMBNAIL_CACHE_DIMENSIONS: (dimensi...
'Calculate whether the thumbnail already exists and that the source is not newer than the thumbnail. If the source and thumbnail file storages are local, their file modification times are used. Otherwise the database cached modification times are used.'
def thumbnail_exists(self, thumbnail_name):
if self.remote_source: return False if utils.is_storage_local(self.source_storage): source_modtime = utils.get_modified_time(self.source_storage, self.name) else: source = self.get_source_cache() if (not source): return False source_modtime = source.modifi...
'Save the file, also saving a reference to the thumbnail cache Source model.'
def save(self, name, content, *args, **kwargs):
super(ThumbnailerFieldFile, self).save(name, content, *args, **kwargs) self.get_source_cache(create=True, update=True)
'Delete the image, along with any generated thumbnails.'
def delete(self, *args, **kwargs):
source_cache = self.get_source_cache() self.delete_thumbnails(source_cache) super(ThumbnailerFieldFile, self).delete(*args, **kwargs) if source_cache: source_cache.delete()
'Delete any thumbnails generated from the source image. :arg source_cache: An optional argument only used for optimisation where the source cache instance is already known. :returns: The number of files deleted.'
def delete_thumbnails(self, source_cache=None):
source_cache = self.get_source_cache() deleted = 0 if source_cache: thumbnail_storage_hash = utils.get_storage_hash(self.thumbnail_storage) for thumbnail_cache in source_cache.thumbnails.all(): if (thumbnail_cache.storage_hash == thumbnail_storage_hash): self.thum...
'Return an iterator which returns ThumbnailFile instances.'
def get_thumbnails(self, *args, **kwargs):
source_cache = self.get_source_cache() if source_cache: thumbnail_storage_hash = utils.get_storage_hash(self.thumbnail_storage) for thumbnail_cache in source_cache.thumbnails.all(): if (thumbnail_cache.storage_hash == thumbnail_storage_hash): (yield ThumbnailFile(name...
'Save the image. The image will be resized down using a ``ThumbnailField`` if ``resize_source`` (a dictionary of thumbnail options) is provided by the field.'
def save(self, name, content, *args, **kwargs):
options = getattr(self.field, 'resize_source', None) if options: if ('quality' not in options): options['quality'] = self.thumbnail_quality content = Thumbnailer(content, name).generate_thumbnail(options) (orig_name, ext) = os.path.splitext(name) generated_ext = os.pa...
'Return a suitable description of this field for South.'
def south_field_triple(self):
from south.modelsinspector import introspector field_class = 'django.db.models.fields.files.FileField' (args, kwargs) = introspector(self) return (field_class, args, kwargs)
'Return a suitable description of this field for South.'
def south_field_triple(self):
from south.modelsinspector import introspector field_class = 'django.db.models.fields.files.ImageField' (args, kwargs) = introspector(self) return (field_class, args, kwargs)
'If thumbnail options are not passed, default options will be used.'
def test_options_default(self):
widget = widgets.ImageClearableFileInput() self.assertEqual(widget.thumbnail_options, {'size': (80, 80)})
'A dictionary can be passed as the thumbnail options. The dictionary is copied so it isn\'t just a mutable reference of the original.'
def test_options_custom(self):
options = {'size': (300, 100), 'crop': True} widget = widgets.ImageClearableFileInput(thumbnail_options=options) options['crop'] = False self.assertEqual(widget.thumbnail_options, {'size': (300, 100), 'crop': True})
'The output contains a link to both the source image and the thumbnail.'
def test_render(self):
source_filename = self.create_image(self.storage, 'test.jpg') widget = widgets.ImageClearableFileInput() source_file = self.storage.open(source_filename) source_file.storage = self.storage source_file.thumbnail_storage = self.storage html = widget.render('photo', source_file) self.assertIn(s...
'The thumbnail is generated using the options provided to the widget.'
def test_render_custom(self):
source_filename = self.create_image(self.storage, 'test.jpg') options = {'size': (100, 500), 'quality': 90, 'crop': True} widget = widgets.ImageClearableFileInput(thumbnail_options=options) source_file = self.storage.open(source_filename) source_file.storage = self.storage source_file.thumbnail_...
'The template used to render the thumbnail and the standard ``ClearableFileInput`` output can be customized.'
def test_custom_template(self):
source_filename = self.create_image(self.storage, 'test.jpg') widget = widgets.ImageClearableFileInput() widget.template_with_thumbnail = u'%(template)s<br /><a href="%(source_url)s">%(thumb)s</a> FOO' source_file = self.storage.open(source_filename) source_file.storage = self.storage s...
'If value not passed, use super widget.'
def test_render_without_value(self):
widget = widgets.ImageClearableFileInput() base_widget = ClearableFileInput() html = widget.render('photo', None) base_html = base_widget.render('photo', None) self.assertEqual(base_html, html)
'The widget treats UploadedFile as no input. Rationale: When widget is used in ModelForm and the form (submitted with upload) is not valid, widget should discard the value (just like standard Django ClearableFileInput does).'
def test_render_uploaded(self):
widget = widgets.ImageClearableFileInput() base_widget = ClearableFileInput() file_name = 'test.jpg' image = self.create_image(None, file_name) upload_file = SimpleUploadedFile(file_name, image.getvalue()) html = widget.render('photo', upload_file) base_html = base_widget.render('photo', upl...
'Just a simple test to see if we can actually import the command without any syntax errors.'
def test_can_import(self):
import easy_thumbnails.management.commands.thumbnail_cleanup
'Create the temporary location.'
def __init__(self, location=None, *args, **kwargs):
if (location is None): location = tempfile.mkdtemp() self.temporary_location = location super(TemporaryStorage, self).__init__(location=location, *args, **kwargs)
'Delete the temporary directory created during initialisation. This storage class should not be used again after this method is called.'
def delete_temporary_storage(self):
temporary_location = getattr(self, 'temporary_location', None) if temporary_location: shutil.rmtree(temporary_location)
'Raise ``NotImplementedError``, since this is the way that easy-thumbnails determines if a storage is remote.'
def path(self, *args, **kwargs):
if self.remote_mode: raise NotImplementedError return super(FakeRemoteStorage, self).path(*args, **kwargs)
'Isolate all settings.'
def setUp(self):
output = super(BaseTest, self).setUp() settings.isolated = True return output
'Restore settings to their original state.'
def tearDown(self):
settings.isolated = False settings.revert() return super(BaseTest, self).tearDown()
'Generate a test image, returning the filename that it was saved as. If ``storage`` is ``None``, the BytesIO containing the image data will be passed instead.'
def create_image(self, storage, filename, size=(800, 600), image_mode='RGB', image_format='JPEG'):
data = BytesIO() Image.new(image_mode, size).save(data, image_format) data.seek(0) if (not storage): return data image_file = ContentFile(data.read()) return storage.save(filename, image_file)
'Non-images raise an exception.'
def test_not_image(self):
self.assertRaises(IOError, source_generators.pil_image, BytesIO(six.b('not an image')))
'Truncated images *don\'t* raise an exception if they can still be read.'
def test_nearly_image(self):
data = self.create_image(None, None) reference = source_generators.pil_image(data) data.seek(0) trunc_data = BytesIO() trunc_data.write(data.read()[:(-10)]) trunc_data.seek(0) im = source_generators.pil_image(trunc_data) self.assertEqual(im.size, reference.size)
'Images with EXIF orientation data are reoriented.'
def test_exif_orientation(self):
reference = image_from_b64(EXIF_REFERENCE) for (exif_orientation, data) in six.iteritems(EXIF_ORIENTATION): im = image_from_b64(data) self.assertEqual(exif_orientation, im._getexif().get(274)) self.assertFalse(near_identical(reference, im)) im = source_generators.pil_image(BytesI...
'Images with EXIF orientation data are not reoriented if the ``exif_orientation`` parameter is ``False``.'
def test_switch_off_exif_orientation(self):
reference = image_from_b64(EXIF_REFERENCE) data = EXIF_ORIENTATION[2] im = image_from_b64(data) self.assertFalse(near_identical(reference, im)) im = source_generators.pil_image(BytesIO(base64.b64decode(data)), exif_orientation=False) self.assertFalse(near_identical(reference, im), 'Image shou...
'Thumbnails are not generated if there isn\'t anything to generate...'
def test_empty(self):
profile = models.Profile(avatar=None) files = self.fake_save(profile) self.assertEqual(len(files), 1)
'Thumbnails are only generated when the file is modified.'
def test_no_change(self):
profile = models.Profile(avatar='avatars/test.jpg') files = self.fake_save(profile) self.assertEqual(len(files), 1)
'When a file is modified, thumbnails are built for all matching non-global aliases.'
def test_changed(self):
profile = models.Profile(avatar='avatars/test.jpg') profile.avatar._committed = False files = self.fake_save(profile) self.assertEqual(len(files), 5)
'Thumbnails are only generated when the file is modified.'
def test_no_change(self):
profile = models.Profile(avatar='avatars/test.jpg') files = self.fake_save(profile) self.assertEqual(len(files), 1)
'When a file is modified, thumbnails are built for all matching and project-wide aliases.'
def test_changed(self):
profile = models.Profile(avatar='avatars/test.jpg') profile.avatar._committed = False files = self.fake_save(profile) self.assertEqual(len(files), 6)
'Create a new Thumbnail in the database'
def test_create_file(self):
img = Thumbnail.objects.get_file(self.storage, self.filename, create=True, source=self.source) self.assertEqual(img.name, self.filename)
'Fetch an existing thumb from database'
def test_get_file(self):
created = Thumbnail.objects.create(storage_hash=self.storage_hash, name=self.filename, source=self.source) fetched = Thumbnail.objects.get_file(self.storage, self.filename, create=False) self.assertTrue(fetched) self.assertEqual(created, fetched)
'Fetch a thumb that is in the storage but not in the database'
def test_get_file_check_cache(self):
try: Thumbnail.objects.get(name=self.filename) self.fail('Thumb should not exist yet') except Thumbnail.DoesNotExist: pass Thumbnail.objects.get_file(self.storage, self.filename, source=self.source, check_cache_miss=True) try: Thumbnail.objects.get(name=self.f...
'use a mock image optimizing post processor doing nothing'
@unittest.skipIf(('easy_thumbnails.optimize' not in settings.INSTALLED_APPS), 'optimize app not installed') @unittest.skipIf((LogCapture is None), 'testfixtures not installed') def test_postprocessor(self):
settings.THUMBNAIL_OPTIMIZE_COMMAND = {'png': 'easy_thumbnails/tests/mockoptim.py {filename}'} with LogCapture() as logcap: self.ext_thumbnailer.thumbnail_extension = 'png' self.ext_thumbnailer.get_thumbnail({'size': (10, 10)}) actual = tuple(logcap.actual())[0] self.assertEqu...
'use a mock image optimizing post processor doing nothing'
@unittest.skipIf(('easy_thumbnails.optimize' not in settings.INSTALLED_APPS), 'optimize app not installed') @unittest.skipIf((LogCapture is None), 'testfixtures not installed') def test_postprocessor_fail(self):
settings.THUMBNAIL_OPTIMIZE_COMMAND = {'png': 'easy_thumbnails/tests/mockoptim_fail.py {filename}'} with LogCapture() as logcap: self.ext_thumbnailer.thumbnail_extension = 'png' self.ext_thumbnailer.get_thumbnail({'size': (10, 10)}) actual = tuple(logcap.actual())[0] self.asse...
'Testing the mirror `easy_thumbnails_tags` templatetag library. Testing the loading {% load easy_thumbnails_tags %} instead of traditional {% load thumbnail %}.'
def test_mirror_templatetag_library(self):
settings.THUMBNAIL_DEBUG = True output = self.render_template('src="{% thumbnail source 240x240 %}"', 'easy_thumbnails_tags') expected = self.verify_thumbnail((240, 180), {'size': (240, 240)}) expected_url = ''.join((settings.MEDIA_URL, expected)) self.assertEqual(output, ('src="%s"' % e...
'Revert any changes made to settings.'
def revert(self):
for (attr, value) in self._changed.items(): setattr(django_settings, attr, value) for attr in self._added: delattr(django_settings, attr) self._changed = {} self._added = [] if self.isolated: self._isolated_overrides = BaseSettings()
'Initialize the Aliases object. :param populate_from_settings: If ``True`` (default) then populate the initial aliases from settings. See :meth:`populate_from_settings`.'
def __init__(self, populate_from_settings=True):
self._aliases = {} if populate_from_settings: self.populate_from_settings()
'Populate the aliases from the ``THUMBNAIL_ALIASES`` setting.'
def populate_from_settings(self):
settings_aliases = settings.THUMBNAIL_ALIASES if settings_aliases: for (target, aliases) in settings_aliases.items(): target_aliases = self._aliases.setdefault(target, {}) target_aliases.update(aliases)
'Add an alias. :param alias: The name of the alias to add. :param options: The easy-thumbnails options dictonary for this alias (should include ``size``). :param target: A field, model, or app to limit this alias to (optional).'
def set(self, alias, options, target=None):
target = (self._coerce_target(target) or '') target_aliases = self._aliases.setdefault(target, {}) target_aliases[alias] = options
'Get a dictionary of aliased options. :param alias: The name of the aliased options. :param target: Get alias for this specific target (optional). If no matching alias is found, returns ``None``.'
def get(self, alias, target=None):
for target_part in reversed(list(self._get_targets(target))): options = self._get(target_part, alias) if options: return options
'Get a dictionary of all aliases and their options. :param target: Include aliases for this specific field, model or app (optional). :param include_global: Include all non target-specific aliases (default ``True``). For example:: >>> aliases.all(target=\'my_app.MyModel\') {\'small\': {\'size\': (100, 100)}, \'large\': ...
def all(self, target=None, include_global=True):
aliases = {} for target_part in self._get_targets(target, include_global): aliases.update(self._aliases.get(target_part, {})) return aliases
'Internal method to get a specific alias.'
def _get(self, target, alias):
if (target not in self._aliases): return return self._aliases[target].get(alias)
'Internal iterator to split up a complete target into the possible parts it may match. For example:: >>> list(aliases._get_targets(\'my_app.MyModel.somefield\')) [\'\', \'my_app\', \'my_app.MyModel\', \'my_app.MyModel.somefield\']'
def _get_targets(self, target, include_global=True):
target = self._coerce_target(target) if include_global: (yield '') if (not target): return target_bits = target.split('.') for i in range(len(target_bits)): (yield '.'.join(target_bits[:(i + 1)]))
'Internal method to coerce a target to a string. The assumption is that if it is not ``None`` and not a string, it is a Django ``FieldFile`` object.'
def _coerce_target(self, target):
if ((not target) or isinstance(target, six.string_types)): return target if (not hasattr(target, 'instance')): return None if getattr(target.instance, '_deferred', False): model = target.instance._meta.proxy_for_model else: model = target.instance.__class__ return ('%...
'Set up the thumbnail options for this widget. :param thumbnail_options: options used to generate the thumbnail. If no ``size`` is given, it\'ll be ``(80, 80)``. If not provided at all, default options will be used from the :attr:`~easy_thumbnails.conf.Settings.THUMBNAIL_WIDGET_OPTIONS` setting.'
def __init__(self, thumbnail_options=None, attrs=None):
thumbnail_options = (thumbnail_options or settings.THUMBNAIL_WIDGET_OPTIONS) thumbnail_options = thumbnail_options.copy() if ('size' not in thumbnail_options): thumbnail_options['size'] = (80, 80) self.thumbnail_options = thumbnail_options super(ImageClearableFileInput, self).__init__(attrs)...
'Return a hex string hash for a storage object (or string containing a pickle of a storage object).'
def get_storage_hash(self, storage):
try: storage_obj = pickle.loads(str(self.pickle)) except: storage_obj = default_storage storage_cls = storage_obj.__class__ name = ('%s.%s' % (storage_cls.__module__, storage_cls.__name__)) return hashlib.md5(name).hexdigest()
'Write your forwards methods here.'
def forwards(self, orm):
for storage in orm.Storage.objects.all(): storage_hash = self.get_storage_hash(storage) orm.Source.objects.filter(storage=storage).update(storage_hash=storage_hash) orm.Thumbnail.objects.filter(storage=storage).update(storage_hash=storage_hash)
'\'min_time\' and \'max_time\' are the the first and last event timestamps. \'reverse_x\' and \'reverse_y\' specify whether the directionality of x and y axes should be reversed.'
def __init__(self, min_time, max_time, reverse_x=True, reverse_y=True):
self._total_secs = (max_time - min_time) self._min_time = min_time self._max_time = max_time self._cur_time = max_time self._width = (iphone_dims[0] - right_margin) self._height = iphone_dims[1] self._roc_max = (float((max_time - min_time)) / self._height) self._roc_min = (float(VFTime._...
'Called to reset the time based on an initial touch point. \'start_pos\' is the iphone screen coordinates of the initial touch point.'
def Start(self, start_pos):
self._last_pos = self._TransformPos(start_pos) self._cur_time = (self._min_time + (self._last_pos[1] * self._roc_max)) self._active = True
'Computes the delta time by integrating the change in time implied by traveling along a linear path between self._last_pos and touch_pos (after transforming). Sets the new time and last position. The time is always adjusted by min and max constraints to account for the discontinuities which would occur when the positio...
def AdjustTime(self, touch_pos):
if (not self._active): return new_pos = self._TransformPos(touch_pos) delta_time = self._IntegrateTime(new_pos) self._cur_time = self._EnforceBounds((self._cur_time + delta_time), new_pos) self._last_pos = new_pos
'Computes the resulting time if the current time was adjusted by a movement to \'pos\'. Similarly to AdjustTime, this is done by integrating the change in time implied by traveling along a linear path between self._last_pos and \'pos\'. Does not mutate the internal state of the object.'
def ComputeTimeAtPos(self, pos, log=False):
new_pos = self._TransformPos(pos) delta_time = self._IntegrateTime(new_pos, log) return (self._cur_time + delta_time)
'Returns the maximum interval in seconds (min, max).'
def GetMaxInterval(self):
return (self._min_time, self._max_time)
'Returns the size of the current interval in seconds (min, max).'
def GetInterval(self):
interval = (self._height * (self._roc_max + (self._roc_slope * self._last_pos[0]))) y_ratio = (float(self._last_pos[1]) / float(self._height)) return ((self._cur_time - (y_ratio * interval)), (self._cur_time + ((1.0 - y_ratio) * interval)))
'Returns the last reported position (untransform to iphone coordinates).'
def GetPos(self):
return self._UntransformPos()
'Returns the current time as seconds since the epoch in UTC.'
def GetTime(self):
return self._cur_time
'Returns a datetime object for the current time.'
def GetDatetime(self):
return datetime.fromtimestamp(self._cur_time)
'Integrates time by movement along the linear path defined by the vector between self._last_pos and new_pos. - \'m\': slope of line from self._last_pos to new_pos. - \'a\': max rate of change (self._roc_max) is (max - min seconds) / screen height - \'b\': rate of change slope (self._roc_slope) - \'c\': last Y position ...
def _IntegrateTime(self, new_pos, log=False):
x_delta = float((new_pos[0] - self._last_pos[0])) y_delta = (new_pos[1] - self._last_pos[1]) if (y_delta == 0.0): return 0.0 m = (x_delta / y_delta) a = self._roc_max b = self._roc_slope c = float(self._last_pos[1]) def _ComputeIntegral(y): return ((0.5 * y) * ((2 * a) + ...
'The current x position defines the interval of time which stretches vertically from 0 to \'self._height\'. As long as fixing \'cur_time\' at the current y position does not imply that the interval would fail to take up the entire screen, no adjustment is necessary.'
def _EnforceBounds(self, cur_time, new_pos):
interval = (self._height * (self._roc_max + (self._roc_slope * new_pos[0]))) y_ratio = (float(new_pos[1]) / float(self._height)) if ((cur_time - (y_ratio * interval)) < self._min_time): cur_time = (self._min_time + (y_ratio * interval)) if ((cur_time + ((1.0 - y_ratio) * interval)) >= self._max_...
'Converts the bounded, transformed current position back to screen dimensions.'
def _UntransformPos(self):
pos = [(self._last_pos[0] + right_margin), self._last_pos[1]] if self._reverse_x: pos[0] = ((iphone_dims[0] - pos[0]) - 1) if self._reverse_y: pos[1] = ((iphone_dims[1] - pos[1]) - 1) return pos
'Returns a transformed position. Uses \'reverse_x\' and \'reverse_y\' to decide whether to reverse the x and y axes.'
def _TransformPos(self, pos):
new_pos = copy.copy(pos) if self._reverse_x: new_pos[0] = ((iphone_dims[0] - new_pos[0]) - 1) if self._reverse_y: new_pos[1] = ((iphone_dims[1] - new_pos[1]) - 1) new_pos[0] = min(self._width, max(0, (new_pos[0] - right_margin))) new_pos[1] = min(self._height, max(0, int(new_pos[1]))...
'Takes a plain-hex-number uuid, uppercases it, and inserts hyphens.'
@staticmethod def ReformatUuid(uuid):
uuid = uuid.upper() if (len(uuid) == 36): pass else: uuid = '-'.join([uuid[0:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:]]) return uuid
'using atos looks up symbols'
@staticmethod def LookupSymbols(path, arch, base, addresses):
atos = subprocess.Popen((['xcrun', 'atos', '-arch', arch, '-l', base, '-o', path] + addresses), stdout=subprocess.PIPE, stderr=subprocess.PIPE) symbols = [] for line in atos.stdout: symbols.append(kSymbolRE.sub('', line.strip())) return symbols
'See `twisted.internet.interfaces.IReactorThreads.callFromThread`'
def callFromThread(self, f, *args, **kw):
assert callable(f), ('%s is not callable' % f) with NullContext(): self._io_loop.add_callback(f, *args, **kw)
'Add a FileDescriptor for notification of data available to read.'
def addReader(self, reader):
if (reader in self._readers): return fd = reader.fileno() self._readers[reader] = fd if (fd in self._fds): (_, writer) = self._fds[fd] self._fds[fd] = (reader, writer) if writer: self._io_loop.update_handler(fd, (IOLoop.READ | IOLoop.WRITE)) else: ...
'Add a FileDescriptor for notification of data available to write.'
def addWriter(self, writer):
if (writer in self._writers): return fd = writer.fileno() self._writers[writer] = fd if (fd in self._fds): (reader, _) = self._fds[fd] self._fds[fd] = (reader, writer) if reader: self._io_loop.update_handler(fd, (IOLoop.READ | IOLoop.WRITE)) else: ...
'Remove a Selectable for notification of data available to read.'
def removeReader(self, reader):
if (reader in self._readers): fd = self._readers.pop(reader) (_, writer) = self._fds[fd] if writer: self._fds[fd] = (None, writer) self._io_loop.update_handler(fd, IOLoop.WRITE) else: del self._fds[fd] self._io_loop.remove_handler(fd)
'Remove a Selectable for notification of data available to write.'
def removeWriter(self, writer):
if (writer in self._writers): fd = self._writers.pop(writer) (reader, _) = self._fds[fd] if reader: self._fds[fd] = (reader, None) self._io_loop.update_handler(fd, IOLoop.READ) else: del self._fds[fd] self._io_loop.remove_handler(fd)
'Returns the read file descriptor for this waker. Must be suitable for use with ``select()`` or equivalent on the local platform.'
def fileno(self):
raise NotImplementedError()
'Returns the write file descriptor for this waker.'
def write_fileno(self):
raise NotImplementedError()
'Triggers activity on the waker\'s file descriptor.'
def wake(self):
raise NotImplementedError()
'Called after the listen has woken up to do any necessary cleanup.'
def consume(self):
raise NotImplementedError()
'Closes the waker\'s file descriptor(s).'
def close(self):
raise NotImplementedError()