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
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.prepare_params
python
def prepare_params(self): if self.options.resolve_fragment: self.fragment_name = self.node.fragment_name.resolve(self.context) else: self.fragment_name = str(self.node.fragment_name) # Remove quotes that surround the name for char in '\'\"': ...
Prepare the parameters passed to the templatetag
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L234-L256
[ "def get_expire_time(self):\n \"\"\"Update the expiry time with the multiplicator.\"\"\"\n expiry_time = super(TestCacheTag, self).get_expire_time()\n return self.multiplicator * expiry_time\n", "def get_expire_time(self):\n \"\"\"\n Return the expire time passed to the templatetag.\n Must be No...
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.get_expire_time
python
def get_expire_time(self): try: expire_time = self.node.expire_time.resolve(self.context) except template.VariableDoesNotExist: raise template.TemplateSyntaxError('"%s" tag got an unknown variable: %r' % (self.node.nodename, self.nod...
Return the expire time passed to the templatetag. Must be None or an integer.
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L258-L281
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.get_version
python
def get_version(self): if not self.node.version: return None try: version = smart_str('%s' % self.node.version.resolve(self.context)) except template.VariableDoesNotExist: raise template.TemplateSyntaxError('"%s" tag got an unknown variable: %r' % ...
Return the stringified version passed to the templatetag.
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L283-L295
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.hash_args
python
def hash_args(self): return hashlib.md5(force_bytes(':'.join([urlquote(force_bytes(var)) for var in self.vary_on]))).hexdigest()
Take all the arguments passed after the fragment name and return a hashed version which will be used in the cache key
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L297-L302
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.get_cache_key_args
python
def get_cache_key_args(self): cache_key_args = dict( nodename=self.node.nodename, name=self.fragment_name, hash=self.hash_args(), ) if self.options.include_pk: cache_key_args['pk'] = self.get_pk() return cache_key_args
Return the arguments to be passed to the base cache key returned by `get_base_cache_key`.
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L326-L338
[ "def hash_args(self):\n \"\"\"\n Take all the arguments passed after the fragment name and return a\n hashed version which will be used in the cache key\n \"\"\"\n return hashlib.md5(force_bytes(':'.join([urlquote(force_bytes(var)) for var in self.vary_on]))).hexdigest()\n", "def get_pk(self):\n ...
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.cache_set
python
def cache_set(self, to_cache): self.cache.set(self.cache_key, to_cache, self.expire_time)
Set content into the cache
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L362-L366
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.join_content_version
python
def join_content_version(self, to_cache): parts = [self.INTERNAL_VERSION] if self.options.versioning: parts.append(force_bytes(self.version)) parts.append(force_bytes(to_cache)) return self.VERSION_SEPARATOR.join(parts)
Add the version(s) to the content to cache : internal version at first and then the template version if versioning is activated. Each version, and the content, are separated with `VERSION_SEPARATOR`. This method is called after the encoding (if "compress" or "compress_spaces" options are...
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L368-L381
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.split_content_version
python
def split_content_version(self): try: nb_parts = 2 if self.options.versioning: nb_parts = 3 parts = self.content.split(self.VERSION_SEPARATOR, nb_parts - 1) assert len(parts) == nb_parts self.content_internal_version = parts[0] ...
Remove and return the version(s) from the cached content. First the internal version, and if versioning is activated, the template one. And finally save the content, but only if all versions match. The content saved is the encoded one (if "compress" or "compress_spaces" options are on). ...
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L383-L406
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.decode_content
python
def decode_content(self): self.content = pickle.loads(zlib.decompress(self.content))
Decode (decompress...) the content got from the cache, to the final html
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L408-L413
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.render_node
python
def render_node(self): self.content = self.node.nodelist.render(self.context)
Render the template and save the generated content
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L421-L425
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.create_content
python
def create_content(self): self.render_node() if self.options.compress_spaces: self.content = self.RE_SPACELESS.sub(' ', self.content) if self.options.compress: to_cache = self.encode_content() else: to_cache = self.content to_cache = self.jo...
Render the template, apply options on it, and save it to the cache.
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L427-L448
[ "def is_template_debug_activated():\n if django_version < (1, 8):\n return settings.TEMPLATE_DEBUG\n\n # not so simple now, it's an option of a template backend\n for template_settings in settings.TEMPLATES:\n if template_settings['BACKEND'] == 'django.template.backends.django.DjangoTemplates...
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.load_content
python
def load_content(self): self.content = None if not self.regenerate: try: self.content = self.cache_get() except Exception: if is_template_debug_activated(): raise logger.exception('Error when getting the cached...
It's the main method of the class. Try to load the template from cache, get the versions and decode the content. If something was wrong during this process (or if we had a `__regenerate__` value to True in the context), create new content and save it in cache.
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L450-L490
[ "def is_template_debug_activated():\n if django_version < (1, 8):\n return settings.TEMPLATE_DEBUG\n\n # not so simple now, it's an option of a template backend\n for template_settings in settings.TEMPLATES:\n if template_settings['BACKEND'] == 'django.template.backends.django.DjangoTemplates...
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.render
python
def render(self): try: self.load_content() except template.TemplateSyntaxError: raise except Exception: if is_template_debug_activated(): raise logger.exception('Error when rendering template fragment') return '' ...
Try to load content (from cache or by rendering the template). If it fails, return an empty string or raise the exception if it's a TemplateSyntaxError. With this, we can no parse and render the content included in the {% nocache %} blocks, but only if we have have this tag and if we don...
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L493-L516
[ "def is_template_debug_activated():\n if django_version < (1, 8):\n return settings.TEMPLATE_DEBUG\n\n # not so simple now, it's an option of a template backend\n for template_settings in settings.TEMPLATES:\n if template_settings['BACKEND'] == 'django.template.backends.django.DjangoTemplates...
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.get_all_tags_and_filters_by_function
python
def get_all_tags_and_filters_by_function(): libraries = get_template_libraries() force = False # We'll force the update of the cache if new libraries where added if hasattr(CacheTag.get_all_tags_and_filters_by_function, '_len_libraries'): if len(libraries) != CacheTag.get_...
Return a dict with all the template tags (in the `tags` entry) and filters (in the `filters` entry) that are available. Both entries are a dict with the function as key, and a tuple with (library name, function name) as value. This is cached after the first call.
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L519-L559
[ "def get_template_libraries():\n try:\n from django.template.base import libraries\n except ImportError:\n # Django >= 1.9\n from django.template import engines\n libraries = engines['django'].engine.template_libraries\n\n return libraries\n" ]
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.get_templatetag_module
python
def get_templatetag_module(cls): if cls not in CacheTag._templatetags_modules: # find the library including the main templatetag of the current class all_tags = cls.get_all_tags_and_filters_by_function()['tags'] CacheTag._templatetags_modules[cls] = all_tags[CacheTag._templat...
Return the templatetags module name for which the current class is used. It's used to render the nocache blocks by loading the correct module
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L562-L571
[ "def get_all_tags_and_filters_by_function():\n \"\"\"\n Return a dict with all the template tags (in the `tags` entry) and filters (in the\n `filters` entry) that are available.\n Both entries are a dict with the function as key, and a tuple with (library name, function\n name) as value.\n This is...
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.render_nocache
python
def render_nocache(self): tmpl = template.Template(''.join([ # start by loading the cache library template.BLOCK_TAG_START, 'load %s' % self.get_templatetag_module(), template.BLOCK_TAG_END, # and surround the cached template by "raw" tags ...
Render the `nocache` blocks of the content and return the whole html
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L573-L588
[ "def get_templatetag_module(cls):\n \"\"\"\n Return the templatetags module name for which the current class is used.\n It's used to render the nocache blocks by loading the correct module\n \"\"\"\n if cls not in CacheTag._templatetags_modules:\n # find the library including the main template...
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.get_template_node_arguments
python
def get_template_node_arguments(cls, tokens): if len(tokens) < 3: raise template.TemplateSyntaxError( "'%r' tag requires at least 2 arguments." % tokens[0]) return tokens[1], tokens[2], tokens[3:]
Return the arguments taken from the templatetag that will be used to the Node class. Take a list of all tokens and return a list of real tokens. Here should be done some validations (number of tokens...) and eventually some parsing...
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L591-L602
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
twidi/django-adv-cache-tag
adv_cache_tag/tag.py
CacheTag.register
python
def register(cls, library_register, nodename='cache', nocache_nodename='nocache'): if cls in CacheTag._templatetags: raise RuntimeError('The adv-cache-tag class %s is already registered' % cls) CacheTag._templatetags[cls] = {} def templatetag_cache(parser, token): """ ...
Register all needed templatetags, with these parameters : * library_register : the `register` object (result of `template.Library()`) in your templatetag module * nodename : the node to use for the cache templatetag (the default is "cache") * nocache_n...
train
https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L605-L726
null
class CacheTag(object, metaclass=CacheTagMetaClass): """ The main class of `django-adv-cache-tag` which does all the work. To change its behaviour, simply change one or more of these settings (see in the `Meta` class for details) : * ADV_CACHE_VERSIONING * ADV_CACHE_COMPRESS * ...
pyfca/pyfca
pyfca/implications.py
L
python
def L(g,i): g1 = g&(2**i) if i: n = Lwidth(i) Ln = L(g,i-1) if g1: return Ln<<(2*n) | Ln<<n | Ln else: return int('1'*n,2)<<(2*n) | Ln<<n | Ln else: if g1: return int('000',2) else: return int('100',2)
recursively constructs L line for g; i = len(g)-1
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L33-L47
[ "Lwidth = Hwidth = lambda n: 3**n\n", "def L(g,i):\n \"\"\"recursively constructs L line for g; i = len(g)-1\"\"\"\n g1 = g&(2**i)\n if i:\n n = Lwidth(i)\n Ln = L(g,i-1)\n if g1:\n return Ln<<(2*n) | Ln<<n | Ln\n else:\n return int('1'*n,2)<<(2...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
H
python
def H(g,i): g1 = g&(2**i) if i: n = Hwidth(i) i=i-1 Hn = H(g,i) if g1: return Hn<<(2*n) | Hn<<n | Hn else: return int('1'*n,2)<<(2*n) | L(g,i)<<n | Hn else: if g1: return int('111',2) else: ...
recursively constructs H line for g; i = len(g)-1
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L48-L63
[ "Lwidth = Hwidth = lambda n: 3**n\n", "def L(g,i):\n \"\"\"recursively constructs L line for g; i = len(g)-1\"\"\"\n g1 = g&(2**i)\n if i:\n n = Lwidth(i)\n Ln = L(g,i-1)\n if g1:\n return Ln<<(2*n) | Ln<<n | Ln\n else:\n return int('1'*n,2)<<(2...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
UV_H
python
def UV_H(Hg,gw): lefts = set() K = [] UV = [] p = Hwidth(gw) pp = 2**p while p: pp = pp>>1 p = p-1 if Hg&pp: y = istr(p,3,gw) yy = y.replace('1','0') if yy not in lefts: if y.find('1') == -1:#y∈{0,2}^n ...
Constructs implications and intents based on H gw = g width Hg = H(g), g is the binary coding of the attribute set UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U) K = all closed sets
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L65-L90
[ "Lwidth = Hwidth = lambda n: 3**n\n", "def istr(i,b,w,c=\"0123456789abcdefghijklmnopqrstuvwxyz\"):\n return ((w<=0 and i==0) and \" \") or (istr(i//b, b, w-1, c).lstrip() + c[i%b])\n" ]
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
A
python
def A(g,i): g1 = g&(2**i) if i: n = Awidth(i) An = A(g,i-1) if g1: return An<<n | An else: return int('1'*n,2)<<n | An else: if g1: return int('00',2) else: return int('10',2)
recursively constructs A line for g; i = len(g)-1
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L93-L107
[ "Awidth = lambda n: 2**n\n", "def A(g,i):\n \"\"\"recursively constructs A line for g; i = len(g)-1\"\"\"\n g1 = g&(2**i)\n if i:\n n = Awidth(i)\n An = A(g,i-1)\n if g1:\n return An<<n | An\n else:\n return int('1'*n,2)<<n | An\n else:\n if g1:...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
B
python
def B(g,i): g1 = g&(2**i) if i: nA = Awidth(i) nB = Bwidth(i) i=i-1 Bn = B(g,i) if g1: return Bn << (nA+nB) | int('1'*nA,2) << nB | Bn else: return int('1'*nB,2) << (nA+nB) | A(g,i) << nB | Bn else: if g1: ...
recursively constructs B line for g; i = len(g)-1
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L109-L125
[ "Awidth = lambda n: 2**n\n", "Bwidth = lambda n:n*2**(n-1)\n", "def A(g,i):\n \"\"\"recursively constructs A line for g; i = len(g)-1\"\"\"\n g1 = g&(2**i)\n if i:\n n = Awidth(i)\n An = A(g,i-1)\n if g1:\n return An<<n | An\n else:\n return int('1'*n,2...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
B012
python
def B012(t,i): if not i: return "1" nA = Awidth(i) nB = Bwidth(i) nBB = nB + nA if t < nB: return "0"+B012(t,i-1) elif t < nBB: return "1"+A012(t-nB,i-1) else: return "2"+B012(t-nBB,i-1)
Constructs ternary implication coding (0=not there, 2=U, 1=V) t is B column position i = |M|-1 to 0
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L135-L151
[ "Awidth = lambda n: 2**n\n", "Bwidth = lambda n:n*2**(n-1)\n", "def A012(t,i):\n if i<0:\n return \"\"\n nA = Awidth(i)\n if t < nA:\n return \"0\"+A012(t,i-1)\n else:\n return \"2\"+A012(t-nA,i-1)\n", "def B012(t,i):\n \"\"\"\n Constructs ternary implication coding (0=n...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
UV_B
python
def UV_B(Bg,gw): UV = [] p = Bwidth(gw) pp = 2**p while p: pp = pp>>1 p = p-1 if Bg&pp: uv = B012(p,gw-1) UV.append(uv) return UV
returns the implications UV based on B Bg = B(g), g∈2^M gw = |M|, M is the set of all attributes
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L153-L168
[ "Bwidth = lambda n:n*2**(n-1)\n", "def B012(t,i):\n \"\"\"\n Constructs ternary implication coding (0=not there, 2=U, 1=V)\n t is B column position\n i = |M|-1 to 0\n \"\"\"\n if not i:\n return \"1\"\n nA = Awidth(i)\n nB = Bwidth(i)\n nBB = nB + nA\n if t < nB:\n retu...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
omega
python
def omega(imps): if isinstance(imps,v_Us_dict): return sum([omega(V) for U,V in imps.items()])#|V|=1 if isinstance(imps,list): return sum([omega(x) for x in imps]) if isinstance(imps,str): #imps = due[-1] try: U,V = imps.split("->") Us = U.split(",") i...
Calculates a measure for the size of the implication basis: \sum |U||V|
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L170-L191
null
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
respects
python
def respects(g,imp): if isinstance(g,str): g = int(g,2) if isinstance(imp,int): imp = istr(imp,3,g.bit_length()) V = int(imp.replace('1','2').replace('2','1'),2) U = int(imp.replace('1','0').replace('2','1'),2) ginU = U&g == U ginV = V&g == V return not ginU or ginV
g is an int, where each bit is an attribute implication UV is ternary coded 1 = ∈V, 2 = ∈U, 0 otherwise g and UV have the same number of digits
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L387-L401
[ "def istr(i,b,w,c=\"0123456789abcdefghijklmnopqrstuvwxyz\"):\n return ((w<=0 and i==0) and \" \") or (istr(i//b, b, w-1, c).lstrip() + c[i%b])\n" ]
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
LL
python
def LL(n): if (n<=0):return Context('0') else: LL1=LL(n-1) r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1 r2 = LL1 - LL1 - LL1 return r1 + r2
constructs the LL context
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L532-L539
[ "def C1(w,h):\n return Context('\\n'.join(['1'*w]*h))\n", "def LL(n):\n \"\"\"constructs the LL context\"\"\"\n if (n<=0):return Context('0')\n else:\n LL1=LL(n-1)\n r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1\n r2 = LL1 - LL1 - LL1\n return r1 + r2\n" ]
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
HH
python
def HH(n): if (n<=0):return Context('1') else: LL1=LL(n-1) HH1=HH(n-1) r1 = C1(3**(n-1),2**(n-1)) - LL1 - HH1 r2 = HH1 - HH1 - HH1 return r1 + r2
constructs the HH context
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L540-L548
[ "def C1(w,h):\n return Context('\\n'.join(['1'*w]*h))\n", "def LL(n):\n \"\"\"constructs the LL context\"\"\"\n if (n<=0):return Context('0')\n else:\n LL1=LL(n-1)\n r1 = C1(3**(n-1),2**(n-1)) - LL1 - LL1\n r2 = LL1 - LL1 - LL1\n return r1 + r2\n", "def HH(n):\n \"\"\"...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
AA
python
def AA(n): if (n<=1):return Context('10\n00') else: AA1=AA(n-1) r1 = C1(2**(n-1),2**(n-1)) - AA1 r2 = AA1 - AA1 return r1 + r2
constructs the AA context
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L550-L557
[ "def C1(w,h):\n return Context('\\n'.join(['1'*w]*h))\n", "def AA(n):\n \"\"\"constructs the AA context\"\"\"\n if (n<=1):return Context('10\\n00')\n else:\n AA1=AA(n-1)\n r1 = C1(2**(n-1),2**(n-1)) - AA1\n r2 = AA1 - AA1\n return r1 + r2\n" ]
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
BB
python
def BB(n): if (n<=1):return Context('0\n1') else: BB1=BB(n-1) AA1=AA(n-1) r1 = C1((n-1)*2**(n-2),2**(n-1)) - AA1 - BB1 r2 = BB1 - C1(2**(n-1),2**(n-1)) - BB1; return r1 + r2
constructs the BB context
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L558-L566
[ "def C1(w,h):\n return Context('\\n'.join(['1'*w]*h))\n", "def AA(n):\n \"\"\"constructs the AA context\"\"\"\n if (n<=1):return Context('10\\n00')\n else:\n AA1=AA(n-1)\n r1 = C1(2**(n-1),2**(n-1)) - AA1\n r2 = AA1 - AA1\n return r1 + r2\n", "def BB(n):\n \"\"\"constr...
#!/usr/bin/env python3 # encoding: utf-8 """ Implications ------------ This uses the python int as a bit field to store the FCA context. See this `blog`_ for more. .. _`blog`: http://rolandpuntaier.blogspot.com/2015/07/implications.html """ from math import trunc, log2 from functools import reduce from itertoo...
pyfca/pyfca
pyfca/implications.py
v_Us_dict.koenig
python
def koenig(self): L = self Y = L - (L*L) while True: Ybar = Y + ~Y take = L - Ybar if not len(take): return Y else: ZZ = list(set(take)-set(Y))#use significant which is not in Y if len(ZZ) > 0: ...
This needs to be L = contextg.v_Us_B()
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L364-L383
null
class v_Us_dict(defaultdict): """ In an implication U→u, u is the significant component. U is coded as int. u is the bit column of the implication's conclusion. {u:[U1,U2,...]} """ def __init__(self,Bg,gw): """ returns the implications {v:Us} based on B v is the signi...
pyfca/pyfca
pyfca/implications.py
Context.column
python
def column(self, i): return ''.join([str(digitat2(r,i)) for r in self])
from right
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L432-L434
null
class Context(list): def __init__(self, *args, **kwargs): """Context can be initialized with - a rectangular text block of 0s and 1s - a list of ints and a "width" keyword argument. A "mapping" keyword argument as list associates the bits with objects of any kind. """ ...
pyfca/pyfca
pyfca/implications.py
Context.UV_H
python
def UV_H(self): h = reduce(lambda x,y:x&y,(H(g,self.width-1) for g in self)) return UV_H(h, self.width)
UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U) K = all closed sets This is UV_H function, but the returned implications are respected by all attribute sets of this context. This corresponds to a multiplication or & operation of the Hg sets.
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L454-L463
[ "def UV_H(Hg,gw):\n \"\"\"\n Constructs implications and intents based on H\n gw = g width\n Hg = H(g), g is the binary coding of the attribute set\n UV = all non-trivial (!V⊂U) implications U->V with UuV closed; in ternary coding (1=V,2=U)\n K = all closed sets\n \"\"\"\n lefts = set()\n ...
class Context(list): def __init__(self, *args, **kwargs): """Context can be initialized with - a rectangular text block of 0s and 1s - a list of ints and a "width" keyword argument. A "mapping" keyword argument as list associates the bits with objects of any kind. """ ...
pyfca/pyfca
pyfca/implications.py
Context.UV_B
python
def UV_B(self): h = reduce(lambda x,y:x&y,(B(g,self.width-1) for g in self)) return UV_B(h, self.width)
returns UV = all respected U->Ux in ternary coding (1=V,2=U)
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L464-L469
[ "def UV_B(Bg,gw):\n \"\"\"\n returns the implications UV based on B\n Bg = B(g), g∈2^M\n gw = |M|, M is the set of all attributes\n \"\"\"\n UV = []\n p = Bwidth(gw)\n pp = 2**p\n while p:\n pp = pp>>1\n p = p-1\n if Bg&pp:\n uv = B012(p,gw-1)\n ...
class Context(list): def __init__(self, *args, **kwargs): """Context can be initialized with - a rectangular text block of 0s and 1s - a list of ints and a "width" keyword argument. A "mapping" keyword argument as list associates the bits with objects of any kind. """ ...
pyfca/pyfca
pyfca/implications.py
Context.v_Us_B
python
def v_Us_B(self): Bg = reduce(lambda x,y:x&y,(B(g,self.width-1) for g in self)) gw = self.width return v_Us_dict(Bg, gw)
returns the implications {v:Us} based on B This is L=∪ min L_i in [1]_
train
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L470-L477
null
class Context(list): def __init__(self, *args, **kwargs): """Context can be initialized with - a rectangular text block of 0s and 1s - a list of ints and a "width" keyword argument. A "mapping" keyword argument as list associates the bits with objects of any kind. """ ...
Metatab/geoid
geoid/core.py
parse_to_gvid
python
def parse_to_gvid(v): from geoid.civick import GVid from geoid.acs import AcsGeoid m1 = '' try: return GVid.parse(v) except ValueError as e: m1 = str(e) try: return AcsGeoid.parse(v).convert(GVid) except ValueError as e: raise ValueError("Failed to parse to...
Parse an ACS Geoid or a GVID to a GVID
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L342-L357
[ "def parse(cls, gvid, exception=True):\n \"\"\"\n Parse a string value into the geoid of this class.\n\n :param gvid: String value to parse.\n :param exception: If true ( default) raise an eception on parse erorrs. If False, return a\n 'null' geoid.\n :return:\n \"\"\"\n\n if gvid == 'invali...
""" CLasses for working with census Geoids """ import inspect import re import sys import six names = { # (summary level value, base 10 chars, Base 62 chars, prefix fields) 'null': 1, 'us': 10, 'region': 20, 'division': 30, 'state': 40, 'county': 50, 'cosub': 60, 'place': 160, ...
Metatab/geoid
geoid/core.py
base62_decode
python
def base62_decode(string): alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' base = len(alphabet) strlen = len(string) num = 0 idx = 0 for char in string: power = (strlen - (idx + 1)) num += alphabet.index(char) * (base ** power) idx += 1 ...
Decode a Base X encoded string into the number Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L384-L405
null
""" CLasses for working with census Geoids """ import inspect import re import sys import six names = { # (summary level value, base 10 chars, Base 62 chars, prefix fields) 'null': 1, 'us': 10, 'region': 20, 'division': 30, 'state': 40, 'county': 50, 'cosub': 60, 'place': 160, ...
Metatab/geoid
geoid/core.py
augment
python
def augment(module_name, base_class): for name, cls in inspect.getmembers(sys.modules[module_name], lambda x : inspect.isclass(x) and issubclass(x, base_class) ): if cls == base_class: continue cls.augment()
Call the augment() method for all of the derived classes in the module
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L408-L416
null
""" CLasses for working with census Geoids """ import inspect import re import sys import six names = { # (summary level value, base 10 chars, Base 62 chars, prefix fields) 'null': 1, 'us': 10, 'region': 20, 'division': 30, 'state': 40, 'county': 50, 'cosub': 60, 'place': 160, ...
Metatab/geoid
geoid/core.py
make_classes
python
def make_classes(base_class, module): from functools import partial for k in names: cls = base_class.class_factory(k.capitalize()) cls.augment() setattr(module, k.capitalize(), cls) setattr(module, 'get_class', partial(get_class, module))
Create derived classes and put them into the same module as the base class. This function is called at the end of each of the derived class modules, acs, census, civik and tiger. It will create a set of new derived class in the module, one for each of the enries in the `summary_levels` dict.
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L428-L446
[ "def class_factory(cls, name):\n def __init__(self, *args, **kwargs):\n cls.__init__(self, *args, **kwargs)\n\n return type(name, (cls,), {\"__init__\": __init__})\n", "def class_factory(cls, name):\n def __init__(self, *args, **kwargs):\n cls.__init__(self, *args, **kwargs)\n\n return t...
""" CLasses for working with census Geoids """ import inspect import re import sys import six names = { # (summary level value, base 10 chars, Base 62 chars, prefix fields) 'null': 1, 'us': 10, 'region': 20, 'division': 30, 'state': 40, 'county': 50, 'cosub': 60, 'place': 160, ...
Metatab/geoid
geoid/core.py
generate_all
python
def generate_all(sumlevel, d): from geoid.civick import GVid from geoid.tiger import TigerGeoid from geoid.acs import AcsGeoid sumlevel = int(sumlevel) d = dict(d.items()) # Map common name variants if 'cousub' in d: d['cosub'] = d['cousub'] del d['cousub'] if 'blkgr...
Generate a dict that includes all of the available geoid values, with keys for the most common names for those values.
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L887-L927
[ "def resolve_summary_level(cls, sl):\n try:\n return cls.sl_map[sl]\n except KeyError:\n return None\n" ]
""" CLasses for working with census Geoids """ import inspect import re import sys import six names = { # (summary level value, base 10 chars, Base 62 chars, prefix fields) 'null': 1, 'us': 10, 'region': 20, 'division': 30, 'state': 40, 'county': 50, 'cosub': 60, 'place': 160, ...
Metatab/geoid
geoid/core.py
_generate_names
python
def _generate_names(): from ambry import get_library l = get_library() counties = l.partition('census.gov-acs-geofile-2009-geofile50-20095-50') states = l.partition('census.gov-acs-geofile-2009-geofile40-20095-40') names = {} for row in counties.remote_datafile.reader: names[(row.sta...
Code to generate the state and county names >>> python -c 'import geoid; geoid._generate_names()'
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L930-L952
null
""" CLasses for working with census Geoids """ import inspect import re import sys import six names = { # (summary level value, base 10 chars, Base 62 chars, prefix fields) 'null': 1, 'us': 10, 'region': 20, 'division': 30, 'state': 40, 'county': 50, 'cosub': 60, 'place': 160, ...
Metatab/geoid
geoid/core.py
CountyName.division_name
python
def division_name(self): """The type designation for the county or county equivalent, such as 'County','Parish' or 'Borough'""" try: return next(e for e in self.type_names_re.search(self.name).groups() if e is not None) except AttributeError: # The search will fail for 'D...
The type designation for the county or county equivalent, such as 'County','Parish' or 'Borough
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L489-L495
null
class CountyName(object): """A Census county name, with methods to create shorter versions and return the types of division, which may be county, parish, borough, etc. """ # Strip the county and state name. THis doesn't work for some locations # where the county is actually called a parish or a bario. ...
Metatab/geoid
geoid/core.py
Geoid.augment
python
def augment(cls): import re level_name = cls.__name__.lower() cls.sl = names[level_name] cls.class_map[cls.__name__.lower()] = cls cls.sl_map[cls.sl] = cls cls.fmt = cls.make_format_string(cls.__name__.lower()) cls.regex_str = cls.make_regex(cls.__name__.lo...
Augment the class with computed formats, regexes, and other things. This caches these values so they don't have to be created for every instance.
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L562-L583
null
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/core.py
Geoid.get_class
python
def get_class(cls, name_or_sl): try: return cls.sl_map[int(name_or_sl)] except TypeError as e: raise TypeError("Bad name or sl: {} : {}".format(name_or_sl, e)) except ValueError: try: return cls.class_map[name_or_sl.lower()] except...
Return a derived class based on the class name or the summary_level
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L587-L598
null
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/core.py
Geoid.geo_name
python
def geo_name(self): if self.level == 'county': return str(self.county_name) elif self.level == 'state': return self.state_name else: if hasattr(self, 'county'): return "{} in {}".format(self.level,str(self.county_name)) elif hasa...
Return a name of the state or county, or, for other lowever levels, the name of the level type in the county. :return:
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L668-L689
null
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/core.py
Geoid.parse
python
def parse(cls, gvid, exception=True): if gvid == 'invalid': return cls.get_class('null')(0) if not bool(gvid): return None if not isinstance(gvid, six.string_types): raise TypeError("Can't parse; not a string. Got a '{}' ".format(type(gvid))) try: ...
Parse a string value into the geoid of this class. :param gvid: String value to parse. :param exception: If true ( default) raise an eception on parse erorrs. If False, return a 'null' geoid. :return:
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L714-L781
[ "def get_class(cls, name_or_sl):\n \"\"\"Return a derived class based on the class name or the summary_level\"\"\"\n try:\n return cls.sl_map[int(name_or_sl)]\n\n except TypeError as e:\n raise TypeError(\"Bad name or sl: {} : {}\".format(name_or_sl, e))\n except ValueError:\n try:\...
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/core.py
Geoid.convert
python
def convert(self, root_cls): d = self.__dict__ d['sl'] = self.sl try: cls = root_cls.get_class(root_cls.sl) except (AttributeError, TypeError): # Hopefully because root_cls is a module cls = root_cls.get_class(self.sl) return cls(**d)
Convert to another derived class. cls is the base class for the derived type, ie AcsGeoid, TigerGeoid, etc.
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L783-L796
[ "def get_class(cls, name_or_sl):\n \"\"\"Return a derived class based on the class name or the summary_level\"\"\"\n try:\n return cls.sl_map[int(name_or_sl)]\n\n except TypeError as e:\n raise TypeError(\"Bad name or sl: {} : {}\".format(name_or_sl, e))\n except ValueError:\n try:\...
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/core.py
Geoid.promote
python
def promote(self, level=None): if level is None: if len(self.fields) < 2: if self.level in ('region', 'division', 'state', 'ua'): cls = self.get_class('us') else: return None else: cls = self.get_cl...
Convert to the next higher level summary level
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L810-L828
[ "def get_class(cls, name_or_sl):\n \"\"\"Return a derived class based on the class name or the summary_level\"\"\"\n try:\n return cls.sl_map[int(name_or_sl)]\n\n except TypeError as e:\n raise TypeError(\"Bad name or sl: {} : {}\".format(name_or_sl, e))\n except ValueError:\n try:\...
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/core.py
Geoid.allval
python
def allval(self): d = dict(self.__dict__.items()) d['sl'] = self.sl d[self.level] = 0 cls = self.get_class(self.sl) return cls(**d)
Convert the last value to zero. This form represents the entire higher summary level at the granularity of the lower summary level. For example, for a county, it means 'All counties in the state'
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L835-L846
[ "def get_class(cls, name_or_sl):\n \"\"\"Return a derived class based on the class name or the summary_level\"\"\"\n try:\n return cls.sl_map[int(name_or_sl)]\n\n except TypeError as e:\n raise TypeError(\"Bad name or sl: {} : {}\".format(name_or_sl, e))\n except ValueError:\n try:\...
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/core.py
Geoid.nullval
python
def nullval(cls): d = dict(cls.__dict__.items()) for k in d: d[k] = 0 d['sl'] = cls.sl d[cls.level] = 0 return cls(**d)
Create a new instance where all of the values are 0
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/core.py#L849-L860
null
class Geoid(object): @classmethod def resolve_summary_level(cls, sl): try: return cls.sl_map[sl] except KeyError: return None @classmethod def make_format_string(cls, level): sl_num = names[level] segs = segments[sl_num] formats = [] ...
Metatab/geoid
geoid/civick.py
GVid.summarize
python
def summarize(self): s = str(self.allval()) return self.parse(s[:2]+ ''.join(['Z']*len(s[2:])))
Convert all of the values to their max values. This form is used to represent the summary level
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/civick.py#L41-L46
[ "def parse(cls, gvid, exception=True):\n \"\"\"\n Parse a string value into the geoid of this class.\n\n :param gvid: String value to parse.\n :param exception: If true ( default) raise an eception on parse erorrs. If False, return a\n 'null' geoid.\n :return:\n \"\"\"\n\n if gvid == 'invali...
class GVid(Geoid): sl = None fmt = None class_map = {} sl_map = {} sl_width = 2 sl_format = '{sl:0>2s}' elem_format = '{{{}:0>{}s}}' elem_str_format = '{{{}:0>{}s}}' sl_regex = '(?P<sl>.{2})' elem_regex = '(?P<{}>.{{{}}})' encode = base62_encode decode = base62_decode...
Metatab/geoid
geoid/util.py
simplify
python
def simplify(geoids): from collections import defaultdict aggregated = defaultdict(set) d = {} for g in geoids: if not bool(g): continue av = g.allval() d[av] = None aggregated[av].add(g) compiled = set() for k, v in aggregated.items(): ...
Given a list of geoids, reduce it to a simpler set. If there are five or more geoids at one summary level convert them to a single geoid at the higher level. :param geoids: :return:
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/util.py#L3-L38
null
"""Utilities""" def isimplify(geoids): """Iteratively simplify until the set stops getting smaller. """ s0 = list(geoids) for i in range(10): s1 = simplify(s0) if len(s1) == len(s0): return s1 s0 = s1 def iallval(t): """Recursively promote and compute allvals "...
Metatab/geoid
geoid/util.py
isimplify
python
def isimplify(geoids): s0 = list(geoids) for i in range(10): s1 = simplify(s0) if len(s1) == len(s0): return s1 s0 = s1
Iteratively simplify until the set stops getting smaller.
train
https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/util.py#L40-L51
[ "def simplify(geoids):\n \"\"\"\n Given a list of geoids, reduce it to a simpler set. If there are five or more geoids at one summary level\n convert them to a single geoid at the higher level.\n\n :param geoids:\n :return:\n \"\"\"\n\n from collections import defaultdict\n\n aggregated = de...
"""Utilities""" def simplify(geoids): """ Given a list of geoids, reduce it to a simpler set. If there are five or more geoids at one summary level convert them to a single geoid at the higher level. :param geoids: :return: """ from collections import defaultdict aggregated = default...
jpscaletti/authcode
authcode/auth.py
Auth.set_hasher
python
def set_hasher(self, hash, rounds=None): hash = hash.replace('-', '_') if hash not in VALID_HASHERS: raise WrongHashAlgorithm(WRONG_HASH_MESSAGE) hasher = getattr(ph, hash) utils.test_hasher(hasher) default_rounds = getattr(hasher, 'default_rounds', 1) min_ro...
Updates the has algorithm and, optionally, the number of rounds to use. Raises: `~WrongHashAlgorithm` if new algorithm isn't one of the three recomended options.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth.py#L140-L167
[ "def test_hasher(hasher):\n hasher.encrypt('test', rounds=hasher.min_rounds)\n" ]
class Auth(AuthenticationMixin, AuthorizationMixin, ViewsMixin): default_settings = { 'session_key': '_uhmac', 'user_name': 'user', 'csrf_key': '_csrf_token', 'csrf_header': 'X-CSRFToken', 'csrf_header_alt': 'X-CSRF-TOKEN', 'redirect_key': 'next', 'sign_in_...
jpscaletti/authcode
authcode/auth_views_mixin.py
ViewsMixin.render_template
python
def render_template(self, name, **kwargs): custom_template = getattr(self, 'template_' + name) if custom_template: return self.render(custom_template, **kwargs) template = TEMPLATES.get(name) return self.default_render(template, **kwargs)
Search for a setting named ``template_<name>`` and renders it. If one is not defined it uses the default template of the library at ``autchode/templates/<name>,html``. To render the template uses the ``render`` function, a property that has been probably overwritten in a ``auth.setup_fo...
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_views_mixin.py#L44-L57
[ "def default_render(self, template, **kwargs):\n tmpl = def_env.get_template(template)\n return tmpl.render(kwargs)\n", "def render(self, template, **kwargs):\n \"\"\"Should be overwritten in the setup\"\"\"\n return self.default_render(template, **kwargs) # pragma: no cover\n" ]
class ViewsMixin(object): ERROR_BAD_CSRF = 'BAD CSRF TOKEN' ERROR_SUSPENDED = 'ACCOUNT SUSPENDED' ERROR_CREDENTIALS = 'BAD CREDENTIALS' ERROR_BAD_TOKEN = 'WRONG TOKEN' ERROR_WRONG_TOKEN_USER = 'WRONG USER' ERROR_PASSW_TOO_SHORT = 'TOO SHORT' ERROR_PASSW_TOO_LONG = 'TOO LONG' ERROR_PAS...
jpscaletti/authcode
authcode/auth_views_mixin.py
ViewsMixin.send_email
python
def send_email(self, user, subject, msg): print('To:', user) print('Subject:', subject) print(msg)
Should be overwritten in the setup
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_views_mixin.py#L67-L71
null
class ViewsMixin(object): ERROR_BAD_CSRF = 'BAD CSRF TOKEN' ERROR_SUSPENDED = 'ACCOUNT SUSPENDED' ERROR_CREDENTIALS = 'BAD CREDENTIALS' ERROR_BAD_TOKEN = 'WRONG TOKEN' ERROR_WRONG_TOKEN_USER = 'WRONG USER' ERROR_PASSW_TOO_SHORT = 'TOO SHORT' ERROR_PASSW_TOO_LONG = 'TOO LONG' ERROR_PAS...
jpscaletti/authcode
authcode/setups/setup_for_bottle.py
setup_for_bottle
python
def setup_for_bottle( auth, app, send_email=None, render=None, session=None, request=None, urloptions=None): import bottle auth.request = request or bottle.request if session is not None: auth.session = session if send_email: auth.send_email = send_email auth.render...
Set the session **before** calling ``setup_for_bottle`` like this: @hook('before_request') def setup_request(): request.session = request.environ['beaker.session']
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/setups/setup_for_bottle.py#L5-L40
[ "def setup_for_bottle_views(auth, app, urloptions):\n urloptions = urloptions or {}\n\n if 'sign_in' in auth.views:\n url_sign_in = eval_url(auth.url_sign_in)\n app.route(\n url_sign_in,\n method=['GET', 'POST'],\n name='{prefix}{name}'.format(\n p...
# coding=utf-8 from ..utils import LazyUser, eval_url def setup_for_bottle_views(auth, app, urloptions): urloptions = urloptions or {} if 'sign_in' in auth.views: url_sign_in = eval_url(auth.url_sign_in) app.route( url_sign_in, method=['GET', 'POST'], name...
jpscaletti/authcode
authcode/wsgi/bottle.py
get_site_name
python
def get_site_name(request): urlparts = request.urlparts return ':'.join([urlparts.hostname, str(urlparts.port)])
Return the domain:port part of the URL without scheme. Eg: facebook.com, 127.0.0.1:8080, etc.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/bottle.py#L10-L15
null
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_FORBIDDEN = 403 def get_full_path(request): """Return the current relative path including the query string. Eg: “/foo/bar/?page=1” """ path = request.fullpath query_string = request.environ.get('QUERY_ST...
jpscaletti/authcode
authcode/wsgi/bottle.py
get_full_path
python
def get_full_path(request): path = request.fullpath query_string = request.environ.get('QUERY_STRING') if query_string: path += '?' + to_native(query_string) return path
Return the current relative path including the query string. Eg: “/foo/bar/?page=1”
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/bottle.py#L18-L26
[ "def to_native(x, charset='utf8', errors='ignore'):\n bb = to_bytes(x, charset=charset, errors=errors)\n if not bb:\n return bb\n return bb.decode('utf8')\n" ]
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_FORBIDDEN = 403 def get_site_name(request): """Return the domain:port part of the URL without scheme. Eg: facebook.com, 127.0.0.1:8080, etc. """ urlparts = request.urlparts return ':'.join([urlparts.hostn...
jpscaletti/authcode
authcode/wsgi/bottle.py
make_full_url
python
def make_full_url(request, url): urlparts = request.urlparts return '{scheme}://{site}/{url}'.format( scheme=urlparts.scheme, site=get_site_name(request), url=url.lstrip('/'), )
Get a relative URL and returns the absolute version. Eg: “/foo/bar?q=is-open” ==> “http://example.com/foo/bar?q=is-open”
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/bottle.py#L29-L38
[ "def get_site_name(request):\n \"\"\"Return the domain:port part of the URL without scheme.\n Eg: facebook.com, 127.0.0.1:8080, etc.\n \"\"\"\n urlparts = request.urlparts\n return ':'.join([urlparts.hostname, str(urlparts.port)])\n" ]
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_FORBIDDEN = 403 def get_site_name(request): """Return the domain:port part of the URL without scheme. Eg: facebook.com, 127.0.0.1:8080, etc. """ urlparts = request.urlparts return ':'.join([urlparts.hostn...
jpscaletti/authcode
authcode/wsgi/bottle.py
make_response
python
def make_response(body, mimetype='text/html'): from bottle import response response.content_type = mimetype return body or u''
Build a framework specific HTPP response, containing ``body`` and marked as the type ``mimetype``.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/bottle.py#L87-L93
null
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_FORBIDDEN = 403 def get_site_name(request): """Return the domain:port part of the URL without scheme. Eg: facebook.com, 127.0.0.1:8080, etc. """ urlparts = request.urlparts return ':'.join([urlparts.hostn...
jpscaletti/authcode
authcode/auth_authentication_mixin.py
AuthenticationMixin.login
python
def login(self, user, remember=True, session=None): logger = logging.getLogger(__name__) logger.debug(u'User `{0}` logged in'.format(user.login)) if session is None: session = self.session session['permanent'] = remember session[self.session_key] = user.get_uhmac() ...
Sets the current user UID in the session. Instead of just storing the user's id, it generates a hash from the password *salt*. That way, an admin or the user herself can invalidate the login in other computers just by changing (or re-saving) her password.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_authentication_mixin.py#L130-L146
null
class AuthenticationMixin(object): def prepare_password(self, secret): return u'{pepper}{secret}'.format( pepper=to_unicode(self.pepper), secret=to_unicode(secret) ) def hash_password(self, secret): if secret is None: return None len_secret ...
jpscaletti/authcode
authcode/auth_authorization_mixin.py
AuthorizationMixin.protected
python
def protected(self, *tests, **kwargs): _role = kwargs.pop('role', None) _roles = kwargs.pop('roles', None) or [] _csrf = kwargs.pop('csrf', None) _url_sign_in = kwargs.pop('url_sign_in', None) _request = kwargs.pop('request', None) if _role: _roles.append(_ro...
Factory of decorators for limit the access to views. :tests: *function, optional One or more functions that takes the args and kwargs of the view and returns either `True` or `False`. All test must return True to show the view. Options: :role: str, optional...
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_authorization_mixin.py#L31-L117
null
class AuthorizationMixin(object): # Useful for setting a cookie only if the CSRF token has changed. csrf_token_has_changed = False def get_csrf_token(self, session=None): logger = logging.getLogger(__name__) if session is None: session = self.session csrf_token = sessio...
jpscaletti/authcode
authcode/auth_authorization_mixin.py
AuthorizationMixin.replace_flask_route
python
def replace_flask_route(self, bp, *args, **kwargs): protected = self.protected def protected_route(rule, **options): """Like :meth:`Flask.route` but for a blueprint. The endpoint for the :func:`url_for` function is prefixed with the name of the blueprint. """ ...
Replace the Flask `app.route` or `blueprint.route` with a version that first apply the protected decorator to the view, so all views are automatically protected.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/auth_authorization_mixin.py#L119-L136
null
class AuthorizationMixin(object): # Useful for setting a cookie only if the CSRF token has changed. csrf_token_has_changed = False def get_csrf_token(self, session=None): logger = logging.getLogger(__name__) if session is None: session = self.session csrf_token = sessio...
jpscaletti/authcode
authcode/wsgi/werkzeug.py
get_full_path
python
def get_full_path(request): path = request.path if request.query_string: path += '?' + to_native(request.query_string) return path
Return the current relative path including the query string. Eg: “/foo/bar/?page=1”
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L10-L17
[ "def to_native(x, charset='utf8', errors='ignore'):\n bb = to_bytes(x, charset=charset, errors=errors)\n if not bb:\n return bb\n return bb.decode('utf8')\n" ]
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_SEE_OTHER = 303 def make_full_url(request, url): """Get a relative URL and returns the absolute version. Eg: “/foo/bar?q=is-open” ==> “http://example.com/foo/bar?q=is-open” """ return request.url_root + url....
jpscaletti/authcode
authcode/wsgi/werkzeug.py
get_from_params
python
def get_from_params(request, key): data = getattr(request, 'json', None) or request.values value = data.get(key) return to_native(value)
Try to read a value named ``key`` from the GET parameters.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L55-L60
[ "def to_native(x, charset='utf8', errors='ignore'):\n bb = to_bytes(x, charset=charset, errors=errors)\n if not bb:\n return bb\n return bb.decode('utf8')\n" ]
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_SEE_OTHER = 303 def get_full_path(request): """Return the current relative path including the query string. Eg: “/foo/bar/?page=1” """ path = request.path if request.query_string: path += '?' + to...
jpscaletti/authcode
authcode/wsgi/werkzeug.py
get_from_headers
python
def get_from_headers(request, key): value = request.headers.get(key) return to_native(value)
Try to read a value named ``key`` from the headers.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L63-L67
[ "def to_native(x, charset='utf8', errors='ignore'):\n bb = to_bytes(x, charset=charset, errors=errors)\n if not bb:\n return bb\n return bb.decode('utf8')\n" ]
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_SEE_OTHER = 303 def get_full_path(request): """Return the current relative path including the query string. Eg: “/foo/bar/?page=1” """ path = request.path if request.query_string: path += '?' + to...
jpscaletti/authcode
authcode/wsgi/werkzeug.py
make_response
python
def make_response(body, mimetype='text/html'): from werkzeug.wrappers import Response if isinstance(body, Response): body.mimetype = mimetype return body return Response(body, mimetype=mimetype)
Build a framework specific HTPP response, containing ``body`` and marked as the type ``mimetype``.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/wsgi/werkzeug.py#L76-L84
null
# coding=utf-8 from __future__ import absolute_import from .._compat import to_native HTTP_SEE_OTHER = 303 def get_full_path(request): """Return the current relative path including the query string. Eg: “/foo/bar/?page=1” """ path = request.path if request.query_string: path += '?' + to...
jpscaletti/authcode
authcode/utils.py
get_uhmac
python
def get_uhmac(user, secret): secret = to_bytes(secret) key = '|'.join([ hashlib.sha1(secret).hexdigest(), str(user.id), get_hash_extract(user.password), ]) key = key.encode('utf8', 'ignore') mac = hmac.new(key, msg=None, digestmod=hashlib.sha512) mac = mac.hexdigest()[:50...
Make an unique identifier for the user (stored in the session), so it can stay logged between requests. By hashing a snippet of the current password hash salt, it makes possible to automatically logout from all other devices just by changing (or refreshing) the password.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/utils.py#L42-L60
[ "def to_bytes(x, charset='utf8', errors='ignore'):\n if x is None:\n return None\n if isinstance(x, (bytes, bytearray, memoryview)):\n return bytes(x)\n if isinstance(x, str):\n return x.encode(charset, errors)\n raise TypeError('Expected bytes')\n", "def get_hash_extract(hash):\n...
# coding=utf-8 import hashlib import hmac from time import time from ._compat import to_bytes, to_unicode def eval_url(url): if callable(url): url = url() return url def test_hasher(hasher): hasher.encrypt('test', rounds=hasher.min_rounds) def to36(number): assert int(number) >= 0, 'Must ...
jpscaletti/authcode
authcode/utils.py
get_token
python
def get_token(user, secret, timestamp=None): timestamp = int(timestamp or time()) secret = to_bytes(secret) key = '|'.join([ hashlib.sha1(secret).hexdigest(), str(user.id), get_hash_extract(user.password), str(getattr(user, 'last_sign_in', 0)), str(timestamp), ]) ...
Make a timestamped one-time-use token that can be used to identifying the user. By hashing the `last_sign_in` attribute and a snippet of the current password hash salt, it produces a token that will be invalidated as soon as the user log in again or the is changed. A hash of the user ID is used, s...
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/utils.py#L63-L90
[ "def to_bytes(x, charset='utf8', errors='ignore'):\n if x is None:\n return None\n if isinstance(x, (bytes, bytearray, memoryview)):\n return bytes(x)\n if isinstance(x, str):\n return x.encode(charset, errors)\n raise TypeError('Expected bytes')\n", "def get_hash_extract(hash):\n...
# coding=utf-8 import hashlib import hmac from time import time from ._compat import to_bytes, to_unicode def eval_url(url): if callable(url): url = url() return url def test_hasher(hasher): hasher.encrypt('test', rounds=hasher.min_rounds) def to36(number): assert int(number) >= 0, 'Must ...
jpscaletti/authcode
authcode/utils.py
LazyUser.__get_user
python
def __get_user(self): storage = object.__getattribute__(self, '_LazyUser__storage') user = getattr(self.__auth, 'get_user')() setattr(storage, self.__user_name, user) return user
Return the real user object.
train
https://github.com/jpscaletti/authcode/blob/91529b6d0caec07d1452758d937e1e0745826139/authcode/utils.py#L116-L122
null
class LazyUser(object): """Acts as a proxy for the current user. Forwards all operations to the proxied user. The only operations not supported for forwarding are right handed operands and any kind of assignment. """ __slots__ = ('__auth', '__storage', '__dict__') def __init__(self, auth, sto...
bearyinnovative/bearychat.py
bearychat/openapi/client.py
Requester.request
python
def request(self, request_method, api_method, *args, **kwargs): url = self._build_url(api_method) resp = requests.request(request_method, url, *args, **kwargs) try: rv = resp.json() except ValueError: raise RequestFailedError(resp, 'not a json body') if ...
Perform a request. Args: request_method: HTTP method for this request. api_method: API method name for this request. *args: Extra arguments to pass to the request. **kwargs: Extra keyword arguments to pass to the request. Returns: A dict cont...
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/openapi/client.py#L82-L109
[ "def _build_url(self, api_method):\n path = '{}/{}'.format(self.base_url.path, api_method.lstrip('/'))\n url = self.base_url._replace(path=path)\n return urlparse.urlunparse(url).rstrip('/')\n" ]
class Requester(object): def __init__(self, base_url): self.base_url = urlparse.urlparse(base_url.rstrip('/')) def _build_url(self, api_method): path = '{}/{}'.format(self.base_url.path, api_method.lstrip('/')) url = self.base_url._replace(path=path) return urlparse.urlunparse(...
bearyinnovative/bearychat.py
bearychat/incoming.py
validate
python
def validate(data): text = data.get('text') if not isinstance(text, _string_types) or len(text) == 0: raise ValueError('text field is required and should not be empty') if 'markdown' in data and not type(data['markdown']) is bool: raise ValueError('markdown field should be bool') if 'a...
Validates incoming data Args: data(dict): the incoming data Returns: True if the data is valid Raises: ValueError: the data is not valid
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/incoming.py#L13-L40
null
import sys PY3 = sys.version_info[0] == 3 import requests if PY3: _string_types = str, else: _string_types = basestring, # noqa def send(url, data): """Sends an incoming message Args: url(str): the incoming hook url data(dict): the sending data Returns: requests.Resp...
bearyinnovative/bearychat.py
bearychat/incoming.py
send
python
def send(url, data): validate(data) return requests.post(url, json=data)
Sends an incoming message Args: url(str): the incoming hook url data(dict): the sending data Returns: requests.Response
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/incoming.py#L43-L55
[ "def validate(data):\n \"\"\"Validates incoming data\n\n Args:\n data(dict): the incoming data\n\n Returns:\n True if the data is valid\n\n Raises:\n ValueError: the data is not valid\n \"\"\"\n text = data.get('text')\n if not isinstance(text, _string_types) or len(text) =...
import sys PY3 = sys.version_info[0] == 3 import requests if PY3: _string_types = str, else: _string_types = basestring, # noqa def validate(data): """Validates incoming data Args: data(dict): the incoming data Returns: True if the data is valid Raises: ValueErro...
bearyinnovative/bearychat.py
examples/rtm_loop.py
RTMLoop.on_open
python
def on_open(self, ws): def keep_alive(interval): while True: time.sleep(interval) self.ping() start_new_thread(keep_alive, (self.keep_alive_interval, ))
Websocket on_open event handler
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L50-L57
null
class RTMLoop(object): """Real Time Message loop _errors(Queue): contains error message(dict("result", "msg")), looks self._set_error() _inbox(Queue): contains RTMMessage _worker(threading.Thread): a thread for running the loop Args: ws_host(str): websocket host """...
bearyinnovative/bearychat.py
examples/rtm_loop.py
RTMLoop.on_message
python
def on_message(self, ws, message): try: data = json.loads(message) except Exception: self._set_error(message, "decode message failed") else: self._inbox.put(RTMMessage(data))
Websocket on_message event handler Saves message as RTMMessage in self._inbox
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L59-L69
[ "def _set_error(self, result, msg):\n \"\"\"Puts a error to self._errors\n\n Args:\n result(mix): received data\n msg(str): message\n \"\"\"\n self._errors.put({\"result\": result, \"msg\": msg})\n" ]
class RTMLoop(object): """Real Time Message loop _errors(Queue): contains error message(dict("result", "msg")), looks self._set_error() _inbox(Queue): contains RTMMessage _worker(threading.Thread): a thread for running the loop Args: ws_host(str): websocket host """...
bearyinnovative/bearychat.py
examples/rtm_loop.py
RTMLoop.send
python
def send(self, message): if "call_id" not in message: message["call_id"] = self.gen_call_id() self._ws.send(message.to_json())
Sends a RTMMessage Should be called after starting the loop Args: message(RTMMessage): the sending message Raises: WebSocketConnectionClosedException: if the loop is closed
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L120-L133
[ "def gen_call_id(self):\n \"\"\"Generates a call_id\n\n Returns:\n int: the call_id\n \"\"\"\n self._call_id += 1\n return self._call_id\n", "def to_json(self):\n \"\"\"Transfers current message to json\n\n Returns:\n json\n \"\"\"\n return json.dumps(self._data)\n" ]
class RTMLoop(object): """Real Time Message loop _errors(Queue): contains error message(dict("result", "msg")), looks self._set_error() _inbox(Queue): contains RTMMessage _worker(threading.Thread): a thread for running the loop Args: ws_host(str): websocket host """...
bearyinnovative/bearychat.py
examples/rtm_loop.py
RTMLoop.get_message
python
def get_message(self, block=False, timeout=None): try: message = self._inbox.get(block=block, timeout=timeout) return message except Exception: return None
Removes and returns a RTMMessage from self._inbox Args: block(bool): if True block until a RTMMessage is available, else it will return None when self._inbox is empty timeout(int): it blocks at most timeout seconds Returns: RTMMessage if sel...
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L135-L150
null
class RTMLoop(object): """Real Time Message loop _errors(Queue): contains error message(dict("result", "msg")), looks self._set_error() _inbox(Queue): contains RTMMessage _worker(threading.Thread): a thread for running the loop Args: ws_host(str): websocket host """...
bearyinnovative/bearychat.py
examples/rtm_loop.py
RTMLoop.get_error
python
def get_error(self, block=False, timeout=None): try: error = self._errors.get(block=block, timeout=timeout) return error except Exception: return None
Removes and returns an error from self._errors Args: block(bool): if True block until a RTMMessage is available, else it will return None when self._inbox is empty timeout(int): it blocks at most timeout seconds Returns: error if inbox is no...
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/examples/rtm_loop.py#L152-L167
null
class RTMLoop(object): """Real Time Message loop _errors(Queue): contains error message(dict("result", "msg")), looks self._set_error() _inbox(Queue): contains RTMMessage _worker(threading.Thread): a thread for running the loop Args: ws_host(str): websocket host """...
bearyinnovative/bearychat.py
bearychat/rtm_client_service.py
RTMCurrentTeam.members
python
def members(self): resp = self._rtm_client.get('v1/current_team.members?all=true') if resp.is_fail(): raise RTMServiceError( 'Failed to get members of current team', resp ) return resp.data['result']
Gets members of current team Returns: list of User Throws: RTMServiceError when request failed
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L33-L48
null
class RTMCurrentTeam(RTMService): def info(self): """Gets current team infomation Returns: Team if success Throws: RTMServiceError when request failed """ resp = self._rtm_client.get('v1/current_team.info') if resp.is_fail(): rais...
bearyinnovative/bearychat.py
bearychat/rtm_client_service.py
RTMCurrentTeam.channels
python
def channels(self): resp = self._rtm_client.get('v1/current_team.channels') if resp.is_fail(): raise RTMServiceError( 'Failed to get channels of current team', resp ) return resp.data['result']
Gets channels of current team Returns: list of Channel Throws: RTMServiceError when request failed
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L50-L65
null
class RTMCurrentTeam(RTMService): def info(self): """Gets current team infomation Returns: Team if success Throws: RTMServiceError when request failed """ resp = self._rtm_client.get('v1/current_team.info') if resp.is_fail(): rais...
bearyinnovative/bearychat.py
bearychat/rtm_client_service.py
RTMUser.info
python
def info(self, user_id): resp = self._rtm_client.get('v1/user.info?user_id={}'.format(user_id)) if resp.is_fail(): raise RTMServiceError('Failed to get user information', resp) return resp.data['result']
Gets user information by user id Args: user_id(int): the id of user Returns: User Throws: RTMServiceError when request failed
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L69-L85
null
class RTMUser(RTMService):
bearyinnovative/bearychat.py
bearychat/rtm_client_service.py
RTMChannel.info
python
def info(self, channel_id): resource = 'v1/channel.info?channel_id={}'.format(channel_id) resp = self._rtm_client.get(resource) if resp.is_fail(): raise RTMServiceError("Failed to get channel information", resp) return resp.data['result']
Gets channel information by channel id Args: channel_id(int): the id of channel Returns: Channel Throws: RTMServiceError when request failed
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client_service.py#L89-L106
null
class RTMChannel(RTMService):
bearyinnovative/bearychat.py
bearychat/rtm_message.py
RTMMessage.reply
python
def reply(self, text): data = {'text': text, 'vchannel_id': self['vchannel_id']} if self.is_p2p(): data['type'] = RTMMessageType.P2PMessage data['to_uid'] = self['uid'] else: data['type'] = RTMMessageType.ChannelMessage data['channel_id'] = self['c...
Replys a text message Args: text(str): message content Returns: RTMMessage
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_message.py#L53-L69
[ "def is_p2p(self):\n \"\"\"\n Returns:\n True if current message is p2p message\n \"\"\"\n return self['type'] in (RTMMessageType.P2PMessage,\n RTMMessageType.P2PTyping)\n" ]
class RTMMessage(object): """RTM Message Args: data(dict): message dict """ def __init__(self, data): self._data = data self.mention_user_ids = set() self.parse_mention_user_ids() def __setitem__(self, name, value): self._data[name] = value def __getit...
bearyinnovative/bearychat.py
bearychat/rtm_message.py
RTMMessage.refer
python
def refer(self, text): data = self.reply(text) data['refer_key'] = self['key'] return data
Refers current message and replys a new message Args: text(str): message content Returns: RTMMessage
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_message.py#L71-L82
[ "def reply(self, text):\n \"\"\"Replys a text message\n\n Args:\n text(str): message content\n\n Returns:\n RTMMessage\n \"\"\"\n data = {'text': text, 'vchannel_id': self['vchannel_id']}\n if self.is_p2p():\n data['type'] = RTMMessageType.P2PMessage\n data['to_uid'] = ...
class RTMMessage(object): """RTM Message Args: data(dict): message dict """ def __init__(self, data): self._data = data self.mention_user_ids = set() self.parse_mention_user_ids() def __setitem__(self, name, value): self._data[name] = value def __getit...
bearyinnovative/bearychat.py
bearychat/rtm_client.py
RTMClient.start
python
def start(self): resp = self.post('start') if resp.is_fail(): return None if 'result' not in resp.data: return None result = resp.data['result'] return { 'user': result['user'], 'ws_host': result['ws_host'], }
Gets the rtm ws_host and user information Returns: None if request failed, else a dict containing "user"(User) and "ws_host"
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L52-L70
[ "def is_fail(self):\n return not self.is_ok()\n", "def post(self, resource, data=None, json=None):\n \"\"\"Sends a POST request\n\n Returns:\n RTMResponse\n \"\"\"\n return self.do(resource, 'POST', data=data, json=json)\n" ]
class RTMClient(object): """Real Time Message client Attributes: current_team(RTMCurrentTeam): service of current team user(RTMUser): service of current user channel(RTMChannel): service of current channel """ def __init__(self, token, api_base="https://rtm.bearychat.com"): ...
bearyinnovative/bearychat.py
bearychat/rtm_client.py
RTMClient.do
python
def do(self, resource, method, params=None, data=None, json=None, headers=None): uri = "{0}/{1}".format(self._api_base, resource) if not params: params = {} params.update({'token': self._token}) req = Request(...
Does the request job Args: resource(str): resource uri(relative path) method(str): HTTP method params(dict): uri queries data(dict): HTTP body(form) json(dict): HTTP body(json) headers(dict): HTTP headers Returns: RTMR...
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L72-L108
null
class RTMClient(object): """Real Time Message client Attributes: current_team(RTMCurrentTeam): service of current team user(RTMUser): service of current user channel(RTMChannel): service of current channel """ def __init__(self, token, api_base="https://rtm.bearychat.com"): ...
bearyinnovative/bearychat.py
bearychat/rtm_client.py
RTMClient.get
python
def get(self, resource, params=None, headers=None): return self.do(resource, 'GET', params=params, headers=headers)
Sends a GET request Returns: RTMResponse
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L110-L116
[ "def do(self,\n resource,\n method,\n params=None,\n data=None,\n json=None,\n headers=None):\n \"\"\"Does the request job\n\n Args:\n resource(str): resource uri(relative path)\n method(str): HTTP method\n params(dict): uri queries\n data(dict):...
class RTMClient(object): """Real Time Message client Attributes: current_team(RTMCurrentTeam): service of current team user(RTMUser): service of current user channel(RTMChannel): service of current channel """ def __init__(self, token, api_base="https://rtm.bearychat.com"): ...
bearyinnovative/bearychat.py
bearychat/rtm_client.py
RTMClient.post
python
def post(self, resource, data=None, json=None): return self.do(resource, 'POST', data=data, json=json)
Sends a POST request Returns: RTMResponse
train
https://github.com/bearyinnovative/bearychat.py/blob/6c7af2d215c2ff7135bb5af66ca333d0ea1089fd/bearychat/rtm_client.py#L118-L124
[ "def do(self,\n resource,\n method,\n params=None,\n data=None,\n json=None,\n headers=None):\n \"\"\"Does the request job\n\n Args:\n resource(str): resource uri(relative path)\n method(str): HTTP method\n params(dict): uri queries\n data(dict):...
class RTMClient(object): """Real Time Message client Attributes: current_team(RTMCurrentTeam): service of current team user(RTMUser): service of current user channel(RTMChannel): service of current channel """ def __init__(self, token, api_base="https://rtm.bearychat.com"): ...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/base_request.py
BaseRequest.set_logger
python
def set_logger(self): """Method to build the base logging system. By default, logging level is set to INFO.""" logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) logger_file = os.path.join(self.logs_path, 'dingtalk_sdk.logs') logger_handler = l...
Method to build the base logging system. By default, logging level is set to INFO.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/base_request.py#L22-L35
null
class BaseRequest(object): """The base request for dingtalk""" logs_path = os.path.dirname(os.path.abspath(__file__)) request_url = None request_methods_valid = [ "get", "post", "put", "delete", "head", "options", "patch" ] def __init__(self, **kwargs): self.kwargs = kwargs ...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/base_request.py
BaseRequest.get_response
python
def get_response(self): """Get the original response of requests""" request = getattr(requests, self.request_method, None) if request is None and self._request_method is None: raise ValueError("A effective http request method must be set") if self.request_url is None: ...
Get the original response of requests
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/base_request.py#L55-L67
null
class BaseRequest(object): """The base request for dingtalk""" logs_path = os.path.dirname(os.path.abspath(__file__)) request_url = None request_methods_valid = [ "get", "post", "put", "delete", "head", "options", "patch" ] def __init__(self, **kwargs): self.kwargs = kwargs ...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/base_request.py
BaseRequest.get_json_response
python
def get_json_response(self): """This method aims at catching the exception of ValueError, detail: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#json """ self.json_response = self.get_response().json() if self.json_response is not None: error_...
This method aims at catching the exception of ValueError, detail: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#json
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/base_request.py#L69-L77
[ "def get_response(self):\n \"\"\"Get the original response of requests\"\"\"\n request = getattr(requests, self.request_method, None)\n if request is None and self._request_method is None:\n raise ValueError(\"A effective http request method must be set\")\n if self.request_url is None:\n ...
class BaseRequest(object): """The base request for dingtalk""" logs_path = os.path.dirname(os.path.abspath(__file__)) request_url = None request_methods_valid = [ "get", "post", "put", "delete", "head", "options", "patch" ] def __init__(self, **kwargs): self.kwargs = kwargs ...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/authority_request.py
PersistentCodeRequest.get_ticket_for_sns_token
python
def get_ticket_for_sns_token(self): """This is a shortcut for getting the sns_token, as a post data of request body.""" self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return { "openid": self.get_openid(), "persistent_code": self.get_per...
This is a shortcut for getting the sns_token, as a post data of request body.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/authority_request.py#L86-L93
[ "def get_openid(self):\n openid = self.json_response.get(\"openid\", None)\n self.logger.info(\"%s\\t%s\" % (self.request_method, self.request_url))\n return openid\n", "def get_persistent_code(self):\n persistent_code = self.json_response.get(\"persistent_code\", None)\n self.logger.info(\"%s\\t%s...
class PersistentCodeRequest(BaseRequest): """ Description: The persistent_code, openid and unionid are contained in the json response of this api, the parameter <access_token> and post data <tmp_auth_code> is required. parameter_R: <access_token> parameter_O: None post_data_R: <tmp_auth_co...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
WorkNoticeRequest.get_task_id
python
def get_task_id(self): """Method to get all department members.""" task_id = self.json_response.get("task_id", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return task_id
Method to get all department members.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L24-L28
null
class WorkNoticeRequest(BaseRequest): """ Description: The WorkNoticeRequest send work notice to specified user (userid), parameters of <userid_list> and <dept_id_list> should NOT keep null simultaneously, or request would fail parameter_R: <access_token> parameter_O: None post_data_R: <ag...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
GetWorkNoticeSendProgressRequest.get_progress
python
def get_progress(self): """Method to get the progress of work notice sending.""" progress = self.json_response.get("progress", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return progress
Method to get the progress of work notice sending.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L48-L52
null
class GetWorkNoticeSendProgressRequest(BaseRequest): """ Description: The response of GetWorkNoticeSendProgressRequest shows the progress of sending work notice parameter_R: <access_token> parameter_O: None post_data_R: <agent_id>, <msg> post_data_O: <userid_list>, <dept_id_list>, <to_all_...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
GetWorkNoticeSendResultRequest.get_send_result
python
def get_send_result(self): """Method to get the progress of work notice sending.""" send_result = self.json_response.get("send_result", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return send_result
Method to get the progress of work notice sending.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L72-L76
null
class GetWorkNoticeSendResultRequest(BaseRequest): """ Description: The response of GetWorkNoticeSendResultRequest shows the result of sending work notice parameter_R: <access_token> parameter_O: None post_data_R: None post_data_O: <agent_id>, <task_id> Return: send result json respon...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
CreateGroupChatRequest.get_chat_id
python
def get_chat_id(self): """Method to get chatid of group created.""" chat_id = self.json_response.get("chatid", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return chat_id
Method to get chatid of group created.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L96-L100
null
class CreateGroupChatRequest(BaseRequest): """ Description: The CreateGroupChatRequest aims to create a group chat for some user(userid) parameter_R: <access_token> parameter_O: None post_data_R: <name>, <owner>, <useridlist> post_data_O: <showHistoryType> Return: the chatid of group ...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
GetGroupChatRequest.get_chat_info
python
def get_chat_info(self): """Method to get chatid of group created.""" chat_info = self.json_response.get("chat_info", None) self.chat_info = chat_info self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return chat_info
Method to get chatid of group created.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L139-L144
null
class GetGroupChatRequest(BaseRequest): """ Description: The GetGroupChatRequest aims to get information of a existed group chat by chatid parameter_R: <access_token> parameter_O: None post_data_R: <chatid> post_data_O: None Return: the chatid of group create json response doc_li...
gmdzy2010/dingtalk_sdk_gmdzy2010
dingtalk_sdk_gmdzy2010/message_request.py
SendGroupChatRequest.get_message_id
python
def get_message_id(self): """Method to get messageId of group created.""" message_id = self.json_response.get("messageId", None) self.logger.info("%s\t%s" % (self.request_method, self.request_url)) return message_id
Method to get messageId of group created.
train
https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/message_request.py#L168-L172
null
class SendGroupChatRequest(BaseRequest): """ Description: The SendGroupChatRequest aims to send group chat message parameter_R: <access_token> parameter_O: None post_data_R: <chatid>, <msg> post_data_O: None Return: the message id of group chat doc_links: https://open-doc.dingtalk.co...