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 |
|---|---|---|---|---|---|---|---|---|---|
RonenNess/Fileter | fileter/files_iterator.py | FilesIterator.match_filters | python | def match_filters(self, path):
# indicate if all required filters were matched
all_required_match = True
# iterate over filters to match files
for filt, ftype in self.__filters:
# handle "Required" filters:
if all_required_match and ftype == self.FilterType.Requ... | Get filename and return True if file pass all filters and should be processed.
:param path: path to check.
:return: True if pass filters, false otherwise. | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/files_iterator.py#L284-L311 | null | class FilesIterator(object):
"""
Base class to iterate over file sources and perform pre-defined actions on them.
This class can be used in two ways:
1. as an iterator, if you want to iterate files and use them externally.
2. as an object that have pre-defined processing function and can iterate an... |
RonenNess/Fileter | fileter/sources/folder_source.py | FolderSource.next | python | def next(self):
# get depth of starting root directory
base_depth = self.__root.count(os.path.sep)
# walk files and folders
for root, subFolders, files in os.walk(self.__root):
# apply folder filter
if not self.filter_folder(root):
continue
... | Return all files in folder. | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/sources/folder_source.py#L41-L71 | [
"def filter_folder(self, folder):\n \"\"\"\n Optional filter to apply on folders. If return False will skip this whole folder tree.\n \"\"\"\n return True\n"
] | class FolderSource(SourceAPI):
"""
A recirsive folders source to scan.
"""
def __init__(self, root, depth_limit=None, ret_files=True, ret_folders=False):
"""
Init the folders source with root folder.
:param root: root folder to scan.
:param depth_limit: how many levels t... |
RonenNess/Fileter | fileter/filters/extension_filter.py | FilterExtension.match | python | def match(self, filepath):
# no extension?
if filepath.find(".") == -1:
return False
# match extension
return filepath.lower().split(".")[-1] in self.__extensions | The function to check file.
Should return True if match, False otherwise. | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/filters/extension_filter.py#L24-L34 | null | class FilterExtension(FilterAPI):
"""
A simple filter by a file extensions.
"""
def __init__(self, extensions):
"""
Create the extensions filter.
:param extensions: a single extension or a list of extensions to accept.
Note: without the dot, for exampl... |
RonenNess/Fileter | fileter/filters/pattern_filter.py | FilterPattern.match | python | def match(self, filepath):
for pattern in self.__pattern:
if len(fnmatch.filter([filepath], pattern)) > 0:
return True
return False | The function to check file.
Should return True if match, False otherwise. | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/filters/pattern_filter.py#L24-L32 | null | class FilterPattern(FilterAPI):
"""
A simple filter by linux-style file patterns.
"""
def __init__(self, pattern):
"""
Create the extensions filter.
:param pattern: a single pattern or a list of patterns to accept.
"""
self.__pattern = pattern if isinstance(patter... |
RonenNess/Fileter | fileter/iterators/remove_files.py | RemoveFiles.process_file | python | def process_file(self, path, dryrun):
# if dryrun just return file path
if dryrun:
return path
# remove and return file
if self.__force or raw_input("Remove file '%s'? [y/N]" % path).lower() == "y":
os.remove(path)
return path | Remove files and return filename. | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/iterators/remove_files.py#L27-L38 | null | class RemoveFiles(files_iterator.FilesIterator):
"""
This iterator will remove all files.
"""
def __init__(self, force=False):
"""
concat all source files into one output file.
:param force: if true, will just remove all files. Else, will ask for every file before.
"""
... |
RonenNess/Fileter | fileter/sources/files_pattern.py | PatternSource.match_pattern | python | def match_pattern(self, path):
for pattern in self.__pattern:
if len(fnmatch.filter([path], pattern)) > 0:
return True
return False | Return if given path match the pattern(s).
:param path: path to check.
:return: True if match, False otherwise. | train | https://github.com/RonenNess/Fileter/blob/5372221b4049d5d46a9926573b91af17681c81f3/fileter/sources/files_pattern.py#L69-L79 | null | class PatternSource(SourceAPI):
"""
A recursive folders scanner with pattern.
"""
def __init__(self, pattern, root='.', depth_limit=None, ret_files=True, ret_folders=False):
"""
Init the folders source with root folder.
:param pattern: fnmatch pattern(s) to match.
... |
jeroyang/txttk | txttk/report.py | Report.update | python | def update(self, report):
self.tp.extend(pack_boxes(report.tp, self.title))
self.fp.extend(pack_boxes(report.fp, self.title))
self.fn.extend(pack_boxes(report.fn, self.title)) | Add the items from the given report. | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/report.py#L117-L123 | [
"def pack_boxes(list_of_content, tag):\n return [TagBox(content, tag) for content in list_of_content]\n"
] | class Report:
"""
Holding the results of experiment, presenting the precision, recall,
f1 score of the experiment.
"""
def __init__(self, tp=[], fp=[], fn=[], title=None):
"""
tp: the ture positive items
fp: the false positive items
fn: the false negative items
... |
jeroyang/txttk | txttk/report.py | Report.from_scale | python | def from_scale(cls, gold_number, precision, recall, title):
tp_count = get_numerator(recall, gold_number)
positive_count = get_denominator(precision, tp_count)
fp_count = positive_count - tp_count
fn_count = gold_number - tp_count
scale_report = cls(['tp'] * tp_count,
... | deprecated, for backward compactbility
try to use from_score | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/report.py#L150-L163 | [
"def get_numerator(ratio, max_denominator):\n fraction = Fraction.from_float(ratio).limit_denominator(max_denominator)\n return int(fraction.numerator * max_denominator / fraction.denominator)\n",
"def get_denominator(ratio, max_numerator):\n return get_numerator(1/ratio, max_numerator)\n"
] | class Report:
"""
Holding the results of experiment, presenting the precision, recall,
f1 score of the experiment.
"""
def __init__(self, tp=[], fp=[], fn=[], title=None):
"""
tp: the ture positive items
fp: the false positive items
fn: the false negative items
... |
jeroyang/txttk | txttk/retools.py | condense | python | def condense(ss_unescaped):
def estimated_len(longg, short):
return (3
+ len(short)
+ sum(map(len, longg))
- len(longg)
* (len(short) - 1)
- 1 )
def stupid_len(longg):
return sum(map(len, longg)) + len(longg)
s... | Given multiple strings, returns a compressed regular expression just
for these strings
>>> condense(['she', 'he', 'her', 'hemoglobin'])
'he(moglobin|r)?|she' | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L10-L73 | [
"def estimated_len(longg, short):\n return (3\n + len(short)\n + sum(map(len, longg))\n - len(longg)\n * (len(short) - 1)\n - 1 )\n",
"def stupid_len(longg):\n return sum(map(len, longg)) + len(longg)\n"
] | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import defaultdict, OrderedDict
from itertools import combinations
import re
def is_solid(regex):
"""
Check the given regular expression... |
jeroyang/txttk | txttk/retools.py | is_solid | python | def is_solid(regex):
shape = re.sub(r'(\\.|[^\[\]\(\)\|\?\+\*])', '#', regex)
skeleton = shape.replace('#', '')
if len(shape) <= 1:
return True
if re.match(r'^\[[^\]]*\][\*\+\?]?$', shape):
return True
if re.match(r'^\([^\(]*\)[\*\+\?]?$', shape):
return True
if re.match... | Check the given regular expression is solid.
>>> is_solid(r'a')
True
>>> is_solid(r'[ab]')
True
>>> is_solid(r'(a|b|c)')
True
>>> is_solid(r'(a|b|c)?')
True
>>> is_solid(r'(a|b)(c)')
False
>>> is_solid(r'(a|b)(c)?')
False | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L75-L104 | null | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import defaultdict, OrderedDict
from itertools import combinations
import re
def condense(ss_unescaped):
"""
Given multiple strings, retu... |
jeroyang/txttk | txttk/retools.py | danger_unpack | python | def danger_unpack(regex):
if is_packed(regex):
return re.sub(r'^\((\?(:|P<.*?>))?(?P<content>.*?)\)$', r'\g<content>', regex)
else:
return regex | Remove the outermost parens
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'abc'
>>> unpack(r'[abc]')
'[abc]' | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L122-L139 | [
"def is_packed(regex):\n \"\"\"\n Check if the regex is solid and packed into a pair of parens\n \"\"\"\n return is_solid(regex) and regex[0] == '('\n"
] | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import defaultdict, OrderedDict
from itertools import combinations
import re
def condense(ss_unescaped):
"""
Given multiple strings, retu... |
jeroyang/txttk | txttk/retools.py | unpack | python | def unpack(regex):
if is_packed(regex) and not regex.startswith('(?P<'):
return re.sub(r'^\((\?:)?(?P<content>.*?)\)$', r'\g<content>', regex)
else:
return regex | Remove the outermost parens, keep the (?P...) one
>>> unpack(r'(abc)')
'abc'
>>> unpack(r'(?:abc)')
'abc'
>>> unpack(r'(?P<xyz>abc)')
'(?P<xyz>abc)'
>>> unpack(r'[abc]')
'[abc]' | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L141-L157 | [
"def is_packed(regex):\n \"\"\"\n Check if the regex is solid and packed into a pair of parens\n \"\"\"\n return is_solid(regex) and regex[0] == '('\n"
] | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import defaultdict, OrderedDict
from itertools import combinations
import re
def condense(ss_unescaped):
"""
Given multiple strings, retu... |
jeroyang/txttk | txttk/retools.py | parallel | python | def parallel(regex_list, sort=False):
if sort:
regex_list = sorted(regex_list, key=len, reverse=True)
return '|'.join([unpack(regex) for regex in regex_list]) | Join the given regexes using r'|'
if the sort=True, regexes will be sorted by lenth before processing
>>> parallel([r'abc', r'def'])
'abc|def'
>>> parallel([r'abc', r'd|ef'])
'abc|def'
>>> parallel([r'abc', r'(d|ef)'])
'abc|d|ef'
>>> parallel([r'abc', r'defg'])
'defg|abc' | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L159-L175 | null | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import defaultdict, OrderedDict
from itertools import combinations
import re
def condense(ss_unescaped):
"""
Given multiple strings, retu... |
jeroyang/txttk | txttk/retools.py | nocatch | python | def nocatch(regex):
if is_solid(regex) and not is_packed(regex):
return regex
else:
return '(?:{})'.format(danger_unpack(regex)) | Put on a pair of parens (with no catch tag) outside the regex,
if the regex is not yet packed;
modified the outmost parens by adding nocatch tag | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L177-L186 | [
"def is_solid(regex):\n \"\"\"\n Check the given regular expression is solid.\n\n >>> is_solid(r'a')\n True\n >>> is_solid(r'[ab]')\n True\n >>> is_solid(r'(a|b|c)')\n True\n >>> is_solid(r'(a|b|c)?')\n True\n >>> is_solid(r'(a|b)(c)')\n False\n >>> is_solid(r'(a|b)(c)?')\n ... | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import defaultdict, OrderedDict
from itertools import combinations
import re
def condense(ss_unescaped):
"""
Given multiple strings, retu... |
jeroyang/txttk | txttk/retools.py | concat | python | def concat(regex_list):
output_list = []
for regex in regex_list:
output_list.append(consolidate(regex))
return r''.join(output_list) | Concat multiple regular expression into one, if the given regular expression is not packed,
a pair of paren will be add.
>>> reg_1 = r'a|b'
>>> reg_2 = r'(c|d|e)'
>>> concat([reg_1, reg2])
(a|b)(c|d|e) | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/retools.py#L188-L202 | [
"def consolidate(regex):\n \"\"\"\n Put on a pair of parens (with no catch tag) outside the regex,\n if the regex is not yet consolidated\n \"\"\"\n if is_solid(regex):\n return regex\n else:\n return '({})'.format(regex)\n"
] | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import defaultdict, OrderedDict
from itertools import combinations
import re
def condense(ss_unescaped):
"""
Given multiple strings, retu... |
jeroyang/txttk | txttk/nlptools.py | sent_tokenize | python | def sent_tokenize(context):
# Define the regular expression
paired_symbols = [("(", ")"),
("[", "]"),
("{", "}")]
paired_patterns = ["%s.*?%s" % (re.escape(lt), re.escape(rt)) for lt, rt in paired_symbols]
number_pattern = ['\d+\.\d+']
arr_pattern = ['(?: \w\.){2... | Cut the given context into sentences.
Avoid a linebreak in between paried symbols, float numbers, and some abbrs.
Nothing will be discard after sent_tokeinze, simply ''.join(sents) will get the original context.
Evey whitespace, tab, linebreak will be kept.
>>> context = "I love you. Please don't leave... | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L12-L45 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
from itertools import chain, combinations, cycle, islice
from collections import namedtuple
def sent_count(context):
"""
... |
jeroyang/txttk | txttk/nlptools.py | clause_tokenize | python | def clause_tokenize(sentence):
clause_re = re.compile(r'((?:\S+\s){2,}\S+,|(?:\S+\s){3,}(?=\((?:\S+\s){2,}\S+\)))')
clause_stem = clause_re.sub(r'\1###clausebreak###', sentence)
return [c for c in clause_stem.split('###clausebreak###') if c != ''] | Split on comma or parenthesis, if there are more then three words for each clause
>>> context = 'While I was walking home, this bird fell down in front of me.'
>>> clause_tokenize(context)
['While I was walking home,', ' this bird fell down in front of me.'] | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L57-L68 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
from itertools import chain, combinations, cycle, islice
from collections import namedtuple
def sent_tokenize(context):
"""
... |
jeroyang/txttk | txttk/nlptools.py | word_tokenize | python | def word_tokenize(sentence):
date_pattern = r'\d\d(\d\d)?[\\-]\d\d[\\-]\d\d(\d\d)?'
number_pattern = r'[\+-]?(\d+\.\d+|\d{1,3},(\d{3},)*\d{3}|\d+)'
arr_pattern = r'(?: \w\.){2,3}|(?:\A|\s)(?:\w\.){2,3}|[A-Z]\. [a-z]'
word_pattern = r'[\w]+'
non_space_pattern = r'[{}]|\w'.format(re.escape('!"#$%&()*,... | A generator which yields tokens based on the given sentence without deleting anything.
>>> context = "I love you. Please don't leave."
>>> list(word_tokenize(context))
['I', ' ', 'love', ' ', 'you', '.', ' ', 'Please', ' ', 'don', "'", 't', ' ', 'leave', '.'] | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L70-L89 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
from itertools import chain, combinations, cycle, islice
from collections import namedtuple
def sent_tokenize(context):
"""
... |
jeroyang/txttk | txttk/nlptools.py | slim_stem | python | def slim_stem(token):
target_sulfixs = ['ic', 'tic', 'e', 'ive', 'ing', 'ical', 'nal', 'al', 'ism', 'ion', 'ation', 'ar', 'sis', 'us', 'ment']
for sulfix in sorted(target_sulfixs, key=len, reverse=True):
if token.endswith(sulfix):
token = token[0:-len(sulfix)]
break
if token.... | A very simple stemmer, for entity of GO stemming.
>>> token = 'interaction'
>>> slim_stem(token)
'interact' | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L91-L107 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
from itertools import chain, combinations, cycle, islice
from collections import namedtuple
def sent_tokenize(context):
"""
... |
jeroyang/txttk | txttk/nlptools.py | ngram | python | def ngram(n, iter_tokens):
z = len(iter_tokens)
return (iter_tokens[i:i+n] for i in range(z-n+1)) | Return a generator of n-gram from an iterable | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L116-L121 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
from itertools import chain, combinations, cycle, islice
from collections import namedtuple
def sent_tokenize(context):
"""
... |
jeroyang/txttk | txttk/nlptools.py | power_ngram | python | def power_ngram(iter_tokens):
return chain.from_iterable(ngram(j, iter_tokens) for j in range(1, len(iter_tokens) + 1)) | Generate unigram, bigram, trigram ... and the max-gram,
different from powerset(), this function will not generate skipped combinations such as (1,3) | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L123-L128 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
from itertools import chain, combinations, cycle, islice
from collections import namedtuple
def sent_tokenize(context):
"""
... |
jeroyang/txttk | txttk/nlptools.py | count_start | python | def count_start(tokenizer):
def wrapper(context, base):
tokens = list(tokenizer(context))
flag = 0
for token in tokens:
start = context.index(token, flag)
flag = start + len(token)
yield (token, base + start)
return wrapper | A decorator which wrap the given tokenizer to yield (token, start).
Notice! the decorated tokenizer must take a int arguments stands for the start position of the input context/sentence
>>> tokenizer = lambda sentence: sentence.split(' ')
>>> tokenizer('The quick brown fox jumps over the lazy dog')
['T... | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/nlptools.py#L130-L154 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
from itertools import chain, combinations, cycle, islice
from collections import namedtuple
def sent_tokenize(context):
"""
... |
jeroyang/txttk | txttk/feature.py | lexical | python | def lexical(token):
lowercase = token.lower()
first4 = lowercase[:4]
last4 = lowercase[-4:]
return OrderedDict([
('lowercase', lowercase),
('first4', first4),
('last4', last4)
]) | Extract lexical features from given token
There are 3 kinds of lexical features, take 'Hello' as an example:
1. lowercase: 'hello'
2. first4: 'hell'
3. last4: 'ello' | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/feature.py#L12-L28 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import OrderedDict
import re
import string
def _char_shape(char):
if char in string.ascii_uppercase:
return '... |
jeroyang/txttk | txttk/feature.py | orthographic | python | def orthographic(token):
return OrderedDict([
('shape', _shape(token)),
('length', len(token)),
('contains_a_letter', _contains_a_letter(token)),
('contains_a_capital', _contains_a_capital(token)),
('begins_with_... | Extract orthographic features from a given token
There are 11 kinds of orthographic features, take 'Windows10' as an example:
1. shape: 'Aaaaaaa00'
2. length: 9
3. contains_a_letter: True
4. contains_a_capital: True
5. begins_with_capital: True
6. all_capital: False
7. contains_a_d... | train | https://github.com/jeroyang/txttk/blob/8e6daf9cbb7dfbc4900870fb365add17929bd4ab/txttk/feature.py#L93-L124 | [
"def _shape(token):\n return ''.join([_char_shape(char) for char in token])\n",
"def _contains_a_letter(token):\n regex = r'[A-Za-z]'\n if re.search(regex, token):\n return True\n else:\n return False\n",
"def _contains_a_capital(token):\n regex = r'[A-Z]'\n if re.search(regex, t... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from collections import OrderedDict
import re
import string
def lexical(token):
"""
Extract lexical features from given token
T... |
delfick/gitmit | gitmit/mit.py | GitTimes.relpath_for | python | def relpath_for(self, path):
if self.parent_dir in (".", ""):
return path
if path == self.parent_dir:
return ""
dirname = os.path.dirname(path) or "."
basename = os.path.basename(path)
cached = self.relpath_cache.get(dirname, empty)
if cached is... | Find the relative path from here from the parent_dir | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L57-L72 | null | class GitTimes(object):
"""
Responsible for determining what files we want commit times for and then
finding those commit times.
The order is something like:
* Git root under ``root_folder``
* Files under ``parent_dir`` relative to the git root
* Only including those files in ``timestamps_... |
delfick/gitmit | gitmit/mit.py | GitTimes.find | python | def find(self):
mtimes = {}
git = Repo(self.root_folder)
all_files = git.all_files()
use_files = set(self.find_files_for_use(all_files))
# the git index won't find the files under a symlink :(
# And we include files under a symlink as seperate copies of the files
... | Find all the files we want to find commit times for, and any extra files
under symlinks.
Then find the commit times for those files and return a dictionary of
{relative_path: commit_time_as_epoch} | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L74-L101 | [
"def commit_times_for(self, git, use_files):\n \"\"\"\n Return commit times for the use_files specified.\n\n We will use a cache of commit times if self.with_cache is Truthy.\n\n Finally, we yield (relpath: epoch) pairs where path is relative\n to self.parent_dir and epoch is the commit time in UTC f... | class GitTimes(object):
"""
Responsible for determining what files we want commit times for and then
finding those commit times.
The order is something like:
* Git root under ``root_folder``
* Files under ``parent_dir`` relative to the git root
* Only including those files in ``timestamps_... |
delfick/gitmit | gitmit/mit.py | GitTimes.commit_times_for | python | def commit_times_for(self, git, use_files):
# Use real_relpath if it exists (SymlinkdPath) and default to just the path
# This is because we _want_ to compare the commits to the _real paths_
# As git only cares about the symlink itself, rather than files under it
# We also want to make s... | Return commit times for the use_files specified.
We will use a cache of commit times if self.with_cache is Truthy.
Finally, we yield (relpath: epoch) pairs where path is relative
to self.parent_dir and epoch is the commit time in UTC for that path. | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L103-L150 | [
"def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):\n \"\"\"\n Get the cached commit times for the combination of this parent_dir and relpaths\n\n Return the commit assigned to this combination and the actual times!\n \"\"\"\n result = get_all_cached_commit_times(root_folder)\n\n ... | class GitTimes(object):
"""
Responsible for determining what files we want commit times for and then
finding those commit times.
The order is something like:
* Git root under ``root_folder``
* Files under ``parent_dir`` relative to the git root
* Only including those files in ``timestamps_... |
delfick/gitmit | gitmit/mit.py | GitTimes.extra_symlinked_files | python | def extra_symlinked_files(self, potential_symlinks):
for key in list(potential_symlinks):
location = os.path.join(self.root_folder, key.path)
real_location = os.path.realpath(location)
if os.path.islink(location) and os.path.isdir(real_location):
for root, di... | Find any symlinkd folders and yield SymlinkdPath objects for each file
that is found under the symlink. | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L152-L181 | null | class GitTimes(object):
"""
Responsible for determining what files we want commit times for and then
finding those commit times.
The order is something like:
* Git root under ``root_folder``
* Files under ``parent_dir`` relative to the git root
* Only including those files in ``timestamps_... |
delfick/gitmit | gitmit/mit.py | GitTimes.find_files_for_use | python | def find_files_for_use(self, all_files):
for path in all_files:
# Find the path relative to the parent dir
relpath = self.relpath_for(path)
# Don't care about the ./
if relpath.startswith("./"):
relpath = relpath[2:]
# Only care about... | Given a list of all the files to consider, only yield Path objects
for those we care about, given our filters | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L183-L198 | [
"def relpath_for(self, path):\n \"\"\"Find the relative path from here from the parent_dir\"\"\"\n if self.parent_dir in (\".\", \"\"):\n return path\n\n if path == self.parent_dir:\n return \"\"\n\n dirname = os.path.dirname(path) or \".\"\n basename = os.path.basename(path)\n\n cac... | class GitTimes(object):
"""
Responsible for determining what files we want commit times for and then
finding those commit times.
The order is something like:
* Git root under ``root_folder``
* Files under ``parent_dir`` relative to the git root
* Only including those files in ``timestamps_... |
delfick/gitmit | gitmit/mit.py | GitTimes.is_filtered | python | def is_filtered(self, relpath):
# Only include files under the parent_dir
if relpath.startswith("../"):
return True
# Ignore files that we don't want timestamps from
if self.timestamps_for is not None and type(self.timestamps_for) is list:
match = False
... | Say whether this relpath is filtered out | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/mit.py#L200-L234 | null | class GitTimes(object):
"""
Responsible for determining what files we want commit times for and then
finding those commit times.
The order is something like:
* Git root under ``root_folder``
* Files under ``parent_dir`` relative to the git root
* Only including those files in ``timestamps_... |
delfick/gitmit | gitmit/repo.py | Repo.all_files | python | def all_files(self):
return set([entry.decode() for entry, _ in self.git.open_index().items()]) | Return a set of all the files under git control | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/repo.py#L45-L47 | null | class Repo(object):
"""
Wrapper around a libgit Repository that knows:
* How to get all the files in the repository
* How to get the oid of HEAD
* How to get the commit times of the files we want commit times for
It's written with speed in mind, given the constraints of making
performant c... |
delfick/gitmit | gitmit/repo.py | Repo.file_commit_times | python | def file_commit_times(self, use_files_paths, debug=False):
prefixes = PrefixTree()
prefixes.fill(use_files_paths)
for entry in self.git.get_walker():
# Commit time taking into account the timezone
commit_time = entry.commit.commit_time - entry.commit.commit_timezone
... | Traverse the commits in the repository, starting from HEAD until we have
found the commit times for all the files we care about.
Yield each file once, only when it is found to be changed in some commit.
If self.debug is true, also output log.debug for the speed we are going
through com... | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/repo.py#L54-L99 | [
"def fill(self, paths):\n \"\"\"\n Initialise the tree.\n\n paths is a list of strings where each string is the relative path to some\n file.\n \"\"\"\n for path in paths:\n tree = self.tree\n parts = tuple(path.split('/'))\n dir_parts = parts[:-1]\n built = ()\n ... | class Repo(object):
"""
Wrapper around a libgit Repository that knows:
* How to get all the files in the repository
* How to get the oid of HEAD
* How to get the commit times of the files we want commit times for
It's written with speed in mind, given the constraints of making
performant c... |
delfick/gitmit | gitmit/repo.py | Repo.entries_in_tree_oid | python | def entries_in_tree_oid(self, prefix, tree_oid):
try:
tree = self.git.get_object(tree_oid)
except KeyError:
log.warning("Couldn't find object {0}".format(tree_oid))
return empty
else:
return frozenset(self.entries_in_tree(prefix, tree)) | Find the tree at this oid and return entries prefixed with ``prefix`` | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/repo.py#L101-L109 | [
"def entries_in_tree(self, prefix, tree):\n \"\"\"\n Traverse the entries in this tree and yield (prefix, is_tree, oid)\n\n Where prefix is a tuple of the given prefix and the name of the entry.\n \"\"\"\n for entry in tree.items():\n if prefix:\n new_prefix = prefix + (entry.path.d... | class Repo(object):
"""
Wrapper around a libgit Repository that knows:
* How to get all the files in the repository
* How to get the oid of HEAD
* How to get the commit times of the files we want commit times for
It's written with speed in mind, given the constraints of making
performant c... |
delfick/gitmit | gitmit/repo.py | Repo.entries_in_tree | python | def entries_in_tree(self, prefix, tree):
for entry in tree.items():
if prefix:
new_prefix = prefix + (entry.path.decode(), )
else:
new_prefix = (entry.path.decode(), )
yield (new_prefix, stat.S_ISDIR(entry.mode), entry.sha) | Traverse the entries in this tree and yield (prefix, is_tree, oid)
Where prefix is a tuple of the given prefix and the name of the entry. | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/repo.py#L111-L123 | null | class Repo(object):
"""
Wrapper around a libgit Repository that knows:
* How to get all the files in the repository
* How to get the oid of HEAD
* How to get the commit times of the files we want commit times for
It's written with speed in mind, given the constraints of making
performant c... |
delfick/gitmit | gitmit/repo.py | Repo.tree_structures_for | python | def tree_structures_for(self, prefix, current_oid, parent_oids, prefixes):
if prefix and prefixes and prefix not in prefixes:
return empty, empty
parent_files = set()
for oid in parent_oids:
parent_files.update(self.entries_in_tree_oid(prefix, oid))
current_file... | Return the entries for this commit, the entries of the parent commits,
and the difference between the two (current_files - parent_files) | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/repo.py#L125-L138 | [
"def entries_in_tree_oid(self, prefix, tree_oid):\n \"\"\"Find the tree at this oid and return entries prefixed with ``prefix``\"\"\"\n try:\n tree = self.git.get_object(tree_oid)\n except KeyError:\n log.warning(\"Couldn't find object {0}\".format(tree_oid))\n return empty\n else:\... | class Repo(object):
"""
Wrapper around a libgit Repository that knows:
* How to get all the files in the repository
* How to get the oid of HEAD
* How to get the commit times of the files we want commit times for
It's written with speed in mind, given the constraints of making
performant c... |
delfick/gitmit | gitmit/repo.py | Repo.differences_between | python | def differences_between(self, current_files, parent_files, changes, prefixes):
parent_oid = None
if any(is_tree for _, is_tree, _ in changes):
if len(changes) == 1:
wanted_path = list(changes)[0][0]
parent_oid = frozenset([oid for path, is_tree, oid in parent... | yield (thing, changes, is_path)
If is_path is true, changes is None and thing is the path as a tuple.
If is_path is false, thing is the current_files and parent_files for
that changed treeentry and changes is the difference between current_files
and parent_files.
The code here... | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/repo.py#L140-L176 | null | class Repo(object):
"""
Wrapper around a libgit Repository that knows:
* How to get all the files in the repository
* How to get the oid of HEAD
* How to get the commit times of the files we want commit times for
It's written with speed in mind, given the constraints of making
performant c... |
delfick/gitmit | gitmit/cache.py | get_all_cached_commit_times | python | def get_all_cached_commit_times(root_folder):
result = []
location = cache_location(root_folder)
if os.path.exists(location):
try:
result = json.load(open(location))
except (TypeError, ValueError) as error:
log.warning("Failed to open gitmit cached commit_times\tloca... | Find the gitmit cached commit_times and return them if they are the right shape.
This means the file is a list of dictionaries.
If they aren't, issue a warning and return an empty list, it is just a cache
after all! | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L20-L42 | [
"def cache_location(root_folder):\n \"\"\"\n Return us the location to the commit times cache\n\n This is <root_folder>/.git/gitmit_cached_commit_times.json\n \"\"\"\n return os.path.join(root_folder, \".git\", \"gitmit_cached_commit_times.json\")\n"
] | """
This holds the functionality to write and read a cache of the modified times
for a repository.
"""
import logging
import json
import os
log = logging.getLogger("gitmit.cache")
def cache_location(root_folder):
"""
Return us the location to the commit times cache
This is <root_folder>/.git/gitmit_cach... |
delfick/gitmit | gitmit/cache.py | get_cached_commit_times | python | def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):
result = get_all_cached_commit_times(root_folder)
for item in result:
if sorted(item.get("sorted_relpaths", [])) == sorted_relpaths and item.get("parent_dir") == parent_dir:
return item.get("commit"), item.get("commit_ti... | Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times! | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L44-L56 | [
"def get_all_cached_commit_times(root_folder):\n \"\"\"\n Find the gitmit cached commit_times and return them if they are the right shape.\n\n This means the file is a list of dictionaries.\n\n If they aren't, issue a warning and return an empty list, it is just a cache\n after all!\n \"\"\"\n ... | """
This holds the functionality to write and read a cache of the modified times
for a repository.
"""
import logging
import json
import os
log = logging.getLogger("gitmit.cache")
def cache_location(root_folder):
"""
Return us the location to the commit times cache
This is <root_folder>/.git/gitmit_cach... |
delfick/gitmit | gitmit/cache.py | set_cached_commit_times | python | def set_cached_commit_times(root_folder, parent_dir, first_commit, commit_times, sorted_relpaths):
current = get_all_cached_commit_times(root_folder)
location = cache_location(root_folder)
found = False
for item in current:
if sorted(item.get("sorted_relpaths", [])) == sorted_relpaths and item.... | Set the cached commit times in a json file at cache_location(root_folder)
We first get what is currently in the cache and either modify the existing
entry for this combo of parent_dir and sorted_relpaths.
Or add to the entries.
We then ensure there's less than 5 entries to keep the cache from growing... | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/cache.py#L58-L96 | [
"def cache_location(root_folder):\n \"\"\"\n Return us the location to the commit times cache\n\n This is <root_folder>/.git/gitmit_cached_commit_times.json\n \"\"\"\n return os.path.join(root_folder, \".git\", \"gitmit_cached_commit_times.json\")\n",
"def get_all_cached_commit_times(root_folder):\... | """
This holds the functionality to write and read a cache of the modified times
for a repository.
"""
import logging
import json
import os
log = logging.getLogger("gitmit.cache")
def cache_location(root_folder):
"""
Return us the location to the commit times cache
This is <root_folder>/.git/gitmit_cach... |
delfick/gitmit | gitmit/prefix_tree.py | PrefixTree.fill | python | def fill(self, paths):
for path in paths:
tree = self.tree
parts = tuple(path.split('/'))
dir_parts = parts[:-1]
built = ()
for part in dir_parts:
self.cache[built] = tree
built += (part, )
parent = tree
... | Initialise the tree.
paths is a list of strings where each string is the relative path to some
file. | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L59-L80 | null | class PrefixTree(object):
"""
Holds a linked list like structure for traversal and a cache of
("path", "to", "folder") to the tree representing that folder.
Each Tree is an instance of TreeItem, as initialised after calling
PrefixTree#fill.
The idea is you fill the tree once and then remove fi... |
delfick/gitmit | gitmit/prefix_tree.py | PrefixTree.remove | python | def remove(self, prefix, name):
tree = self.cache.get(prefix, empty)
if tree is empty:
return False
if name not in tree.files:
return False
tree.files.remove(name)
self.remove_folder(tree, list(prefix))
return True | Remove a path from the tree
prefix is a tuple of the parts in the dirpath
name is a string representing the name of the file itself.
Any empty folders from the point of the file backwards to the root of
the tree is removed. | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L82-L103 | [
"def remove_folder(self, tree, prefix):\n \"\"\"\n Used to remove any empty folders\n\n If this folder is empty then it is removed. If the parent is empty as a\n result, then the parent is also removed, and so on.\n \"\"\"\n while True:\n child = tree\n tree = tree.parent\n\n ... | class PrefixTree(object):
"""
Holds a linked list like structure for traversal and a cache of
("path", "to", "folder") to the tree representing that folder.
Each Tree is an instance of TreeItem, as initialised after calling
PrefixTree#fill.
The idea is you fill the tree once and then remove fi... |
delfick/gitmit | gitmit/prefix_tree.py | PrefixTree.remove_folder | python | def remove_folder(self, tree, prefix):
while True:
child = tree
tree = tree.parent
if not child.folders and not child.files:
del self.cache[tuple(prefix)]
if tree:
del tree.folders[prefix.pop()]
if not tree or ... | Used to remove any empty folders
If this folder is empty then it is removed. If the parent is empty as a
result, then the parent is also removed, and so on. | train | https://github.com/delfick/gitmit/blob/ae0aef14a06b25ad2811f8f47cc97e68a0910eae/gitmit/prefix_tree.py#L105-L122 | null | class PrefixTree(object):
"""
Holds a linked list like structure for traversal and a cache of
("path", "to", "folder") to the tree representing that folder.
Each Tree is an instance of TreeItem, as initialised after calling
PrefixTree#fill.
The idea is you fill the tree once and then remove fi... |
emencia/emencia-django-forum | forum/models.py | Category.get_last_thread | python | def get_last_thread(self):
cache_key = '_get_last_thread_cache'
if not hasattr(self, cache_key):
item = None
res = self.thread_set.filter(visible=True).order_by('-modified')[0:1]
if len(res)>0:
item = res[0]
setattr(self, cache_key, item)
... | Return the last modified thread | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L31-L42 | null | class Category(models.Model):
"""
Category
"""
created = models.DateTimeField(_("created"), auto_now_add=True)
slug = models.SlugField(_('slug'), unique=True, max_length=50)
order = models.SmallIntegerField(_('order'))
title = models.CharField(_("title"), blank=False, max_length=255, unique=... |
emencia/emencia-django-forum | forum/models.py | Thread.get_first_post | python | def get_first_post(self):
cache_key = '_get_starter_cache'
if not hasattr(self, cache_key):
item = None
res = self.post_set.all().order_by('created')[0:1]
if len(res)>0:
item = res[0]
setattr(self, cache_key, item)
return getattr(se... | Retourne le premier post en date, celui créé lors de la création du fil | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L73-L84 | null | class Thread(models.Model):
"""
Thread
"""
created = models.DateTimeField(_("created"), editable=False, null=True, blank=True)
modified = models.DateTimeField(_("modified"), editable=False, null=True, blank=True, help_text=_("This only filled when a message is added."))
author = models.ForeignKe... |
emencia/emencia-django-forum | forum/models.py | Thread.save | python | def save(self, *args, **kwargs):
if self.created is None:
self.created = tz_now()
if self.modified is None:
self.modified = self.created
super(Thread, self).save(*args, **kwargs) | Fill 'created' and 'modified' attributes on first create | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L99-L109 | null | class Thread(models.Model):
"""
Thread
"""
created = models.DateTimeField(_("created"), editable=False, null=True, blank=True)
modified = models.DateTimeField(_("modified"), editable=False, null=True, blank=True, help_text=_("This only filled when a message is added."))
author = models.ForeignKe... |
emencia/emencia-django-forum | forum/models.py | Post.get_paginated_urlargs | python | def get_paginated_urlargs(self):
position = self.get_paginated_position()
if not position:
return '#forum-post-{0}'.format(self.id)
return '?page={0}#forum-post-{1}'.format(position, self.id) | Return url arguments to retrieve the Post in a paginated list | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L150-L159 | [
"def get_paginated_position(self):\n \"\"\"\n Return the Post position in the paginated list\n \"\"\"\n # If Post list is not paginated\n if not settings.FORUM_THREAD_DETAIL_PAGINATE:\n return 0\n\n count = Post.objects.filter(thread=self.thread_id, created__lt=self.created).count() + 1\n\n... | class Post(models.Model):
"""
Thread message
"""
author = models.ForeignKey(User, verbose_name=_("author"), blank=False)
thread = models.ForeignKey(Thread, verbose_name=_("thread"))
created = models.DateTimeField(_("created"), editable=False, blank=True, null=True)
modified = models.DateTime... |
emencia/emencia-django-forum | forum/models.py | Post.get_paginated_position | python | def get_paginated_position(self):
# If Post list is not paginated
if not settings.FORUM_THREAD_DETAIL_PAGINATE:
return 0
count = Post.objects.filter(thread=self.thread_id, created__lt=self.created).count() + 1
return int(math.ceil(count / float(settings.FORU... | Return the Post position in the paginated list | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L161-L171 | null | class Post(models.Model):
"""
Thread message
"""
author = models.ForeignKey(User, verbose_name=_("author"), blank=False)
thread = models.ForeignKey(Thread, verbose_name=_("thread"))
created = models.DateTimeField(_("created"), editable=False, blank=True, null=True)
modified = models.DateTime... |
emencia/emencia-django-forum | forum/models.py | Post.save | python | def save(self, *args, **kwargs):
edited = not(self.created is None)
if self.created is None:
self.created = tz_now()
# Update de la date de modif. du message
if self.modified is None:
self.modified = self.created
else:
self.mo... | Fill 'created' and 'modified' attributes on first create and allways update
the thread's 'modified' attribute | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/models.py#L173-L194 | null | class Post(models.Model):
"""
Thread message
"""
author = models.ForeignKey(User, verbose_name=_("author"), blank=False)
thread = models.ForeignKey(Thread, verbose_name=_("thread"))
created = models.DateTimeField(_("created"), editable=False, blank=True, null=True)
modified = models.DateTime... |
emencia/emencia-django-forum | forum/forms/crispies.py | category_helper | python | def category_helper(form_tag=True):
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
helper.layout = Layout(
Row(
Column(
'title',
css_class='small-12'
),
),
... | Category's form layout helper | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L9-L53 | null | """
Crispy forms layouts
"""
from django.utils.translation import ugettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, ButtonHolderPanel, Submit
def category_helper(form_tag=True):
"""
Category's form layout helper
"""
helper = F... |
emencia/emencia-django-forum | forum/forms/crispies.py | thread_helper | python | def thread_helper(form_tag=True, edit_mode=False, for_moderator=False):
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'subject',
css_class='small-12'
... | Thread's form layout helper | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L57-L145 | null | """
Crispy forms layouts
"""
from django.utils.translation import ugettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, ButtonHolderPanel, Submit
def category_helper(form_tag=True):
"""
Category's form layout helper
"""
helper = F... |
emencia/emencia-django-forum | forum/forms/crispies.py | post_helper | python | def post_helper(form_tag=True, edit_mode=False):
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'text',
css_class='small-12'
),
),
... | Post's form layout helper | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L148-L186 | null | """
Crispy forms layouts
"""
from django.utils.translation import ugettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, ButtonHolderPanel, Submit
def category_helper(form_tag=True):
"""
Category's form layout helper
"""
helper = F... |
emencia/emencia-django-forum | forum/forms/crispies.py | post_delete_helper | python | def post_delete_helper(form_tag=True):
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
helper.layout = Layout(
ButtonHolderPanel(
Row(
Column(
'confirm',
css_c... | Message's delete form layout helper | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/crispies.py#L191-L215 | null | """
Crispy forms layouts
"""
from django.utils.translation import ugettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import Layout, Row, Column, ButtonHolderPanel, Submit
def category_helper(form_tag=True):
"""
Category's form layout helper
"""
helper = F... |
emencia/emencia-django-forum | forum/forms/thread.py | ThreadCreateForm.clean_text | python | def clean_text(self):
text = self.cleaned_data.get("text")
validation_helper = safe_import_module(settings.FORUM_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, text)
else:
return text | Text content validation | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/thread.py#L43-L52 | [
"def safe_import_module(path, default=None):\n \"\"\"\n Try to import the specified module from the given Python path\n\n @path is a string containing a Python path to the wanted module, @default is \n an object to return if import fails, it can be None, a callable or whatever you need.\n\n Return a ... | class ThreadCreateForm(CrispyFormMixin, forms.ModelForm):
"""
Thread's create form
"""
crispy_form_helper_path = 'forum.forms.crispies.thread_helper'
crispy_form_helper_kwargs = {}
text = forms.CharField(label=_('Message'), required=True, widget=forms.Textarea(attrs={'cols':'50'}))
threadwa... |
emencia/emencia-django-forum | forum/markup.py | clean_restructuredtext | python | def clean_restructuredtext(form_instance, content):
if content:
errors = SourceReporter(content)
if errors:
raise ValidationError(map(map_parsing_errors, errors))
return content | RST syntax validation | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/markup.py#L20-L28 | null | """
Some markup utilities for RST and DjangoCodeMirror usage
"""
from django.forms import ValidationError
from rstview.parser import SourceReporter, map_parsing_errors
from djangocodemirror.fields import DjangoCodeMirrorField
def get_text_field(form_instance, **kwargs):
"""
Return a DjangoCodeMirrorField fie... |
emencia/emencia-django-forum | forum/views/post.py | PostEditView.get_object | python | def get_object(self, *args, **kwargs):
self.category_instance = get_object_or_404(Category, slug=self.kwargs['category_slug'])
return get_object_or_404(Post, thread__id=self.kwargs['thread_id'], thread__category=self.category_instance, pk=self.kwargs['post_id']) | Should memoize the object to avoid multiple query if get_object is used many times in the view | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/views/post.py#L42-L47 | null | class PostEditView(LoginRequiredMixin, ModeratorCheckMixin, generic.UpdateView):
"""
Message edit view
Restricted to message owner and moderators
"""
model = Post
form_class = PostEditForm
template_name = 'forum/post/form.html'
context_object_name = "post_instance"
def check_permi... |
emencia/emencia-django-forum | forum/forms/category.py | CategoryForm.clean_description | python | def clean_description(self):
description = self.cleaned_data.get("description")
validation_helper = safe_import_module(settings.FORUM_TEXT_VALIDATOR_HELPER_PATH)
if validation_helper is not None:
return validation_helper(self, description)
else:
return description | Text content validation | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/forms/category.py#L29-L38 | [
"def safe_import_module(path, default=None):\n \"\"\"\n Try to import the specified module from the given Python path\n\n @path is a string containing a Python path to the wanted module, @default is \n an object to return if import fails, it can be None, a callable or whatever you need.\n\n Return a ... | class CategoryForm(CrispyFormMixin, forms.ModelForm):
"""
Category form
"""
crispy_form_helper_path = 'forum.forms.crispies.category_helper'
def __init__(self, *args, **kwargs):
super(CategoryForm, self).__init__(*args, **kwargs)
super(forms.ModelForm, self).__init__(*args, **kwargs... |
emencia/emencia-django-forum | forum/admin.py | ThreadAdmin.save_model | python | def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
if not(instance.created):
instance.author = request.user
instance.save()
form.save_m2m()
return instance | Surclasse la méthode de sauvegarde de l'admin du modèle pour y
rajouter automatiquement l'auteur qui créé l'objet | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/admin.py#L9-L20 | null | class ThreadAdmin(admin.ModelAdmin):
|
emencia/emencia-django-forum | forum/mixins.py | ModeratorCheckMixin.check_moderator_permissions | python | def check_moderator_permissions(self, request):
has_perms = self.has_moderator_permissions(request)
# Return a forbidden response if no permission has been finded
if not has_perms:
raise PermissionDenied
return False | Check if user have global or per object permission (on category
instance and on thread instance), finally return a 403 response if no
permissions has been finded.
If a permission has been finded, return False, then the dispatcher
should so return the "normal" response from th... | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/mixins.py#L18-L33 | [
"def has_moderator_permissions(self, request):\n \"\"\"\n Find if user have global or per object permission firstly on category instance, \n if not then on thread instance\n \"\"\"\n return any(request.user.has_perm(perm) for perm in self.permission_required)\n"
] | class ModeratorCheckMixin(object):
"""
Mixin to include checking for moderator permission on category or thread
"""
permission_required = ['forum.moderate_category', 'forum.moderate_thread']
def check_moderator_permissions(self, request):
"""
Check if user have global or per object ... |
emencia/emencia-django-forum | forum/mixins.py | ModeratorCheckMixin.has_moderator_permissions | python | def has_moderator_permissions(self, request):
return any(request.user.has_perm(perm) for perm in self.permission_required) | Find if user have global or per object permission firstly on category instance,
if not then on thread instance | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/mixins.py#L35-L40 | null | class ModeratorCheckMixin(object):
"""
Mixin to include checking for moderator permission on category or thread
"""
permission_required = ['forum.moderate_category', 'forum.moderate_thread']
def check_moderator_permissions(self, request):
"""
Check if user have global or per object ... |
emencia/emencia-django-forum | forum/utils/imports.py | safe_import_module | python | def safe_import_module(path, default=None):
if path is None:
return default
dot = path.rindex('.')
module_name = path[:dot]
class_name = path[dot + 1:]
try:
_class = getattr(import_module(module_name), class_name)
return _class
except (ImportError, AttributeError):
... | Try to import the specified module from the given Python path
@path is a string containing a Python path to the wanted module, @default is
an object to return if import fails, it can be None, a callable or whatever you need.
Return a object or None | train | https://github.com/emencia/emencia-django-forum/blob/cda74ed7e5822675c340ee5ec71548d981bccd3b/forum/utils/imports.py#L6-L26 | null | # -*- coding: utf-8 -*-
import warnings
from django.utils.importlib import import_module
def safe_import_module(path, default=None):
"""
Try to import the specified module from the given Python path
@path is a string containing a Python path to the wanted module, @default is
an object to return if i... |
foxx/python-helpful | helpful.py | unique_iter | python | def unique_iter(seq):
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] | See http://www.peterbe.com/plog/uniqifiers-benchmark
Originally f8 written by Dave Kirby | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L55-L61 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | ensure_subclass | python | def ensure_subclass(value, types):
ensure_class(value)
if not issubclass(value, types):
raise TypeError(
"expected subclass of {}, not {}".format(
types, value)) | Ensure value is a subclass of types
>>> class Hello(object): pass
>>> ensure_subclass(Hello, Hello)
>>> ensure_subclass(object, Hello)
Traceback (most recent call last):
TypeError: | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L157-L171 | [
"def ensure_class(obj):\n \"\"\"\n Ensure object is a class\n\n >>> ensure_class(object)\n >>> ensure_class(object())\n Traceback (most recent call last):\n TypeError:\n >>> ensure_class(1)\n Traceback (most recent call last):\n TypeError:\n \"\"\"\n if not inspect.isclass(obj):\n ... | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | ensure_instance | python | def ensure_instance(value, types):
if not isinstance(value, types):
raise TypeError(
"expected instance of {}, got {}".format(
types, value)) | Ensure value is an instance of a certain type
>>> ensure_instance(1, [str])
Traceback (most recent call last):
TypeError:
>>> ensure_instance(1, str)
Traceback (most recent call last):
TypeError:
>>> ensure_instance(1, int)
>>> ensure_instance(1, (int, str))
:attr types: Type of ... | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L173-L193 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | iter_ensure_instance | python | def iter_ensure_instance(iterable, types):
ensure_instance(iterable, Iterable)
[ ensure_instance(item, types) for item in iterable ] | Iterate over object and check each item type
>>> iter_ensure_instance([1,2,3], [str])
Traceback (most recent call last):
TypeError:
>>> iter_ensure_instance([1,2,3], int)
>>> iter_ensure_instance(1, int)
Traceback (most recent call last):
TypeError: | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L196-L209 | [
"def ensure_instance(value, types):\n \"\"\"\n Ensure value is an instance of a certain type\n\n >>> ensure_instance(1, [str])\n Traceback (most recent call last):\n TypeError:\n\n >>> ensure_instance(1, str)\n Traceback (most recent call last):\n TypeError:\n\n >>> ensure_instance(1, int... | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | import_recursive | python | def import_recursive(path):
results = {}
obj = importlib.import_module(path)
results[path] = obj
path = getattr(obj, '__path__', os.path.dirname(obj.__file__))
for loader, name, is_pkg in pkgutil.walk_packages(path):
full_name = obj.__name__ + '.' + name
results[full_name] = importli... | Recursively import all modules and packages
Thanks http://stackoverflow.com/a/25562415/1267398
XXX: Needs UT
:attr path: Path to package/module | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L224-L241 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | extend_instance | python | def extend_instance(instance, *bases, **kwargs):
last = kwargs.get('last', False)
bases = tuple(bases)
for base in bases:
assert inspect.isclass(base), "bases must be classes"
assert not inspect.isclass(instance)
base_cls = instance.__class__
base_cls_name = instance.__class__.__name__
... | Apply subclass (mixin) to a class object or its instance
By default, the mixin is placed at the start of bases
to ensure its called first as per MRO. If you wish to
have it injected last, which is useful for monkeypatching,
then you can specify 'last=True'. See here:
http://stackoverflow.com/a/1001... | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L244-L281 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | add_bases | python | def add_bases(cls, *bases):
assert inspect.isclass(cls), "Expected class object"
for mixin in bases:
assert inspect.isclass(mixin), "Expected class object for bases"
new_bases = (bases + cls.__bases__)
cls.__bases__ = new_bases | Add bases to class
>>> class Base(object): pass
>>> class A(Base): pass
>>> class B(Base): pass
>>> issubclass(A, B)
False
>>> add_bases(A, B)
>>> issubclass(A, B)
True | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L284-L301 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | subclass | python | def subclass(cls, *bases, **kwargs):
last = kwargs.get('last', False)
bases = tuple(bases)
for base in bases:
assert inspect.isclass(base), "bases must be classes"
new_bases = (cls,)+bases if last else bases+(cls,)
new_cls = type(cls.__name__, tuple(new_bases), {})
return new_cls | Add bases to class (late subclassing)
Annoyingly we cannot yet modify __bases__ of an existing
class, instead we must create another subclass, see here;
http://bugs.python.org/issue672115
>>> class A(object): pass
>>> class B(object): pass
>>> class C(object): pass
>>> issubclass(B, A)
... | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L304-L329 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | import_from_path | python | def import_from_path(path):
try:
return importlib.import_module(path)
except ImportError:
if '.' not in path:
raise
module_name, attr_name = path.rsplit('.', 1)
if not does_module_exist(module_name):
raise ImportError("No object found at '{}'".format(path)... | Imports a package, module or attribute from path
Thanks http://stackoverflow.com/a/14050282/1267398
>>> import_from_path('os.path')
<module 'posixpath' ...
>>> import_from_path('os.path.basename')
<function basename at ...
>>> import_from_path('os')
<module 'os' from ...
>>> import_from... | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L332-L365 | [
"def does_module_exist(path):\n \"\"\"\n Check if Python module exists at path\n\n >>> does_module_exist('os.path')\n True\n >>> does_module_exist('dummy.app')\n False\n \"\"\"\n try:\n importlib.import_module(path)\n return True\n except ImportError:\n return False\n... | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | sort_dict_by_key | python | def sort_dict_by_key(obj):
sort_func = lambda x: x[0]
return OrderedDict(sorted(obj.items(), key=sort_func)) | Sort dict by its keys
>>> sort_dict_by_key(dict(c=1, b=2, a=3, d=4))
OrderedDict([('a', 3), ('b', 2), ('c', 1), ('d', 4)]) | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L384-L392 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | generate_random_token | python | def generate_random_token(length=32):
chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits)
return ''.join(random.choice(chars) for _ in range(length)) | Generate random secure token
>>> len(generate_random_token())
32
>>> len(generate_random_token(6))
6 | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L395-L405 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | default | python | def default(*args, **kwargs):
default = kwargs.get('default', None)
for arg in args:
if arg:
return arg
return default | Return first argument which is "truthy"
>>> default(None, None, 1)
1
>>> default(None, None, 123)
123
>>> print(default(None, None))
None | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L408-L423 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | urljoin | python | def urljoin(*args):
value = "/".join(map(lambda x: str(x).strip('/'), args))
return "/{}".format(value) | Joins given arguments into a url, removing duplicate slashes
Thanks http://stackoverflow.com/a/11326230/1267398
>>> urljoin('/lol', '///lol', '/lol//')
'/lol/lol/lol' | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L426-L435 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | is_int | python | def is_int(value):
ensure_instance(value, (int, str, bytes, float, Decimal))
if isinstance(value, int):
return True
elif isinstance(value, float):
return False
elif isinstance(value, Decimal):
return str(value).isdigit()
elif isinstance(value, (str, bytes)):
return va... | Check if value is an int
:type value: int, str, bytes, float, Decimal
>>> is_int(123), is_int('123'), is_int(Decimal('10'))
(True, True, True)
>>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1'))
(False, False, False)
>>> is_int(object)
Traceback (most recent call last):
TypeError: | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L455-L478 | [
"def ensure_instance(value, types):\n \"\"\"\n Ensure value is an instance of a certain type\n\n >>> ensure_instance(1, [str])\n Traceback (most recent call last):\n TypeError:\n\n >>> ensure_instance(1, str)\n Traceback (most recent call last):\n TypeError:\n\n >>> ensure_instance(1, int... | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | padded_split | python | def padded_split(value, sep, maxsplit=None, pad=None):
result = value.split(sep, maxsplit)
if maxsplit is not None:
result.extend(
[pad] * (1+maxsplit-len(result)))
return result | Modified split() to include padding
See http://code.activestate.com/lists/python-ideas/3366/
:attr value: see str.split()
:attr sep: see str.split()
:attr maxsplit: see str.split()
:attr pad: Value to use for padding maxsplit
>>> padded_split('text/html', ';', 1)
['text/html', None]
>>... | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L481-L508 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | coerce_to_bytes | python | def coerce_to_bytes(x, charset=sys.getdefaultencoding(), errors='strict'):
PY2 = sys.version_info[0] == 2
if PY2: # pragma: nocover
if x is None:
return None
if isinstance(x, (bytes, bytearray, buffer)):
return bytes(x)
if isinstance(x, unicode):
retur... | Coerce value to bytes
>>> a = coerce_to_bytes('hello')
>>> assert isinstance(a, bytes)
>>> a = coerce_to_bytes(b'hello')
>>> assert isinstance(a, bytes)
>>> a = coerce_to_bytes(None)
>>> assert a is None
>>> coerce_to_bytes(object())
Traceback (most recent call last):
...
TypeEr... | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L511-L543 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | random_date_between | python | def random_date_between(start_date, end_date):
assert isinstance(start_date, datetime.date)
delta_secs = int((end_date - start_date).total_seconds())
delta = datetime.timedelta(seconds=random.randint(0, delta_secs))
return (start_date + delta) | Return random date between start/end | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L567-L572 | null | import six
import os
import shutil
import warnings
import tempfile
import importlib
import pkgutil
import inspect
import string
import random
import sys
import itertools
import datetime
from decimal import Decimal
from collections import OrderedDict, Iterable
if six.PY2: # pragma: nocover
text_type = unicode
... |
foxx/python-helpful | helpful.py | Tempfile.cleanup | python | def cleanup(self):
for path in self.paths:
if isinstance(path, tuple):
os.close(path[0])
os.unlink(path[1])
else:
shutil.rmtree(path)
self.paths = [] | Remove any created temp paths | train | https://github.com/foxx/python-helpful/blob/e31ad9bdf45051d8b9a0d1808d214e2293c3bbed/helpful.py#L599-L607 | null | class Tempfile(object):
"""
Tempfile wrapper with cleanup support
XXX: Needs UT
"""
def __init__(self):
self.paths = []
def mkstemp(self, *args, **kwargs):
path = tempfile.mkstemp(*args, **kwargs)
self.paths.append(path)
return path
def mkdtemp(self, *args... |
dstufft/crust | crust/utils.py | subclass_exception | python | def subclass_exception(name, parents, module, attached_to=None):
class_dict = {'__module__': module}
if attached_to is not None:
def __reduce__(self):
# Exceptions are special - they've got state that isn't
# in self.__dict__. We assume it is all in self.args.
return ... | Create exception subclass.
If 'attached_to' is supplied, the exception will be created in a way that
allows it to be pickled, assuming the returned exception class will be added
as an attribute to the 'attached_to' class. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/utils.py#L7-L28 | null | def unpickle_inner_exception(klass, exception_name):
# Get the exception class from the class it is attached to:
exception = getattr(klass, exception_name)
return exception.__new__(exception)
|
dstufft/crust | crust/resources.py | Resource.save | python | def save(self, force_insert=False, force_update=False):
if force_insert and force_update:
raise ValueError("Cannot force both insert and updating in resource saving.")
data = {}
for name, field in self._meta.fields.items():
if field.serialize:
data[name]... | Saves the current instance. Override this in a subclass if you want to
control the saving process.
The 'force_insert' and 'force_update' parameters can be used to insist
that the "save" must be a POST or PUT respectively. Normally, they
should not be set. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/resources.py#L129-L164 | null | class Resource(six.with_metaclass(ResourceBase, object)):
def __init__(self, resource_uri=None, *args, **kwargs):
self.resource_uri = resource_uri
for name, field in self._meta.fields.items():
val = kwargs.pop(name, None)
setattr(self, name, field.hydrate(val))
def __r... |
dstufft/crust | crust/resources.py | Resource.delete | python | def delete(self):
if self.resource_uri is None:
raise ValueError("{0} object cannot be deleted because resource_uri attribute cannot be None".format(self._meta.resource_name))
self._meta.api.http_resource("DELETE", self.resource_uri) | Deletes the current instance. Override this in a subclass if you want to
control the deleting process. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/resources.py#L166-L174 | null | class Resource(six.with_metaclass(ResourceBase, object)):
def __init__(self, resource_uri=None, *args, **kwargs):
self.resource_uri = resource_uri
for name, field in self._meta.fields.items():
val = kwargs.pop(name, None)
setattr(self, name, field.hydrate(val))
def __r... |
dstufft/crust | crust/api.py | Api.http_resource | python | def http_resource(self, method, url, params=None, data=None):
url = urllib_parse.urljoin(self.url, url)
url = url if url.endswith("/") else url + "/"
headers = None
if method.lower() in self.unsupported_methods:
headers = {"X-HTTP-Method-Override": method.upper()}
... | Makes an HTTP request. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/api.py#L69-L87 | null | class Api(object):
resources = {}
unsupported_methods = []
def __init__(self, session=None, *args, **kwargs):
super(Api, self).__init__(*args, **kwargs)
if session is None:
session = requests.session()
self.session = session
self.unsupported_methods = [metho... |
dstufft/crust | crust/query.py | Query.clone | python | def clone(self, klass=None, memo=None, **kwargs):
obj = Empty()
obj.__class__ = klass or self.__class__
obj.resource = self.resource
obj.filters = self.filters.copy()
obj.order_by = self.order_by
obj.low_mark = self.low_mark
obj.high_mark = self.high_mark
... | Creates a copy of the current instance. The 'kwargs' parameter can be
used by clients to update attributes after copying has taken place. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L35-L53 | null | class Query(object):
"""
A single API query.
"""
def __init__(self, resource, *args, **kwargs):
super(Query, self).__init__(*args, **kwargs)
self.resource = resource
self.filters = {}
self.order_by = None
self.low_mark = 0
self.high_mark = None
d... |
dstufft/crust | crust/query.py | Query.set_limits | python | def set_limits(self, low=None, high=None):
if high is not None:
if self.high_mark is not None:
self.high_mark = min(self.high_mark, self.low_mark + high)
else:
self.high_mark = self.low_mark + high
if low is not None:
if self.high_mark ... | Adjusts the limits on the rows retrieved. We use low/high to set these,
as it makes it more Pythonic to read and write. When the API query is
created, they are converted to the appropriate offset and limit values.
Any limits passed in here are applied relative to the existing
constraint... | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L80-L99 | null | class Query(object):
"""
A single API query.
"""
def __init__(self, resource, *args, **kwargs):
super(Query, self).__init__(*args, **kwargs)
self.resource = resource
self.filters = {}
self.order_by = None
self.low_mark = 0
self.high_mark = None
de... |
dstufft/crust | crust/query.py | Query.results | python | def results(self, limit=100):
limited = True if self.high_mark is not None else False
rmax = self.high_mark - self.low_mark if limited else None
rnum = 0
params = self.get_params()
params["offset"] = self.low_mark
params["limit"] = limit
while not limited and rm... | Yields the results from the API, efficiently handling the pagination and
properly passing all paramaters. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L101-L132 | [
"def get_params(self):\n params = {}\n\n # Apply filters\n params.update(self.filters)\n\n # Apply Ordering\n if self.order_by is not None:\n params[\"order_by\"] = self.order_by\n\n return params\n"
] | class Query(object):
"""
A single API query.
"""
def __init__(self, resource, *args, **kwargs):
super(Query, self).__init__(*args, **kwargs)
self.resource = resource
self.filters = {}
self.order_by = None
self.low_mark = 0
self.high_mark = None
de... |
dstufft/crust | crust/query.py | Query.delete | python | def delete(self):
uris = [obj["resource_uri"] for obj in self.results()]
data = self.resource._meta.api.resource_serialize({"objects": [], "deleted_objects": uris})
self.resource._meta.api.http_resource("PATCH", self.resource._meta.resource_name, data=data)
return len(uris) | Deletes the results of this query, it first fetches all the items to be
deletes and then issues a PATCH against the list uri of the resource. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L134-L143 | [
"def results(self, limit=100):\n \"\"\"\n Yields the results from the API, efficiently handling the pagination and\n properly passing all paramaters.\n \"\"\"\n limited = True if self.high_mark is not None else False\n rmax = self.high_mark - self.low_mark if limited else None\n rnum = 0\n\n ... | class Query(object):
"""
A single API query.
"""
def __init__(self, resource, *args, **kwargs):
super(Query, self).__init__(*args, **kwargs)
self.resource = resource
self.filters = {}
self.order_by = None
self.low_mark = 0
self.high_mark = None
de... |
dstufft/crust | crust/query.py | Query.get_count | python | def get_count(self):
params = self.get_params()
params["offset"] = self.low_mark
params["limit"] = 1
r = self.resource._meta.api.http_resource("GET", self.resource._meta.resource_name, params=params)
data = self.resource._meta.api.resource_deserialize(r.text)
number = d... | Gets the total_count using the current filter constraints. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L157-L176 | [
"def get_params(self):\n params = {}\n\n # Apply filters\n params.update(self.filters)\n\n # Apply Ordering\n if self.order_by is not None:\n params[\"order_by\"] = self.order_by\n\n return params\n"
] | class Query(object):
"""
A single API query.
"""
def __init__(self, resource, *args, **kwargs):
super(Query, self).__init__(*args, **kwargs)
self.resource = resource
self.filters = {}
self.order_by = None
self.low_mark = 0
self.high_mark = None
de... |
dstufft/crust | crust/query.py | QuerySet.iterator | python | def iterator(self):
for item in self.query.results():
obj = self.resource(**item)
yield obj | An iterator over the results from applying this QuerySet to the api. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L335-L343 | null | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet.count | python | def count(self):
if self._result_cache is not None and not self._iter:
return len(self._result_cache)
return self.query.get_count() | Returns the number of records as an integer.
If the QuerySet is already fully cached this simply returns the length
of the cached results set to avoid an api call. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L345-L355 | null | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet.get | python | def get(self, *args, **kwargs):
clone = self.filter(*args, **kwargs)
if self.query.can_filter():
clone = clone.order_by()
num = len(clone)
if num == 1:
return clone._result_cache[0]
if not num:
raise self.resource.DoesNotExist(
... | Performs the query and returns a single object matching the given
keyword arguments. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L357-L380 | [
"def filter(self, **kwargs):\n \"\"\"\n Returns a new QuerySet instance with the args ANDed to the existing\n set.\n \"\"\"\n if kwargs:\n assert self.query.can_filter(), \"Cannot filter a query once a slice has been taken.\"\n\n clone = self._clone()\n clone.query.add_filters(**kwargs)\... | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet.create | python | def create(self, **kwargs):
obj = self.resource(**kwargs)
obj.save(force_insert=True)
return obj | Creates a new object with the given kwargs, saving it to the api
and returning the created object. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L382-L389 | null | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet.get_or_create | python | def get_or_create(self, **kwargs):
assert kwargs, "get_or_create() must be passed at least one keyword argument"
defaults = kwargs.pop("defaults", {})
lookup = kwargs.copy()
try:
return self.get(**lookup), False
except self.resource.DoesNotExist:
params ... | Looks up an object with the given kwargs, creating one if necessary.
Returns a tuple of (object, created), where created is a boolean
specifying whether an object was created. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L391-L409 | [
"def get(self, *args, **kwargs):\n \"\"\"\n Performs the query and returns a single object matching the given\n keyword arguments.\n \"\"\"\n clone = self.filter(*args, **kwargs)\n\n if self.query.can_filter():\n clone = clone.order_by()\n\n num = len(clone)\n\n if num == 1:\n ... | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet.delete | python | def delete(self):
assert self.query.can_filter(), "Cannot use 'limit' or 'offset' with delete."
del_query = self._clone()
# Disable non-supported fields.
del_query.query.clear_ordering()
return del_query.query.delete() | Deletes the records in the current QuerySet. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L411-L422 | null | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet.filter | python | def filter(self, **kwargs):
if kwargs:
assert self.query.can_filter(), "Cannot filter a query once a slice has been taken."
clone = self._clone()
clone.query.add_filters(**kwargs)
return clone | Returns a new QuerySet instance with the args ANDed to the existing
set. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L439-L450 | [
"def _clone(self, klass=None, setup=False, **kwargs):\n if klass is None:\n klass = self.__class__\n\n query = self.query.clone()\n\n c = klass(resource=self.resource, query=query)\n c.__dict__.update(kwargs)\n\n return c\n"
] | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet.order_by | python | def order_by(self, field_name=None):
assert self.query.can_filter(), "Cannot reorder a query once a slice has been taken."
clone = self._clone()
clone.query.clear_ordering()
if field_name is not None:
clone.query.add_ordering(field_name)
return clone | Returns a new QuerySet instance with the ordering changed. | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L452-L464 | null | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
dstufft/crust | crust/query.py | QuerySet._fill_cache | python | def _fill_cache(self, num=None):
if self._iter:
try:
for i in range(num or ITER_CHUNK_SIZE):
self._result_cache.append(next(self._iter))
except StopIteration:
self._iter = None | Fills the result cache with 'num' more entries (or until the results
iterator is exhausted). | train | https://github.com/dstufft/crust/blob/5d4011ecace12fd3f68a03a17dbefb78390a9fc0/crust/query.py#L501-L511 | null | class QuerySet(object):
"""
Represents a lazy api lookup for a set of objects.
"""
def __init__(self, resource, query=None, *args, **kwargs):
super(QuerySet, self).__init__(*args, **kwargs)
self.resource = resource
self.query = query or Query(self.resource)
self._resul... |
Othernet-Project/conz | conz/console.py | Console.pstd | python | def pstd(self, *args, **kwargs):
kwargs['file'] = self.out
self.print(*args, **kwargs)
sys.stdout.flush() | Console to STDOUT | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L67-L71 | [
"def print(self, *args, **kwargs):\n \"\"\" Thin wrapper around print\n\n All other methods must go through this method for all printing needs.\n \"\"\"\n print(*args, **kwargs)\n"
] | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.perr | python | def perr(self, *args, **kwargs):
kwargs['file'] = self.err
self.print(*args, **kwargs)
sys.stderr.flush() | Console to STERR | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L73-L77 | [
"def print(self, *args, **kwargs):\n \"\"\" Thin wrapper around print\n\n All other methods must go through this method for all printing needs.\n \"\"\"\n print(*args, **kwargs)\n"
] | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.pok | python | def pok(self, val, ok='OK'):
self.pstd(self.color.green('{}: {}'.format(val, ok))) | Print val: OK in green on STDOUT | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L79-L81 | [
"def pstd(self, *args, **kwargs):\n \"\"\" Console to STDOUT \"\"\"\n kwargs['file'] = self.out\n self.print(*args, **kwargs)\n sys.stdout.flush()\n"
] | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Othernet-Project/conz | conz/console.py | Console.png | python | def png(self, val, ng='ERR'):
self.pstd(self.color.red('{}: {}'.format(val, ng))) | Print val: ERR in red on STDOUT | train | https://github.com/Othernet-Project/conz/blob/051214fa95a837c21595b03426a2c54c522d07a0/conz/console.py#L83-L85 | [
"def pstd(self, *args, **kwargs):\n \"\"\" Console to STDOUT \"\"\"\n kwargs['file'] = self.out\n self.print(*args, **kwargs)\n sys.stdout.flush()\n"
] | class Console:
"""
Wrapper around print with helper methods that cover typical ``print()``
usage in console programs.
"""
ProgressEnd = progress.ProgressEnd
ProgressOK = progress.ProgressOK
ProgressAbrt = progress.ProgressAbrt
color = ansi_colors.color
def __init__(self, verbose=F... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.