signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def packet_queue(self, pkt): | pkt.pos = <NUM_LIT:0><EOL>pkt.to_process = pkt.packet_length<EOL>self.out_packet.append(pkt)<EOL>return NC.ERR_SUCCESS<EOL> | Enqueue packet to out_packet queue. | f3688:c0:m5 |
def packet_write(self): | bytes_written = <NUM_LIT:0><EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN, bytes_written<EOL><DEDENT>while len(self.out_packet) > <NUM_LIT:0>:<EOL><INDENT>pkt = self.out_packet[<NUM_LIT:0>]<EOL>write_length, status = nyamuk_net.write(self.sock, pkt.payload)<EOL>if write_length > <NUM_LIT:0>:<... | Write packet to network. | f3688:c0:m6 |
def packet_read(self): | bytes_received = <NUM_LIT:0><EOL>if self.sock == NC.INVALID_SOCKET:<EOL><INDENT>return NC.ERR_NO_CONN<EOL><DEDENT>if self.in_packet.command == <NUM_LIT:0>:<EOL><INDENT>ba_data, errnum, errmsg = nyamuk_net.read(self.sock, <NUM_LIT:1>)<EOL>if errnum == <NUM_LIT:0> and len(ba_data) == <NUM_LIT:1>:<EOL><INDENT>bytes_receiv... | Read packet from network. | f3688:c0:m7 |
def socket_close(self): | if self.sock != NC.INVALID_SOCKET:<EOL><INDENT>self.sock.close()<EOL><DEDENT>self.sock = NC.INVALID_SOCKET<EOL> | Close our socket. | f3688:c0:m8 |
def build_publish_pkt(self, mid, topic, payload, qos, retain, dup): | pkt = MqttPkt()<EOL>payloadlen = len(payload)<EOL>packetlen = <NUM_LIT:2> + len(topic) + payloadlen<EOL>if qos > <NUM_LIT:0>:<EOL><INDENT>packetlen += <NUM_LIT:2><EOL><DEDENT>pkt.mid = mid<EOL>pkt.command = NC.CMD_PUBLISH | ((dup & <NUM_LIT>) << <NUM_LIT:3>) | (qos << <NUM_LIT:1>) | retain<EOL>pkt.remaining_length = pa... | Build PUBLISH packet. | f3688:c0:m10 |
def send_simple_command(self, cmd): | pkt = MqttPkt()<EOL>pkt.command = cmd<EOL>pkt.remaining_length = <NUM_LIT:0><EOL>ret = pkt.alloc()<EOL>if ret != NC.ERR_SUCCESS:<EOL><INDENT>return ret<EOL><DEDENT>return self.packet_queue(pkt)<EOL> | Send simple mqtt commands. | f3688:c0:m11 |
def register(model): | moderator.register(model, Akismet)<EOL> | Just a wrapper around django_comments.moderation.register.
It's only argument is the model for comment moderation. | f3690:m0 |
def allow(self, comment, content_object, request): | POST = urlencode({<EOL>"<STR_LIT>": settings.AKISMET_BLOG.encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": comment.ip_address,<EOL>"<STR_LIT>": request.META.get('<STR_LIT>', "<STR_LIT>").<EOL>encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>": request.META.get('<STR_LIT>', "<STR_LIT>").<EOL>encode("<STR_LIT:utf-8>"),<EOL>"<STR_LIT>... | Moderates comments. | f3690:c1:m0 |
def spammer_view(request): | <EOL>context = RequestContext(request, {})<EOL>template = Template("<STR_LIT>")<EOL>response = HttpResponse(template.render(context))<EOL>response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True,<EOL>expires=datetime.now()+timedelta(days=<NUM_LIT>))<EOL>if DJANGOSPAM_LOG:<EOL><INDENT>log("<STR_LIT>", request.me... | View for setting cookies on spammers. | f3693:m0 |
def process_request(self, request): | if COOKIE_KEY in request.COOKIES andrequest.COOKIES[COOKIE_KEY] == COOKIE_SPAM:<EOL><INDENT>response = HttpResponse("<STR_LIT>")<EOL>response.status_code = <NUM_LIT><EOL>if DJANGOSPAM_LOG:<EOL><INDENT>logger.log("<STR_LIT>", request.method,<EOL>request.path_info,<EOL>request.META.get("<STR_LIT>", "<STR_LIT>"))<EOL><DED... | Discovers if a request is from a knwon spam bot and denies access. | f3694:c0:m0 |
def process_response(self, request, response): | if COOKIE_KEY not in request.COOKIES:<EOL><INDENT>response.set_cookie(COOKIE_KEY, COOKIE_PASS, httponly=True,<EOL>expires=datetime.now()+timedelta(days=<NUM_LIT:30>))<EOL>if DJANGOSPAM_LOG:<EOL><INDENT>logger.log("<STR_LIT>", request.method, request.path_info,<EOL>request.META.get("<STR_LIT>", "<STR_LIT>")) ... | Sets "Ok" cookie on unknown users. | f3694:c0:m1 |
def register(model): | moderator.register(model, CookieModerator)<EOL> | Just a wrapper around django_comments.moderation.register.
It's only argument is the model for comment moderation. | f3695:m0 |
def allow(self, comment, content_object, request): | <EOL>if settings.COOKIE_KEY not in request.COOKIESand (settings.DISCARD_SPAM or settings.DISCARD_NO_COOKIE):<EOL><INDENT>return False<EOL><DEDENT>elif settings.COOKIE_KEY not in request.COOKIES:<EOL><INDENT>comment.is_removed = True<EOL>comment.is_public = False<EOL>return True<EOL><DEDENT>return True<EOL> | Tests comment post requests for the djangospam cookie. | f3695:c0:m0 |
def log(ltype, method, page, user_agent): | try:<EOL><INDENT>f = open(settings.DJANGOSPAM_LOG, "<STR_LIT:a>")<EOL>f.write("<STR_LIT>" %(datetime.datetime.now(), ltype, method, page, user_agent))<EOL>f.close()<EOL><DEDENT>except:<EOL><INDENT>if settings.DJANGOSPAM_FAIL_ON_LOG:<EOL><INDENT>exc_type, exc_value = sys.exc_info()[:<NUM_LIT:2>]<EOL>raise LogError(exc_t... | Writes to the log a message in the following format::
"<datetime>: <exception> method <HTTP method> page <path> \
user agent <user_agent>" | f3698:m0 |
def __init__(self, data): | self.data = data<EOL> | : param data: :type list of lists
Example usage:
data = [
['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'],
['2004', 1000, 400, 100, 600],
['2005', 1170, 460, 120, 310],
['2006', 660, 1120, 50, -460],
['2007', 1030, 540, 100, 200],
]
sd = SimpleDataSource(data) | f3701:c0:m0 |
def get_first_column(self): | data_not_header = self.data[<NUM_LIT:1>:]<EOL>return [el[<NUM_LIT:0>] for el in data_not_header]<EOL> | Get the first column. Generally would be the x axis.
: return: :type list of strings
Example:
For the example shown in __init__, it would return the following:
['2004', '2005', '2006', '2007'] | f3701:c0:m3 |
def __init__(self, queryset, fields=None): | self.queryset = queryset<EOL>if fields:<EOL><INDENT>self.fields = fields<EOL><DEDENT>else:<EOL><INDENT>self.fields = [el.name for el in self.queryset.model._meta.fields]<EOL><DEDENT>self.data = self.create_data()<EOL> | : param queryset: :type Django ORM queryset
: param fields: :type list of strings
Example usage:
queryset = Account.objects.all()
mds = ModelDataSource(queryset, fields=['year', 'sales', 'expenses'])
# This assumes the following model Account:
class Account(models.Model):
year = models.IntegerF... | f3702:c0:m0 |
def get_data(self): | raise GraphosException("<STR_LIT>")<EOL> | Get all the data. Subclasses should override this | f3703:c0:m1 |
def get_header(self): | raise GraphosException("<STR_LIT>")<EOL> | Get the header - First row. Subclasses should override this | f3703:c0:m2 |
def get_first_column(self): | raise GraphosException("<STR_LIT>")<EOL> | Get the first column. Generally would be the x axis.
Subclasses should override this | f3703:c0:m3 |
def __init__(self, csv_file, fields=None): | reader = csv.reader(csv_file)<EOL>data =[row for row in reader]<EOL>self.data = data<EOL>self.fields = fields<EOL> | csv_file: A file like object which should be charted | f3704:c0:m0 |
def get_series(self): | data = self.get_data()<EOL>series_names = data[<NUM_LIT:0>][<NUM_LIT:1>:]<EOL>serieses = []<EOL>options = self.get_options()<EOL>if '<STR_LIT>' in options:<EOL><INDENT>data = self.get_data()<EOL>annotation_list = options['<STR_LIT>']<EOL>for i, name in enumerate(series_names):<EOL><INDENT>new_data = []<EOL>if name in a... | Example usage:
data = [
['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit'],
['2004', 1000, 400, 100, 600],
['2005', 1170, 460, 120, 310],
['2006', 660, 1120, 50, -460],
['2007', 1030, 540, 100, 200],
]
sd = SimpleDataSource(data)
hc = BaseHighCharts(sd)
hc.g... | f3710:c0:m2 |
def get_categories(self): | return column(self.get_data(), <NUM_LIT:0>)[<NUM_LIT:1>:]<EOL> | This would return ['2004', '2005', '2006', '2007'] | f3710:c0:m5 |
def get_series(self): | if self.series_type == '<STR_LIT>':<EOL><INDENT>serieses = self.calculate_single_series()<EOL><DEDENT>else:<EOL><INDENT>serieses = self.calculate_multi_series()<EOL><DEDENT>return serieses<EOL> | Different serieses should come up based on different data formats passed.
1. Single series
This would be a choropleth map where the color intensity of different regions/polygons
differ based on the integer values in series. Two things are important here
a: It works with a colorAxis
... | f3710:c11:m1 |
def __init__(self, data_source, html_id=None,<EOL>width=None, height=None,<EOL>options=None, encoder=GraphosEncoder,<EOL>*args, **kwargs): | self.data_source = data_source<EOL>self.html_id = html_id or get_random_string()<EOL>self.height = height or DEFAULT_HEIGHT<EOL>self.width = width or DEFAULT_WIDTH<EOL>self.options = options or {}<EOL>self.header = data_source.get_header()<EOL>self.encoder = encoder<EOL>self.context_data = kwargs<EOL> | : param data_source: :type graphos.sources.base.BaseDataSource subclass instance.
: param html_id: :type string: Id of the div where you would like chart to be rendered
: param width: :type integer: Width of the chart div
: param height: :type integer: Height of the chart div | f3712:c0:m0 |
def get_default_options(graph_type="<STR_LIT>"): | options = {"<STR_LIT>": {"<STR_LIT:%s>" % graph_type: {"<STR_LIT>": "<STR_LIT:true>"}},<EOL>"<STR_LIT>": {"<STR_LIT>": '<STR_LIT>'},<EOL>"<STR_LIT:title>": "<STR_LIT>"}<EOL>return options<EOL> | default options | f3717:m1 |
def get_db(db_name=None): | import pymongo<EOL>return pymongo.Connection(host=DB_HOST,<EOL>port=DB_PORT)[db_name]<EOL> | GetDB - simple function to wrap getting a database
connection from the connection pool. | f3717:m2 |
def find_package_data(<EOL>where='<STR_LIT:.>', package='<STR_LIT>',<EOL>exclude=standard_exclude,<EOL>exclude_directories=standard_exclude_directories,<EOL>only_in_packages=True,<EOL>show_ignored=True): | out = {}<EOL>stack = [(convert_path(where), '<STR_LIT>', package, only_in_packages)]<EOL>while stack:<EOL><INDENT>where, prefix, package, only_in_packages = stack.pop(<NUM_LIT:0>)<EOL>for name in os.listdir(where):<EOL><INDENT>fn = os.path.join(where, name)<EOL>if os.path.isdir(fn):<EOL><INDENT>bad_name = False<EOL>for... | Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{'package': [files]}
Where ``files`` is a list of all the files in that package that
don't match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level directories that
are no... | f3733:m2 |
def setUp(self): | self.ticker = '<STR_LIT>'<EOL>self.stock = Stock(self.ticker)<EOL> | SetUp. | f3735:c0:m0 |
def setUp(self): | self.ticker = '<STR_LIT>'<EOL>self.stock = Stock(self.ticker)<EOL> | SetUp. | f3735:c1:m0 |
def setUp(self): | self.ticker = '<STR_LIT>'<EOL>self.stock = Stock(self.ticker)<EOL>self.start_date = '<STR_LIT>'<EOL>self.end_date = '<STR_LIT>'<EOL>self.keys = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL> | SetUp. | f3735:c2:m0 |
def setUp(self): | self.tickers_list = ['<STR_LIT>', '<STR_LIT>']<EOL>self.fields = ['<STR_LIT:Name>', '<STR_LIT>']<EOL> | SetUp. | f3736:c0:m0 |
def setUp(self): | self.tickers_list = ['<STR_LIT>', '<STR_LIT>']<EOL>self.start_date = '<STR_LIT>'<EOL>self.end_date = '<STR_LIT>'<EOL>self.keys = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL> | SetUp. | f3736:c1:m0 |
def setUp(self): | self.tickers_list = ['<STR_LIT>', '<STR_LIT>']<EOL>os.makedirs('<STR_LIT>')<EOL>self.output_folder = '<STR_LIT>'<EOL> | SetUp. | f3736:c2:m0 |
def tearDown(self): | for root, dirs, files in os.walk(self.output_folder, topdown=False):<EOL><INDENT>for name in files:<EOL><INDENT>os.remove(os.path.join(root, name))<EOL><DEDENT>for name in dirs:<EOL><INDENT>os.rmdir(os.path.join(root, name))<EOL><DEDENT><DEDENT>os.rmdir(self.output_folder)<EOL> | Cleaning up. | f3736:c2:m3 |
def load_key(pubkey): | try:<EOL><INDENT>return load_pem_public_key(pubkey.encode(), default_backend())<EOL><DEDENT>except ValueError:<EOL><INDENT>pubkey = pubkey.replace('<STR_LIT>', '<STR_LIT>').replace('<STR_LIT>', '<STR_LIT>')<EOL>return load_pem_public_key(pubkey.encode(), default_backend())<EOL><DEDENT> | Load public RSA key, with work-around for keys using
incorrect header/footer format.
Read more about RSA encryption with cryptography:
https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ | f3737:m0 |
def encrypt(pubkey, password): | key = load_key(pubkey)<EOL>encrypted_password = key.encrypt(password, PKCS1v15())<EOL>return base64.b64encode(encrypted_password)<EOL> | Encrypt password using given RSA public key and encode it with base64.
The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis). | f3737:m1 |
def fetch_public_key(repo): | keyurl = '<STR_LIT>'.format(repo)<EOL>data = json.loads(urlopen(keyurl).read().decode())<EOL>if '<STR_LIT:key>' not in data:<EOL><INDENT>errmsg = "<STR_LIT>".format(repo)<EOL>errmsg += "<STR_LIT>"<EOL>raise ValueError(errmsg)<EOL><DEDENT>return data['<STR_LIT:key>']<EOL> | Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys | f3737:m2 |
def prepend_line(filepath, line): | with open(filepath) as f:<EOL><INDENT>lines = f.readlines()<EOL><DEDENT>lines.insert(<NUM_LIT:0>, line)<EOL>with open(filepath, '<STR_LIT:w>') as f:<EOL><INDENT>f.writelines(lines)<EOL><DEDENT> | Rewrite a file adding a line to its beginning. | f3737:m3 |
def update_travis_deploy_password(encrypted_password): | config = load_yaml_config(TRAVIS_CONFIG_FILE)<EOL>config['<STR_LIT>']['<STR_LIT:password>'] = dict(secure=encrypted_password)<EOL>save_yaml_config(TRAVIS_CONFIG_FILE, config)<EOL>line = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>prepend_line(TRAVIS_CONFIG_FILE, line)<EOL> | Update the deploy section of the .travis.yml file
to use the given encrypted password. | f3737:m6 |
def __validate_list(list_to_validate): | if not type(list_to_validate) is list:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>" +<EOL>type(list_to_validate).__name__ + "<STR_LIT>"<EOL>)<EOL><DEDENT> | Validate list. | f3739:m0 |
def __validate_dates(start_date, end_date): | try:<EOL><INDENT>start_date = datetime.datetime.strptime(start_date, '<STR_LIT>')<EOL>end_date = datetime.datetime.strptime(end_date, '<STR_LIT>')<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (end_date - start_date).days > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>" +<... | Validate if a date string.
Validate if a string is a date on yyyy-mm-dd format and it the
period between them is less than a year. | f3739:m1 |
def __yahoo_request(query): | query = quote(query)<EOL>url = '<STR_LIT>' + query +'<STR_LIT>'<EOL>response = urlopen(url).read()<EOL>return json.loads(response.decode('<STR_LIT:utf-8>'))['<STR_LIT>']['<STR_LIT>']<EOL> | Request Yahoo Finance information.
Request information from YQL.
`Check <http://goo.gl/8AROUD>`_ for more information on YQL. | f3739:m2 |
def request_quotes(tickers_list, selected_columns=['<STR_LIT:*>']): | __validate_list(tickers_list)<EOL>__validate_list(selected_columns)<EOL>query = '<STR_LIT>'<EOL>query = query.format(<EOL>cols='<STR_LIT:U+002CU+0020>'.join(selected_columns),<EOL>vals='<STR_LIT:U+002CU+0020>'.join('<STR_LIT>'.format(s) for s in tickers_list)<EOL>)<EOL>response = __yahoo_request(query)<EOL>if not respo... | Request Yahoo Finance recent quotes.
Returns quotes information from YQL. The columns to be requested are
listed at selected_columns. Check `here <http://goo.gl/8AROUD>`_ for more
information on YQL.
>>> request_quotes(['AAPL'], ['Name', 'PreviousClose'])
{
'PreviousClose': '95.60',
... | f3739:m3 |
def request_historical(ticker, start_date, end_date): | __validate_dates(start_date, end_date)<EOL>cols = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>query = '<STR_LIT>' +'<STR_LIT>' +'<STR_LIT>'<EOL>query = query.format(<EOL>cols='<STR_LIT:U+002CU+0020>'.join(cols),<EOL>ticker=ticker,<EOL>start_date=start_date,<EOL>end_da... | Get stock's daily historical information.
Returns a dictionary with Adj Close, Close, High, Low, Open and
Volume, between the start_date and the end_date. Is start_date and
end_date were not provided all the available information will be
retrieved. Information provided by YQL platform.
Check `here ... | f3739:m4 |
def download_historical(tickers_list, output_folder): | __validate_list(tickers_list)<EOL>for ticker in tickers_list:<EOL><INDENT>file_name = os.path.join(output_folder, ticker + '<STR_LIT>')<EOL>with open(file_name, '<STR_LIT:wb>') as f:<EOL><INDENT>base_url = '<STR_LIT>'<EOL>try:<EOL><INDENT>urlopen(base_url + ticker)<EOL>urlretrieve(base_url + ticker, f.name)<EOL><DEDENT... | Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume. Files
will be saved to output_folder as <ticker>.csv.
:param tickers_list: List of tickers that will be returned.
... | f3739:m5 |
def __init__(self, ticker): | self.__ticker = ticker<EOL> | Instantiate Stock class. | f3741:c0:m0 |
def __repr__(self): | return '<STR_LIT>'.format(ticker=self.__ticker)<EOL> | An unambiguous representation of a Stock's instance. | f3741:c0:m1 |
def __eq__(self, other): | if isinstance(other, Stock):<EOL><INDENT>return self.__repr__() == other.__repr__()<EOL><DEDENT>return False<EOL> | Equality comparison operator. | f3741:c0:m2 |
def __ne__(self, other): | return not self.__eq__() == other.__repr__()<EOL> | Inquality comparison operator. | f3741:c0:m3 |
def __hash__(self): | return hash(self.__repr__())<EOL> | Hash representation of a Stock's instance. | f3741:c0:m4 |
def get_ticker(self): | return self.__ticker<EOL> | Get stock's ticker.
>>> stock.get_ticker()
'AAPL'
:returns: Ticker.
:rtype: string | f3741:c0:m5 |
def set_ticker(self, ticker): | self.__ticker = ticker<EOL> | Set stock's ticker.
>>> stock.set_ticker('YHOO')
>>> print(stock)
<Stock YHOO>
:param ticker: Stock ticker in Yahoo Finances format.
:type ticker: string | f3741:c0:m6 |
def get_info(self): | keys = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'... | Get all stock's information provided by Yahoo Finance.
There is no guarantee that all the fields will be available for all
stocks. That being said, the following fields will be retrieved by
this method as a python dictionary from YQL platform:
- Ask
- AverageDailyVolume
... | f3741:c0:m8 |
def get_historical(self, start_date, end_date): | return request_historical(self.__ticker, start_date, end_date)<EOL> | Get stock's daily historical information.
Returns a dictionary with Adj Close, Close, High, Low, Open and
Volume, between the start_date and the end_date. Is start_date and
end_date were not provided all the available information will be
retrieved. Information provided by YQL platform.
... | f3741:c0:m9 |
def save_historical(self, output_folder): | download_historical([self.__ticker], output_folder)<EOL> | Download historical data from Yahoo Finance.
Downloads full historical data from Yahoo Finance as CSV. The following
fields are available: Adj Close, Close, High, Low, Open and Volume.
Files will be saved to output_folder as <ticker>.csv.
:param output_folder: Output folder path
... | f3741:c0:m10 |
def setUp(self): | base_dir = os.path.join(os.path.dirname(__file__), "<STR_LIT>",<EOL>"<STR_LIT>")<EOL>self.legacy_regex_1 = ['<STR_LIT>']<EOL>self.legacy_regex_2 = ['<STR_LIT>', '<STR_LIT>']<EOL>self.file_1 = base_dir + '<STR_LIT>'<EOL>self.file_2 = base_dir + '<STR_LIT>'<EOL>self.file_3 = base_dir + '<STR_LIT>'<EOL> | Setup. | f3747:c0:m0 |
def __init__(self): | self.queue = []<EOL> | Initialize an empty queue. | f3753:c0:m0 |
def __len__(self): | return len(self.queue)<EOL> | Length of the queue. | f3753:c0:m1 |
def dequeue(self): | return self.queue.pop()<EOL> | Remove one item from the queue. | f3753:c0:m2 |
def enqueue(self, *args, **kwargs): | self.queue.insert(<NUM_LIT:0>, args)<EOL> | Add items to the queue.
:param args: tuple is appended to list
:param kwargs: are ignored. | f3753:c0:m3 |
def _get_files_modified(): | cmd = "<STR_LIT>"<EOL>_, files_modified, _ = run(cmd)<EOL>extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + ["<STR_LIT>"]]<EOL>test = "<STR_LIT>".format("<STR_LIT:|>".join(extensions))<EOL>return list(filter(lambda f: re.search(test, f), files_modified))<EOL> | Get the list of modified files that are Python or Jinja2. | f3756:m0 |
def _get_git_author(): | _, stdout, _ = run("<STR_LIT>")<EOL>git_author = stdout[<NUM_LIT:0>]<EOL>return git_author[:git_author.find("<STR_LIT:>>") + <NUM_LIT:1>]<EOL> | Return the git author from the git variables. | f3756:m1 |
def _get_component(filename, default="<STR_LIT>"): | if hasattr(filename, "<STR_LIT>"):<EOL><INDENT>filename = filename.decode()<EOL><DEDENT>parts = filename.split(os.path.sep)<EOL>if len(parts) >= <NUM_LIT:3>:<EOL><INDENT>if parts[<NUM_LIT:1>] in "<STR_LIT>".split():<EOL><INDENT>return parts[<NUM_LIT:2>]<EOL><DEDENT><DEDENT>if len(parts) >= <NUM_LIT:2>:<EOL><INDENT>if p... | Get component name from filename. | f3756:m2 |
def _get_components(files): | return tuple(set(_get_component(f) for f in files))<EOL> | Compile the components list from the given files. | f3756:m3 |
def _prepare_commit_msg(tmp_file, author, files_modified=None, template=None): | files_modified = files_modified or []<EOL>template = template or "<STR_LIT>"<EOL>if hasattr(template, "<STR_LIT>"):<EOL><INDENT>template = template.decode()<EOL><DEDENT>with open(tmp_file, "<STR_LIT:r>", "<STR_LIT:utf-8>") as fh:<EOL><INDENT>contents = fh.readlines()<EOL>msg = filter(lambda x: not (x.startswith("<STR_L... | Prepare the commit message in tmp_file.
It will build the commit message prefilling the component line, as well
as the signature using the git author and the modified files.
The file remains untouched if it is not empty. | f3756:m4 |
def _check_message(message, options): | options = options or dict()<EOL>options.update(get_options())<EOL>options.update(_read_local_kwalitee_configuration())<EOL>errors = check_message(message, **options)<EOL>if errors:<EOL><INDENT>for error in errors:<EOL><INDENT>print(error, file=sys.stderr)<EOL><DEDENT>return False<EOL><DEDENT>return True<EOL> | Checking the message and printing the errors. | f3756:m5 |
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def prepare_commit_msg_hook(argv): | options = get_options()<EOL>options.update(_read_local_kwalitee_configuration())<EOL>_prepare_commit_msg(argv[<NUM_LIT:1>],<EOL>_get_git_author(),<EOL>_get_files_modified(),<EOL>options.get('<STR_LIT>'))<EOL>return <NUM_LIT:0><EOL> | Hook: prepare a commit message. | f3756:m6 |
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def commit_msg_hook(argv): | with open(argv[<NUM_LIT:1>], "<STR_LIT:r>", "<STR_LIT:utf-8>") as fh:<EOL><INDENT>message = "<STR_LIT:\n>".join(filter(lambda x: not x.startswith("<STR_LIT:#>"),<EOL>fh.readlines()))<EOL><DEDENT>options = {"<STR_LIT>": True}<EOL>if not _check_message(message, options):<EOL><INDENT>click.echo(<EOL>"<STR_LIT>"<EOL>"<STR_... | Hook: for checking commit message (prevent commit). | f3756:m7 |
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def post_commit_hook(argv): | _, stdout, _ = run("<STR_LIT>")<EOL>message = "<STR_LIT:\n>".join(stdout)<EOL>options = {"<STR_LIT>": True}<EOL>if not _check_message(message, options):<EOL><INDENT>click.echo(<EOL>"<STR_LIT>",<EOL>file=sys.stderr)<EOL>return <NUM_LIT:1> <EOL><DEDENT>return <NUM_LIT:0><EOL> | Hook: for checking commit message. | f3756:m8 |
def _read_local_kwalitee_configuration(directory="<STR_LIT:.>"): | filepath = os.path.abspath(os.path.join(directory, '<STR_LIT>'))<EOL>data = {}<EOL>if os.path.exists(filepath):<EOL><INDENT>with open(filepath, '<STR_LIT:r>') as file_read:<EOL><INDENT>data = yaml.load(file_read.read())<EOL><DEDENT><DEDENT>return data<EOL> | Check if the repo has a ``.kwalitee.yaml`` file. | f3756:m9 |
def _pre_commit(files, options): | errors = []<EOL>tmpdir = mkdtemp()<EOL>files_to_check = []<EOL>try:<EOL><INDENT>for (file_, content) in files:<EOL><INDENT>dirname, filename = os.path.split(os.path.abspath(file_))<EOL>prefix = os.path.commonprefix([dirname, tmpdir])<EOL>dirname = os.path.relpath(dirname, start=prefix)<EOL>dirname = os.path.join(tmpdir... | Run the check on files of the added version.
They might be different than the one on disk. Equivalent than doing a git
stash, check, and git stash pop. | f3756:m10 |
@click.command()<EOL>@click.argument('<STR_LIT>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>def pre_commit_hook(argv): | options = get_options()<EOL>options.update(_read_local_kwalitee_configuration())<EOL>files = []<EOL>for filename in _get_files_modified():<EOL><INDENT>_, stdout, _ = run("<STR_LIT>".format(filename), raw_output=True)<EOL>files.append((filename, stdout))<EOL><DEDENT>errors = _pre_commit(files, options)<EOL>for error in ... | Hook: checking the staged files. | f3756:m11 |
def run(command, raw_output=False): | p = Popen(command.split(), stdout=PIPE, stderr=PIPE)<EOL>(stdout, stderr) = p.communicate()<EOL>if not raw_output:<EOL><INDENT>return (<EOL>p.returncode,<EOL>[line.rstrip() for line in stdout.decode("<STR_LIT:utf-8>").splitlines()],<EOL>[line.rstrip() for line in stderr.decode("<STR_LIT:utf-8>").splitlines()]<EOL>)<EOL... | Run a command using subprocess.
:param command: command line to be run
:type command: str
:param raw_output: does not attempt to convert the output as unicode
:type raw_output: bool
:return: error code, output (``stdout``) and error (``stderr``)
:rtype: tuple | f3756:m12 |
@click.group()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', envvar='<STR_LIT>', default='<STR_LIT:.>')<EOL>@click.pass_context<EOL>def prepare(ctx, repository): | ctx.obj = Repo(repository=repository)<EOL> | Assist with release process. | f3758:m0 |
def analyse_body_paragraph(body_paragraph, labels=None): | <EOL>for label, dummy in labels:<EOL><INDENT>if body_paragraph.startswith('<STR_LIT>' + label):<EOL><INDENT>return (label, body_paragraph[len(label) + <NUM_LIT:3>:].replace('<STR_LIT>',<EOL>'<STR_LIT:U+0020>'))<EOL><DEDENT><DEDENT>if body_paragraph.startswith('<STR_LIT>'):<EOL><INDENT>return (None, body_paragraph[<NUM_... | Analyse commit body paragraph and return (label, message).
>>> analyse_body_paragraph('* BETTER Foo and bar.',
>>> ... {'BETTER': 'Improvements'})
('BETTER', 'Foo and bar.')
>>> analyse_body_paragraph('* Foo and bar.')
(None, 'Foo and bar.')
>>> analyse_body_paragraph('Foo and bar.')
(None,... | f3758:m1 |
def remove_ticket_directives(message): | if message:<EOL><INDENT>message = re.sub(r'<STR_LIT>', '<STR_LIT:#>', message)<EOL>message = re.sub(r'<STR_LIT>', '<STR_LIT:#>', message)<EOL>message = re.sub(r'<STR_LIT>', '<STR_LIT:#>', message)<EOL><DEDENT>return message<EOL> | Remove ticket directives like "(closes #123).
>>> remove_ticket_directives('(closes #123)')
'(#123)'
>>> remove_ticket_directives('(foo #123)')
'(foo #123)' | f3758:m2 |
def amended_commits(commits): | <EOL>amended_sha1s = []<EOL>for message in commits.values():<EOL><INDENT>amended_sha1s.extend(re.findall(r'<STR_LIT>', message))<EOL><DEDENT>return amended_sha1s<EOL> | Return those git commit sha1s that have been amended later. | f3758:m3 |
def enrich_git_log_dict(messages, labels): | for commit_sha1, message in messages.items():<EOL><INDENT>component = None<EOL>title = message.split('<STR_LIT:\n>')[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>component, title = title.split("<STR_LIT::>", <NUM_LIT:1>)<EOL>component = component.strip()<EOL><DEDENT>except ValueError:<EOL><INDENT>pass <EOL><DEDENT>paragraphs = [... | Enrich git log with related information on tickets. | f3758:m4 |
@prepare.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT:-c>', '<STR_LIT>', is_flag=True, help='<STR_LIT>')<EOL>@pass_repo<EOL>def release(obj, commit='<STR_LIT>', components=False): | options = obj.options<EOL>repository = obj.repository<EOL>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _pygit2_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>try:<EOL><INDENT>sha = '<STR_LIT>'<EOL>commits = _git_commits(commit, repository)<EOL><DEDENT>except ImportError:<EOL><INDENT>click.e... | Generate release notes. | f3758:m5 |
@click.group()<EOL>@click.option('<STR_LIT>', '<STR_LIT>', envvar='<STR_LIT>', default='<STR_LIT:.>')<EOL>@click.option('<STR_LIT:-c>', '<STR_LIT>', type=click.File('<STR_LIT:rb>'), default=None)<EOL>@click.pass_context<EOL>def check(ctx, repository, config): | ctx.obj = Repo(repository=repository, config=config)<EOL> | Check commits. | f3759:m0 |
def _is_merge_commit(commit): | if len(commit.parents) > <NUM_LIT:1>:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL> | Test whether the commit is a merge commit or not. | f3759:m3 |
@check.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@pass_repo<EOL>def message(obj, commit='<STR_LIT>', skip_merge_commits=False): | from ..kwalitee import check_message<EOL>options = obj.options<EOL>repository = obj.repository<EOL>if options.get('<STR_LIT>') is not False:<EOL><INDENT>colorama.init(autoreset=True)<EOL>reset = colorama.Style.RESET_ALL<EOL>yellow = colorama.Fore.YELLOW<EOL>green = colorama.Fore.GREEN<EOL>red = colorama.Fore.RED<EOL><D... | Check the messages of the commits. | f3759:m4 |
@check.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@pass_repo<EOL>def files(obj, commit='<STR_LIT>', skip_merge_commits=False): | from ..kwalitee import check_file, SUPPORTED_FILES<EOL>from ..hooks import run<EOL>options = obj.options<EOL>repository = obj.repository<EOL>if options.get('<STR_LIT>') is not False:<EOL><INDENT>colorama.init(autoreset=True)<EOL>reset = colorama.Style.RESET_ALL<EOL>yellow = colorama.Fore.YELLOW<EOL>green = colorama.For... | Check the files of the commits. | f3759:m5 |
@check.command()<EOL>@click.argument('<STR_LIT>', metavar='<STR_LIT>',<EOL>default='<STR_LIT>') <EOL>@click.option('<STR_LIT>', '<STR_LIT>', is_flag=True,<EOL>help='<STR_LIT>')<EOL>@pass_repo<EOL>def authors(obj, commit='<STR_LIT>', skip_merge_commits=False): | from ..kwalitee import check_author<EOL>options = obj.options<EOL>repository = obj.repository<EOL>if options.get('<STR_LIT>') is not False:<EOL><INDENT>colorama.init(autoreset=True)<EOL>reset = colorama.Style.RESET_ALL<EOL>yellow = colorama.Fore.YELLOW<EOL>green = colorama.Fore.GREEN<EOL>red = colorama.Fore.RED<EOL><DE... | Check the authors of the commits. | f3759:m6 |
def __init__(self, repository='<STR_LIT:.>', config=None): | self.repository = repository<EOL>self.options = get_options()<EOL>self.options.update(_read_local_kwalitee_configuration(<EOL>directory=repository))<EOL>if config:<EOL><INDENT>self.options.update(<EOL>yaml.load(config.read())<EOL>)<EOL><DEDENT> | Store information about repository and get kwalitee options. | f3759:c0:m0 |
@click.group()<EOL>def main(): | Perform various checks on a Git repository.
It eases developers life by automatizing boring stuff like commit message
checks or release notes generations. | f3760:m0 | |
@click.group()<EOL>def githooks(): | Install githooks for kwalitee checks. | f3761:m0 | |
@githooks.command()<EOL>@click.option("<STR_LIT>", "<STR_LIT>", is_flag=True,<EOL>help="<STR_LIT>", default=False)<EOL>def install(force=False): | ret, git_dir, _ = run("<STR_LIT>")<EOL>if ret != <NUM_LIT:0>:<EOL><INDENT>click.echo(<EOL>"<STR_LIT>",<EOL>file=sys.stderr)<EOL>raise click.Abort<EOL><DEDENT>git_dir = git_dir[<NUM_LIT:0>]<EOL>hooks_dir = os.path.join(git_dir, HOOK_PATH)<EOL>for hook in HOOKS:<EOL><INDENT>hook_path = os.path.join(hooks_dir, hook)<EOL>i... | Install git hooks. | f3761:m1 |
@githooks.command()<EOL>def uninstall(): | ret, git_dir, _ = run("<STR_LIT>")<EOL>if ret != <NUM_LIT:0>:<EOL><INDENT>click.echo(<EOL>"<STR_LIT>",<EOL>file=sys.stderr)<EOL>raise click.Abort<EOL><DEDENT>git_dir = git_dir[<NUM_LIT:0>]<EOL>hooks_dir = os.path.join(git_dir, HOOK_PATH)<EOL>for hook in HOOKS:<EOL><INDENT>hook_path = os.path.join(hooks_dir, hook)<EOL>i... | Uninstall git hooks. | f3761:m2 |
def _check_1st_line(line, **kwargs): | components = kwargs.get("<STR_LIT>", ())<EOL>max_first_line = kwargs.get("<STR_LIT>", <NUM_LIT:50>)<EOL>errors = []<EOL>lineno = <NUM_LIT:1><EOL>if len(line) > max_first_line:<EOL><INDENT>errors.append(("<STR_LIT>", lineno, max_first_line, len(line)))<EOL><DEDENT>if line.endswith("<STR_LIT:.>"):<EOL><INDENT>errors.appe... | First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:param max_first_line: maximum length of the firs... | f3762:m0 |
def _check_bullets(lines, **kwargs): | max_length = kwargs.get("<STR_LIT:max_length>", <NUM_LIT>)<EOL>labels = {l for l, _ in kwargs.get("<STR_LIT>", tuple())}<EOL>def _strip_ticket_directives(line):<EOL><INDENT>return re.sub(r'<STR_LIT>', '<STR_LIT>', line)<EOL><DEDENT>errors = []<EOL>missed_lines = []<EOL>skipped = []<EOL>for (i, line) in enumerate(lines[... | Check that the bullet point list is well formatted.
Each bullet point shall have one space before and after it. The bullet
character is the "*" and there is no space before it but one after it
meaning the next line are starting with two blanks spaces to respect the
indentation.
:param lines: all t... | f3762:m1 |
def _check_signatures(lines, **kwargs): | trusted = kwargs.get("<STR_LIT>", ())<EOL>signatures = tuple(kwargs.get("<STR_LIT>", ()))<EOL>alt_signatures = tuple(kwargs.get("<STR_LIT>", ()))<EOL>min_reviewers = kwargs.get("<STR_LIT>", <NUM_LIT:3>)<EOL>matching = []<EOL>errors = []<EOL>signatures += alt_signatures<EOL>test_signatures = re.compile("<STR_LIT>".forma... | Check that the signatures are valid.
There should be at least three signatures. If not, one of them should be a
trusted developer/reviewer.
Formatting supported being: [signature] full name <email@address>
:param lines: lines (lineno, content) to verify.
:type lines: list
:param signatures: l... | f3762:m2 |
def check_message(message, **kwargs): | if kwargs.pop("<STR_LIT>", False):<EOL><INDENT>if not message or message.isspace():<EOL><INDENT>return []<EOL><DEDENT><DEDENT>lines = re.split(r"<STR_LIT>", message)<EOL>errors = _check_1st_line(lines[<NUM_LIT:0>], **kwargs)<EOL>err, signature_lines = _check_bullets(lines, **kwargs)<EOL>errors += err<EOL>errors += _che... | Check the message format.
Rules:
- the first line must start by a component name
- and a short description (52 chars),
- then bullet points are expected
- and finally signatures.
:param components: compontents, e.g. ``('auth', 'utils', 'misc')``
:type components: `list`
:param signatu... | f3762:m3 |
def _register_pyflakes_check(): | from flake8_isort import Flake8Isort<EOL>from flake8_blind_except import check_blind_except<EOL>codes = {<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>"<STR_LIT>": "<STR_LIT>",<EOL>... | Register the pyFlakes checker into PEP8 set of checks. | f3762:m4 |
def is_file_excluded(filename, excludes): | <EOL>return any([exclude and re.match(exclude, filename) is not None<EOL>for exclude in excludes])<EOL> | Check if the file should be excluded.
:param filename: file name
:param excludes: list of regex to match
:return: True if the file should be excluded | f3762:m5 |
def check_pep8(filename, **kwargs): | options = {<EOL>"<STR_LIT:ignore>": kwargs.get("<STR_LIT:ignore>"),<EOL>"<STR_LIT>": kwargs.get("<STR_LIT>"),<EOL>}<EOL>if not _registered_pyflakes_check and kwargs.get("<STR_LIT>", True):<EOL><INDENT>_register_pyflakes_check()<EOL><DEDENT>checker = pep8.Checker(filename, reporter=_Report, **options)<EOL>checker.check_... | Perform static analysis on the given file.
:param filename: path of file to check.
:type filename: str
:param ignore: codes to ignore, e.g. ``('E111', 'E123')``
:type ignore: `list`
:param select: codes to explicitly select.
:type select: `list`
:param pyflakes: run the pyflakes checks too ... | f3762:m6 |
def check_pydocstyle(filename, **kwargs): | ignore = kwargs.get("<STR_LIT:ignore>")<EOL>match = kwargs.get("<STR_LIT>", None)<EOL>match_dir = kwargs.get("<STR_LIT>", None)<EOL>errors = []<EOL>if match and not re.match(match, os.path.basename(filename)):<EOL><INDENT>return errors<EOL><DEDENT>if match_dir:<EOL><INDENT>path = os.path.split(os.path.abspath(filename)... | Perform static analysis on the given file docstrings.
:param filename: path of file to check.
:type filename: str
:param ignore: codes to ignore, e.g. ('D400',)
:type ignore: `list`
:param match: regex the filename has to match to be checked
:type match: str
:param match_dir: regex everydir... | f3762:m7 |
def check_license(filename, **kwargs): | year = kwargs.pop("<STR_LIT>", datetime.now().year)<EOL>python_style = kwargs.pop("<STR_LIT>", True)<EOL>ignores = kwargs.get("<STR_LIT:ignore>")<EOL>template = "<STR_LIT>"<EOL>if python_style:<EOL><INDENT>re_comment = re.compile(r"<STR_LIT>")<EOL>starter = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>re_comment = re.comp... | Perform a license check on the given file.
The license format should be commented using # and live at the top of the
file. Also, the year should be the current one.
:param filename: path of file to check.
:type filename: str
:param year: default current year
:type year: int
:param ignore: ... | f3762:m8 |
def check_file(filename, **kwargs): | excludes = kwargs.get("<STR_LIT>", [])<EOL>errors = []<EOL>if is_file_excluded(filename, excludes):<EOL><INDENT>return None<EOL><DEDENT>if filename.endswith("<STR_LIT>"):<EOL><INDENT>if kwargs.get("<STR_LIT>", True):<EOL><INDENT>errors += check_pep8(filename, **kwargs)<EOL><DEDENT>if kwargs.get("<STR_LIT>", True):<EOL>... | Perform static analysis on the given file.
.. seealso::
- :data:`.SUPPORTED_FILES`
- :func:`.check_pep8`
- :func:`.check_pydocstyle`
- and :func:`.check_license`
:param filename: path of file to check.
:type filename: str
:return: errors sorted by line number or None i... | f3762:m9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.