repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
xtream1101/cutil
cutil/database.py
Database.update
python
def update(self, table, data_list, matched_field=None, return_cols='id'): data_list = copy.deepcopy(data_list) # Create deepcopy so the original list does not get modified if matched_field is None: # Assume the id field logger.info("Matched field not defined, assuming the `id` f...
Create a bulk insert statement which is much faster (~2x in tests with 10k & 100k rows and 4 cols) for inserting data then executemany() TODO: Is there a limit of length the query can be? If so handle it.
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/database.py#L213-L289
[ "def _check_values(in_values):\n \"\"\" Check if values need to be converted before they get mogrify'd\n \"\"\"\n out_values = []\n for value in in_values:\n # if isinstance(value, (dict, list)):\n # out_values.append(json.dumps(value))\n # else:\n ...
class Database: def __init__(self, db_config, table_raw=None, max_connections=10): from psycopg2.pool import ThreadedConnectionPool self.table_raw = table_raw try: # Set default port is port is not passed if 'db_port' not in db_config: db_config['db_...
xtream1101/cutil
cutil/config.py
Config.load_configs
python
def load_configs(self, conf_file): with open(conf_file) as stream: lines = itertools.chain(("[global]",), stream) self._config.read_file(lines) return self._config['global']
Assumes that the config file does not have any sections, so throw it all in global
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/config.py#L12-L19
null
class Config: def __init__(self, conf_file=None): self._config = configparser.ConfigParser() self._config.optionxform = str # Keep case of keys self.config_values = self.remove_quotes(self.load_configs(conf_file)) def remove_quotes(self, configs): """ Because some val...
xtream1101/cutil
cutil/config.py
Config.remove_quotes
python
def remove_quotes(self, configs): for key in configs: value = configs[key] if value[0] == "'" and value[-1] == "'": configs[key] = value[1:-1] return configs
Because some values are wraped in single quotes
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/config.py#L21-L29
null
class Config: def __init__(self, conf_file=None): self._config = configparser.ConfigParser() self._config.optionxform = str # Keep case of keys self.config_values = self.remove_quotes(self.load_configs(conf_file)) def load_configs(self, conf_file): """ Assumes that the...
xtream1101/cutil
cutil/__init__.py
multikey_sort
python
def multikey_sort(items, columns): comparers = [ ((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in columns ] def cmp(a, b): return (a > b) - (a < b) def comparer(left, right): comparer_iter = ( cmp(fn(lef...
Source: https://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L108-L125
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
sanitize
python
def sanitize(string): replace_chars = [ ['\\', '-'], [':', '-'], ['/', '-'], ['?', ''], ['<', ''], ['>', ''], ['`', '`'], ['|', '-'], ['*', '`'], ['"', '\''], ['.', ''], ['&', 'and'] ] for ch in replace_chars: string = string.replace(ch[0], ch[1]) return string
Catch and replace invalid path chars [replace, with]
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L159-L172
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
chunks_of
python
def chunks_of(max_chunk_size, list_to_chunk): for i in range(0, len(list_to_chunk), max_chunk_size): yield list_to_chunk[i:i + max_chunk_size]
Yields the list with a max size of max_chunk_size
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L216-L221
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
split_into
python
def split_into(max_num_chunks, list_to_chunk): max_chunk_size = math.ceil(len(list_to_chunk) / max_num_chunks) return chunks_of(max_chunk_size, list_to_chunk)
Yields the list with a max total size of max_num_chunks
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L224-L229
[ "def chunks_of(max_chunk_size, list_to_chunk):\n \"\"\"\n Yields the list with a max size of max_chunk_size\n \"\"\"\n for i in range(0, len(list_to_chunk), max_chunk_size):\n yield list_to_chunk[i:i + max_chunk_size]\n" ]
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
norm_path
python
def norm_path(path): # path = os.path.normcase(path) path = os.path.expanduser(path) path = os.path.expandvars(path) path = os.path.normpath(path) return path
:return: Proper path for os with vars expanded out
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L240-L248
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
create_hashed_path
python
def create_hashed_path(base_path, name, depth=2): if depth > 16: logger.warning("depth cannot be greater then 16, setting to 16") depth = 16 name_hash = hashlib.md5(str(name).encode('utf-8')).hexdigest() if base_path.endswith(os.path.sep): save_path = base_path else: sav...
Create a directory structure using the hashed filename :return: string of the path to save to not including filename/ext
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L251-L272
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
create_path
python
def create_path(path, is_dir=False): path = norm_path(path) path_check = path if not is_dir: path_check = os.path.dirname(path) does_path_exists = os.path.exists(path_check) if does_path_exists: return path try: os.makedirs(path_check) except OSError: pass ...
Check if path exists, if not create it :param path: path or file to create directory for :param is_dir: pass True if we are passing in a directory, default = False :return: os safe path from `path`
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L275-L297
[ "def norm_path(path):\n \"\"\"\n :return: Proper path for os with vars expanded out\n \"\"\"\n # path = os.path.normcase(path)\n path = os.path.expanduser(path)\n path = os.path.expandvars(path)\n path = os.path.normpath(path)\n return path\n" ]
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
rate_limited
python
def rate_limited(num_calls=1, every=1.0): frequency = abs(every) / float(num_calls) def decorator(func): """ Extend the behaviour of the following function, forwarding method invocations if the time window hes elapsed. Arguments: func (function): The function ...
Source: https://github.com/tomasbasham/ratelimit/tree/0ca5a616fa6d184fa180b9ad0b6fd0cf54c46936 Need to make a few changes that included having num_calls be a float Prevent a method from being called if it was previously called before a time widows has elapsed. Keyword Arguments: num_calls ...
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L388-L440
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
rate_limited_old
python
def rate_limited_old(max_per_second): lock = threading.Lock() min_interval = 1.0 / max_per_second def decorate(func): last_time_called = time.perf_counter() @wraps(func) def rate_limited_function(*args, **kwargs): lock.acquire() nonlocal last_time_called ...
Source: https://gist.github.com/gregburek/1441055
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L443-L470
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
timeit
python
def timeit(stat_tracker_func, name): def _timeit(func): def wrapper(*args, **kw): start_time = time.time() result = func(*args, **kw) stop_time = time.time() stat_tracker_func(name, stop_time - start_time) return result return wrapper ...
Pass in a function and the name of the stat Will time the function that this is a decorator to and send the `name` as well as the value (in seconds) to `stat_tracker_func` `stat_tracker_func` can be used to either print out the data or save it
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L473-L491
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
get_proxy_parts
python
def get_proxy_parts(proxy): proxy_parts = {'schema': None, 'user': None, 'password': None, 'host': None, 'port': None, } # Find parts results = re.match(proxy_parts_pattern, proxy) if results: matched ...
Take a proxy url and break it up to its parts
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L501-L524
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
xtream1101/cutil
cutil/__init__.py
remove_html_tag
python
def remove_html_tag(input_str='', tag=None): result = input_str if tag is not None: pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag)) result = re.sub(pattern, '', str(input_str)) return result
Returns a string with the html tag and all its contents from a string
train
https://github.com/xtream1101/cutil/blob/2e4d1f00e66154b44d4ccffb9b1db3f37e87f2e8/cutil/__init__.py#L527-L536
null
from cutil.database import Database # noqa: F401 from cutil.config import Config # noqa: F401 from cutil.custom_terminal import CustomTerminal # noqa: F401 from cutil.repeating_timer import RepeatingTimer # noqa: F401 import os import re import sys import uuid import math import time import pytz import json import...
stephrdev/django-tapeforms
tapeforms/utils.py
join_css_class
python
def join_css_class(css_class, *additional_css_classes): css_set = set(chain.from_iterable( c.split(' ') for c in [css_class, *additional_css_classes] if c)) return ' '.join(css_set)
Returns the union of one or more CSS classes as a space-separated string. Note that the order will not be preserved.
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/utils.py#L4-L11
null
from itertools import chain
stephrdev/django-tapeforms
tapeforms/fieldsets.py
TapeformFieldset.visible_fields
python
def visible_fields(self): form_visible_fields = self.form.visible_fields() if self.render_fields: fields = self.render_fields else: fields = [field.name for field in form_visible_fields] filtered_fields = [field for field in fields if field not in self.exclude_...
Returns the reduced set of visible fields to output from the form. This method respects the provided ``fields`` configuration _and_ exlcudes all fields from the ``exclude`` configuration. If no ``fields`` where provided when configuring this fieldset, all visible fields minus the exclu...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/fieldsets.py#L76-L97
null
class TapeformFieldset(TapeformLayoutMixin, object): """ Class to render a subset of a form's fields. From a template perspective, a fieldset looks quite similar to a form (and can use the same template tag to render: ``form``. """ def __init__( self, form, fields=None, exclude=None, pr...
stephrdev/django-tapeforms
tapeforms/fieldsets.py
TapeformFieldsetsMixin.get_fieldsets
python
def get_fieldsets(self, fieldsets=None): fieldsets = fieldsets or self.fieldsets if not fieldsets: raise StopIteration # Search for primary marker in at least one of the fieldset kwargs. has_primary = any(fieldset.get('primary') for fieldset in fieldsets) for field...
This method returns a generator which yields fieldset instances. The method uses the optional fieldsets argument to generate fieldsets for. If no fieldsets argument is passed, the class property ``fieldsets`` is used. When generating the fieldsets, the method ensures that at least one fielset ...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/fieldsets.py#L132-L163
null
class TapeformFieldsetsMixin: """ Mixin to generate fieldsets based on the `fieldsets` property of a ``TapeformFieldsetsMixin`` enabled form. """ #: Default fieldset class to use when instantiating a fieldset. fieldset_class = TapeformFieldset #: List/tuple of kwargs as `dict`` to generate...
stephrdev/django-tapeforms
tapeforms/templatetags/tapeforms.py
form
python
def form(context, form, **kwargs): if not isinstance(form, (forms.BaseForm, TapeformFieldset)): raise template.TemplateSyntaxError( 'Provided form should be a `Form` instance, actual type: {0}'.format( form.__class__.__name__)) return render_to_string( form.get_layo...
The `form` template tag will render a tape-form enabled form using the template provided by `get_layout_template` method of the form using the context generated by `get_layout_context` method of the form. Usage:: {% load tapeforms %} {% form my_form %} You can override the used layout...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/templatetags/tapeforms.py#L11-L39
null
from django import forms, template from django.template.loader import render_to_string from ..fieldsets import TapeformFieldset register = template.Library() @register.simple_tag(takes_context=True) @register.simple_tag(takes_context=True) def formfield(context, bound_field, **kwargs): """ The `formfiel...
stephrdev/django-tapeforms
tapeforms/templatetags/tapeforms.py
formfield
python
def formfield(context, bound_field, **kwargs): if not isinstance(bound_field, forms.BoundField): raise template.TemplateSyntaxError( 'Provided field should be a `BoundField` instance, actual type: {0}'.format( bound_field.__class__.__name__)) return render_to_string( ...
The `formfield` template tag will render a form field of a tape-form enabled form using the template provided by `get_field_template` method of the form together with the context generated by `get_field_context` method of the form. Usage:: {% load tapeforms %} {% formfield my_form.my_field...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/templatetags/tapeforms.py#L43-L71
null
from django import forms, template from django.template.loader import render_to_string from ..fieldsets import TapeformFieldset register = template.Library() @register.simple_tag(takes_context=True) def form(context, form, **kwargs): """ The `form` template tag will render a tape-form enabled form using th...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformLayoutMixin.get_layout_template
python
def get_layout_template(self, template_name=None): if template_name: return template_name if self.layout_template: return self.layout_template return defaults.LAYOUT_DEFAULT_TEMPLATE
Returns the layout template to use when rendering the form to HTML. Preference of template selection: 1. Provided method argument `template_name` 2. Form class property `layout_template` 3. Globally defined default template from `defaults.LAYOUT_DEFAULT_TEMPLATE` :param templa...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L18-L37
null
class TapeformLayoutMixin: """ Mixin to render a form of fieldset as HTML. """ #: Layout template to use when rendering the form. Optional. layout_template = None def get_layout_context(self): """ Returns the context which is used when rendering the form to HTML. The ...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformLayoutMixin.get_layout_context
python
def get_layout_context(self): errors = self.non_field_errors() for field in self.hidden_fields(): errors.extend(field.errors) return { 'form': self, 'errors': errors, 'hidden_fields': self.hidden_fields(), 'visible_fields': self.visibl...
Returns the context which is used when rendering the form to HTML. The generated template context will contain the following variables: * form: `Form` instance * errors: `ErrorList` instance with non field errors and hidden field errors * hidden_fields: All hidden fields to render. ...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L39-L61
null
class TapeformLayoutMixin: """ Mixin to render a form of fieldset as HTML. """ #: Layout template to use when rendering the form. Optional. layout_template = None def get_layout_template(self, template_name=None): """ Returns the layout template to use when rendering the form t...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.full_clean
python
def full_clean(self, *args, **kwargs): super().full_clean(*args, **kwargs) for field in self.errors: if field != NON_FIELD_ERRORS: self.apply_widget_invalid_options(field)
The full_clean method is hijacked to apply special treatment to invalid field inputs. For example adding extra options/classes to widgets.
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L119-L127
[ "def apply_widget_invalid_options(self, field_name):\n \"\"\"\n Applies additional widget options for an invalid field.\n\n This method is called when there is some error on a field to apply\n additional options on its widget. It does the following:\n\n * Sets the aria-invalid property of the widget ...
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.get_field_template
python
def get_field_template(self, bound_field, template_name=None): if template_name: return template_name templates = self.field_template_overrides or {} template_name = templates.get(bound_field.name, None) if template_name: return template_name template_n...
Returns the field template to use when rendering a form field to HTML. Preference of template selection: 1. Provided method argument `template_name` 2. Template from `field_template_overrides` selected by field name 3. Template from `field_template_overrides` selected by field class ...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L129-L161
null
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.get_field_label_css_class
python
def get_field_label_css_class(self, bound_field): class_name = self.field_label_css_class if bound_field.errors and self.field_label_invalid_css_class: class_name = join_css_class( class_name, self.field_label_invalid_css_class) return class_name or None
Returns the optional label CSS class to use when rendering a field template. By default, returns the Form class property `field_label_css_class`. If the field has errors and the Form class property `field_label_invalid_css_class` is defined, its value is appended to the CSS class. :par...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L174-L191
[ "def join_css_class(css_class, *additional_css_classes):\n \"\"\"\n Returns the union of one or more CSS classes as a space-separated string.\n Note that the order will not be preserved.\n \"\"\"\n css_set = set(chain.from_iterable(\n c.split(' ') for c in [css_class, *additional_css_classes] ...
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.get_field_context
python
def get_field_context(self, bound_field): widget = bound_field.field.widget widget_class_name = widget.__class__.__name__.lower() # Check if we have an overwritten id in widget attrs, # if not use auto_id of bound field. field_id = widget.attrs.get('id') or bound_field.auto_id ...
Returns the context which is used when rendering a form field to HTML. The generated template context will contain the following variables: * form: `Form` instance * field: `BoundField` instance of the field * field_id: Field ID to use in `<label for="..">` * field_name: Name o...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L193-L237
[ "def get_field_container_css_class(self, bound_field):\n \"\"\"\n Returns the container CSS class to use when rendering a field template.\n\n By default, returns the Form class property `field_container_css_class`.\n\n :param bound_field: `BoundField` instance to return CSS class for.\n :return: A CS...
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.apply_widget_options
python
def apply_widget_options(self, field_name): widget = self.fields[field_name].widget if isinstance(widget, forms.DateInput): widget.input_type = 'date' if isinstance(widget, forms.TimeInput): widget.input_type = 'time' if isinstance(widget, forms.SplitDateTimeWi...
Applies additional widget options like changing the input type of DateInput and TimeInput to "date" / "time" to enable Browser date pickers or other attributes/properties.
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L239-L255
null
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.apply_widget_template
python
def apply_widget_template(self, field_name): field = self.fields[field_name] template_name = self.get_widget_template(field_name, field) if template_name: field.widget.template_name = template_name
Applies widget template overrides if available. The method uses the `get_widget_template` method to determine if the widget template should be exchanged. If a template is available, the template_name property of the widget instance is updated. :param field_name: A field name of the for...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L257-L271
[ "def get_widget_template(self, field_name, field):\n \"\"\"\n Returns the optional widget template to use when rendering the widget\n for a form field.\n\n Preference of template selection:\n 1. Template from `widget_template_overrides` selected by field name\n 2. Template from `widget_tem...
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.get_widget_template
python
def get_widget_template(self, field_name, field): templates = self.widget_template_overrides or {} template_name = templates.get(field_name, None) if template_name: return template_name template_name = templates.get(field.widget.__class__, None) if template_name: ...
Returns the optional widget template to use when rendering the widget for a form field. Preference of template selection: 1. Template from `widget_template_overrides` selected by field name 2. Template from `widget_template_overrides` selected by widget class By default...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L273-L298
null
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.apply_widget_css_class
python
def apply_widget_css_class(self, field_name): field = self.fields[field_name] class_name = self.get_widget_css_class(field_name, field) if class_name: field.widget.attrs['class'] = join_css_class( field.widget.attrs.get('class', None), class_name)
Applies CSS classes to widgets if available. The method uses the `get_widget_css_class` method to determine if the widget CSS class should be changed. If a CSS class is returned, it is appended to the current value of the class property of the widget instance. :param field_name: A fiel...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L300-L315
[ "def join_css_class(css_class, *additional_css_classes):\n \"\"\"\n Returns the union of one or more CSS classes as a space-separated string.\n Note that the order will not be preserved.\n \"\"\"\n css_set = set(chain.from_iterable(\n c.split(' ') for c in [css_class, *additional_css_classes] ...
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/mixins.py
TapeformMixin.apply_widget_invalid_options
python
def apply_widget_invalid_options(self, field_name): field = self.fields[field_name] class_name = self.get_widget_invalid_css_class(field_name, field) if class_name: field.widget.attrs['class'] = join_css_class( field.widget.attrs.get('class', None), class_name) ...
Applies additional widget options for an invalid field. This method is called when there is some error on a field to apply additional options on its widget. It does the following: * Sets the aria-invalid property of the widget for accessibility. * Adds an invalid CSS class, which is de...
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/mixins.py#L330-L351
[ "def join_css_class(css_class, *additional_css_classes):\n \"\"\"\n Returns the union of one or more CSS classes as a space-separated string.\n Note that the order will not be preserved.\n \"\"\"\n css_set = set(chain.from_iterable(\n c.split(' ') for c in [css_class, *additional_css_classes] ...
class TapeformMixin(TapeformLayoutMixin): """ Mixin to extend the forms capability to render itself as HTML output. (using the template tags provided by `tapeforms`). """ #: Field template to use when rendering a bound form-field. Optional. field_template = None #: A dictionary of form-fie...
stephrdev/django-tapeforms
tapeforms/contrib/foundation.py
FoundationTapeformMixin.get_field_template
python
def get_field_template(self, bound_field, template_name=None): template_name = super().get_field_template(bound_field, template_name) if (template_name == self.field_template and isinstance(bound_field.field.widget, ( forms.RadioSelect, forms.CheckboxSelectMultiple))...
Uses a special field template for widget with multiple inputs. It only applies if no other template than the default one has been defined.
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/contrib/foundation.py#L27-L39
[ "def get_field_template(self, bound_field, template_name=None):\n \"\"\"\n Returns the field template to use when rendering a form field to HTML.\n\n Preference of template selection:\n\n 1. Provided method argument `template_name`\n 2. Template from `field_template_overrides` selected by field name\...
class FoundationTapeformMixin(TapeformMixin): """ Tapeform Mixin to render Foundation compatible forms. (using the template tags provided by `tapeforms`). """ #: Use a special layout template for Foundation compatible forms. layout_template = 'tapeforms/layouts/foundation.html' #: Use a spe...
stephrdev/django-tapeforms
tapeforms/contrib/bootstrap.py
BootstrapTapeformMixin.get_field_label_css_class
python
def get_field_label_css_class(self, bound_field): # If we render CheckboxInputs, Bootstrap requires a different # field label css class for checkboxes. if isinstance(bound_field.field.widget, forms.CheckboxInput): return 'form-check-label' return super().get_field_label_css_...
Returns 'form-check-label' if widget is CheckboxInput. For all other fields, no css class is added.
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/contrib/bootstrap.py#L43-L53
[ "def get_field_label_css_class(self, bound_field):\n \"\"\"\n Returns the optional label CSS class to use when rendering a field template.\n\n By default, returns the Form class property `field_label_css_class`. If the\n field has errors and the Form class property `field_label_invalid_css_class`\n i...
class BootstrapTapeformMixin(TapeformMixin): """ Tapeform Mixin to render Bootstrap4 compatible forms. (using the template tags provided by `tapeforms`). """ #: Use a special layout template for Bootstrap compatible forms. layout_template = 'tapeforms/layouts/bootstrap.html' #: Use a specia...
stephrdev/django-tapeforms
tapeforms/contrib/bootstrap.py
BootstrapTapeformMixin.get_widget_css_class
python
def get_widget_css_class(self, field_name, field): # If we render CheckboxInputs, Bootstrap requires a different # widget css class for checkboxes. if isinstance(field.widget, forms.CheckboxInput): return 'form-check-input' # Idem for fileinput. if isinstance(field.w...
Returns 'form-check-input' if widget is CheckboxInput or 'form-control-file' if widget is FileInput. For all other fields return the default value from the form property ("form-control").
train
https://github.com/stephrdev/django-tapeforms/blob/255602de43777141f18afaf30669d7bdd4f7c323/tapeforms/contrib/bootstrap.py#L55-L70
null
class BootstrapTapeformMixin(TapeformMixin): """ Tapeform Mixin to render Bootstrap4 compatible forms. (using the template tags provided by `tapeforms`). """ #: Use a special layout template for Bootstrap compatible forms. layout_template = 'tapeforms/layouts/bootstrap.html' #: Use a specia...
ten10solutions/Geist
geist/backends/replay.py
geist_replay
python
def geist_replay(wrapped, instance, args, kwargs): path_parts = [] file_parts = [] if hasattr(wrapped, '__module__'): module = wrapped.__module__ module_file = sys.modules[module].__file__ root, _file = os.path.split(module_file) path_parts.append(root) _file, _ = os...
Wraps a test of other function and injects a Geist GUI which will enable replay (set environment variable GEIST_REPLAY_MODE to 'record' to active record mode.
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/backends/replay.py#L51-L84
[ "def get_platform_backend(**kwargs):\n if sys.platform.startswith('win'):\n import geist.backends.windows\n return geist.backends.windows.GeistWindowsBackend(**kwargs)\n else:\n import geist.backends.xvfb\n return geist.backends.xvfb.GeistXvfbBackend(**kwargs)\n", "def is_in_reco...
from __future__ import division, absolute_import, print_function import os import sys import json import base64 import StringIO import wrapt from PIL import Image from . import get_platform_backend from ..core import GUI from ..finders import Location, LocationList from ._common import BackendActionBuilder import numpy...
ten10solutions/Geist
geist/backends/xvfb.py
GeistXvfbBackend._find_display
python
def _find_display(self): self.display_num = 2 while os.path.isdir(XVFB_PATH % (self.display_num,)): self.display_num += 1
Find a usable display, which doesn't have an existing Xvfb file
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/backends/xvfb.py#L85-L91
null
class GeistXvfbBackend(GeistXBase): _FB_OFFSET = 3232 def __init__(self, **kwargs): self.display_num = kwargs.get('display_num', None) width = kwargs.get('width', 1280) height = kwargs.get('height', 1024) if self.display_num is None: self._find_display() di...
ten10solutions/Geist
geist/vision.py
pad_bin_image_to_shape
python
def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ih, iw = image.shape assert ih <= h assert iw <= w if iw < w: result = numpy.hstack((image, numpy.zeros((ih, w - iw), bool))) else: result = image if i...
Padd image to size :shape: with zeros
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L13-L27
null
from __future__ import division from numpy.fft import irfft2, rfft2 import numpy import itertools import operator def subimage(rect, image): x, y, w, h = rect return image[y:y + h, x:x + w] def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ...
ten10solutions/Geist
geist/vision.py
best_convolution
python
def best_convolution(bin_template, bin_image, tollerance=0.5, overlap_table=OVERLAP_TABLE): """ Selects and applies the best convolution method to find template in image. Returns a list of matches in (width, height, x offset, y offset) format (where the x and y offsets are fr...
Selects and applies the best convolution method to find template in image. Returns a list of matches in (width, height, x offset, y offset) format (where the x and y offsets are from the top left corner). As the images are binary images, we can utilise the extra bit space in the float64's by cut...
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L57-L100
null
from __future__ import division from numpy.fft import irfft2, rfft2 import numpy import itertools import operator def subimage(rect, image): x, y, w, h = rect return image[y:y + h, x:x + w] def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ...
ten10solutions/Geist
geist/vision.py
overlapped_convolution
python
def overlapped_convolution(bin_template, bin_image, tollerance=0.5, splits=(4, 2)): """ As each of these images are hold only binary values, and RFFT2 works on float64 greyscale values, we can make the convolution more efficient by breaking the image up into :splits: sect...
As each of these images are hold only binary values, and RFFT2 works on float64 greyscale values, we can make the convolution more efficient by breaking the image up into :splits: sectons. Each one of these sections then has its greyscale value adjusted and then stacked. We then apply the convolut...
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L138-L201
null
from __future__ import division from numpy.fft import irfft2, rfft2 import numpy import itertools import operator def subimage(rect, image): x, y, w, h = rect return image[y:y + h, x:x + w] def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ...
ten10solutions/Geist
geist/vision.py
get_partition_scores
python
def get_partition_scores(image, min_w=1, min_h=1): """Return list of best to worst binary splits along the x and y axis. """ h, w = image.shape[:2] if w == 0 or h == 0: return [] area = h * w cnz = numpy.count_nonzero total = cnz(image) if total == 0 or area == total: ...
Return list of best to worst binary splits along the x and y axis.
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L259-L285
null
from __future__ import division from numpy.fft import irfft2, rfft2 import numpy import itertools import operator def subimage(rect, image): x, y, w, h = rect return image[y:y + h, x:x + w] def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ...
ten10solutions/Geist
geist/vision.py
binary_partition_image
python
def binary_partition_image(image, min_w=1, min_h=1, depth=0, max_depth=-1): """Return a bsp of [pos, axis, [before_node, after_node]] nodes where leaf nodes == None. If max_depth < 0 this function will continue until all leaf nodes have been found, if it is >= 0 leaf nodes will be created at that ...
Return a bsp of [pos, axis, [before_node, after_node]] nodes where leaf nodes == None. If max_depth < 0 this function will continue until all leaf nodes have been found, if it is >= 0 leaf nodes will be created at that depth. min_w and min_h are the minimum width or height of a partition.
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L296-L322
[ "def binary_partition_image(image, min_w=1, min_h=1, depth=0, max_depth=-1):\n \"\"\"Return a bsp of [pos, axis, [before_node, after_node]] nodes where leaf\n nodes == None.\n\n If max_depth < 0 this function will continue until all leaf nodes have\n been found, if it is >= 0 leaf nodes will be created ...
from __future__ import division from numpy.fft import irfft2, rfft2 import numpy import itertools import operator def subimage(rect, image): x, y, w, h = rect return image[y:y + h, x:x + w] def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ...
ten10solutions/Geist
geist/vision.py
find_threshold_near_density
python
def find_threshold_near_density(img, density, low=0, high=255): """Find a threshold where the fraction of pixels above the threshold is closest to density where density is (count of pixels above threshold / count of pixels). The highest threshold closest to the desired density will be returned. ...
Find a threshold where the fraction of pixels above the threshold is closest to density where density is (count of pixels above threshold / count of pixels). The highest threshold closest to the desired density will be returned. Use low and high to exclude undesirable thresholds. :param i...
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L450-L485
null
from __future__ import division from numpy.fft import irfft2, rfft2 import numpy import itertools import operator def subimage(rect, image): x, y, w, h = rect return image[y:y + h, x:x + w] def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ...
ten10solutions/Geist
geist/vision.py
filter_greys_using_image
python
def filter_greys_using_image(image, target): """Filter out any values in target not in image :param image: image containing values to appear in filtered image :param target: the image to filter :rtype: 2d :class:`numpy.ndarray` containing only value in image and with the same dimensions ...
Filter out any values in target not in image :param image: image containing values to appear in filtered image :param target: the image to filter :rtype: 2d :class:`numpy.ndarray` containing only value in image and with the same dimensions as target
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/vision.py#L488-L499
null
from __future__ import division from numpy.fft import irfft2, rfft2 import numpy import itertools import operator def subimage(rect, image): x, y, w, h = rect return image[y:y + h, x:x + w] def pad_bin_image_to_shape(image, shape): """ Padd image to size :shape: with zeros """ h, w = shape ...
ten10solutions/Geist
geist/match_position_finder_helpers.py
find_potential_match_regions
python
def find_potential_match_regions(template, transformed_array, method='correlation', raw_tolerance=0.666): if method == 'correlation': match_value = np.sum(template**2) # this will be the value of the match in the elif method == 'squared difference': match_value = 0 elif method == 'correlati...
To prevent prohibitively slow calculation of normalisation coefficient at each point in image find potential match points, and normalise these only these. This function uses the definitions of the matching functions to calculate the expected match value and finds positions in the transformed array ...
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/match_position_finder_helpers.py#L4-L21
null
import numpy as np # trsnposition and omparison above take most time # correlation coefficient matches at top left- perfect for tiling # correlation matches to bottom right- so requires transformation for tiling def get_tiles_at_potential_match_regions(image, template, transformed_array, method='correlation', raw_t...
ten10solutions/Geist
geist/match_position_finder_helpers.py
normalise_correlation
python
def normalise_correlation(image_tile_dict, transformed_array, template, normed_tolerance=1): template_norm = np.linalg.norm(template) image_norms = {(x,y):np.linalg.norm(image_tile_dict[(x,y)])*template_norm for (x,y) in image_tile_dict.keys()} match_points = image_tile_dict.keys() # for correlation, th...
Calculates the normalisation coefficients of potential match positions Then normalises the correlation at these positions, and returns them if they do indeed constitute a match
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/match_position_finder_helpers.py#L44-L57
null
import numpy as np def find_potential_match_regions(template, transformed_array, method='correlation', raw_tolerance=0.666): """To prevent prohibitively slow calculation of normalisation coefficient at each point in image find potential match points, and normalise these only these. This function use...
ten10solutions/Geist
geist/match_position_finder_helpers.py
normalise_correlation_coefficient
python
def normalise_correlation_coefficient(image_tile_dict, transformed_array, template, normed_tolerance=1): template_mean = np.mean(template) template_minus_mean = template - template_mean template_norm = np.linalg.norm(template_minus_mean) image_norms = {(x,y):np.linalg.norm(image_tile_dict[(x,y)]- np.mea...
As above, but for when the correlation coefficient matching method is used
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/match_position_finder_helpers.py#L61-L73
null
import numpy as np def find_potential_match_regions(template, transformed_array, method='correlation', raw_tolerance=0.666): """To prevent prohibitively slow calculation of normalisation coefficient at each point in image find potential match points, and normalise these only these. This function use...
ten10solutions/Geist
geist/match_position_finder_helpers.py
calculate_squared_differences
python
def calculate_squared_differences(image_tile_dict, transformed_array, template, sq_diff_tolerance=0.1): template_norm_squared = np.sum(template**2) image_norms_squared = {(x,y):np.sum(image_tile_dict[(x,y)]**2) for (x,y) in image_tile_dict.keys()} match_points = image_tile_dict.keys() # for correlation,...
As above, but for when the squared differences matching method is used
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/match_position_finder_helpers.py#L77-L89
null
import numpy as np def find_potential_match_regions(template, transformed_array, method='correlation', raw_tolerance=0.666): """To prevent prohibitively slow calculation of normalisation coefficient at each point in image find potential match points, and normalise these only these. This function use...
ten10solutions/Geist
geist/backends/_x11_common.py
GeistXBase.create_process
python
def create_process(self, command, shell=True, stdout=None, stderr=None, env=None): env = env if env is not None else dict(os.environ) env['DISPLAY'] = self.display return subprocess.Popen(command, shell=shell, stdout=stdout, stderr=stderr, ...
Execute a process using subprocess.Popen, setting the backend's DISPLAY
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/backends/_x11_common.py#L54-L63
null
class GeistXBase(object): KEY_NAME_TO_CODE = keysyms KEY_NAME_TO_CODE_IGNORE_CASE = {name.lower(): value for name, value in keysyms.iteritems()} def __init__(self, **kwargs): display = kwargs.get('display', ':0') self._display = display self._co...
ten10solutions/Geist
geist/matchers.py
match_via_correlation
python
def match_via_correlation(image, template, raw_tolerance=1, normed_tolerance=0.9): h, w = image.shape th, tw = template.shape # fft based convolution enables fast matching of large images correlation = fftconvolve(image, template[::-1,::-1]) # trim the returned image, fftconvolve returns an image of...
Matchihng algorithm based on normalised cross correlation. Using this matching prevents false positives occuring for bright patches in the image
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/matchers.py#L8-L22
[ "def get_tiles_at_potential_match_regions(image, template, transformed_array, method='correlation', raw_tolerance=0.001):\n if method not in ['correlation', 'correlation coefficient', 'squared difference']:\n raise ValueError('Matching method not implemented')\n h, w = template.shape\n match_points ...
from .match_position_finder_helpers import get_tiles_at_potential_match_regions, normalise_correlation, normalise_correlation_coefficient, find_potential_match_regions from scipy.signal import fftconvolve from scipy.ndimage.measurements import label, find_objects import numpy as np # both these methods return array of...
ten10solutions/Geist
geist/matchers.py
match_via_squared_difference
python
def match_via_squared_difference(image, template, raw_tolerance=1, sq_diff_tolerance=0.1): h, w = image.shape th, tw = template.shape # fft based convolution enables fast matching of large images correlation = fftconvolve(image, template[::-1,::-1]) # trim the returned image, fftconvolve returns an ...
Matchihng algorithm based on normalised cross correlation. Using this matching prevents false positives occuring for bright patches in the image
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/matchers.py#L25-L39
[ "def get_tiles_at_potential_match_regions(image, template, transformed_array, method='correlation', raw_tolerance=0.001):\n if method not in ['correlation', 'correlation coefficient', 'squared difference']:\n raise ValueError('Matching method not implemented')\n h, w = template.shape\n match_points ...
from .match_position_finder_helpers import get_tiles_at_potential_match_regions, normalise_correlation, normalise_correlation_coefficient, find_potential_match_regions from scipy.signal import fftconvolve from scipy.ndimage.measurements import label, find_objects import numpy as np # both these methods return array of...
ten10solutions/Geist
geist/matchers.py
match_via_correlation_coefficient
python
def match_via_correlation_coefficient(image, template, raw_tolerance=1, normed_tolerance=0.9): h, w = image.shape th, tw = template.shape temp_mean = np.mean(template) temp_minus_mean = template - temp_mean convolution = fftconvolve(image, temp_minus_mean[::-1,::-1]) convolution = convolution[th...
Matching algorithm based on 2-dimensional version of Pearson product-moment correlation coefficient. This is more robust in the case where the match might be scaled or slightly rotated. From experimentation, this method is less prone to false positives than the correlation method.
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/matchers.py#L43-L59
[ "def get_tiles_at_potential_match_regions(image, template, transformed_array, method='correlation', raw_tolerance=0.001):\n if method not in ['correlation', 'correlation coefficient', 'squared difference']:\n raise ValueError('Matching method not implemented')\n h, w = template.shape\n match_points ...
from .match_position_finder_helpers import get_tiles_at_potential_match_regions, normalise_correlation, normalise_correlation_coefficient, find_potential_match_regions from scipy.signal import fftconvolve from scipy.ndimage.measurements import label, find_objects import numpy as np # both these methods return array of...
ten10solutions/Geist
geist/matchers.py
fuzzy_match
python
def fuzzy_match(image, template, normed_tolerance=None, raw_tolerance=None, method='correlation'): if method == 'correlation': if not raw_tolerance: raw_tolerance = 0.95 if not normed_tolerance: normed_tolerance = 0.95 results = np.array(match_via_correlation(image, t...
Determines, using one of two methods, whether a match(es) is present and returns the positions of the bottom right corners of the matches. Fuzzy matches returns regions, so the center of each region is returned as the final match location USE THIS FUNCTION IF you need to match, e.g. the same image...
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/matchers.py#L64-L110
[ "def match_positions(shape, list_of_coords):\n \"\"\" In cases where we have multiple matches, each highlighted by a region of coordinates,\n we need to separate matches, and find mean of each to return as match position\n \"\"\"\n match_array = np.zeros(shape)\n try:\n # excpetion hit on ...
from .match_position_finder_helpers import get_tiles_at_potential_match_regions, normalise_correlation, normalise_correlation_coefficient, find_potential_match_regions from scipy.signal import fftconvolve from scipy.ndimage.measurements import label, find_objects import numpy as np # both these methods return array of...
ten10solutions/Geist
geist/matchers.py
match_positions
python
def match_positions(shape, list_of_coords): match_array = np.zeros(shape) try: # excpetion hit on this line if nothing in list_of_coords- i.e. no matches match_array[list_of_coords[:,0],list_of_coords[:,1]] = 1 labelled = label(match_array) objects = find_objects(labelled[0]) ...
In cases where we have multiple matches, each highlighted by a region of coordinates, we need to separate matches, and find mean of each to return as match position
train
https://github.com/ten10solutions/Geist/blob/a1ef16d8b4c3777735008b671a50acfde3ce7bf1/geist/matchers.py#L114-L130
null
from .match_position_finder_helpers import get_tiles_at_potential_match_regions, normalise_correlation, normalise_correlation_coefficient, find_potential_match_regions from scipy.signal import fftconvolve from scipy.ndimage.measurements import label, find_objects import numpy as np # both these methods return array of...
stxnext/mappet
mappet/helpers.py
no_empty_value
python
def no_empty_value(func): @wraps(func) def wrapper(value): if not value: raise Exception("Empty value not allowed") return func(value) return wrapper
Raises an exception if function argument is empty.
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L38-L45
null
# -*- coding: utf-8 -*- u"""Helper functions. .. :module: helpers :synopsis: Helper functions. """ from collections import defaultdict from decimal import Decimal from functools import partial, wraps import datetime from lxml import etree import dateutil.parser __all__ = [ 'to_bool', 'to_date', 'to_d...
stxnext/mappet
mappet/helpers.py
to_bool
python
def to_bool(value): cases = { '0': False, 'false': False, 'no': False, '1': True, 'true': True, 'yes': True, } value = value.lower() if isinstance(value, basestring) else value return cases.get(value, bool(value))
Converts human boolean-like values to Python boolean. Falls back to :class:`bool` when ``value`` is not recognized. :param value: the value to convert :returns: ``True`` if value is truthy, ``False`` otherwise :rtype: bool
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L48-L67
null
# -*- coding: utf-8 -*- u"""Helper functions. .. :module: helpers :synopsis: Helper functions. """ from collections import defaultdict from decimal import Decimal from functools import partial, wraps import datetime from lxml import etree import dateutil.parser __all__ = [ 'to_bool', 'to_date', 'to_d...
stxnext/mappet
mappet/helpers.py
etree_to_dict
python
def etree_to_dict(t, trim=True, **kw): u"""Converts an lxml.etree object to Python dict. >>> etree_to_dict(etree.Element('root')) {'root': None} :param etree.Element t: lxml tree to convert :returns d: a dict representing the lxml tree ``t`` :rtype: dict """ d = {t.tag: {} if t.attrib ...
u"""Converts an lxml.etree object to Python dict. >>> etree_to_dict(etree.Element('root')) {'root': None} :param etree.Element t: lxml tree to convert :returns d: a dict representing the lxml tree ``t`` :rtype: dict
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L174-L212
null
# -*- coding: utf-8 -*- u"""Helper functions. .. :module: helpers :synopsis: Helper functions. """ from collections import defaultdict from decimal import Decimal from functools import partial, wraps import datetime from lxml import etree import dateutil.parser __all__ = [ 'to_bool', 'to_date', 'to_d...
stxnext/mappet
mappet/helpers.py
dict_to_etree
python
def dict_to_etree(d, root): u"""Converts a dict to lxml.etree object. >>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS <Element root at 0x...> :param dict d: dict representing the XML tree :param etree.Element root: XML node which will...
u"""Converts a dict to lxml.etree object. >>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS <Element root at 0x...> :param dict d: dict representing the XML tree :param etree.Element root: XML node which will be assigned the resulting tree ...
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L215-L275
[ "def _to_etree(d, node):\n if d is None or len(d) == 0:\n return\n elif isinstance(d, basestring):\n node.text = d\n elif isinstance(d, dict):\n for k, v in d.items():\n assert isinstance(k, basestring)\n if k.startswith('#'):\n assert k == '#text'\...
# -*- coding: utf-8 -*- u"""Helper functions. .. :module: helpers :synopsis: Helper functions. """ from collections import defaultdict from decimal import Decimal from functools import partial, wraps import datetime from lxml import etree import dateutil.parser __all__ = [ 'to_bool', 'to_date', 'to_d...
stxnext/mappet
mappet/mappet.py
Node.getattr
python
def getattr(self, key, default=None, callback=None): u"""Getting the attribute of an element. >>> xml = etree.Element('root') >>> xml.text = 'text' >>> Node(xml).getattr('text') 'text' >>> Node(xml).getattr('text', callback=str.upper) 'TEXT' >>> Node(xml)...
u"""Getting the attribute of an element. >>> xml = etree.Element('root') >>> xml.text = 'text' >>> Node(xml).getattr('text') 'text' >>> Node(xml).getattr('text', callback=str.upper) 'TEXT' >>> Node(xml).getattr('wrong_attr', default='default') 'default'
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L75-L88
null
class Node(object): u"""Base class representing an XML node.""" #: The lxml object representing parsed XML. _xml = None def __init__(self, xml): self._xml = xml def __repr__(self): u"""Represent an XML node as a string with child count. >>> xml = etree.Element('root') ...
stxnext/mappet
mappet/mappet.py
Node.setattr
python
def setattr(self, key, value): u"""Sets an attribute on a node. >>> xml = etree.Element('root') >>> Node(xml).setattr('text', 'text2') >>> Node(xml).getattr('text') 'text2' >>> Node(xml).setattr('attr', 'val') >>> Node(xml).getattr('attr') 'val' "...
u"""Sets an attribute on a node. >>> xml = etree.Element('root') >>> Node(xml).setattr('text', 'text2') >>> Node(xml).getattr('text') 'text2' >>> Node(xml).setattr('attr', 'val') >>> Node(xml).getattr('attr') 'val'
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L90-L104
null
class Node(object): u"""Base class representing an XML node.""" #: The lxml object representing parsed XML. _xml = None def __init__(self, xml): self._xml = xml def __repr__(self): u"""Represent an XML node as a string with child count. >>> xml = etree.Element('root') ...
stxnext/mappet
mappet/mappet.py
Literal.get
python
def get(self, default=None, callback=None): u"""Returns leaf's value.""" value = self._xml.text if self._xml.text else default return callback(value) if callback else value
u"""Returns leaf's value.
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L209-L212
null
class Literal(Node): u"""Represents a leaf in an XML tree.""" def __str__(self): u"""Represents a leaf as a str. Returns node's text as a string, if it's not None.""" return str(self.get()) #: Represents the leaf as unicode. __unicode__ = __str__ def __repr__(self): ...
stxnext/mappet
mappet/mappet.py
Mappet.to_str
python
def to_str(self, pretty_print=False, encoding=None, **kw): u"""Converts a node with all of it's children to a string. Remaining arguments are passed to etree.tostring as is. kwarg without_comments: bool because it works only in C14N flags: 'pretty print' and 'encoding' are ignored. ...
u"""Converts a node with all of it's children to a string. Remaining arguments are passed to etree.tostring as is. kwarg without_comments: bool because it works only in C14N flags: 'pretty print' and 'encoding' are ignored. :param bool pretty_print: whether to format the output ...
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L384-L406
null
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.iter_children
python
def iter_children(self, key=None): u"""Iterates over children. :param key: A key for filtering children by tagname. """ tag = None if key: tag = self._get_aliases().get(key) if not tag: raise KeyError(key) for child in self._xml...
u"""Iterates over children. :param key: A key for filtering children by tagname.
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L412-L429
[ "def _get_aliases(self):\n u\"\"\"Creates a dict with aliases.\n\n The key is a normalized tagname, value the original tagname.\n \"\"\"\n if self._aliases is None:\n self._aliases = {}\n\n if self._xml is not None:\n for child in self._xml.iterchildren():\n self....
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.update
python
def update(self, **kwargs): u"""Updating or creation of new simple nodes. Each dict key is used as a tagname and value as text. """ for key, value in kwargs.items(): helper = helpers.CAST_DICT.get(type(value), str) tag = self._get_aliases().get(key, key) ...
u"""Updating or creation of new simple nodes. Each dict key is used as a tagname and value as text.
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L438-L455
[ "def _get_aliases(self):\n u\"\"\"Creates a dict with aliases.\n\n The key is a normalized tagname, value the original tagname.\n \"\"\"\n if self._aliases is None:\n self._aliases = {}\n\n if self._xml is not None:\n for child in self._xml.iterchildren():\n self....
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.sget
python
def sget(self, path, default=NONE_NODE): u"""Enables access to nodes if one or more of them don't exist. Example: >>> m = Mappet('<root><tag attr1="attr text">text value</tag></root>') >>> m.sget('tag') text value >>> m.sget('tag.@attr1') 'attr text' >>> ...
u"""Enables access to nodes if one or more of them don't exist. Example: >>> m = Mappet('<root><tag attr1="attr text">text value</tag></root>') >>> m.sget('tag') text value >>> m.sget('tag.@attr1') 'attr text' >>> m.sget('tag.#text') 'text value' ...
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L457-L507
[ "def getattr(self, key, default=None, callback=None):\n u\"\"\"Getting the attribute of an element.\n\n >>> xml = etree.Element('root')\n >>> xml.text = 'text'\n >>> Node(xml).getattr('text')\n 'text'\n >>> Node(xml).getattr('text', callback=str.upper)\n 'TEXT'\n >>> Node(xml).getattr('wrong...
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.create
python
def create(self, tag, value): u"""Creates a node, if it doesn't exist yet. Unlike attribute access, this allows to pass a node's name with hyphens. Those hyphens will be normalized automatically. In case the required element already exists, raises an exception. Updating/overwri...
u"""Creates a node, if it doesn't exist yet. Unlike attribute access, this allows to pass a node's name with hyphens. Those hyphens will be normalized automatically. In case the required element already exists, raises an exception. Updating/overwriting should be done using `update``.
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L509-L523
[ "def set(self, name, value):\n u\"\"\"Assigns a new XML structure to the node.\n\n A literal value, dict or list can be passed in. Works for all nested levels.\n\n Dictionary:\n >>> m = Mappet('<root/>')\n >>> m.head = {'a': 'A', 'b': {'#text': 'B', '@attr': 'val'}}\n >>> m.head.to_str()\n '<he...
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.set
python
def set(self, name, value): u"""Assigns a new XML structure to the node. A literal value, dict or list can be passed in. Works for all nested levels. Dictionary: >>> m = Mappet('<root/>') >>> m.head = {'a': 'A', 'b': {'#text': 'B', '@attr': 'val'}} >>> m.head.to_str() ...
u"""Assigns a new XML structure to the node. A literal value, dict or list can be passed in. Works for all nested levels. Dictionary: >>> m = Mappet('<root/>') >>> m.head = {'a': 'A', 'b': {'#text': 'B', '@attr': 'val'}} >>> m.head.to_str() '<head><a>A</a><b attr="val">...
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L525-L563
[ "def assign_dict(self, node, xml_dict):\n \"\"\"Assigns a Python dict to a ``lxml`` node.\n\n :param node: A node to assign the dict to.\n :param xml_dict: The dict with attributes/children to use.\n \"\"\"\n new_node = etree.Element(node.tag)\n\n # Replaces the previous node with the new one\n ...
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.assign_dict
python
def assign_dict(self, node, xml_dict): new_node = etree.Element(node.tag) # Replaces the previous node with the new one self._xml.replace(node, new_node) # Copies #text and @attrs from the xml_dict helpers.dict_to_etree(xml_dict, new_node)
Assigns a Python dict to a ``lxml`` node. :param node: A node to assign the dict to. :param xml_dict: The dict with attributes/children to use.
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L565-L577
[ "def dict_to_etree(d, root):\n u\"\"\"Converts a dict to lxml.etree object.\n\n >>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS\n <Element root at 0x...>\n\n :param dict d: dict representing the XML tree\n :param etree.Element root: XML ...
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.assign_literal
python
def assign_literal(element, value): u"""Assigns a literal. If a given node doesn't exist, it will be created. :param etree.Element element: element to which we assign. :param value: the value to assign """ # Searches for a conversion method specific to the type of value...
u"""Assigns a literal. If a given node doesn't exist, it will be created. :param etree.Element element: element to which we assign. :param value: the value to assign
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L591-L604
null
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.to_dict
python
def to_dict(self, **kw): u"""Converts the lxml object to a dict. possible kwargs: without_comments: bool """ _, value = helpers.etree_to_dict(self._xml, **kw).popitem() return value
u"""Converts the lxml object to a dict. possible kwargs: without_comments: bool
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L606-L613
[ "def etree_to_dict(t, trim=True, **kw):\n u\"\"\"Converts an lxml.etree object to Python dict.\n\n >>> etree_to_dict(etree.Element('root'))\n {'root': None}\n\n :param etree.Element t: lxml tree to convert\n :returns d: a dict representing the lxml tree ``t``\n :rtype: dict\n \"\"\"\n d = {t...
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet._get_aliases
python
def _get_aliases(self): u"""Creates a dict with aliases. The key is a normalized tagname, value the original tagname. """ if self._aliases is None: self._aliases = {} if self._xml is not None: for child in self._xml.iterchildren(): ...
u"""Creates a dict with aliases. The key is a normalized tagname, value the original tagname.
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L615-L627
[ "def normalize_tag(tag):\n u\"\"\"Normalizes tag name.\n\n :param str tag: tag name to normalize\n :rtype: str\n :returns: normalized tag name\n\n >>> normalize_tag('tag-NaMe')\n 'tag_name'\n \"\"\"\n return tag.lower().replace('-', '_')\n" ]
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.xpath
python
def xpath( self, path, namespaces=None, regexp=False, smart_strings=True, single_use=False, ): u"""Executes XPath query on the ``lxml`` object and returns a correct object. :param str path: XPath string e.g., 'cars'/'car' ...
u"""Executes XPath query on the ``lxml`` object and returns a correct object. :param str path: XPath string e.g., 'cars'/'car' :param str/dict namespaces: e.g., 'exslt', 're' or ``{'re': "http://exslt.org/regular-expressions"}`` :param bool regexp: if ``True`` and no namespaces is ...
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L629-L677
[ "def xpath_evaluator(self, namespaces=None, regexp=False, smart_strings=True):\n u\"\"\"Creates an XPathEvaluator instance for an ElementTree or an Element.\n\n :returns: ``XPathEvaluator`` instance\n \"\"\"\n return etree.XPathEvaluator(\n self._xml,\n namespaces=namespaces,\n rege...
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
stxnext/mappet
mappet/mappet.py
Mappet.xpath_evaluator
python
def xpath_evaluator(self, namespaces=None, regexp=False, smart_strings=True): u"""Creates an XPathEvaluator instance for an ElementTree or an Element. :returns: ``XPathEvaluator`` instance """ return etree.XPathEvaluator( self._xml, namespaces=namespaces, ...
u"""Creates an XPathEvaluator instance for an ElementTree or an Element. :returns: ``XPathEvaluator`` instance
train
https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/mappet.py#L679-L689
null
class Mappet(Node): u"""A node that may have children.""" _aliases = None u"""Dictionary with node aliases. The keys are normalized tagnames, values are the original tagnames. _aliases = { 'car_model_desc': 'car-model-desc', 'car': 'Car', } """ def __init__(self, xml):...
hackedd/gw2api
gw2api/__init__.py
set_cache_dir
python
def set_cache_dir(directory): global cache_dir if directory is None: cache_dir = None return if not os.path.exists(directory): os.makedirs(directory) if not os.path.isdir(directory): raise ValueError("not a directory") cache_dir = directory
Set the directory to cache JSON responses from most API endpoints.
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/__init__.py#L38-L51
null
import os import requests VERSION = "v1" BASE_URL = "https://api.guildwars2.com/%s/" % VERSION LANGUAGES = {"en": "English", "es": "Spanish", "de": "German", "fr": "French"} TYPE_COIN, TYPE_ITEM, TYPE_TEXT, TYPE_MAP = 1, 2, 3, 4 TYPE_PVP_GAME, TYPE_SKILL, TYPE_TRAIT, TYPE_USER = 5, 6, 7, 8 TYPE_RECIPE, TYPE_SKIN, TYP...
hackedd/gw2api
gw2api/v2/endpoint.py
EndpointBase.get_cached
python
def get_cached(self, path, cache_name, **kwargs): if gw2api.cache_dir and gw2api.cache_time and cache_name: cache_file = os.path.join(gw2api.cache_dir, cache_name) if mtime(cache_file) >= time.time() - gw2api.cache_time: with open(cache_file, "r") as fp: ...
Request a resource form the API, first checking if there is a cached response available. Returns the parsed JSON data.
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/v2/endpoint.py#L42-L61
[ "def _get(self, path, **kwargs):\n token = kwargs.pop(\"token\") if \"token\" in kwargs else self.token\n if token:\n headers = kwargs.setdefault(\"headers\", {})\n headers.setdefault(\"Authorization\", \"Bearer \" + token)\n return super(AuthenticatedMixin, self)._get(path, **kwargs)\n", "...
class EndpointBase(object): response_types = { list: ListResponse, dict: DictResponse, } def __init__(self, name): super(EndpointBase, self).__init__() self.name = name def has_cached(self, cache_name): if gw2api.cache_dir and gw2api.cache_time and cache_name: ...
hackedd/gw2api
gw2api/skins.py
skin_details
python
def skin_details(skin_id, lang="en"): params = {"skin_id": skin_id, "lang": lang} cache_name = "skin_details.%(skin_id)s.%(lang)s.json" % params return get_cached("skin_details.json", cache_name, params=params)
This resource returns details about a single skin. :param skin_id: The skin to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties depends on the type of item the skin applies ...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/skins.py#L16-L53
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("skins", "skin_details") def skins(): """This resource returns a list of skins that were discovered by players in the game. Details about a single skin can be obtained using the :func:`skin_details` resource. """ return get_cached("skins.json").get("skins...
hackedd/gw2api
gw2api/mumble.py
GuildWars2FileMapping.get_map_location
python
def get_map_location(self): map_data = self.get_map() (bounds_e, bounds_n), (bounds_w, bounds_s) = map_data["continent_rect"] (map_e, map_n), (map_w, map_s) = map_data["map_rect"] assert bounds_w < bounds_e assert bounds_n < bounds_s assert map_w < map_e assert m...
Get the location of the player, converted to world coordinates. :return: a tuple (x, y, z).
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/mumble.py#L93-L117
[ "def get_map(self, lang=\"en\"):\n return maps(self.context.mapId, lang)\n" ]
class GuildWars2FileMapping(FileMapping): def __init__(self, name=u"MumbleLink", value_struct=LinkedMem, create=True): super(GuildWars2FileMapping, self).__init__(name, value_struct, create) def get_map(self, lang="en"): return maps(self.context.mapId, lang)
hackedd/gw2api
gw2api/wvw.py
matches
python
def matches(): wvw_matches = get_cached("wvw/matches.json", False).get("wvw_matches") for match in wvw_matches: match["start_time"] = parse_datetime(match["start_time"]) match["end_time"] = parse_datetime(match["end_time"]) return wvw_matches
This resource returns a list of the currently running WvW matches, with the participating worlds included in the result. Further details about a match can be requested using the ``match_details`` function. The response is a list of match objects, each of which contains the following properties: wv...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/wvw.py#L20-L51
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from datetime import datetime from .util import get_cached __all__ = ("matches", "match_details", "objective_names") def parse_datetime(date_string): """Parse a datetime string as returned by the ``matches`` endpoint to a datetime object. >>> parse_datetime('2014-07-04T18:00:00Z') datetime.datetim...
hackedd/gw2api
gw2api/wvw.py
objective_names
python
def objective_names(lang="en"): params = {"lang": lang} cache_name = "objective_names.%(lang)s.json" % params data = get_cached("wvw/objective_names.json", cache_name, params=params) return dict([(objective["id"], objective["name"]) for objective in data])
This resource returns a list of the localized WvW objective names for the specified language. :param lang: The language to query the names for. :return: A dictionary mapping the objective Ids to the names. *Note that these are not the names displayed in the game, but rather the abstract type.*
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/wvw.py#L117-L131
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from datetime import datetime from .util import get_cached __all__ = ("matches", "match_details", "objective_names") def parse_datetime(date_string): """Parse a datetime string as returned by the ``matches`` endpoint to a datetime object. >>> parse_datetime('2014-07-04T18:00:00Z') datetime.datetim...
hackedd/gw2api
gw2api/util.py
mtime
python
def mtime(path): if not os.path.exists(path): return -1 stat = os.stat(path) return stat.st_mtime
Get the modification time of a file, or -1 if the file does not exist.
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/util.py#L14-L20
null
import os import time import json from struct import pack, unpack from base64 import b64encode, b64decode import gw2api __all__ = ("encode_item_link", "encode_coin_link", "encode_chat_link", "decode_chat_link") def get_cached(path, cache_name=None, **kwargs): """Request a resource form the API, fir...
hackedd/gw2api
gw2api/util.py
get_cached
python
def get_cached(path, cache_name=None, **kwargs): if gw2api.cache_dir and gw2api.cache_time and cache_name is not False: if cache_name is None: cache_name = path cache_file = os.path.join(gw2api.cache_dir, cache_name) if mtime(cache_file) >= time.time() - gw2api.cache_time: ...
Request a resource form the API, first checking if there is a cached response available. Returns the parsed JSON data.
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/util.py#L23-L54
null
import os import time import json from struct import pack, unpack from base64 import b64encode, b64decode import gw2api __all__ = ("encode_item_link", "encode_coin_link", "encode_chat_link", "decode_chat_link") def mtime(path): """Get the modification time of a file, or -1 if the file does not exist...
hackedd/gw2api
gw2api/util.py
encode_item_link
python
def encode_item_link(item_id, number=1, skin_id=None, upgrade1=None, upgrade2=None): return encode_chat_link(gw2api.TYPE_ITEM, id=item_id, number=number, skin_id=skin_id, upgrade1=upgrade1, upgrade2=upgrade2)
Encode a chat link for an item (or a stack of items). :param item_id: the Id of the item :param number: the number of items in the stack :param skin_id: the id of the skin applied to the item :param upgrade1: the id of the first upgrade component :param upgrade2: the id of the second upgrade compon...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/util.py#L57-L69
[ "def encode_chat_link(link_type, **kwargs):\n if link_type in gw2api.LINK_TYPES:\n link_type = gw2api.LINK_TYPES[link_type]\n\n if link_type == gw2api.TYPE_COIN:\n if \"copper\" in kwargs or \"silver\" in kwargs or \"gold\" in kwargs:\n amount = (kwargs.get(\"gold\", 0) * 100 * 100 +\...
import os import time import json from struct import pack, unpack from base64 import b64encode, b64decode import gw2api __all__ = ("encode_item_link", "encode_coin_link", "encode_chat_link", "decode_chat_link") def mtime(path): """Get the modification time of a file, or -1 if the file does not exist...
hackedd/gw2api
gw2api/util.py
encode_coin_link
python
def encode_coin_link(copper, silver=0, gold=0): return encode_chat_link(gw2api.TYPE_COIN, copper=copper, silver=silver, gold=gold)
Encode a chat link for an amount of coins.
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/util.py#L72-L76
[ "def encode_chat_link(link_type, **kwargs):\n if link_type in gw2api.LINK_TYPES:\n link_type = gw2api.LINK_TYPES[link_type]\n\n if link_type == gw2api.TYPE_COIN:\n if \"copper\" in kwargs or \"silver\" in kwargs or \"gold\" in kwargs:\n amount = (kwargs.get(\"gold\", 0) * 100 * 100 +\...
import os import time import json from struct import pack, unpack from base64 import b64encode, b64decode import gw2api __all__ = ("encode_item_link", "encode_coin_link", "encode_chat_link", "decode_chat_link") def mtime(path): """Get the modification time of a file, or -1 if the file does not exist...
hackedd/gw2api
gw2api/items.py
item_details
python
def item_details(item_id, lang="en"): params = {"item_id": item_id, "lang": lang} cache_name = "item_details.%(item_id)s.%(lang)s.json" % params return get_cached("item_details.json", cache_name, params=params)
This resource returns a details about a single item. :param item_id: The item to query for. :param lang: The language to display the texts in. The response is an object with at least the following properties. Note that the availability of some properties depends on the type of the item. item_id (...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/items.py#L24-L85
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("items", "recipes", "item_details", "recipe_details") def items(): """This resource returns a list of items that were discovered by players in the game. Details about a single item can be obtained using the :func:`item_details` resource. """ return get_ca...
hackedd/gw2api
gw2api/items.py
recipe_details
python
def recipe_details(recipe_id, lang="en"): params = {"recipe_id": recipe_id, "lang": lang} cache_name = "recipe_details.%(recipe_id)s.%(lang)s.json" % params return get_cached("recipe_details.json", cache_name, params=params)
This resource returns a details about a single recipe. :param recipe_id: The recipe to query for. :param lang: The language to display the texts in. The response is an object with the following properties: recipe_id (number): The recipe id. type (string): The type of the produced...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/items.py#L88-L139
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("items", "recipes", "item_details", "recipe_details") def items(): """This resource returns a list of items that were discovered by players in the game. Details about a single item can be obtained using the :func:`item_details` resource. """ return get_ca...
hackedd/gw2api
gw2api/misc.py
colors
python
def colors(lang="en"): cache_name = "colors.%s.json" % lang data = get_cached("colors.json", cache_name, params=dict(lang=lang)) return data["colors"]
This resource returns all dyes in the game, including localized names and their color component information. :param lang: The language to query the names for. The response is a dictionary where color ids are mapped to an dictionary containing the following properties: name (string): The n...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/misc.py#L15-L62
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("build", "colors", "files") def build(): """This resource returns the current build id of the game. The result of this function is not cached. """ return get_cached("build.json", False).get("build_id") def files(): """This resource returns commonly req...
hackedd/gw2api
gw2api/events.py
event_names
python
def event_names(lang="en"): cache_name = "event_names.%s.json" % lang data = get_cached("event_names.json", cache_name, params=dict(lang=lang)) return dict([(event["id"], event["name"]) for event in data])
This resource returns an unordered list of the localized event names for the specified language. :param lang: The language to query the names for. :return: A dictionary where the key is the event id and the value is the name of the event in the specified language.
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/events.py#L7-L18
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("event_names", "event_details") def event_details(event_id=None, lang="en"): """This resource returns static details about available events. :param event_id: Only list this event. :param lang: Show localized texts in the specified language. The response is ...
hackedd/gw2api
gw2api/events.py
event_details
python
def event_details(event_id=None, lang="en"): if event_id: cache_name = "event_details.%s.%s.json" % (event_id, lang) params = {"event_id": event_id, "lang": lang} else: cache_name = "event_details.%s.json" % lang params = {"lang": lang} data = get_cached("event_details.json"...
This resource returns static details about available events. :param event_id: Only list this event. :param lang: Show localized texts in the specified language. The response is a dictionary where the key is the event id, and the value is a dictionary containing the following properties: name (str...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/events.py#L21-L79
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("event_names", "event_details") def event_names(lang="en"): """This resource returns an unordered list of the localized event names for the specified language. :param lang: The language to query the names for. :return: A dictionary where the key is the event ...
hackedd/gw2api
gw2api/guild.py
guild_details
python
def guild_details(guild_id=None, name=None): if guild_id and name: warnings.warn("both guild_id and name are specified, " "name will be ignored") if guild_id: params = {"guild_id": guild_id} cache_name = "guild_details.%s.json" % guild_id elif name: par...
This resource returns details about a guild. :param guild_id: The guild id to query for. :param name: The guild name to query for. *Note: Only one parameter is required; if both are set, the guild Id takes precedence and a warning will be logged.* The response is a dictionary with the following k...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/guild.py#L9-L68
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
import warnings from .util import get_cached __all__ = ("guild_details", )
hackedd/gw2api
gw2api/map.py
map_names
python
def map_names(lang="en"): cache_name = "map_names.%s.json" % lang data = get_cached("map_names.json", cache_name, params=dict(lang=lang)) return dict([(item["id"], item["name"]) for item in data])
This resource returns an dictionary of the localized map names for the specified language. Only maps with events are listed - if you need a list of all maps, use ``maps.json`` instead. :param lang: The language to query the names for. :return: the response is a dictionary where the key is the map id an...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/map.py#L35-L47
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("continents", "map_names", "maps", "map_floor") def continents(): """This resource returns static information about the continents used with the map_floor resource. The response is a dictionary where the key is the continent id, and the value is a dictionary ...
hackedd/gw2api
gw2api/map.py
maps
python
def maps(map_id=None, lang="en"): if map_id: cache_name = "maps.%s.%s.json" % (map_id, lang) params = {"map_id": map_id, "lang": lang} else: cache_name = "maps.%s.json" % lang params = {"lang": lang} data = get_cached("maps.json", cache_name, params=params).get("maps") r...
This resource returns details about maps in the game, including details about floor and translation data on how to translate between world coordinates and map coordinates. :param map_id: Only list this map. :param lang: Show localized texts in the specified language. The response is a dictionary w...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/map.py#L50-L105
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("continents", "map_names", "maps", "map_floor") def continents(): """This resource returns static information about the continents used with the map_floor resource. The response is a dictionary where the key is the continent id, and the value is a dictionary ...
hackedd/gw2api
gw2api/map.py
map_floor
python
def map_floor(continent_id, floor, lang="en"): cache_name = "map_floor.%s-%s.%s.json" % (continent_id, floor, lang) params = {"continent_id": continent_id, "floor": floor, "lang": lang} return get_cached("map_floor.json", cache_name, params=params)
This resource returns details about a map floor, used to populate a world map. All coordinates are map coordinates. The returned data only contains static content. Dynamic content, such as vendors, is not currently available. :param continent_id: The continent. :param floor: The map floor. :pa...
train
https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/map.py#L108-L236
[ "def get_cached(path, cache_name=None, **kwargs):\n \"\"\"Request a resource form the API, first checking if there is a cached\n response available. Returns the parsed JSON data.\n \"\"\"\n if gw2api.cache_dir and gw2api.cache_time and cache_name is not False:\n if cache_name is None:\n ...
from .util import get_cached __all__ = ("continents", "map_names", "maps", "map_floor") def continents(): """This resource returns static information about the continents used with the map_floor resource. The response is a dictionary where the key is the continent id, and the value is a dictionary ...
NickMonzillo/SmartCloud
SmartCloud/wordplay.py
separate
python
def separate(text): '''Takes text and separates it into a list of words''' alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: if char in alphabet or char in alphabet.upper(): news...
Takes text and separates it into a list of words
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/wordplay.py#L1-L13
null
def read_file(filename): '''Reads in a .txt file.''' with open(filename,'r') as f: content = f.read() return content def eliminate_repeats(text): '''Returns a list of words that occur in the text. Eliminates stopwords.''' bannedwords = read_file('stopwords.txt') alphabet = 'abcdefgh...
NickMonzillo/SmartCloud
SmartCloud/wordplay.py
eliminate_repeats
python
def eliminate_repeats(text): '''Returns a list of words that occur in the text. Eliminates stopwords.''' bannedwords = read_file('stopwords.txt') alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: ...
Returns a list of words that occur in the text. Eliminates stopwords.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/wordplay.py#L21-L36
[ "def read_file(filename):\n '''Reads in a .txt file.'''\n with open(filename,'r') as f:\n content = f.read()\n return content\n" ]
def separate(text): '''Takes text and separates it into a list of words''' alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: if char in alphabet or char in alphabet.upper(): news...
NickMonzillo/SmartCloud
SmartCloud/wordplay.py
wordcount
python
def wordcount(text): '''Returns the count of the words in a file.''' bannedwords = read_file('stopwords.txt') wordcount = {} separated = separate(text) for word in separated: if word not in bannedwords: if not wordcount.has_key(word): wordcount[word] = 1 ...
Returns the count of the words in a file.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/wordplay.py#L38-L49
[ "def separate(text):\n '''Takes text and separates it into a list of words'''\n alphabet = 'abcdefghijklmnopqrstuvwxyz'\n words = text.split()\n standardwords = []\n for word in words:\n newstr = ''\n for char in word:\n if char in alphabet or char in alphabet.upper():\n ...
def separate(text): '''Takes text and separates it into a list of words''' alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: if char in alphabet or char in alphabet.upper(): news...
NickMonzillo/SmartCloud
SmartCloud/wordplay.py
tuplecount
python
def tuplecount(text): '''Changes a dictionary into a list of tuples.''' worddict = wordcount(text) countlist = [] for key in worddict.keys(): countlist.append((key,worddict[key])) countlist = list(reversed(sorted(countlist,key = lambda x: x[1]))) return countlist
Changes a dictionary into a list of tuples.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/wordplay.py#L51-L58
[ "def wordcount(text):\n '''Returns the count of the words in a file.'''\n bannedwords = read_file('stopwords.txt')\n wordcount = {}\n separated = separate(text)\n for word in separated:\n if word not in bannedwords:\n if not wordcount.has_key(word):\n wordcount[word] ...
def separate(text): '''Takes text and separates it into a list of words''' alphabet = 'abcdefghijklmnopqrstuvwxyz' words = text.split() standardwords = [] for word in words: newstr = '' for char in word: if char in alphabet or char in alphabet.upper(): news...
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.render_word
python
def render_word(self,word,size,color): '''Creates a surface that contains a word.''' pygame.font.init() font = pygame.font.Font(None,size) self.rendered_word = font.render(word,0,color) self.word_size = font.size(word)
Creates a surface that contains a word.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L16-L21
null
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def plot_word(self,position): '''Blits a rendered word o...
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.plot_word
python
def plot_word(self,position): '''Blits a rendered word on to the main display surface''' posrectangle = pygame.Rect(position,self.word_size) self.used_pos.append(posrectangle) self.cloud.blit(self.rendered_word,position)
Blits a rendered word on to the main display surface
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L23-L27
null
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def render_word(self,word,size,color): '''Creates a surfa...
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.collides
python
def collides(self,position,size): '''Returns True if the word collides with another plotted word.''' word_rect = pygame.Rect(position,self.word_size) if word_rect.collidelistall(self.used_pos) == []: return False else: return True
Returns True if the word collides with another plotted word.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L29-L35
null
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def render_word(self,word,size,color): '''Creates a surfa...
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.expand
python
def expand(self,delta_width,delta_height): '''Makes the cloud surface bigger. Maintains all word positions.''' temp_surface = pygame.Surface((self.width + delta_width,self.height + delta_height)) (self.width,self.height) = (self.width + delta_width, self.height + delta_height) temp_surfa...
Makes the cloud surface bigger. Maintains all word positions.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L37-L42
null
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def render_word(self,word,size,color): '''Creates a surfa...
NickMonzillo/SmartCloud
SmartCloud/__init__.py
Cloud.smart_cloud
python
def smart_cloud(self,input,max_text_size=72,min_text_size=12,exclude_words = True): '''Creates a word cloud using the input. Input can be a file, directory, or text. Set exclude_words to true if you want to eliminate words that only occur once.''' self.exclude_words = exclude_words...
Creates a word cloud using the input. Input can be a file, directory, or text. Set exclude_words to true if you want to eliminate words that only occur once.
train
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L44-L58
[ "def read_file(filename):\n '''Reads in a .txt file.'''\n with open(filename,'r') as f:\n content = f.read()\n return content\n", "def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):\n '''Creates a word cloud using files from ...
class Cloud(object): def __init__(self,width=500,height=500): pygame.init() pygame.font.init() self.width = width self.height = height self.cloud = pygame.Surface((width,height)) self.used_pos = [] def render_word(self,word,size,color): '''Creates a surfa...