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
kalbhor/MusicNow
musicnow/repair.py
get_lyrics_letssingit
python
def get_lyrics_letssingit(song_name): ''' Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement ''' lyrics = "" url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html =...
Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L76-L104
null
#!/usr/bin/env python ''' Tries to find the metadata of songs based on the file name https://github.com/lakshaykalbhor/MusicRepair ''' try: from . import albumsearch from . import improvename from . import log except: import albumsearch import improvename import log from os import rename, env...
kalbhor/MusicNow
musicnow/repair.py
get_lyrics_genius
python
def get_lyrics_genius(song_title): ''' Scrapes the lyrics from Genius.com ''' base_url = "http://api.genius.com" headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)} search_url = base_url + "/search" data = {'q': song_title} response = requests.get(search_url, data=data, headers=heade...
Scrapes the lyrics from Genius.com
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L106-L130
null
#!/usr/bin/env python ''' Tries to find the metadata of songs based on the file name https://github.com/lakshaykalbhor/MusicRepair ''' try: from . import albumsearch from . import improvename from . import log except: import albumsearch import improvename import log from os import rename, env...
kalbhor/MusicNow
musicnow/repair.py
get_details_spotify
python
def get_details_spotify(song_name): ''' Tries finding metadata through Spotify ''' song_name = improvename.songname(song_name) spotify = spotipy.Spotify() results = spotify.search(song_name, limit=1) # Find top result log.log_indented('* Finding metadata from Spotify.') try: ...
Tries finding metadata through Spotify
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L133-L166
[ "def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n", "def songname(song_name):\n '''\n Improves file name by removing crap words\n '''\n try:\n song_name = splitext(song_name)[0]...
#!/usr/bin/env python ''' Tries to find the metadata of songs based on the file name https://github.com/lakshaykalbhor/MusicRepair ''' try: from . import albumsearch from . import improvename from . import log except: import albumsearch import improvename import log from os import rename, env...
kalbhor/MusicNow
musicnow/repair.py
get_details_letssingit
python
def get_details_letssingit(song_name): ''' Gets the song details if song details not found through spotify ''' song_name = improvename.songname(song_name) url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = ur...
Gets the song details if song details not found through spotify
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L169-L227
[ "def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n", "def songname(song_name):\n '''\n Improves file name by removing crap words\n '''\n try:\n song_name = splitext(song_name)[0]...
#!/usr/bin/env python ''' Tries to find the metadata of songs based on the file name https://github.com/lakshaykalbhor/MusicRepair ''' try: from . import albumsearch from . import improvename from . import log except: import albumsearch import improvename import log from os import rename, env...
kalbhor/MusicNow
musicnow/repair.py
add_albumart
python
def add_albumart(albumart, song_title): ''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: ...
Adds the album art to the song
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L230-L258
[ "def log(text='', newline=False, trailing_newline=False):\n newline_char = ''\n trailing_newline_char = ''\n if newline:\n newline_char = '\\n'\n if trailing_newline:\n trailing_newline_char = '\\n'\n print('%s%s%s' % (newline_char, text, trailing_newline_char))\n", "def log_error(tex...
#!/usr/bin/env python ''' Tries to find the metadata of songs based on the file name https://github.com/lakshaykalbhor/MusicRepair ''' try: from . import albumsearch from . import improvename from . import log except: import albumsearch import improvename import log from os import rename, env...
kalbhor/MusicNow
musicnow/repair.py
add_details
python
def add_details(file_name, title, artist, album, lyrics=""): ''' Adds the details to song ''' tags = EasyMP3(file_name) tags["title"] = title tags["artist"] = artist tags["album"] = album tags.save() tags = ID3(file_name) uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc'...
Adds the details to song
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L261-L281
[ "def log(text='', newline=False, trailing_newline=False):\n newline_char = ''\n trailing_newline_char = ''\n if newline:\n newline_char = '\\n'\n if trailing_newline:\n trailing_newline_char = '\\n'\n print('%s%s%s' % (newline_char, text, trailing_newline_char))\n", "def log_indented(...
#!/usr/bin/env python ''' Tries to find the metadata of songs based on the file name https://github.com/lakshaykalbhor/MusicRepair ''' try: from . import albumsearch from . import improvename from . import log except: import albumsearch import improvename import log from os import rename, env...
kalbhor/MusicNow
musicnow/repair.py
fix_music
python
def fix_music(file_name): ''' Searches for '.mp3' files in directory (optionally recursive) and checks whether they already contain album art and album name tags or not. ''' setup() if not Py3: file_name = file_name.encode('utf-8') tags = File(file_name) log.log(file_name) ...
Searches for '.mp3' files in directory (optionally recursive) and checks whether they already contain album art and album name tags or not.
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L284-L330
[ "def log(text='', newline=False, trailing_newline=False):\n newline_char = ''\n trailing_newline_char = ''\n if newline:\n newline_char = '\\n'\n if trailing_newline:\n trailing_newline_char = '\\n'\n print('%s%s%s' % (newline_char, text, trailing_newline_char))\n", "def setup():\n ...
#!/usr/bin/env python ''' Tries to find the metadata of songs based on the file name https://github.com/lakshaykalbhor/MusicRepair ''' try: from . import albumsearch from . import improvename from . import log except: import albumsearch import improvename import log from os import rename, env...
kalbhor/MusicNow
musicnow/albumsearch.py
img_search_bing
python
def img_search_bing(album): ''' Bing image search ''' setup() album = album + " Album Art" api_key = "Key" endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search" links_dict = {} headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)} param = {'q': album, 'count': '1'...
Bing image search
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/albumsearch.py#L42-L68
[ "def setup():\n \"\"\"\n Gathers all configs\n \"\"\"\n\n global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR \n\n LOG_FILENAME = 'musicrepair_log.txt'\n LOG_LINE_SEPERATOR = '........................\\n'\n\n CONFIG = configparser.ConfigParser()\n config_path =...
''' Return Album Art url ''' try: from . import log except: import log import requests import json from bs4 import BeautifulSoup import six from os import environ from os.path import realpath, basename if six.PY2: from urllib2 import urlopen, Request from urllib2 import quote elif six.PY3: from ur...
kalbhor/MusicNow
musicnow/albumsearch.py
img_search_google
python
def img_search_google(album): ''' google image search ''' album = album + " Album Art" url = ("https://www.google.com/search?q=" + quote(album.encode('utf-8')) + "&source=lnms&tbm=isch") header = {'User-Agent': '''Mozilla/5.0 (Windows NT 6.1; WOW64) AppleW...
google image search
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/albumsearch.py#L70-L91
null
''' Return Album Art url ''' try: from . import log except: import log import requests import json from bs4 import BeautifulSoup import six from os import environ from os.path import realpath, basename if six.PY2: from urllib2 import urlopen, Request from urllib2 import quote elif six.PY3: from ur...
kalbhor/MusicNow
musicnow/improvename.py
songname
python
def songname(song_name): ''' Improves file name by removing crap words ''' try: song_name = splitext(song_name)[0] except IndexError: pass # Words to omit from song title for better results through spotify's API chars_filter = "()[]{}-:_/=+\"\'" words_filter = ('official...
Improves file name by removing crap words
train
https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/improvename.py#L5-L28
null
import re from os.path import splitext
pavlov99/jsonapi
jsonapi/serializers.py
DatetimeDecimalEncoder.default
python
def default(self, o): if isinstance(o, (datetime.datetime, datetime.date, datetime.time)): return o.isoformat() if isinstance(o, decimal.Decimal): return float(o) return json.JSONEncoder.default(self, o)
Encode JSON. :return str: A JSON encoded string
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/serializers.py#L17-L29
null
class DatetimeDecimalEncoder(json.JSONEncoder): """ Encoder for datetime and decimal serialization. Usage: json.dumps(object, cls=DatetimeDecimalEncoder) NOTE: _iterencode does not work """
pavlov99/jsonapi
jsonapi/serializers.py
Serializer.dump_document
python
def dump_document(cls, instance, fields_own=None, fields_to_many=None): if fields_own is not None: fields_own = {f.name for f in fields_own} else: fields_own = { f.name for f in instance._meta.fields if f.rel is None and f.serialize } ...
Get document for model_instance. redefine dump rule for field x: def dump_document_x :param django.db.models.Model instance: model instance :param list<Field> or None fields: model_instance field to dump :return dict: document Related documents are not included to current one....
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/serializers.py#L66-L148
null
class Serializer(object): """ Serializer class. Serializer has methods dump_document and load_document to convert model into document. Document is dictionary with following format: { "id" // The document SHOULD contain an "id" key. } * The "id" key in a document represent...
pavlov99/jsonapi
jsonapi/utils.py
_cached
python
def _cached(f): attr_name = '_cached_' + f.__name__ def wrapper(obj, *args, **kwargs): if not hasattr(obj, attr_name): setattr(obj, attr_name, f(obj, *args, **kwargs)) return getattr(obj, attr_name) return wrapper
Decorator that makes a method cached.
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/utils.py#L21-L30
null
""" JSON:API utils.""" class _classproperty(property): """ Implement property behaviour for classes. class A(): @_classproperty @classmethod def name(cls): return cls.__name__ """ def __get__(self, obj, type_): return self.fget.__get__(None, type_)() ...
pavlov99/jsonapi
jsonapi/model_inspector.py
ModelInspector._filter_child_model_fields
python
def _filter_child_model_fields(cls, fields): indexes_to_remove = set([]) for index1, field1 in enumerate(fields): for index2, field2 in enumerate(fields): if index1 < index2 and index1 not in indexes_to_remove and\ index2 not in indexes_to_remove: ...
Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. after inspection BMany would have links to B and C. Keep only B. Parent model A could not be used (It would not be in fields) :param list fields: model fields. ...
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/model_inspector.py#L113-L139
null
class ModelInspector(object): """ Inspect Django models.""" def inspect(self): user_model = get_user_model() self.models = { model: ModelInfo( get_model_name(model), fields_own=self._get_fields_own(model), fields_to_one=self._get_fie...
pavlov99/jsonapi
jsonapi/resource.py
get_concrete_model
python
def get_concrete_model(model): if not(inspect.isclass(model) and issubclass(model, models.Model)): model = get_model_by_name(model) return model
Get model defined in Meta. :param str or django.db.models.Model model: :return: model or None :rtype django.db.models.Model or None: :raise ValueError: model is not found or abstract
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L67-L79
[ "def get_model_by_name(model_name):\n \"\"\" Get model by its name.\n\n :param str model_name: name of model.\n :return django.db.models.Model:\n\n Example:\n get_concrete_model_by_name('auth.User')\n django.contrib.auth.models.User\n\n \"\"\"\n if isinstance(model_name, six.string_t...
""" Resource definition. There are two tipes of resources: * simple resources * model resources Simple resources require name Meta property to be defined. Example: class SimpleResource(Resource): class Meta: name = "simple_name" Django model resources require model to be defined Examp...
pavlov99/jsonapi
jsonapi/resource.py
get_resource_name
python
def get_resource_name(meta): if meta.name is None and not meta.is_model: msg = "Either name or model for resource.Meta shoud be provided" raise ValueError(msg) name = meta.name or get_model_name(get_concrete_model(meta.model)) return name
Define resource name based on Meta information. :param Resource.Meta meta: resource meta information :return: name of resource :rtype: str :raises ValueError:
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L82-L96
[ "def get_model_name(model):\n \"\"\" Get model name for the field.\n\n Django 1.5 uses module_name, does not support model_name\n Django 1.6 uses module_name and model_name\n DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning\n\n \"\"\"\n opts = model._meta\n if django.VERS...
""" Resource definition. There are two tipes of resources: * simple resources * model resources Simple resources require name Meta property to be defined. Example: class SimpleResource(Resource): class Meta: name = "simple_name" Django model resources require model to be defined Examp...
pavlov99/jsonapi
jsonapi/resource.py
merge_metas
python
def merge_metas(*metas): metadict = {} for meta in metas: metadict.update(meta.__dict__) metadict = {k: v for k, v in metadict.items() if not k.startswith('__')} return type('Meta', (object, ), metadict)
Merge meta parameters. next meta has priority over current, it will overwrite attributes. :param class or None meta: class with properties. :return class: merged meta.
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/resource.py#L99-L113
null
""" Resource definition. There are two tipes of resources: * simple resources * model resources Simple resources require name Meta property to be defined. Example: class SimpleResource(Resource): class Meta: name = "simple_name" Django model resources require model to be defined Examp...
pavlov99/jsonapi
jsonapi/django_utils.py
get_model_by_name
python
def get_model_by_name(model_name): if isinstance(model_name, six.string_types) and \ len(model_name.split('.')) == 2: app_name, model_name = model_name.split('.') if django.VERSION[:2] < (1, 8): model = models.get_model(app_name, model_name) else: from dj...
Get model by its name. :param str model_name: name of model. :return django.db.models.Model: Example: get_concrete_model_by_name('auth.User') django.contrib.auth.models.User
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L12-L35
null
""" Django specific utils. Utils are used to work with different django versions. """ import django from django.db import models from django.http import QueryDict from . import six def get_model_name(model): """ Get model name for the field. Django 1.5 uses module_name, does not support model_name Dja...
pavlov99/jsonapi
jsonapi/django_utils.py
get_model_name
python
def get_model_name(model): opts = model._meta if django.VERSION[:2] < (1, 7): model_name = opts.module_name else: model_name = opts.model_name return model_name
Get model name for the field. Django 1.5 uses module_name, does not support model_name Django 1.6 uses module_name and model_name DJango 1.7 uses model_name, module_name raises RemovedInDjango18Warning
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L38-L52
null
""" Django specific utils. Utils are used to work with different django versions. """ import django from django.db import models from django.http import QueryDict from . import six def get_model_by_name(model_name): """ Get model by its name. :param str model_name: name of model. :return django.db.mode...
pavlov99/jsonapi
jsonapi/django_utils.py
clear_app_cache
python
def clear_app_cache(app_name): loading_cache = django.db.models.loading.cache if django.VERSION[:2] < (1, 7): loading_cache.app_models[app_name].clear() else: loading_cache.all_models[app_name].clear()
Clear django cache for models. :param str ap_name: name of application to clear model cache
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/django_utils.py#L55-L66
null
""" Django specific utils. Utils are used to work with different django versions. """ import django from django.db import models from django.http import QueryDict from . import six def get_model_by_name(model_name): """ Get model by its name. :param str model_name: name of model. :return django.db.mode...
pavlov99/jsonapi
jsonapi/api.py
API.register
python
def register(self, resource=None, **kwargs): if resource is None: def wrapper(resource): return self.register(resource, **kwargs) return wrapper for key, value in kwargs.items(): setattr(resource.Meta, key, value) if resource.Meta.name in sel...
Register resource for currnet API. :param resource: Resource to be registered :type resource: jsonapi.resource.Resource or None :return: resource :rtype: jsonapi.resource.Resource .. versionadded:: 0.4.1 :param kwargs: Extra meta parameters
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L69-L109
null
class API(object): """ API handler.""" CONTENT_TYPE = "application/vnd.api+json" def __init__(self): self._resources = [] self.base_url = None # base server url self.api_url = None # api root url @property def resource_map(self): """ Resource map of api. ...
pavlov99/jsonapi
jsonapi/api.py
API.urls
python
def urls(self): from django.conf.urls import url urls = [ url(r'^$', self.documentation), url(r'^map$', self.map_view), ] for resource_name in self.resource_map: urls.extend([ url(r'(?P<resource_name>{})$'.format( r...
Get all of the api endpoints. NOTE: only for django as of now. NOTE: urlpatterns are deprecated since Django1.8 :return list: urls
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L112-L135
null
class API(object): """ API handler.""" CONTENT_TYPE = "application/vnd.api+json" def __init__(self): self._resources = [] self.base_url = None # base server url self.api_url = None # api root url @property def resource_map(self): """ Resource map of api. ...
pavlov99/jsonapi
jsonapi/api.py
API.update_urls
python
def update_urls(self, request, resource_name=None, ids=None): http_host = request.META.get('HTTP_HOST', None) if http_host is None: http_host = request.META['SERVER_NAME'] if request.META['SERVER_PORT'] not in ('80', '443'): http_host = "{}:{}".format( ...
Update url configuration. :param request: :param resource_name: :type resource_name: str or None :param ids: :rtype: None
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L137-L166
null
class API(object): """ API handler.""" CONTENT_TYPE = "application/vnd.api+json" def __init__(self): self._resources = [] self.base_url = None # base server url self.api_url = None # api root url @property def resource_map(self): """ Resource map of api. ...
pavlov99/jsonapi
jsonapi/api.py
API.map_view
python
def map_view(self, request): self.update_urls(request) resource_info = { "resources": [{ "id": index + 1, "href": "{}/{}".format(self.api_url, resource_name), } for index, (resource_name, resource) in enumerate( sorted(self.resource...
Show information about available resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L168-L189
[ "def update_urls(self, request, resource_name=None, ids=None):\n \"\"\" Update url configuration.\n\n :param request:\n :param resource_name:\n :type resource_name: str or None\n :param ids:\n :rtype: None\n\n \"\"\"\n http_host = request.META.get('HTTP_HOST', None)\n\n if http_host is No...
class API(object): """ API handler.""" CONTENT_TYPE = "application/vnd.api+json" def __init__(self): self._resources = [] self.base_url = None # base server url self.api_url = None # api root url @property def resource_map(self): """ Resource map of api. ...
pavlov99/jsonapi
jsonapi/api.py
API.documentation
python
def documentation(self, request): self.update_urls(request) context = { "resources": sorted(self.resource_map.items()) } return render(request, "jsonapi/index.html", context)
Resource documentation. .. versionadded:: 0.7.2 Content-Type check :return django.http.HttpResponse
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L191-L204
[ "def update_urls(self, request, resource_name=None, ids=None):\n \"\"\" Update url configuration.\n\n :param request:\n :param resource_name:\n :type resource_name: str or None\n :param ids:\n :rtype: None\n\n \"\"\"\n http_host = request.META.get('HTTP_HOST', None)\n\n if http_host is No...
class API(object): """ API handler.""" CONTENT_TYPE = "application/vnd.api+json" def __init__(self): self._resources = [] self.base_url = None # base server url self.api_url = None # api root url @property def resource_map(self): """ Resource map of api. ...
pavlov99/jsonapi
jsonapi/api.py
API.handler_view
python
def handler_view(self, request, resource_name, ids=None): signal_request.send(sender=self, request=request) time_start = time.time() self.update_urls(request, resource_name=resource_name, ids=ids) resource = self.resource_map[resource_name] allowed_http_methods = resource.Meta.a...
Handler for resources. .. versionadded:: 0.5.7 Content-Type check :return django.http.HttpResponse
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/api.py#L258-L312
[ "def update_urls(self, request, resource_name=None, ids=None):\n \"\"\" Update url configuration.\n\n :param request:\n :param resource_name:\n :type resource_name: str or None\n :param ids:\n :rtype: None\n\n \"\"\"\n http_host = request.META.get('HTTP_HOST', None)\n\n if http_host is No...
class API(object): """ API handler.""" CONTENT_TYPE = "application/vnd.api+json" def __init__(self): self._resources = [] self.base_url = None # base server url self.api_url = None # api root url @property def resource_map(self): """ Resource map of api. ...
pavlov99/jsonapi
jsonapi/request_parser.py
RequestParser.parse
python
def parse(cls, querydict): for key in querydict.keys(): if not any((key in JSONAPIQueryDict._fields, cls.RE_FIELDS.match(key))): msg = "Query parameter {} is not known".format(key) raise ValueError(msg) result = JSONAPIQueryDict( ...
Parse querydict data. There are expected agruments: distinct, fields, filter, include, page, sort Parameters ---------- querydict : django.http.request.QueryDict MultiValueDict with query arguments. Returns ------- result : dict ...
train
https://github.com/pavlov99/jsonapi/blob/c27943f22f1f1d30d651fe267a99d2b38f69d604/jsonapi/request_parser.py#L23-L61
[ "def prepare_values(cls, values):\n return [x for value in values for x in value.split(\",\")]\n", "def parse_fields(cls, querydict):\n fields = cls.prepare_values(querydict.getlist('fields'))\n fields_typed = []\n\n for key in querydict.keys():\n fields_match = cls.RE_FIELDS.match(key)\n\n ...
class RequestParser(object): """ Rarser for Django request.GET parameters.""" RE_FIELDS = re.compile('^fields\[(?P<resource>\w+)\]$') @classmethod @classmethod def prepare_values(cls, values): return [x for value in values for x in value.split(",")] @classmethod def parse_field...
faide/py3o.template
py3o/template/main.py
detect_keep_boundary
python
def detect_keep_boundary(start, end, namespaces): result_start, result_end = False, False parent_start = start.getparent() parent_end = end.getparent() if parent_start.tag == "{%s}p" % namespaces['text']: # more than one child in the containing paragraph ? # we keep the boundary ...
a helper to inspect a link and see if we should keep the link boundary
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L49-L66
null
# -*- encoding: utf-8 -*- import decimal import logging import os import lxml.etree import zipfile from copy import copy from io import BytesIO from uuid import uuid4 from six.moves import urllib from genshi.template import MarkupTemplate from genshi.filters.transform import Transformer from pyjon.utils import get...
faide/py3o.template
py3o/template/main.py
move_siblings
python
def move_siblings( start, end, new_, keep_start_boundary=False, keep_end_boundary=False ): old_ = start.getparent() if keep_start_boundary: new_.append(copy(start)) else: if start.tail: # copy the existing tail as text new_.text = start.tail ...
a helper function that will replace a start/end node pair by a new containing element, effectively moving all in-between siblings This is particularly helpful to replace for /for loops in tables with the content resulting from the iteration This function call returns None. The parent xml tree is modifi...
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L69-L125
null
# -*- encoding: utf-8 -*- import decimal import logging import os import lxml.etree import zipfile from copy import copy from io import BytesIO from uuid import uuid4 from six.moves import urllib from genshi.template import MarkupTemplate from genshi.filters.transform import Transformer from pyjon.utils import get...
faide/py3o.template
py3o/template/main.py
get_list_transformer
python
def get_list_transformer(namespaces): return Transformer( '//list[namespace-uri()="%s"]' % namespaces.get( 'text' ) ).attr( '{0}id'.format(XML_NS), lambda *args: "list{0}".format(uuid4().hex) )
this function returns a transformer to find all list elements and recompute their xml:id. Because if we duplicate lists we create invalid XML. Each list must have its own xml:id This is important if you want to be able to reopen the produced document wih an XML parser. LibreOffice will fix those ...
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L128-L145
null
# -*- encoding: utf-8 -*- import decimal import logging import os import lxml.etree import zipfile from copy import copy from io import BytesIO from uuid import uuid4 from six.moves import urllib from genshi.template import MarkupTemplate from genshi.filters.transform import Transformer from pyjon.utils import get...
faide/py3o.template
py3o/template/main.py
Template.__prepare_namespaces
python
def __prepare_namespaces(self): # create needed namespaces self.namespaces = dict( text="urn:text", draw="urn:draw", table="urn:table", office="urn:office", xlink="urn:xlink", svg="urn:svg", manifest="urn:manifest", ...
create proper namespaces for our document
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L208-L232
null
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.get_user_instructions
python
def get_user_instructions(self): res = [] # TODO: Check if instructions can be stored in other content_trees for e in get_instructions(self.content_trees[0], self.namespaces): childs = e.getchildren() if childs: res.extend([c.text for c in childs]) ...
Public method to help report engine to find all instructions
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L234-L245
[ "def get_instructions(content_tree, namespaces):\n # find all links that have a py3o\n xpath_expr = \"//text:a[starts-with(@xlink:href, 'py3o://')]\"\n return content_tree.xpath(\n xpath_expr,\n namespaces=namespaces\n )\n" ]
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.get_user_instructions_mapping
python
def get_user_instructions_mapping(self): instructions = self.get_user_instructions() user_variables = self.get_user_variables() # For now we just want for loops instructions = [i for i in instructions if i.startswith('for') or i == '/for'] # Now we call ...
Public method to get the mapping of all variables defined in the template
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L252-L299
[ "def add_child(self, child):\n child.parent = self\n self.childs.append(child)\n", "def add_attr(self, attr):\n self.attrs.append(attr)\n", "def decode_py3o_instruction(self, instruction):\n # We convert py3o for loops into valid python for loop\n inst_str = \"for \" + instruction.split('\"')[1] ...
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.handle_link
python
def handle_link(self, link, py3o_base, closing_link): # OLD open office version if link.text is not None and link.text.strip(): if not link.text == py3o_base: msg = "url and text do not match in '%s'" % link.text raise TemplateException(msg) # new ope...
transform a py3o link into a proper Genshi statement rebase a py3o link at a proper place in the tree to be ready for Genshi replacement
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L329-L412
[ "def detect_keep_boundary(start, end, namespaces):\n \"\"\"a helper to inspect a link and see if we should keep the link boundary\n \"\"\"\n result_start, result_end = False, False\n parent_start = start.getparent()\n parent_end = end.getparent()\n\n if parent_start.tag == \"{%s}p\" % namespaces['...
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.get_user_variables
python
def get_user_variables(self): """a public method to help report engines to introspect a template and find what data it needs and how it will be used returns a list of user variable names without starting 'py3o.'""" # TODO: Check if some user fields are stored in other content_tre...
a public method to help report engines to introspect a template and find what data it needs and how it will be used returns a list of user variable names without starting 'py3o.
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L414-L423
[ "def get_user_fields(content_tree, namespaces):\n field_expr = \"//text:user-field-decl[starts-with(@text:name, 'py3o.')]\"\n return content_tree.xpath(\n field_expr,\n namespaces=namespaces\n )\n" ]
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.__prepare_usertexts
python
def __prepare_usertexts(self): field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]" for content_tree in self.content_trees: for userfield in content_tree.xpath( field_expr, namespaces=self.namespaces ): parent =...
Replace user-type text fields that start with "py3o." with genshi instructions.
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L452-L532
null
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.__replace_image_links
python
def __replace_image_links(self): image_expr = "//draw:frame[starts-with(@draw:name, 'py3o.')]" for content_tree in self.content_trees: # Find draw:frame tags. for draw_frame in content_tree.xpath( image_expr, namespaces=self.namespaces ...
Replace links of placeholder images (the name of which starts with "py3o.") to point to a file saved the "Pictures" directory of the archive.
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L534-L569
null
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.__add_images_to_manifest
python
def __add_images_to_manifest(self): xpath_expr = "//manifest:manifest[1]" for content_tree in self.content_trees: # Find manifest:manifest tags. manifest_e = content_tree.xpath( xpath_expr, namespaces=self.namespaces ) if...
Add entries for py3o images into the manifest file.
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L571-L597
null
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.render_tree
python
def render_tree(self, data): # TODO: find a way to make this localization aware... # because ATM it formats texts using French style numbers... # best way would be to let the user inject its own vars... # but this would not work on fusion servers... # so we must find a way to loc...
prepare the flows without saving to file this method has been decoupled from render_flow to allow better unit testing
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L599-L680
[ "def remove_soft_breaks(self):\n for soft_break in get_soft_breaks(\n self.content_trees[0], self.namespaces):\n soft_break.getparent().remove(soft_break)\n", "def handle_instructions(content_trees, namespaces):\n\n opened_starts = list()\n starting_tags = list()\n closing_tags = dic...
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.render_flow
python
def render_flow(self, data): self.render_tree(data) # then reconstruct a new ODT document with the generated content for status in self.__save_output(): yield status
render the OpenDocument with the user data @param data: the input stream of user data. This should be a dictionary mapping, keys being the values accessible to your report. @type data: dictionary
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L682-L694
[ "def render_tree(self, data):\n \"\"\"prepare the flows without saving to file\n this method has been decoupled from render_flow to allow better\n unit testing\n \"\"\"\n # TODO: find a way to make this localization aware...\n # because ATM it formats texts using French style numbers...\n # bes...
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.set_image_path
python
def set_image_path(self, identifier, path): f = open(path, 'rb') self.set_image_data(identifier, f.read()) f.close()
Set data for an image mentioned in the template. @param identifier: Identifier of the image; refer to the image in the template by setting "py3o.[identifier]" as the name of that image. @type identifier: string @param path: Image path on the file system @type path: string
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L707-L720
[ "def set_image_data(self, identifier, data):\n \"\"\"Set data for an image mentioned in the template.\n\n @param identifier: Identifier of the image; refer to the image in the\n template by setting \"py3o.[identifier]\" as the name of that image.\n @type identifier: string\n\n @param data: Contents o...
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/main.py
Template.__save_output
python
def __save_output(self): out = zipfile.ZipFile(self.outputfilename, 'w') for info_zip in self.infile.infolist(): if info_zip.filename in self.templated_files: # Template file - we have edited these. # get a temp file streamout = open(get_sec...
Saves the output into a native OOo document format.
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L735-L779
[ "def get_list_transformer(namespaces):\n \"\"\"this function returns a transformer to\n find all list elements and recompute their xml:id.\n Because if we duplicate lists we create invalid XML.\n Each list must have its own xml:id\n\n This is important if you want to be able to reopen the produced\n...
class Template(object): templated_files = ['content.xml', 'styles.xml', 'META-INF/manifest.xml'] def __init__(self, template, outfile, ignore_undefined_variables=False): """A template object exposes the API to render it to an OpenOffice document. @param template: a py3o template file. ...
faide/py3o.template
py3o/template/decoder.py
ForList.__recur_to_dict
python
def __recur_to_dict(forlist, data_dict, res): # First we go through all attrs from the ForList and add respective # keys on the dict. for a in forlist.attrs: a_list = a.split('.') if len(a_list) == 1: res = data_dict[a_list[0]] return res ...
Recursive function that fills up the dictionary
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/decoder.py#L52-L92
[ "def __recur_to_dict(forlist, data_dict, res):\n \"\"\"Recursive function that fills up the dictionary\n \"\"\"\n # First we go through all attrs from the ForList and add respective\n # keys on the dict.\n for a in forlist.attrs:\n a_list = a.split('.')\n if len(a_list) == 1:\n ...
class ForList(object): def __init__(self, name, var_from): self.name = str(name) self.childs = [] self.attrs = [] self._parent = None self.var_from = var_from def __eq__(self, other): return self.name == other.name def add_child(self, child): child.p...
faide/py3o.template
py3o/template/decoder.py
ForList.to_dict
python
def to_dict(for_lists, global_vars, data_dict): res = {} # The first level is a little bit special # Manage global variables for a in global_vars: a_list = a.split('.') tmp = res for i in a_list[:-1]: if not i in tmp: ...
Construct a dict object from a list of ForList object :param for_lists: list of for_list :param global_vars: list of global vars to add :param data_dict: data from an orm-like object (with dot notation) :return: a dict representation of the ForList objects
train
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/decoder.py#L95-L142
[ "def __recur_to_dict(forlist, data_dict, res):\n \"\"\"Recursive function that fills up the dictionary\n \"\"\"\n # First we go through all attrs from the ForList and add respective\n # keys on the dict.\n for a in forlist.attrs:\n a_list = a.split('.')\n if len(a_list) == 1:\n ...
class ForList(object): def __init__(self, name, var_from): self.name = str(name) self.childs = [] self.attrs = [] self._parent = None self.var_from = var_from def __eq__(self, other): return self.name == other.name def add_child(self, child): child.p...
borntyping/python-riemann-client
riemann_client/transport.py
socket_recvall
python
def socket_recvall(socket, length, bufsize=4096): data = b"" while len(data) < length: data += socket.recv(bufsize) return data
A helper method to read of bytes from a socket to a maximum length
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L21-L26
[ "def recv(self, bufsize):\n return self.data.pop(0)\n" ]
"""Transports are used for direct communication with the Riemann server. They are usually used inside a :py:class:`.Client`, and are used to send and receive protocol buffer objects.""" from __future__ import absolute_import import abc import socket import ssl import struct import riemann_client.riemann_pb2 # Defa...
borntyping/python-riemann-client
riemann_client/transport.py
UDPTransport.send
python
def send(self, message): self.socket.sendto(message.SerializeToString(), self.address) return None
Sends a message, but does not return a response :returns: None - can't receive a response over UDP
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L102-L108
null
class UDPTransport(SocketTransport): def connect(self): """Creates a UDP socket""" self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def disconnect(self): """Closes the socket""" self.socket.close()
borntyping/python-riemann-client
riemann_client/transport.py
TCPTransport.connect
python
def connect(self): self.socket = socket.create_connection(self.address, self.timeout)
Connects to the given host
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L122-L124
null
class TCPTransport(SocketTransport): def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT): """Communicates with Riemann over TCP :param str host: The hostname to connect to :param int port: The port to connect to :param int timeout: The time in seconds to wait before raising an...
borntyping/python-riemann-client
riemann_client/transport.py
TCPTransport.send
python
def send(self, message): message = message.SerializeToString() self.socket.sendall(struct.pack('!I', len(message)) + message) length = struct.unpack('!I', self.socket.recv(4))[0] response = riemann_client.riemann_pb2.Msg() response.ParseFromString(socket_recvall(self.socket, len...
Sends a message to a Riemann server and returns it's response :param message: The message to send to the Riemann server :returns: The response message from Riemann :raises RiemannError: if the server returns an error
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L130-L147
[ "def socket_recvall(socket, length, bufsize=4096):\n \"\"\"A helper method to read of bytes from a socket to a maximum length\"\"\"\n data = b\"\"\n while len(data) < length:\n data += socket.recv(bufsize)\n return data\n" ]
class TCPTransport(SocketTransport): def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT): """Communicates with Riemann over TCP :param str host: The hostname to connect to :param int port: The port to connect to :param int timeout: The time in seconds to wait before raising an...
borntyping/python-riemann-client
riemann_client/transport.py
TLSTransport.connect
python
def connect(self): super(TLSTransport, self).connect() self.socket = ssl.wrap_socket( self.socket, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_REQUIRED, ca_certs=self.ca_certs)
Connects using :py:meth:`TLSTransport.connect` and wraps with TLS
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L161-L168
[ "def connect(self):\n \"\"\"Connects to the given host\"\"\"\n self.socket = socket.create_connection(self.address, self.timeout)\n" ]
class TLSTransport(TCPTransport): def __init__(self, host=HOST, port=PORT, timeout=TIMEOUT, ca_certs=None): """Communicates with Riemann over TCP + TLS Options are the same as :py:class:`.TCPTransport` unless noted :param str ca_certs: Path to a CA Cert bundle used to create the socket ...
borntyping/python-riemann-client
riemann_client/transport.py
BlankTransport.send
python
def send(self, message): for event in message.events: self.events.append(event) reply = riemann_client.riemann_pb2.Msg() reply.ok = True return reply
Adds a message to the list, returning a fake 'ok' response :returns: A response message with ``ok = True``
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/transport.py#L186-L195
null
class BlankTransport(Transport): """A transport that collects events in a list, and has no connection Used by ``--transport none``, which is useful for testing commands without contacting a Riemann server. This is also used by the automated tests in ``riemann_client/tests/test_riemann_command.py``. ...
borntyping/python-riemann-client
riemann_client/client.py
Client.create_event
python
def create_event(data): event = riemann_client.riemann_pb2.Event() event.host = socket.gethostname() event.tags.extend(data.pop('tags', [])) for key, value in data.pop('attributes', {}).items(): attribute = event.attributes.add() attribute.key, attribute.value = ...
Translates a dictionary of event attributes to an Event object :param dict data: The attributes to be set on the event :returns: A protocol buffer ``Event`` object
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L78-L95
null
class Client(object): """A client for sending events and querying a Riemann server. Two sets of methods are provided - an API dealing directly with protocol buffer objects and an extended API that takes and returns dictionaries representing events. Protocol buffer API: - :py:meth:`.send_e...
borntyping/python-riemann-client
riemann_client/client.py
Client.send_events
python
def send_events(self, events): message = riemann_client.riemann_pb2.Msg() for event in events: message.events.add().MergeFrom(event) return self.transport.send(message)
Sends multiple events to Riemann in a single message :param events: A list or iterable of ``Event`` objects :returns: The response message from Riemann
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L97-L106
null
class Client(object): """A client for sending events and querying a Riemann server. Two sets of methods are provided - an API dealing directly with protocol buffer objects and an extended API that takes and returns dictionaries representing events. Protocol buffer API: - :py:meth:`.send_e...
borntyping/python-riemann-client
riemann_client/client.py
Client.events
python
def events(self, *events): return self.send_events(self.create_event(e) for e in events)
Sends multiple events in a single message >>> client.events({'service': 'riemann-client', 'state': 'awesome'}) :param \*events: event dictionaries for :py:func:`create_event` :returns: The response message from Riemann
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L116-L124
[ "def send_events(self, events):\n \"\"\"Sends multiple events to Riemann in a single message\n\n :param events: A list or iterable of ``Event`` objects\n :returns: The response message from Riemann\n \"\"\"\n message = riemann_client.riemann_pb2.Msg()\n for event in events:\n message.events...
class Client(object): """A client for sending events and querying a Riemann server. Two sets of methods are provided - an API dealing directly with protocol buffer objects and an extended API that takes and returns dictionaries representing events. Protocol buffer API: - :py:meth:`.send_e...
borntyping/python-riemann-client
riemann_client/client.py
Client.create_dict
python
def create_dict(event): data = dict() for descriptor, value in event.ListFields(): if descriptor.name == 'tags': value = list(value) elif descriptor.name == 'attributes': value = dict(((a.key, a.value) for a in value)) data[descriptor...
Translates an Event object to a dictionary of event attributes All attributes are included, so ``create_dict(create_event(input))`` may return more attributes than were present in the input. :param event: A protocol buffer ``Event`` object :returns: A dictionary of event attributes
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L137-L156
null
class Client(object): """A client for sending events and querying a Riemann server. Two sets of methods are provided - an API dealing directly with protocol buffer objects and an extended API that takes and returns dictionaries representing events. Protocol buffer API: - :py:meth:`.send_e...
borntyping/python-riemann-client
riemann_client/client.py
Client.send_query
python
def send_query(self, query): message = riemann_client.riemann_pb2.Msg() message.query.string = query return self.transport.send(message)
Sends a query to the Riemann server :returns: The response message from Riemann
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L158-L165
null
class Client(object): """A client for sending events and querying a Riemann server. Two sets of methods are provided - an API dealing directly with protocol buffer objects and an extended API that takes and returns dictionaries representing events. Protocol buffer API: - :py:meth:`.send_e...
borntyping/python-riemann-client
riemann_client/client.py
Client.query
python
def query(self, query): if isinstance(self.transport, riemann_client.transport.UDPTransport): raise Exception('Cannot query the Riemann server over UDP') response = self.send_query(query) return [self.create_dict(e) for e in response.events]
Sends a query to the Riemann server >>> client.query('true') :returns: A list of event dictionaries taken from the response :raises Exception: if used with a :py:class:`.UDPTransport`
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L167-L178
[ "def send_query(self, query):\n \"\"\"Sends a query to the Riemann server\n\n :returns: The response message from Riemann\n \"\"\"\n message = riemann_client.riemann_pb2.Msg()\n message.query.string = query\n return self.transport.send(message)\n" ]
class Client(object): """A client for sending events and querying a Riemann server. Two sets of methods are provided - an API dealing directly with protocol buffer objects and an extended API that takes and returns dictionaries representing events. Protocol buffer API: - :py:meth:`.send_e...
borntyping/python-riemann-client
riemann_client/client.py
QueuedClient.send_events
python
def send_events(self, events): for event in events: self.queue.events.add().MergeFrom(event) return None
Adds multiple events to the queued message :returns: None - nothing has been sent to the Riemann server yet
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/client.py#L210-L217
null
class QueuedClient(Client): """A Riemann client using a queue that can be used to batch send events. A message object is used as a queue, with the :py:meth:`.send_event` and :py:meth:`.send_events` methods adding new events to the message and the :py:meth:`.flush` sending the message. """ def ...
borntyping/python-riemann-client
riemann_client/command.py
echo_event
python
def echo_event(data): return click.echo(json.dumps(data, sort_keys=True, indent=2))
Echo a json dump of an object using click
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L38-L40
null
"""Riemann command line client""" from __future__ import absolute_import, print_function import json import sys import click import riemann_client import riemann_client.client import riemann_client.transport __all__ = ['main'] class CommandLineClient(riemann_client.client.Client): """Prints to STDERR when an...
borntyping/python-riemann-client
riemann_client/command.py
main
python
def main(ctx, host, port, transport_type, timeout, ca_certs): if transport_type == 'udp': if timeout is not None: ctx.fail('--timeout cannot be used with the UDP transport') transport = riemann_client.transport.UDPTransport(host, port) elif transport_type == 'tcp': transport ...
Connects to a Riemann server to send events or query the index By default, will attempt to contact Riemann on localhost:5555 over TCP. The RIEMANN_HOST and RIEMANN_PORT environment variables can be used to configure the host and port used. Command line parameters will override the environment variables...
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L57-L81
null
"""Riemann command line client""" from __future__ import absolute_import, print_function import json import sys import click import riemann_client import riemann_client.client import riemann_client.transport __all__ = ['main'] class CommandLineClient(riemann_client.client.Client): """Prints to STDERR when an...
borntyping/python-riemann-client
riemann_client/command.py
send
python
def send(transport, time, state, host, description, service, tag, attribute, ttl, metric_f, echo): client = CommandLineClient(transport) event = client.create_event({ 'time': time, 'state': state, 'host': host, 'description': description, 'service': service, ...
Send a single event to Riemann
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L106-L125
[ "def echo_event(data):\n \"\"\"Echo a json dump of an object using click\"\"\"\n return click.echo(json.dumps(data, sort_keys=True, indent=2))\n", "def create_event(data):\n \"\"\"Translates a dictionary of event attributes to an Event object\n\n :param dict data: The attributes to be set on the event...
"""Riemann command line client""" from __future__ import absolute_import, print_function import json import sys import click import riemann_client import riemann_client.client import riemann_client.transport __all__ = ['main'] class CommandLineClient(riemann_client.client.Client): """Prints to STDERR when an...
borntyping/python-riemann-client
riemann_client/command.py
query
python
def query(transport, query): with CommandLineClient(transport) as client: echo_event(client.query(query))
Query the Riemann server
train
https://github.com/borntyping/python-riemann-client/blob/3e181d90bdf685afd21c1ec5ee20e6840b011ea5/riemann_client/command.py#L131-L134
[ "def echo_event(data):\n \"\"\"Echo a json dump of an object using click\"\"\"\n return click.echo(json.dumps(data, sort_keys=True, indent=2))\n" ]
"""Riemann command line client""" from __future__ import absolute_import, print_function import json import sys import click import riemann_client import riemann_client.client import riemann_client.transport __all__ = ['main'] class CommandLineClient(riemann_client.client.Client): """Prints to STDERR when an...
mishbahr/django-connected
connected_accounts/admin.py
AccountAdmin.get_urls
python
def get_urls(self): urls = super(AccountAdmin, self).get_urls() from django.conf.urls import url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = se...
Add the export view to urls.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/admin.py#L71-L92
[ "def wrap(view):\n def wrapper(*args, **kwargs):\n return self.admin_site.admin_view(view)(*args, **kwargs)\n return update_wrapper(wrapper, view)\n" ]
class AccountAdmin(admin.ModelAdmin): actions = None change_form_template = 'admin/connected_accounts/account/change_form.html' readonly_fields = ('avatar', 'uid', 'provider', 'profile_url', 'oauth_token', 'oauth_token_secret', 'user', 'expires_at', 'date_added'...
mishbahr/django-connected
connected_accounts/providers/base.py
BaseOAuthProvider.get_profile_data
python
def get_profile_data(self, raw_token): try: response = self.request('get', self.profile_url, token=raw_token) response.raise_for_status() except RequestException as e: logger.error('Unable to fetch user profile: {0}'.format(e)) return None else: ...
Fetch user profile information.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L73-L82
[ "def request(self, method, url, **kwargs):\n \"\"\"Build remote url request.\"\"\"\n return request(method, url, **kwargs)\n" ]
class BaseOAuthProvider(object): id = '' name = '' account_class = ProviderAccount authorization_url = '' access_token_url = '' profile_url = '' consumer_key = '' consumer_secret = '' scope = [] scope_separator = ' ' def __init__(self, token=''): self.token = toke...
mishbahr/django-connected
connected_accounts/providers/base.py
BaseOAuthProvider.get_redirect_url
python
def get_redirect_url(self, request, callback, parameters=None): args = self.get_redirect_args(request, callback=callback) additional = parameters or {} args.update(additional) params = urlencode(args) return '{0}?{1}'.format(self.authorization_url, params)
Build authentication redirect url.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L88-L94
[ "def get_redirect_args(self, request, callback):\n \"\"\"Get request parameters for redirect url.\"\"\"\n raise NotImplementedError('Defined in a sub-class') # pragma: no cover\n" ]
class BaseOAuthProvider(object): id = '' name = '' account_class = ProviderAccount authorization_url = '' access_token_url = '' profile_url = '' consumer_key = '' consumer_secret = '' scope = [] scope_separator = ' ' def __init__(self, token=''): self.token = toke...
mishbahr/django-connected
connected_accounts/providers/base.py
OAuthProvider.get_request_token
python
def get_request_token(self, request, callback): callback = force_text(request.build_absolute_uri(callback)) try: response = self.request('post', self.request_token_url, oauth_callback=callback) response.raise_for_status() except RequestException as e: logger.e...
Fetch the OAuth request token. Only required for OAuth 1.0.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L152-L162
[ "def request(self, method, url, **kwargs):\n \"\"\"Build remote url request. Constructs necessary auth.\"\"\"\n user_token = kwargs.pop('token', self.token)\n token, secret, _ = self.parse_raw_token(user_token)\n callback = kwargs.pop('oauth_callback', None)\n verifier = kwargs.get('data', {}).pop('o...
class OAuthProvider(BaseOAuthProvider): request_token_url = '' def get_access_token(self, request, callback=None): """Fetch access token from callback request.""" raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_to...
mishbahr/django-connected
connected_accounts/providers/base.py
OAuthProvider.get_redirect_args
python
def get_redirect_args(self, request, callback): callback = force_text(request.build_absolute_uri(callback)) raw_token = self.get_request_token(request, callback) token, secret, _ = self.parse_raw_token(raw_token) if token is not None and secret is not None: request.session[se...
Get request parameters for redirect url.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L164-L180
[ "def get_scope(self, request):\n dynamic_scope = request.GET.get('scope', None)\n if dynamic_scope:\n self.scope.extend(dynamic_scope.split(','))\n return self.scope\n", "def get_request_token(self, request, callback):\n \"\"\"Fetch the OAuth request token. Only required for OAuth 1.0.\"\"\"\n ...
class OAuthProvider(BaseOAuthProvider): request_token_url = '' def get_access_token(self, request, callback=None): """Fetch access token from callback request.""" raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_to...
mishbahr/django-connected
connected_accounts/providers/base.py
OAuthProvider.parse_raw_token
python
def parse_raw_token(self, raw_token): if raw_token is None: return (None, None, None) qs = parse_qs(raw_token) token = qs.get('oauth_token', [None])[0] token_secret = qs.get('oauth_token_secret', [None])[0] return (token, token_secret, None)
Parse token and secret from raw token response.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L182-L189
null
class OAuthProvider(BaseOAuthProvider): request_token_url = '' def get_access_token(self, request, callback=None): """Fetch access token from callback request.""" raw_token = request.session.get(self.session_key, None) verifier = request.GET.get('oauth_verifier', None) if raw_to...
mishbahr/django-connected
connected_accounts/providers/base.py
OAuth2Provider.get_access_token
python
def get_access_token(self, request, callback=None): callback = request.build_absolute_uri(callback or request.path) if not self.check_application_state(request): logger.error('Application state check failed.') return None if 'code' in request.GET: args = { ...
Fetch access token from callback request.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L232-L256
[ "def check_application_state(self, request):\n \"\"\"Check optional state parameter.\"\"\"\n stored = request.session.get(self.session_key, None)\n returned = request.GET.get('state', None)\n check = False\n if stored is not None:\n if returned is not None:\n check = constant_time_c...
class OAuth2Provider(BaseOAuthProvider): supports_state = True expires_in_key = 'expires_in' auth_params = {} def check_application_state(self, request): """Check optional state parameter.""" stored = request.session.get(self.session_key, None) returned = request.GET.get('state'...
mishbahr/django-connected
connected_accounts/providers/base.py
OAuth2Provider.get_redirect_args
python
def get_redirect_args(self, request, callback): callback = request.build_absolute_uri(callback) args = { 'client_id': self.consumer_key, 'redirect_uri': callback, 'response_type': 'code', } scope = self.get_scope(request) if scope: ...
Get request parameters for redirect url.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L285-L307
[ "def get_scope(self, request):\n dynamic_scope = request.GET.get('scope', None)\n if dynamic_scope:\n self.scope.extend(dynamic_scope.split(','))\n return self.scope\n", "def get_application_state(self, request, callback):\n \"\"\"Generate state optional parameter.\"\"\"\n return get_random_...
class OAuth2Provider(BaseOAuthProvider): supports_state = True expires_in_key = 'expires_in' auth_params = {} def check_application_state(self, request): """Check optional state parameter.""" stored = request.session.get(self.session_key, None) returned = request.GET.get('state'...
mishbahr/django-connected
connected_accounts/providers/base.py
OAuth2Provider.parse_raw_token
python
def parse_raw_token(self, raw_token): if raw_token is None: return (None, None, None) # Load as json first then parse as query string try: token_data = json.loads(raw_token) except ValueError: qs = parse_qs(raw_token) token = qs.get('access...
Parse token and secret from raw token response.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L309-L329
null
class OAuth2Provider(BaseOAuthProvider): supports_state = True expires_in_key = 'expires_in' auth_params = {} def check_application_state(self, request): """Check optional state parameter.""" stored = request.session.get(self.session_key, None) returned = request.GET.get('state'...
mishbahr/django-connected
connected_accounts/providers/base.py
OAuth2Provider.request
python
def request(self, method, url, **kwargs): user_token = kwargs.pop('token', self.token) token, secret, expires_at = self.parse_raw_token(user_token) if token is not None: params = kwargs.get('params', {}) params['access_token'] = token kwargs['params'] = params...
Build remote url request. Constructs necessary auth.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/base.py#L331-L339
[ "def request(self, method, url, **kwargs):\n \"\"\"Build remote url request.\"\"\"\n return request(method, url, **kwargs)\n", "def parse_raw_token(self, raw_token):\n \"\"\"Parse token and secret from raw token response.\"\"\"\n if raw_token is None:\n return (None, None, None)\n # Load as ...
class OAuth2Provider(BaseOAuthProvider): supports_state = True expires_in_key = 'expires_in' auth_params = {} def check_application_state(self, request): """Check optional state parameter.""" stored = request.session.get(self.session_key, None) returned = request.GET.get('state'...
mishbahr/django-connected
connected_accounts/providers/mailchimp.py
MailChimpProvider.get_profile_data
python
def get_profile_data(self, raw_token): token_data = json.loads(raw_token) # This header is the 'magic' that makes this empty GET request work. headers = {'Authorization': 'OAuth %s' % token_data['access_token']} try: response = self.request('get', self.profile_url, headers=h...
Fetch user profile information.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/providers/mailchimp.py#L49-L62
[ "def request(self, method, url, **kwargs):\n \"\"\"Build remote url request. Constructs necessary auth.\"\"\"\n user_token = kwargs.pop('token', self.token)\n token, secret, expires_at = self.parse_raw_token(user_token)\n if token is not None:\n params = kwargs.get('params', {})\n params['...
class MailChimpProvider(OAuth2Provider): id = 'mailchimp' name = _('MailChimp') account_class = MailChimpAccount expires_in_key = '' authorization_url = 'https://login.mailchimp.com/oauth2/authorize' access_token_url = 'https://login.mailchimp.com/oauth2/token' profile_url = 'https://login....
mishbahr/django-connected
connected_accounts/views.py
OAuthProvidertMixin.get_provider
python
def get_provider(self, provider): if self.provider is not None: return self.provider return providers.by_id(provider)
Get instance of the OAuth client for this provider.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L25-L29
[ "def by_id(self, id):\n self.discover_providers()\n return self.provider_map.get(id)\n" ]
class OAuthProvidertMixin(object): """Mixin for getting OAuth client for a provider.""" provider = None
mishbahr/django-connected
connected_accounts/views.py
OAuthRedirect.get_callback_url
python
def get_callback_url(self, provider): info = self.model._meta.app_label, self.model._meta.model_name return reverse('admin:%s_%s_callback' % info, kwargs={'provider': provider.id})
Return the callback url for this provider.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L42-L45
null
class OAuthRedirect(OAuthProvidertMixin, RedirectView): """Redirect user to OAuth provider to enable access.""" model = Account permanent = False def get_additional_parameters(self, provider): """Return additional redirect parameters for this provider.""" return {} def get_redire...
mishbahr/django-connected
connected_accounts/views.py
OAuthRedirect.get_redirect_url
python
def get_redirect_url(self, **kwargs): provider_id = kwargs.get('provider', '') provider = self.get_provider(provider_id) if not provider: raise Http404('Unknown OAuth provider.') callback = self.get_callback_url(provider) params = self.get_additional_parameters(provid...
Build redirect url for a given provider.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L47-L55
null
class OAuthRedirect(OAuthProvidertMixin, RedirectView): """Redirect user to OAuth provider to enable access.""" model = Account permanent = False def get_additional_parameters(self, provider): """Return additional redirect parameters for this provider.""" return {} def get_callbac...
mishbahr/django-connected
connected_accounts/views.py
OAuthCallback.get_login_redirect
python
def get_login_redirect(self, provider, account): info = self.model._meta.app_label, self.model._meta.model_name # inline import to prevent circular imports. from .admin import PRESERVED_FILTERS_SESSION_KEY preserved_filters = self.request.session.get(PRESERVED_FILTERS_SESSION_KEY, None) ...
Return url to redirect authenticated users.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L119-L129
null
class OAuthCallback(OAuthProvidertMixin, View): """Base OAuth callback view.""" model = Account def get(self, request, *args, **kwargs): name = kwargs.get('provider', '') provider = self.get_provider(name) if not provider: raise Http404('Unknown OAuth provider.') ...
mishbahr/django-connected
connected_accounts/views.py
OAuthCallback.get_error_redirect
python
def get_error_redirect(self, provider, reason): info = self.model._meta.app_label, self.model._meta.model_name return reverse('admin:%s_%s_changelist' % info)
Return url to redirect on login failure.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L131-L134
null
class OAuthCallback(OAuthProvidertMixin, View): """Base OAuth callback view.""" model = Account def get(self, request, *args, **kwargs): name = kwargs.get('provider', '') provider = self.get_provider(name) if not provider: raise Http404('Unknown OAuth provider.') ...
mishbahr/django-connected
connected_accounts/views.py
OAuthCallback.handle_login_failure
python
def handle_login_failure(self, provider, reason): logger.error('Authenication Failure: {0}'.format(reason)) messages.error(self.request, 'Authenication Failed. Please try again') return redirect(self.get_error_redirect(provider, reason))
Message user and redirect on error.
train
https://github.com/mishbahr/django-connected/blob/7ec1f042786fef2eb6c00b1479ce47c90341ba81/connected_accounts/views.py#L136-L140
null
class OAuthCallback(OAuthProvidertMixin, View): """Base OAuth callback view.""" model = Account def get(self, request, *args, **kwargs): name = kwargs.get('provider', '') provider = self.get_provider(name) if not provider: raise Http404('Unknown OAuth provider.') ...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment._python_rpath
python
def _python_rpath(self): # Windows virtualenv installation installs pip to the [Ss]cripts # folder. Here's a simple check to support: if sys.platform == 'win32': return os.path.join('Scripts', 'python.exe') return os.path.join('bin', 'python')
The relative path (from environment root) to python.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L51-L57
null
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.pip_version
python
def pip_version(self): if not self._pip_exists: return None if not hasattr(self, '_pip_version'): # don't call `self._execute_pip` here as that method calls this one output = self._execute(self._pip + ['-V'], log=False).split()[1] self._pip_version = tuple...
Version of installed pip.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L60-L68
[ "def _execute(self, args, log=True):\n \"\"\"Executes the given command inside the environment and returns the output.\"\"\"\n if not self._ready:\n self.open_or_create()\n output = ''\n error = ''\n try:\n proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIP...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment._create
python
def _create(self): if self.readonly: raise VirtualenvReadonlyException() args = ['virtualenv'] if self.system_site_packages: args.append('--system-site-packages') if self.python is None: args.append(self.name) else: args.extend(['-p...
Executes `virtualenv` to create a new environment.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L90-L107
[ "def _write_to_log(self, s, truncate=False):\n \"\"\"Writes the given output to the log file, appending unless `truncate` is True.\"\"\"\n # if truncate is True, set write mode to truncate\n with open(self._logfile, 'w' if truncate else 'a') as fp:\n fp.writelines((to_text(s) if six.PY2 else to_text...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment._execute_pip
python
def _execute_pip(self, args, log=True): # Copy the pip calling arguments so they can be extended exec_args = list(self._pip) # Older versions of pip don't support the version check argument. # Fixes https://github.com/sjkingo/virtualenv-api/issues/35 if self.pip_version[0] >= 6...
Executes pip commands. :param args: Arguments to pass to pip (list[str]) :param log: Log the output to a file [default: True] (boolean) :return: See _execute
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L109-L127
[ "def _execute(self, args, log=True):\n \"\"\"Executes the given command inside the environment and returns the output.\"\"\"\n if not self._ready:\n self.open_or_create()\n output = ''\n error = ''\n try:\n proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIP...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment._execute
python
def _execute(self, args, log=True): if not self._ready: self.open_or_create() output = '' error = '' try: proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = proc.communicate() ...
Executes the given command inside the environment and returns the output.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L129-L158
[ "def to_text(source):\n if six.PY3:\n if isinstance(source, str):\n return source\n else:\n return source.decode(\"utf-8\")\n elif six.PY2:\n if isinstance(source, unicode):\n return source.encode(\"utf-8\")\n return source\n else:\n retur...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment._write_to_log
python
def _write_to_log(self, s, truncate=False): # if truncate is True, set write mode to truncate with open(self._logfile, 'w' if truncate else 'a') as fp: fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
Writes the given output to the log file, appending unless `truncate` is True.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L160-L164
null
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment._write_to_error
python
def _write_to_error(self, s, truncate=False): # if truncate is True, set write mode to truncate with open(self._errorfile, 'w' if truncate else 'a') as fp: fp.writelines((to_text(s)), )
Writes the given output to the error file, appending unless `truncate` is True.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L166-L170
null
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment._pip_exists
python
def _pip_exists(self): return os.path.isfile(os.path.join(self.path, 'bin', 'pip'))
Returns True if pip exists inside the virtual environment. Can be used as a naive way to verify that the environment is installed.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L172-L175
null
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.install
python
def install(self, package, force=False, upgrade=False, options=None): if self.readonly: raise VirtualenvReadonlyException() if options is None: options = [] if isinstance(package, tuple): package = '=='.join(package) if package.startswith(('-e', '-r'))...
Installs the given package into this virtual environment, as specified in pip's package syntax or a tuple of ('name', 'ver'), only if it is not already installed. Some valid examples: 'Django' 'Django==1.5' ('Django', '1.5') '-e .' '-r requirements.txt' ...
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L185-L225
[ "def _execute_pip(self, args, log=True):\n \"\"\"\n Executes pip commands.\n\n :param args: Arguments to pass to pip (list[str])\n :param log: Log the output to a file [default: True] (boolean)\n :return: See _execute\n \"\"\"\n\n # Copy the pip calling arguments so they can be extended\n ex...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.uninstall
python
def uninstall(self, package): if isinstance(package, tuple): package = '=='.join(package) if not self.is_installed(package): self._write_to_log('%s is not installed, skipping' % package) return try: self._execute_pip(['uninstall', '-y', package]) ...
Uninstalls the given package (given in pip's package syntax or a tuple of ('name', 'ver')) from this virtual environment.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L227-L238
[ "def is_installed(self, package):\n \"\"\"Returns True if the given package (given in pip's package syntax or a\n tuple of ('name', 'ver')) is installed in the virtual environment.\"\"\"\n if isinstance(package, tuple):\n package = '=='.join(package)\n if package.endswith('.git'):\n pkg_na...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.wheel
python
def wheel(self, package, options=None): if self.readonly: raise VirtualenvReadonlyException() if options is None: options = [] if isinstance(package, tuple): package = '=='.join(package) if not self.is_installed('wheel'): raise PackageWheel...
Creates a wheel of the given package from this virtual environment, as specified in pip's package syntax or a tuple of ('name', 'ver'), only if it is not already installed. Some valid examples: 'Django' 'Django==1.5' ('Django', '1.5') The `options` is a list of strin...
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L240-L264
[ "def is_installed(self, package):\n \"\"\"Returns True if the given package (given in pip's package syntax or a\n tuple of ('name', 'ver')) is installed in the virtual environment.\"\"\"\n if isinstance(package, tuple):\n package = '=='.join(package)\n if package.endswith('.git'):\n pkg_na...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.is_installed
python
def is_installed(self, package): if isinstance(package, tuple): package = '=='.join(package) if package.endswith('.git'): pkg_name = os.path.split(package)[1][:-4] return pkg_name in self.installed_package_names or \ pkg_name.replace('_', '-') in s...
Returns True if the given package (given in pip's package syntax or a tuple of ('name', 'ver')) is installed in the virtual environment.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L266-L279
[ "def split_package_name(p):\n \"\"\"Splits the given package name and returns a tuple (name, ver).\"\"\"\n s = p.split(six.u('=='))\n if len(s) == 1:\n return (to_text(s[0]), None)\n else:\n return (to_text(s[0]), to_text(s[1]))\n" ]
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.upgrade
python
def upgrade(self, package, force=False): self.install(package, upgrade=True, force=force)
Shortcut method to upgrade a package. If `force` is set to True, the package and all of its dependencies will be reinstalled, otherwise if the package is up to date, this command is a no-op.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L281-L285
[ "def install(self, package, force=False, upgrade=False, options=None):\n \"\"\"Installs the given package into this virtual environment, as\n specified in pip's package syntax or a tuple of ('name', 'ver'),\n only if it is not already installed. Some valid examples:\n\n 'Django'\n 'Django==1.5'\n ...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.upgrade_all
python
def upgrade_all(self): for pkg in self.installed_package_names: self.install(pkg, upgrade=True)
Upgrades all installed packages to their latest versions.
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L287-L292
[ "def install(self, package, force=False, upgrade=False, options=None):\n \"\"\"Installs the given package into this virtual environment, as\n specified in pip's package syntax or a tuple of ('name', 'ver'),\n only if it is not already installed. Some valid examples:\n\n 'Django'\n 'Django==1.5'\n ...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.search
python
def search(self, term): packages = {} results = self._execute_pip(['search', term], log=False) # Don't want to log searches for result in results.split(linesep): try: name, description = result.split(six.u(' - '), 1) except ValueError: # '...
Searches the PyPi repository for the given `term` and returns a dictionary of results. New in 2.1.5: returns a dictionary instead of list of tuples
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L294-L315
[ "def _execute_pip(self, args, log=True):\n \"\"\"\n Executes pip commands.\n\n :param args: Arguments to pass to pip (list[str])\n :param log: Log the output to a file [default: True] (boolean)\n :return: See _execute\n \"\"\"\n\n # Copy the pip calling arguments so they can be extended\n ex...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/manage.py
VirtualEnvironment.installed_packages
python
def installed_packages(self): freeze_options = ['-l', '--all'] if self.pip_version >= (8, 1, 0) else ['-l'] return list(map(split_package_name, filter(None, self._execute_pip( ['freeze'] + freeze_options).split(linesep))))
List of all packages that are installed in this environment in the format [(name, ver), ..].
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L321-L328
[ "def _execute_pip(self, args, log=True):\n \"\"\"\n Executes pip commands.\n\n :param args: Arguments to pass to pip (list[str])\n :param log: Log the output to a file [default: True] (boolean)\n :return: See _execute\n \"\"\"\n\n # Copy the pip calling arguments so they can be extended\n ex...
class VirtualEnvironment(object): def __init__(self, path=None, python=None, cache=None, readonly=False, system_site_packages=False): if path is None: path = get_env_path() if not path: raise VirtualenvPathNotFound('Path for virtualenv is not define or virtualenv is not ac...
sjkingo/virtualenv-api
virtualenvapi/util.py
split_package_name
python
def split_package_name(p): s = p.split(six.u('==')) if len(s) == 1: return (to_text(s[0]), None) else: return (to_text(s[0]), to_text(s[1]))
Splits the given package name and returns a tuple (name, ver).
train
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/util.py#L40-L46
[ "def to_text(source):\n if six.PY3:\n if isinstance(source, str):\n return source\n else:\n return source.decode(\"utf-8\")\n elif six.PY2:\n if isinstance(source, unicode):\n return source.encode(\"utf-8\")\n return source\n else:\n retur...
from os import environ import six import sys def to_text(source): if six.PY3: if isinstance(source, str): return source else: return source.decode("utf-8") elif six.PY2: if isinstance(source, unicode): return source.encode("utf-8") return sou...
davidrpugh/pyCollocation
pycollocation/basis_functions/basis_splines.py
BSplineBasis._basis_spline_factory
python
def _basis_spline_factory(coef, degree, knots, der, ext): return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext)
Return a B-Spline given some coefficients.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/basis_splines.py#L18-L20
null
class BSplineBasis(basis_functions.BasisFunctionLike): @staticmethod @classmethod def derivatives_factory(cls, coef, degree, knots, ext, **kwargs): """ Given some coefficients, return a the derivative of a B-spline. """ return cls._basis_spline_factory(coef, degree, knots...
davidrpugh/pyCollocation
pycollocation/basis_functions/basis_splines.py
BSplineBasis.derivatives_factory
python
def derivatives_factory(cls, coef, degree, knots, ext, **kwargs): return cls._basis_spline_factory(coef, degree, knots, 1, ext)
Given some coefficients, return a the derivative of a B-spline.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/basis_splines.py#L23-L28
null
class BSplineBasis(basis_functions.BasisFunctionLike): @staticmethod def _basis_spline_factory(coef, degree, knots, der, ext): """Return a B-Spline given some coefficients.""" return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext) @classmethod @class...
davidrpugh/pyCollocation
pycollocation/basis_functions/basis_splines.py
BSplineBasis.functions_factory
python
def functions_factory(cls, coef, degree, knots, ext, **kwargs): return cls._basis_spline_factory(coef, degree, knots, 0, ext)
Given some coefficients, return a B-spline.
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/basis_functions/basis_splines.py#L36-L41
null
class BSplineBasis(basis_functions.BasisFunctionLike): @staticmethod def _basis_spline_factory(coef, degree, knots, der, ext): """Return a B-Spline given some coefficients.""" return functools.partial(interpolate.splev, tck=(knots, coef, degree), der=der, ext=ext) @classmethod def deri...
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
SolverLike._evaluate_rhs
python
def _evaluate_rhs(cls, funcs, nodes, problem): evald_funcs = cls._evaluate_functions(funcs, nodes) evald_rhs = problem.rhs(nodes, *evald_funcs, **problem.params) return evald_rhs
Compute the value of the right-hand side of the system of ODEs. Parameters ---------- basis_funcs : list(function) nodes : numpy.ndarray problem : TwoPointBVPLike Returns ------- evaluated_rhs : list(float)
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L41-L58
null
class SolverLike(object): """ Class describing the protocol the all SolverLike objects should satisfy. Notes ----- Subclasses should implement `solve` method as described below. """ @property def basis_functions(self): r""" Functions used to approximate the solution to...
davidrpugh/pyCollocation
pycollocation/solvers/solvers.py
SolverLike._assess_approximation
python
def _assess_approximation(self, boundary_points, derivs, funcs, nodes, problem): interior_residuals = self._compute_interior_residuals(derivs, funcs, nodes, problem) boundary_residuals = self._compute_boundary_residuals(boundary_points, ...
Parameters ---------- basis_derivs : list(function) basis_funcs : list(function) problem : TwoPointBVPLike Returns ------- resids : numpy.ndarray
train
https://github.com/davidrpugh/pyCollocation/blob/9376f3488a992dc416cfd2a4dbb396d094927569/pycollocation/solvers/solvers.py#L105-L122
null
class SolverLike(object): """ Class describing the protocol the all SolverLike objects should satisfy. Notes ----- Subclasses should implement `solve` method as described below. """ @property def basis_functions(self): r""" Functions used to approximate the solution to...