body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def GETorHEAD(self, req):
'Handler for HTTP GET/HEAD requests.'
length_limit = self.get_name_length_limit()
if (len(self.account_name) > length_limit):
resp = HTTPBadRequest(request=req)
resp.body = (b'Account name length of %d longer than %d' % (len(self.account_name), length_limit))
... | -2,028,738,259,296,392,200 | Handler for HTTP GET/HEAD requests. | swift/proxy/controllers/account.py | GETorHEAD | AymericDu/swift | python | def GETorHEAD(self, req):
length_limit = self.get_name_length_limit()
if (len(self.account_name) > length_limit):
resp = HTTPBadRequest(request=req)
resp.body = (b'Account name length of %d longer than %d' % (len(self.account_name), length_limit))
return resp
partition = self.ap... |
@public
def PUT(self, req):
'HTTP PUT request handler.'
if (not self.app.allow_account_management):
return HTTPMethodNotAllowed(request=req, headers={'Allow': ', '.join(self.allowed_methods)})
error_response = check_metadata(req, 'account')
if error_response:
return error_response
le... | -8,082,433,754,177,956,000 | HTTP PUT request handler. | swift/proxy/controllers/account.py | PUT | AymericDu/swift | python | @public
def PUT(self, req):
if (not self.app.allow_account_management):
return HTTPMethodNotAllowed(request=req, headers={'Allow': ', '.join(self.allowed_methods)})
error_response = check_metadata(req, 'account')
if error_response:
return error_response
length_limit = self.get_name_... |
@public
def POST(self, req):
'HTTP POST request handler.'
length_limit = self.get_name_length_limit()
if (len(self.account_name) > length_limit):
resp = HTTPBadRequest(request=req)
resp.body = (b'Account name length of %d longer than %d' % (len(self.account_name), length_limit))
retu... | -7,641,809,301,346,970,000 | HTTP POST request handler. | swift/proxy/controllers/account.py | POST | AymericDu/swift | python | @public
def POST(self, req):
length_limit = self.get_name_length_limit()
if (len(self.account_name) > length_limit):
resp = HTTPBadRequest(request=req)
resp.body = (b'Account name length of %d longer than %d' % (len(self.account_name), length_limit))
return resp
error_response =... |
@public
def DELETE(self, req):
'HTTP DELETE request handler.'
if req.query_string:
return HTTPBadRequest(request=req)
if (not self.app.allow_account_management):
return HTTPMethodNotAllowed(request=req, headers={'Allow': ', '.join(self.allowed_methods)})
(account_partition, accounts) = s... | 8,040,606,574,105,074,000 | HTTP DELETE request handler. | swift/proxy/controllers/account.py | DELETE | AymericDu/swift | python | @public
def DELETE(self, req):
if req.query_string:
return HTTPBadRequest(request=req)
if (not self.app.allow_account_management):
return HTTPMethodNotAllowed(request=req, headers={'Allow': ', '.join(self.allowed_methods)})
(account_partition, accounts) = self.app.account_ring.get_nodes... |
def section_text(text):
'Splits text into sections.\n\n Assumes text is in a radiology report format, e.g.:\n\n COMPARISON: Chest radiograph dated XYZ.\n\n IMPRESSION: ABC...\n\n Given text like this, it will output text from each section, \n where the section type is determined by the all ... | 7,319,260,994,792,756,000 | Splits text into sections.
Assumes text is in a radiology report format, e.g.:
COMPARISON: Chest radiograph dated XYZ.
IMPRESSION: ABC...
Given text like this, it will output text from each section,
where the section type is determined by the all caps header.
Returns a three element tuple:
sections ... | src/data/datasets/mimic_cxr/section_parser.py | section_text | philip-mueller/lovt | python | def section_text(text):
'Splits text into sections.\n\n Assumes text is in a radiology report format, e.g.:\n\n COMPARISON: Chest radiograph dated XYZ.\n\n IMPRESSION: ABC...\n\n Given text like this, it will output text from each section, \n where the section type is determined by the all ... |
@_rewrite_parameters(body_name='text_files')
def find_structure(self, *, text_files: t.Union[(t.List[t.Any], t.Tuple[(t.Any, ...)])], charset: t.Optional[str]=None, column_names: t.Optional[str]=None, delimiter: t.Optional[str]=None, explain: t.Optional[bool]=None, format: t.Optional[str]=None, grok_pattern: t.Optional... | 6,677,154,515,690,402,000 | Finds the structure of a text file. The text file must contain data that is suitable
to be ingested into Elasticsearch.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/find-structure.html>`_
:param text_files:
:param charset: The text’s character set. It must be a character set that is
supported... | elasticsearch/_sync/client/text_structure.py | find_structure | neubloc/elasticsearch-py | python | @_rewrite_parameters(body_name='text_files')
def find_structure(self, *, text_files: t.Union[(t.List[t.Any], t.Tuple[(t.Any, ...)])], charset: t.Optional[str]=None, column_names: t.Optional[str]=None, delimiter: t.Optional[str]=None, explain: t.Optional[bool]=None, format: t.Optional[str]=None, grok_pattern: t.Optional... |
def test_now_in_utc():
'now_in_utc() should return the current time set to the UTC time zone'
now = now_in_utc()
assert is_near_now(now)
assert (now.tzinfo == pytz.UTC) | 1,980,469,855,028,686,800 | now_in_utc() should return the current time set to the UTC time zone | main/utils_test.py | test_now_in_utc | mitodl/bootcamp-ecommerce | python | def test_now_in_utc():
now = now_in_utc()
assert is_near_now(now)
assert (now.tzinfo == pytz.UTC) |
def test_is_near_now():
'\n Test is_near_now for now\n '
now = datetime.datetime.now(tz=pytz.UTC)
assert (is_near_now(now) is True)
later = (now + datetime.timedelta(0, 6))
assert (is_near_now(later) is False)
earlier = (now - datetime.timedelta(0, 6))
assert (is_near_now(earlier) is F... | 5,014,501,646,750,768,000 | Test is_near_now for now | main/utils_test.py | test_is_near_now | mitodl/bootcamp-ecommerce | python | def test_is_near_now():
'\n \n '
now = datetime.datetime.now(tz=pytz.UTC)
assert (is_near_now(now) is True)
later = (now + datetime.timedelta(0, 6))
assert (is_near_now(later) is False)
earlier = (now - datetime.timedelta(0, 6))
assert (is_near_now(earlier) is False) |
def test_first_or_none():
'\n Assert that first_or_none returns the first item in an iterable or None\n '
assert (first_or_none([]) is None)
assert (first_or_none(set()) is None)
assert (first_or_none([1, 2, 3]) == 1)
assert (first_or_none(range(1, 5)) == 1) | -2,245,960,498,571,180,800 | Assert that first_or_none returns the first item in an iterable or None | main/utils_test.py | test_first_or_none | mitodl/bootcamp-ecommerce | python | def test_first_or_none():
'\n \n '
assert (first_or_none([]) is None)
assert (first_or_none(set()) is None)
assert (first_or_none([1, 2, 3]) == 1)
assert (first_or_none(range(1, 5)) == 1) |
def test_first_matching_item():
'first_matching_item should return the first item where the predicate function returns true'
assert (first_matching_item([1, 2, 3, 4, 5], (lambda x: ((x % 2) == 0))) == 2)
assert (first_matching_item([], (lambda x: True)) is None)
assert (first_matching_item(['x', 'y', 'z... | -6,679,562,110,484,070,000 | first_matching_item should return the first item where the predicate function returns true | main/utils_test.py | test_first_matching_item | mitodl/bootcamp-ecommerce | python | def test_first_matching_item():
assert (first_matching_item([1, 2, 3, 4, 5], (lambda x: ((x % 2) == 0))) == 2)
assert (first_matching_item([], (lambda x: True)) is None)
assert (first_matching_item(['x', 'y', 'z'], (lambda x: False)) is None) |
def test_max_or_none():
'\n Assert that max_or_none returns the max of some iterable, or None if the iterable has no items\n '
assert (max_or_none((i for i in [5, 4, 3, 2, 1])) == 5)
assert (max_or_none([1, 3, 5, 4, 2]) == 5)
assert (max_or_none([]) is None) | 5,047,917,916,077,396,000 | Assert that max_or_none returns the max of some iterable, or None if the iterable has no items | main/utils_test.py | test_max_or_none | mitodl/bootcamp-ecommerce | python | def test_max_or_none():
'\n \n '
assert (max_or_none((i for i in [5, 4, 3, 2, 1])) == 5)
assert (max_or_none([1, 3, 5, 4, 2]) == 5)
assert (max_or_none([]) is None) |
def test_unique():
'\n Assert that unique() returns a generator of unique elements from a provided iterable\n '
assert (list(unique([1, 2, 2, 3, 3, 0, 3])) == [1, 2, 3, 0])
assert (list(unique(('a', 'b', 'a', 'c', 'C', None))) == ['a', 'b', 'c', 'C', None]) | 986,328,228,094,812,800 | Assert that unique() returns a generator of unique elements from a provided iterable | main/utils_test.py | test_unique | mitodl/bootcamp-ecommerce | python | def test_unique():
'\n \n '
assert (list(unique([1, 2, 2, 3, 3, 0, 3])) == [1, 2, 3, 0])
assert (list(unique(('a', 'b', 'a', 'c', 'C', None))) == ['a', 'b', 'c', 'C', None]) |
def test_unique_ignore_case():
'\n Assert that unique_ignore_case() returns a generator of unique lowercase strings from a\n provided iterable\n '
assert (list(unique_ignore_case(['ABC', 'def', 'AbC', 'DEf'])) == ['abc', 'def']) | -9,212,515,244,537,056,000 | Assert that unique_ignore_case() returns a generator of unique lowercase strings from a
provided iterable | main/utils_test.py | test_unique_ignore_case | mitodl/bootcamp-ecommerce | python | def test_unique_ignore_case():
'\n Assert that unique_ignore_case() returns a generator of unique lowercase strings from a\n provided iterable\n '
assert (list(unique_ignore_case(['ABC', 'def', 'AbC', 'DEf'])) == ['abc', 'def']) |
def test_item_at_index_or_none():
"\n Assert that item_at_index_or_none returns an item at a given index, or None if that index\n doesn't exist\n "
arr = [1, 2, 3]
assert (item_at_index_or_none(arr, 1) == 2)
assert (item_at_index_or_none(arr, 10) is None) | 9,027,047,907,124,018,000 | Assert that item_at_index_or_none returns an item at a given index, or None if that index
doesn't exist | main/utils_test.py | test_item_at_index_or_none | mitodl/bootcamp-ecommerce | python | def test_item_at_index_or_none():
"\n Assert that item_at_index_or_none returns an item at a given index, or None if that index\n doesn't exist\n "
arr = [1, 2, 3]
assert (item_at_index_or_none(arr, 1) == 2)
assert (item_at_index_or_none(arr, 10) is None) |
def test_all_equal():
'\n Assert that all_equal returns True if all of the provided args are equal to each other\n '
assert (all_equal(1, 1, 1) is True)
assert (all_equal(1, 2, 1) is False)
assert (all_equal() is True) | 6,843,933,897,489,577,000 | Assert that all_equal returns True if all of the provided args are equal to each other | main/utils_test.py | test_all_equal | mitodl/bootcamp-ecommerce | python | def test_all_equal():
'\n \n '
assert (all_equal(1, 1, 1) is True)
assert (all_equal(1, 2, 1) is False)
assert (all_equal() is True) |
def test_all_unique():
'\n Assert that all_unique returns True if all of the items in the iterable argument are unique\n '
assert (all_unique([1, 2, 3, 4]) is True)
assert (all_unique((1, 2, 3, 4)) is True)
assert (all_unique([1, 2, 3, 1]) is False) | -4,191,406,065,421,053,000 | Assert that all_unique returns True if all of the items in the iterable argument are unique | main/utils_test.py | test_all_unique | mitodl/bootcamp-ecommerce | python | def test_all_unique():
'\n \n '
assert (all_unique([1, 2, 3, 4]) is True)
assert (all_unique((1, 2, 3, 4)) is True)
assert (all_unique([1, 2, 3, 1]) is False) |
def test_has_all_keys():
'\n Assert that has_all_keys returns True if the given dict has all of the specified keys\n '
d = {'a': 1, 'b': 2, 'c': 3}
assert (has_all_keys(d, ['a', 'c']) is True)
assert (has_all_keys(d, ['a', 'z']) is False) | -3,950,808,303,279,116,000 | Assert that has_all_keys returns True if the given dict has all of the specified keys | main/utils_test.py | test_has_all_keys | mitodl/bootcamp-ecommerce | python | def test_has_all_keys():
'\n \n '
d = {'a': 1, 'b': 2, 'c': 3}
assert (has_all_keys(d, ['a', 'c']) is True)
assert (has_all_keys(d, ['a', 'z']) is False) |
def test_is_blank():
'\n Assert that is_blank returns True if the given value is None or a blank string\n '
assert (is_blank('') is True)
assert (is_blank(None) is True)
assert (is_blank(0) is False)
assert (is_blank(' ') is False)
assert (is_blank(False) is False)
assert (is_blank('va... | -20,777,822,704,435,870 | Assert that is_blank returns True if the given value is None or a blank string | main/utils_test.py | test_is_blank | mitodl/bootcamp-ecommerce | python | def test_is_blank():
'\n \n '
assert (is_blank() is True)
assert (is_blank(None) is True)
assert (is_blank(0) is False)
assert (is_blank(' ') is False)
assert (is_blank(False) is False)
assert (is_blank('value') is False) |
def test_group_into_dict():
'\n Assert that group_into_dict takes an iterable of items and returns a dictionary of those items\n grouped by generated keys\n '
class Car():
def __init__(self, make, model):
self.make = make
self.model = model
cars = [Car(make='Honda'... | -6,935,898,489,097,271,000 | Assert that group_into_dict takes an iterable of items and returns a dictionary of those items
grouped by generated keys | main/utils_test.py | test_group_into_dict | mitodl/bootcamp-ecommerce | python | def test_group_into_dict():
'\n Assert that group_into_dict takes an iterable of items and returns a dictionary of those items\n grouped by generated keys\n '
class Car():
def __init__(self, make, model):
self.make = make
self.model = model
cars = [Car(make='Honda'... |
def test_filter_dict_by_key_set():
'\n Test that filter_dict_by_key_set returns a dict with only the given keys\n '
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
assert (filter_dict_by_key_set(d, {'a', 'c'}) == {'a': 1, 'c': 3})
assert (filter_dict_by_key_set(d, {'a', 'c', 'nonsense'}) == {'a': 1, 'c': 3})... | -1,523,572,021,128,611,600 | Test that filter_dict_by_key_set returns a dict with only the given keys | main/utils_test.py | test_filter_dict_by_key_set | mitodl/bootcamp-ecommerce | python | def test_filter_dict_by_key_set():
'\n \n '
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
assert (filter_dict_by_key_set(d, {'a', 'c'}) == {'a': 1, 'c': 3})
assert (filter_dict_by_key_set(d, {'a', 'c', 'nonsense'}) == {'a': 1, 'c': 3})
assert (filter_dict_by_key_set(d, {'nonsense'}) == {}) |
def test_partition_to_lists():
'\n Assert that partition_to_lists splits an iterable into two lists according to a condition\n '
nums = [1, 2, 1, 3, 1, 4, 0, None, None]
(not_ones, ones) = partition_to_lists(nums, (lambda n: (n == 1)))
assert (not_ones == [2, 3, 4, 0, None, None])
assert (ones... | 8,380,860,281,203,333,000 | Assert that partition_to_lists splits an iterable into two lists according to a condition | main/utils_test.py | test_partition_to_lists | mitodl/bootcamp-ecommerce | python | def test_partition_to_lists():
'\n \n '
nums = [1, 2, 1, 3, 1, 4, 0, None, None]
(not_ones, ones) = partition_to_lists(nums, (lambda n: (n == 1)))
assert (not_ones == [2, 3, 4, 0, None, None])
assert (ones == [1, 1, 1])
(falsey, truthy) = partition_to_lists(nums)
assert (falsey == [0, ... |
def test_partition_around_index():
'partition_around_index should split a list into two lists around an index'
assert (partition_around_index([1, 2, 3, 4], 2) == ([1, 2], [4]))
assert (partition_around_index([1, 2, 3, 4], 0) == ([], [2, 3, 4]))
assert (partition_around_index([1, 2, 3, 4], 3) == ([1, 2, ... | 8,945,775,255,869,581,000 | partition_around_index should split a list into two lists around an index | main/utils_test.py | test_partition_around_index | mitodl/bootcamp-ecommerce | python | def test_partition_around_index():
assert (partition_around_index([1, 2, 3, 4], 2) == ([1, 2], [4]))
assert (partition_around_index([1, 2, 3, 4], 0) == ([], [2, 3, 4]))
assert (partition_around_index([1, 2, 3, 4], 3) == ([1, 2, 3], []))
with pytest.raises(ValueError):
partition_around_index... |
@pytest.mark.parametrize('content,content_type,exp_summary_content,exp_url_in_summary', [['{"bad": "response"}', 'application/json', '{"bad": "response"}', False], ['plain text', 'text/plain', 'plain text', False], ['<div>HTML content</div>', 'text/html; charset=utf-8', '(HTML body ignored)', True]])
def test_get_error... | 3,631,322,079,011,886,600 | get_error_response_summary should provide a summary of an error HTTP response object with the correct bits of
information depending on the type of content. | main/utils_test.py | test_get_error_response_summary | mitodl/bootcamp-ecommerce | python | @pytest.mark.parametrize('content,content_type,exp_summary_content,exp_url_in_summary', [['{"bad": "response"}', 'application/json', '{"bad": "response"}', False], ['plain text', 'text/plain', 'plain text', False], ['<div>HTML content</div>', 'text/html; charset=utf-8', '(HTML body ignored)', True]])
def test_get_error... |
@pytest.mark.django_db
def test_jsonfield(settings):
'\n Test a model with a JSONField is handled correctly\n '
settings.CYBERSOURCE_SECURITY_KEY = 'asdf'
receipt = ReceiptFactory.create()
assert (serialize_model_object(receipt) == {'created_on': format_as_iso8601(receipt.created_on), 'data': rece... | -4,728,769,654,445,678,000 | Test a model with a JSONField is handled correctly | main/utils_test.py | test_jsonfield | mitodl/bootcamp-ecommerce | python | @pytest.mark.django_db
def test_jsonfield(settings):
'\n \n '
settings.CYBERSOURCE_SECURITY_KEY = 'asdf'
receipt = ReceiptFactory.create()
assert (serialize_model_object(receipt) == {'created_on': format_as_iso8601(receipt.created_on), 'data': receipt.data, 'id': receipt.id, 'updated_on': format_a... |
def test_get_field_names():
'\n Assert that get_field_names does not include related fields\n '
assert (set(get_field_names(Order)) == {'user', 'status', 'total_price_paid', 'application', 'created_on', 'updated_on', 'payment_type'}) | -7,139,863,925,248,950,000 | Assert that get_field_names does not include related fields | main/utils_test.py | test_get_field_names | mitodl/bootcamp-ecommerce | python | def test_get_field_names():
'\n \n '
assert (set(get_field_names(Order)) == {'user', 'status', 'total_price_paid', 'application', 'created_on', 'updated_on', 'payment_type'}) |
def test_is_empty_file():
'is_empty_file should return True if the given object is None or has a blank name property'
fake_file = None
assert (is_empty_file(fake_file) is True)
fake_file = SimpleNamespace(name='')
assert (is_empty_file(fake_file) is True)
fake_file = SimpleNamespace(name='path/t... | 8,666,167,418,031,092,000 | is_empty_file should return True if the given object is None or has a blank name property | main/utils_test.py | test_is_empty_file | mitodl/bootcamp-ecommerce | python | def test_is_empty_file():
fake_file = None
assert (is_empty_file(fake_file) is True)
fake_file = SimpleNamespace(name=)
assert (is_empty_file(fake_file) is True)
fake_file = SimpleNamespace(name='path/to/file.txt')
assert (is_empty_file(fake_file) is False) |
def test_chunks():
'\n test for chunks\n '
input_list = list(range(113))
output_list = []
for nums in chunks(input_list):
output_list += nums
assert (output_list == input_list)
output_list = []
for nums in chunks(input_list, chunk_size=1):
output_list += nums
assert... | -6,628,668,773,888,255,000 | test for chunks | main/utils_test.py | test_chunks | mitodl/bootcamp-ecommerce | python | def test_chunks():
'\n \n '
input_list = list(range(113))
output_list = []
for nums in chunks(input_list):
output_list += nums
assert (output_list == input_list)
output_list = []
for nums in chunks(input_list, chunk_size=1):
output_list += nums
assert (output_list =... |
def test_chunks_iterable():
'\n test that chunks works on non-list iterables too\n '
count = 113
input_range = range(count)
chunk_output = []
for chunk in chunks(input_range, chunk_size=10):
chunk_output.append(chunk)
assert (len(chunk_output) == ceil((113 / 10)))
range_list = ... | 5,628,105,431,535,348,000 | test that chunks works on non-list iterables too | main/utils_test.py | test_chunks_iterable | mitodl/bootcamp-ecommerce | python | def test_chunks_iterable():
'\n \n '
count = 113
input_range = range(count)
chunk_output = []
for chunk in chunks(input_range, chunk_size=10):
chunk_output.append(chunk)
assert (len(chunk_output) == ceil((113 / 10)))
range_list = []
for chunk in chunk_output:
range_... |
def test_format_month_day():
'\n format_month_day should format the month and day from a datetime\n '
dt = datetime.datetime(year=2020, month=1, day=1, tzinfo=pytz.UTC)
assert (format_month_day(dt) == 'Jan 1')
assert (format_month_day(dt, month_fmt='%b') == 'Jan 1')
assert (format_month_day(dt... | -5,556,454,043,159,934,000 | format_month_day should format the month and day from a datetime | main/utils_test.py | test_format_month_day | mitodl/bootcamp-ecommerce | python | def test_format_month_day():
'\n \n '
dt = datetime.datetime(year=2020, month=1, day=1, tzinfo=pytz.UTC)
assert (format_month_day(dt) == 'Jan 1')
assert (format_month_day(dt, month_fmt='%b') == 'Jan 1')
assert (format_month_day(dt, month_fmt='%B') == 'January 1') |
def test_has_equal_properties():
'\n Assert that has_equal_properties returns True if an object has equivalent properties to a given dict\n '
obj = SimpleNamespace(a=1, b=2, c=3)
assert (has_equal_properties(obj, {}) is True)
assert (has_equal_properties(obj, dict(a=1, b=2)) is True)
assert (h... | -3,059,819,990,250,566,000 | Assert that has_equal_properties returns True if an object has equivalent properties to a given dict | main/utils_test.py | test_has_equal_properties | mitodl/bootcamp-ecommerce | python | def test_has_equal_properties():
'\n \n '
obj = SimpleNamespace(a=1, b=2, c=3)
assert (has_equal_properties(obj, {}) is True)
assert (has_equal_properties(obj, dict(a=1, b=2)) is True)
assert (has_equal_properties(obj, dict(a=1, b=2, c=3)) is True)
assert (has_equal_properties(obj, dict(a=... |
def __init__(self, file_pattern, min_bundle_size, compression_type, strip_trailing_newlines, coder, buffer_size=DEFAULT_READ_BUFFER_SIZE, validate=True, skip_header_lines=0, header_processor_fns=(None, None)):
'Initialize a _TextSource\n\n Args:\n header_processor_fns (tuple): a tuple of a `header_matcher` ... | 7,102,111,700,206,611,000 | Initialize a _TextSource
Args:
header_processor_fns (tuple): a tuple of a `header_matcher` function
and a `header_processor` function. The `header_matcher` should
return `True` for all lines at the start of the file that are part
of the file header and `False` otherwise. These header lines will
not b... | sdks/python/apache_beam/io/textio.py | __init__ | AhnLab-OSS/beam | python | def __init__(self, file_pattern, min_bundle_size, compression_type, strip_trailing_newlines, coder, buffer_size=DEFAULT_READ_BUFFER_SIZE, validate=True, skip_header_lines=0, header_processor_fns=(None, None)):
'Initialize a _TextSource\n\n Args:\n header_processor_fns (tuple): a tuple of a `header_matcher` ... |
def _skip_lines(self, file_to_read, read_buffer, num_lines):
'Skip num_lines from file_to_read, return num_lines+1 start position.'
if (file_to_read.tell() > 0):
file_to_read.seek(0)
position = 0
for _ in range(num_lines):
(_, num_bytes_to_next_record) = self._read_record(file_to_read, r... | -6,993,979,125,286,766,000 | Skip num_lines from file_to_read, return num_lines+1 start position. | sdks/python/apache_beam/io/textio.py | _skip_lines | AhnLab-OSS/beam | python | def _skip_lines(self, file_to_read, read_buffer, num_lines):
if (file_to_read.tell() > 0):
file_to_read.seek(0)
position = 0
for _ in range(num_lines):
(_, num_bytes_to_next_record) = self._read_record(file_to_read, read_buffer)
if (num_bytes_to_next_record < 0):
bre... |
def __init__(self, file_path_prefix, file_name_suffix='', append_trailing_newlines=True, num_shards=0, shard_name_template=None, coder=coders.ToStringCoder(), compression_type=CompressionTypes.AUTO, header=None):
"Initialize a _TextSink.\n\n Args:\n file_path_prefix: The file path to write to. The files wri... | 2,864,030,333,706,770,000 | Initialize a _TextSink.
Args:
file_path_prefix: The file path to write to. The files written will begin
with this prefix, followed by a shard identifier (see num_shards), and
end in a common extension, if given by file_name_suffix. In most cases,
only this argument is specified and nu... | sdks/python/apache_beam/io/textio.py | __init__ | AhnLab-OSS/beam | python | def __init__(self, file_path_prefix, file_name_suffix=, append_trailing_newlines=True, num_shards=0, shard_name_template=None, coder=coders.ToStringCoder(), compression_type=CompressionTypes.AUTO, header=None):
"Initialize a _TextSink.\n\n Args:\n file_path_prefix: The file path to write to. The files writt... |
def write_encoded_record(self, file_handle, encoded_value):
'Writes a single encoded record.'
file_handle.write(encoded_value)
if self._append_trailing_newlines:
file_handle.write(b'\n') | -7,928,732,276,254,415,000 | Writes a single encoded record. | sdks/python/apache_beam/io/textio.py | write_encoded_record | AhnLab-OSS/beam | python | def write_encoded_record(self, file_handle, encoded_value):
file_handle.write(encoded_value)
if self._append_trailing_newlines:
file_handle.write(b'\n') |
def __init__(self, min_bundle_size=0, desired_bundle_size=DEFAULT_DESIRED_BUNDLE_SIZE, compression_type=CompressionTypes.AUTO, strip_trailing_newlines=True, coder=coders.StrUtf8Coder(), skip_header_lines=0, **kwargs):
"Initialize the ``ReadAllFromText`` transform.\n\n Args:\n min_bundle_size: Minimum size o... | 6,986,434,036,015,012,000 | Initialize the ``ReadAllFromText`` transform.
Args:
min_bundle_size: Minimum size of bundles that should be generated when
splitting this source into bundles. See ``FileBasedSource`` for more
details.
desired_bundle_size: Desired size of bundles that should be generated when
splitting this source into ... | sdks/python/apache_beam/io/textio.py | __init__ | AhnLab-OSS/beam | python | def __init__(self, min_bundle_size=0, desired_bundle_size=DEFAULT_DESIRED_BUNDLE_SIZE, compression_type=CompressionTypes.AUTO, strip_trailing_newlines=True, coder=coders.StrUtf8Coder(), skip_header_lines=0, **kwargs):
"Initialize the ``ReadAllFromText`` transform.\n\n Args:\n min_bundle_size: Minimum size o... |
def __init__(self, file_pattern=None, min_bundle_size=0, compression_type=CompressionTypes.AUTO, strip_trailing_newlines=True, coder=coders.StrUtf8Coder(), validate=True, skip_header_lines=0, **kwargs):
"Initialize the :class:`ReadFromText` transform.\n\n Args:\n file_pattern (str): The file path to read fr... | 7,339,110,293,041,342,000 | Initialize the :class:`ReadFromText` transform.
Args:
file_pattern (str): The file path to read from as a local file path or a
GCS ``gs://`` path. The path can contain glob characters
(``*``, ``?``, and ``[...]`` sets).
min_bundle_size (int): Minimum size of bundles that should be generated
when splitt... | sdks/python/apache_beam/io/textio.py | __init__ | AhnLab-OSS/beam | python | def __init__(self, file_pattern=None, min_bundle_size=0, compression_type=CompressionTypes.AUTO, strip_trailing_newlines=True, coder=coders.StrUtf8Coder(), validate=True, skip_header_lines=0, **kwargs):
"Initialize the :class:`ReadFromText` transform.\n\n Args:\n file_pattern (str): The file path to read fr... |
def __init__(self, file_path_prefix, file_name_suffix='', append_trailing_newlines=True, num_shards=0, shard_name_template=None, coder=coders.ToStringCoder(), compression_type=CompressionTypes.AUTO, header=None):
"Initialize a :class:`WriteToText` transform.\n\n Args:\n file_path_prefix (str): The file path... | 1,442,425,946,996,938,800 | Initialize a :class:`WriteToText` transform.
Args:
file_path_prefix (str): The file path to write to. The files written will
begin with this prefix, followed by a shard identifier (see
**num_shards**), and end in a common extension, if given by
**file_name_suffix**. In most cases, only this argument is s... | sdks/python/apache_beam/io/textio.py | __init__ | AhnLab-OSS/beam | python | def __init__(self, file_path_prefix, file_name_suffix=, append_trailing_newlines=True, num_shards=0, shard_name_template=None, coder=coders.ToStringCoder(), compression_type=CompressionTypes.AUTO, header=None):
"Initialize a :class:`WriteToText` transform.\n\n Args:\n file_path_prefix (str): The file path t... |
def register_extensions(app: Flask):
'注册需要的扩展程序包到 Flask 程序实例 app 中'
db.init_app(app)
login_manager.init_app(app)
csrf.init_app(app)
moment.init_app(app) | 8,959,475,275,388,297,000 | 注册需要的扩展程序包到 Flask 程序实例 app 中 | telechat/__init__.py | register_extensions | Sefank/telechat | python | def register_extensions(app: Flask):
db.init_app(app)
login_manager.init_app(app)
csrf.init_app(app)
moment.init_app(app) |
def register_blueprints(app: Flask):
'注册需要的蓝图程序包到 Flask 程序实例 app 中'
app.register_blueprint(auth_bp)
app.register_blueprint(oauth_bp)
app.register_blueprint(chat_bp)
app.register_blueprint(admin_bp) | 7,145,644,853,949,605,000 | 注册需要的蓝图程序包到 Flask 程序实例 app 中 | telechat/__init__.py | register_blueprints | Sefank/telechat | python | def register_blueprints(app: Flask):
app.register_blueprint(auth_bp)
app.register_blueprint(oauth_bp)
app.register_blueprint(chat_bp)
app.register_blueprint(admin_bp) |
def register_errors(app: Flask):
'注册需要的错误处理程序包到 Flask 程序实例 app 中'
@app.errorhandler(400)
def bad_request(e):
return (render_template('error.html', description=e.description, code=e.code), 400)
@app.errorhandler(404)
def page_not_found(e):
return (render_template('error.html', descr... | 1,824,958,579,672,288,500 | 注册需要的错误处理程序包到 Flask 程序实例 app 中 | telechat/__init__.py | register_errors | Sefank/telechat | python | def register_errors(app: Flask):
@app.errorhandler(400)
def bad_request(e):
return (render_template('error.html', description=e.description, code=e.code), 400)
@app.errorhandler(404)
def page_not_found(e):
return (render_template('error.html', description=e.description, code=e.cod... |
def register_commands(app: Flask):
'注册需要的CLI命令程序包到 Flask 程序实例 app 中'
@app.cli.command()
@click.option('--drop', is_flag=True, help='创建之前销毁数据库')
def initdb(drop: bool):
'初始化数据库结构'
if drop:
pass
pass
@app.cli.command()
@click.option('--num', default=300, help=... | 1,707,144,654,204,815,000 | 注册需要的CLI命令程序包到 Flask 程序实例 app 中 | telechat/__init__.py | register_commands | Sefank/telechat | python | def register_commands(app: Flask):
@app.cli.command()
@click.option('--drop', is_flag=True, help='创建之前销毁数据库')
def initdb(drop: bool):
'初始化数据库结构'
if drop:
pass
pass
@app.cli.command()
@click.option('--num', default=300, help='消息数量,默认为300')
def forge(num:... |
def create_app(config_name=None):
'程序工厂:创建 Flask 程序,加载配置,注册扩展、蓝图等程序包'
if (config_name is None):
config_name = os.getenv('FLASK_CONFIG', 'development')
app = Flask('telechat')
app.config.from_object(config[config_name])
register_extensions(app)
register_blueprints(app)
register_errors... | -5,401,803,342,700,037,000 | 程序工厂:创建 Flask 程序,加载配置,注册扩展、蓝图等程序包 | telechat/__init__.py | create_app | Sefank/telechat | python | def create_app(config_name=None):
if (config_name is None):
config_name = os.getenv('FLASK_CONFIG', 'development')
app = Flask('telechat')
app.config.from_object(config[config_name])
register_extensions(app)
register_blueprints(app)
register_errors(app)
register_commands(app)
... |
@app.cli.command()
@click.option('--drop', is_flag=True, help='创建之前销毁数据库')
def initdb(drop: bool):
'初始化数据库结构'
if drop:
pass
pass | -6,779,515,592,460,771,000 | 初始化数据库结构 | telechat/__init__.py | initdb | Sefank/telechat | python | @app.cli.command()
@click.option('--drop', is_flag=True, help='创建之前销毁数据库')
def initdb(drop: bool):
if drop:
pass
pass |
@app.cli.command()
@click.option('--num', default=300, help='消息数量,默认为300')
def forge(num: int):
'生成虚拟数据'
pass | -5,643,895,302,043,924,000 | 生成虚拟数据 | telechat/__init__.py | forge | Sefank/telechat | python | @app.cli.command()
@click.option('--num', default=300, help='消息数量,默认为300')
def forge(num: int):
pass |
def load_configuration(configuration_file_path, parameters_file_path, bundles):
'Combines the configuration and parameters and build the configuration object'
mappings = {}
for bundle in bundles:
if hasattr(bundle, 'config_mapping'):
mappings.update(bundle.config_mapping)
loader = Ym... | 259,998,891,701,529,540 | Combines the configuration and parameters and build the configuration object | applauncher/configuration.py | load_configuration | applauncher-team/applauncher | python | def load_configuration(configuration_file_path, parameters_file_path, bundles):
mappings = {}
for bundle in bundles:
if hasattr(bundle, 'config_mapping'):
mappings.update(bundle.config_mapping)
loader = YmlLoader()
return loader.build_config(mappings, config_source=configuration... |
def is_string(value):
'Check if the value is actually a string or not'
try:
float(value)
return False
except ValueError:
if (value.lower() in ['true', 'false']):
return False
return True | 3,238,916,346,945,022,500 | Check if the value is actually a string or not | applauncher/configuration.py | is_string | applauncher-team/applauncher | python | def is_string(value):
try:
float(value)
return False
except ValueError:
if (value.lower() in ['true', 'false']):
return False
return True |
@abstractmethod
def load_parameters(self, source):
'Convert the source into a dictionary' | -4,875,817,250,234,026,000 | Convert the source into a dictionary | applauncher/configuration.py | load_parameters | applauncher-team/applauncher | python | @abstractmethod
def load_parameters(self, source):
|
@abstractmethod
def load_config(self, config_source, parameters_source):
'Prase the config file and build a dictionary' | -2,837,957,084,366,495,000 | Prase the config file and build a dictionary | applauncher/configuration.py | load_config | applauncher-team/applauncher | python | @abstractmethod
def load_config(self, config_source, parameters_source):
|
def build_config(self, config_mappings, config_source, parameters_source):
'By using the loaded parameters and loaded config, build the final configuration object'
configuration_class = create_model('Configuration', **{k: (v, ...) for (k, v) in config_mappings.items()})
return configuration_class(**self.loa... | 311,806,605,572,668,300 | By using the loaded parameters and loaded config, build the final configuration object | applauncher/configuration.py | build_config | applauncher-team/applauncher | python | def build_config(self, config_mappings, config_source, parameters_source):
configuration_class = create_model('Configuration', **{k: (v, ...) for (k, v) in config_mappings.items()})
return configuration_class(**self.load_config(config_source, parameters_source)) |
def load_parameters(self, source):
'For YML, the source it the file path'
with open(source, encoding=locale.getpreferredencoding(False)) as parameters_source:
loaded = yaml.safe_load(parameters_source.read())
if loaded:
for (key, value) in loaded.items():
if isinstanc... | 9,100,939,142,661,697,000 | For YML, the source it the file path | applauncher/configuration.py | load_parameters | applauncher-team/applauncher | python | def load_parameters(self, source):
with open(source, encoding=locale.getpreferredencoding(False)) as parameters_source:
loaded = yaml.safe_load(parameters_source.read())
if loaded:
for (key, value) in loaded.items():
if isinstance(value, str):
loa... |
def load_config(self, config_source, parameters_source):
'For YML, the source it the file path'
with open(config_source, encoding=locale.getpreferredencoding(False)) as config_source_file:
config_raw = config_source_file.read()
parameters = {}
if os.path.isfile(parameters_source):
... | -1,562,659,037,624,938,800 | For YML, the source it the file path | applauncher/configuration.py | load_config | applauncher-team/applauncher | python | def load_config(self, config_source, parameters_source):
with open(config_source, encoding=locale.getpreferredencoding(False)) as config_source_file:
config_raw = config_source_file.read()
parameters = {}
if os.path.isfile(parameters_source):
params = self.load_parameters(pa... |
def test_insert_heterogeneous_params(self):
'test that executemany parameters are asserted to match the\n parameter set of the first.'
users = self.tables.users
assert_raises_message(exc.StatementError, "\\(sqlalchemy.exc.InvalidRequestError\\) A value is required for bind parameter 'user_name', in p... | -7,232,828,510,795,666,000 | test that executemany parameters are asserted to match the
parameter set of the first. | test/sql/test_insert_exec.py | test_insert_heterogeneous_params | AngelLiang/hacking-sqlalchemy | python | def test_insert_heterogeneous_params(self):
'test that executemany parameters are asserted to match the\n parameter set of the first.'
users = self.tables.users
assert_raises_message(exc.StatementError, "\\(sqlalchemy.exc.InvalidRequestError\\) A value is required for bind parameter 'user_name', in p... |
def _test_lastrow_accessor(self, table_, values, assertvalues):
'Tests the inserted_primary_key and lastrow_has_id() functions.'
def insert_values(engine, table_, values):
'\n Inserts a row into a table, returns the full list of values\n INSERTed including defaults that fired off ... | -6,284,793,476,165,940,000 | Tests the inserted_primary_key and lastrow_has_id() functions. | test/sql/test_insert_exec.py | _test_lastrow_accessor | AngelLiang/hacking-sqlalchemy | python | def _test_lastrow_accessor(self, table_, values, assertvalues):
def insert_values(engine, table_, values):
'\n Inserts a row into a table, returns the full list of values\n INSERTed including defaults that fired off on the DB side and\n detects rows that had defaults a... |
def insert_values(engine, table_, values):
'\n Inserts a row into a table, returns the full list of values\n INSERTed including defaults that fired off on the DB side and\n detects rows that had defaults and post-fetches.\n '
if engine.dialect.implicit_returning:
... | 1,840,504,308,974,259,000 | Inserts a row into a table, returns the full list of values
INSERTed including defaults that fired off on the DB side and
detects rows that had defaults and post-fetches. | test/sql/test_insert_exec.py | insert_values | AngelLiang/hacking-sqlalchemy | python | def insert_values(engine, table_, values):
'\n Inserts a row into a table, returns the full list of values\n INSERTed including defaults that fired off on the DB side and\n detects rows that had defaults and post-fetches.\n '
if engine.dialect.implicit_returning:
... |
@pytest.fixture
def start_south(self, add_south, remove_data_file, remove_directories, south_branch, fledge_url):
' This fixture clone a south repo and starts south instance\n add_south: Fixture that starts any south service with given configuration\n remove_data_file: Fixture that remove data... | -5,151,229,683,836,889,000 | This fixture clone a south repo and starts south instance
add_south: Fixture that starts any south service with given configuration
remove_data_file: Fixture that remove data file created during the tests
remove_directories: Fixture that remove directories created during the tests | tests/system/python/e2e/test_e2e_notification_service_with_plugins.py | start_south | YashTatkondawar/fledge | python | @pytest.fixture
def start_south(self, add_south, remove_data_file, remove_directories, south_branch, fledge_url):
' This fixture clone a south repo and starts south instance\n add_south: Fixture that starts any south service with given configuration\n remove_data_file: Fixture that remove data... |
def prepare_template_reading_from_fogbench(self):
' Define the template file for fogbench readings '
fogbench_template_path = os.path.join(os.path.expandvars('${FLEDGE_ROOT}'), 'data/{}'.format(self.FOGBENCH_TEMPLATE))
with open(fogbench_template_path, 'w') as f:
f.write(('[{"name": "%s", "sensor_va... | -4,634,762,238,000,365,000 | Define the template file for fogbench readings | tests/system/python/e2e/test_e2e_notification_service_with_plugins.py | prepare_template_reading_from_fogbench | YashTatkondawar/fledge | python | def prepare_template_reading_from_fogbench(self):
' '
fogbench_template_path = os.path.join(os.path.expandvars('${FLEDGE_ROOT}'), 'data/{}'.format(self.FOGBENCH_TEMPLATE))
with open(fogbench_template_path, 'w') as f:
f.write(('[{"name": "%s", "sensor_values": [{"name": "sensor", "type": "number", "... |
def get_ratio_data(vocabpath, sizecap, ratio, tags4positive, tags4negative, excludebelow=0, excludeabove=3000):
" Loads metadata, selects instances for the positive\n and negative classes (using a ratio to dilute the positive\n class with negative instances), creates a lexicon if one doesn't\n already exis... | 2,959,876,061,134,097,000 | Loads metadata, selects instances for the positive
and negative classes (using a ratio to dilute the positive
class with negative instances), creates a lexicon if one doesn't
already exist, and creates a pandas dataframe storing
texts as rows and words/features as columns. A refactored
and simplified version of get_dat... | variation/methodological_experiment.py | get_ratio_data | tedunderwood/fiction | python | def get_ratio_data(vocabpath, sizecap, ratio, tags4positive, tags4negative, excludebelow=0, excludeabove=3000):
" Loads metadata, selects instances for the positive\n and negative classes (using a ratio to dilute the positive\n class with negative instances), creates a lexicon if one doesn't\n already exis... |
def kldivergence(p, q):
'Kullback-Leibler divergence D(P || Q) for discrete distributions\n Parameters\n ----------\n p, q : array-like, dtype=float, shape=n\n Discrete probability distributions.\n '
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
return np.sum(np.wher... | -3,483,818,306,852,924,400 | Kullback-Leibler divergence D(P || Q) for discrete distributions
Parameters
----------
p, q : array-like, dtype=float, shape=n
Discrete probability distributions. | variation/methodological_experiment.py | kldivergence | tedunderwood/fiction | python | def kldivergence(p, q):
'Kullback-Leibler divergence D(P || Q) for discrete distributions\n Parameters\n ----------\n p, q : array-like, dtype=float, shape=n\n Discrete probability distributions.\n '
p = np.asarray(p, dtype=np.float)
q = np.asarray(q, dtype=np.float)
return np.sum(np.wher... |
def get_divergences(gold, testname, itera, size, pct):
'\n This function gets several possible measures of divergence\n between two models.\n '
model1 = (('../measuredivergence/modeloutput/' + gold) + '.pkl')
meta1 = (('../measuredivergence/modeloutput/' + gold) + '.csv')
testpath = ('../measur... | -5,795,583,140,593,156,000 | This function gets several possible measures of divergence
between two models. | variation/methodological_experiment.py | get_divergences | tedunderwood/fiction | python | def get_divergences(gold, testname, itera, size, pct):
'\n This function gets several possible measures of divergence\n between two models.\n '
model1 = (('../measuredivergence/modeloutput/' + gold) + '.pkl')
meta1 = (('../measuredivergence/modeloutput/' + gold) + '.csv')
testpath = ('../measur... |
def get_divergence(sampleA, sampleB, twodatafolder='../data/', onedatafolder='../data/'):
'\n This function applies model a to b, and vice versa, and returns\n a couple of measures of divergence: notably lost accuracy and\n z-tranformed spearman correlation.\n '
model1 = (('../measuredivergence/newm... | 2,197,540,136,824,818,000 | This function applies model a to b, and vice versa, and returns
a couple of measures of divergence: notably lost accuracy and
z-tranformed spearman correlation. | variation/methodological_experiment.py | get_divergence | tedunderwood/fiction | python | def get_divergence(sampleA, sampleB, twodatafolder='../data/', onedatafolder='../data/'):
'\n This function applies model a to b, and vice versa, and returns\n a couple of measures of divergence: notably lost accuracy and\n z-tranformed spearman correlation.\n '
model1 = (('../measuredivergence/newm... |
@pytest.fixture
def start_of_recurrence(future_date):
'\n Date object representing the first day of a record with recurrence\n '
return future_date | 5,637,887,532,328,062,000 | Date object representing the first day of a record with recurrence | moneyforecast/tests/records/fixtures.py | start_of_recurrence | curaloucura/money-forecast | python | @pytest.fixture
def start_of_recurrence(future_date):
'\n \n '
return future_date |
@pytest.fixture
def end_of_recurrence(future_date):
'\n Return a date which is used to determine the end month the recurrence\n should occur\n '
date = (future_date + relativedelta(months=6))
return date | -4,469,297,031,474,214,400 | Return a date which is used to determine the end month the recurrence
should occur | moneyforecast/tests/records/fixtures.py | end_of_recurrence | curaloucura/money-forecast | python | @pytest.fixture
def end_of_recurrence(future_date):
'\n Return a date which is used to determine the end month the recurrence\n should occur\n '
date = (future_date + relativedelta(months=6))
return date |
@pytest.fixture
def month_control(user, current_date):
'\n Return a MonthControl object for the current date.\n\n Important: currently any Record fixture should come before month_control\n '
month_control = MonthControl(user, current_date.month, current_date.year, cache={})
return month_control | 6,479,720,257,097,776,000 | Return a MonthControl object for the current date.
Important: currently any Record fixture should come before month_control | moneyforecast/tests/records/fixtures.py | month_control | curaloucura/money-forecast | python | @pytest.fixture
def month_control(user, current_date):
'\n Return a MonthControl object for the current date.\n\n Important: currently any Record fixture should come before month_control\n '
month_control = MonthControl(user, current_date.month, current_date.year, cache={})
return month_control |
@pytest.fixture
def month_control_with_budget(user, current_date):
'\n Return a MonthControlWithBudget object for the current date.\n\n Important: currently any Record fixture should come before month_control\n '
month_control = MonthControlWithBudget(user, current_date.month, current_date.year, cache=... | 5,738,756,399,209,524,000 | Return a MonthControlWithBudget object for the current date.
Important: currently any Record fixture should come before month_control | moneyforecast/tests/records/fixtures.py | month_control_with_budget | curaloucura/money-forecast | python | @pytest.fixture
def month_control_with_budget(user, current_date):
'\n Return a MonthControlWithBudget object for the current date.\n\n Important: currently any Record fixture should come before month_control\n '
month_control = MonthControlWithBudget(user, current_date.month, current_date.year, cache=... |
@pytest.fixture
def outcome(user):
'\n Main category of outcome type\n '
category = Category.objects.create(name='outcome', type_category=OUTCOME, user=user)
return category | 6,987,829,848,362,085,000 | Main category of outcome type | moneyforecast/tests/records/fixtures.py | outcome | curaloucura/money-forecast | python | @pytest.fixture
def outcome(user):
'\n \n '
category = Category.objects.create(name='outcome', type_category=OUTCOME, user=user)
return category |
@pytest.fixture
def income(user):
'\n Main category of income type\n '
category = Category.objects.create(name='income', type_category=INCOME, user=user)
return category | 4,078,536,843,082,901,500 | Main category of income type | moneyforecast/tests/records/fixtures.py | income | curaloucura/money-forecast | python | @pytest.fixture
def income(user):
'\n \n '
category = Category.objects.create(name='income', type_category=INCOME, user=user)
return category |
@pytest.fixture
def savings(user):
'\n Category of Savings\n '
category = Category.objects.create(name='savings', type_category=SAVINGS, user=user)
return category | -7,184,796,791,208,873,000 | Category of Savings | moneyforecast/tests/records/fixtures.py | savings | curaloucura/money-forecast | python | @pytest.fixture
def savings(user):
'\n \n '
category = Category.objects.create(name='savings', type_category=SAVINGS, user=user)
return category |
@pytest.fixture
def outcome_current(user, outcome, current_date):
'\n Record of type Outcome set to today (current date)\n '
record = Record.objects.create(category=outcome, amount=1, start_date=current_date, user=user)
return record | 4,778,692,088,416,692,000 | Record of type Outcome set to today (current date) | moneyforecast/tests/records/fixtures.py | outcome_current | curaloucura/money-forecast | python | @pytest.fixture
def outcome_current(user, outcome, current_date):
'\n \n '
record = Record.objects.create(category=outcome, amount=1, start_date=current_date, user=user)
return record |
@pytest.fixture
def outcome_future(user, outcome, future_date):
'\n Record of type Outcome set in the future\n '
record = Record.objects.create(category=outcome, amount=1, start_date=future_date, user=user)
return record | 2,979,084,224,250,077,700 | Record of type Outcome set in the future | moneyforecast/tests/records/fixtures.py | outcome_future | curaloucura/money-forecast | python | @pytest.fixture
def outcome_future(user, outcome, future_date):
'\n \n '
record = Record.objects.create(category=outcome, amount=1, start_date=future_date, user=user)
return record |
@pytest.fixture
def outcome_recurrent(user, outcome, start_of_recurrence):
'\n Record of type Outcome set in the future with a day of the month set\n to create a recurring record\n\n This fixture should not be used with outcome_recurrent_limited and\n outcome_with_parent since they change the instance o... | -1,136,533,490,107,749,800 | Record of type Outcome set in the future with a day of the month set
to create a recurring record
This fixture should not be used with outcome_recurrent_limited and
outcome_with_parent since they change the instance of this own record | moneyforecast/tests/records/fixtures.py | outcome_recurrent | curaloucura/money-forecast | python | @pytest.fixture
def outcome_recurrent(user, outcome, start_of_recurrence):
'\n Record of type Outcome set in the future with a day of the month set\n to create a recurring record\n\n This fixture should not be used with outcome_recurrent_limited and\n outcome_with_parent since they change the instance o... |
@pytest.fixture
def outcome_recurrent_limited(user, outcome_recurrent, end_of_recurrence):
'\n Record of type Outcome set in the future with a recurring day of the month\n set and limited to a certain time\n '
outcome_recurrent.end_date = end_of_recurrence
outcome_recurrent.save()
return outcom... | -463,034,850,628,568,500 | Record of type Outcome set in the future with a recurring day of the month
set and limited to a certain time | moneyforecast/tests/records/fixtures.py | outcome_recurrent_limited | curaloucura/money-forecast | python | @pytest.fixture
def outcome_recurrent_limited(user, outcome_recurrent, end_of_recurrence):
'\n Record of type Outcome set in the future with a recurring day of the month\n set and limited to a certain time\n '
outcome_recurrent.end_date = end_of_recurrence
outcome_recurrent.save()
return outcom... |
@pytest.fixture
def savings_current(request, user, savings, current_date):
'\n Record of type Outcome set in the future\n '
record = Record.objects.create(category=savings, amount=1, start_date=current_date, user=user)
return record | -8,849,889,830,254,215,000 | Record of type Outcome set in the future | moneyforecast/tests/records/fixtures.py | savings_current | curaloucura/money-forecast | python | @pytest.fixture
def savings_current(request, user, savings, current_date):
'\n \n '
record = Record.objects.create(category=savings, amount=1, start_date=current_date, user=user)
return record |
def __init__(self, weight=1.0):
'Constructor for this class does following tasks, if not already downloaded , it first downloads text detector dnn weights file from public URL ands save it at USER_HOME/.katna directory, or /tmp/.katna directory. After this initializer code initializes internal ... | 8,590,788,004,543,124,000 | Constructor for this class does following tasks, if not already downloaded , it first downloads text detector dnn weights file from public URL ands save it at USER_HOME/.katna directory, or /tmp/.katna directory. After this initializer code initializes internal parameter: min_confidence (fo... | Katna/image_filters/text_detector.py | __init__ | jibinmathew69/katna | python | def __init__(self, weight=1.0):
'\n '
super().__init__(weight)
self.min_confidence = config.TextDetector.min_confidence
self.merge_threshold = config.TextDetector.merge_threshold
self.layerNames = config.TextDetector.layerNames
self.frozen_weights = config.TextDetector.frozen_weights
... |
def download_data(self):
'Public function for downloading the network weight from the URL link, to be used for\n text detection functionality. \n Troubleshooting tip: If you get FileNotFound error during text detector initialization,\n initialize the text detector and call this function directl... | 8,059,587,863,676,840,000 | Public function for downloading the network weight from the URL link, to be used for
text detection functionality.
Troubleshooting tip: If you get FileNotFound error during text detector initialization,
initialize the text detector and call this function directly to download the model file from public URL link. | Katna/image_filters/text_detector.py | download_data | jibinmathew69/katna | python | def download_data(self):
'Public function for downloading the network weight from the URL link, to be used for\n text detection functionality. \n Troubleshooting tip: If you get FileNotFound error during text detector initialization,\n initialize the text detector and call this function directl... |
def __decode_predictions(self, scores, geometry):
'Internal Function for getting bounding box and confidence values \n from text detector dnn network output (scores, geometry)\n function takes the number of rows and columns from the scores volume, then\n initializes set of bounding box rectangl... | 4,351,937,684,898,817,500 | Internal Function for getting bounding box and confidence values
from text detector dnn network output (scores, geometry)
function takes the number of rows and columns from the scores volume, then
initializes set of bounding box rectangles and corresponding confidence scores | Katna/image_filters/text_detector.py | __decode_predictions | jibinmathew69/katna | python | def __decode_predictions(self, scores, geometry):
'Internal Function for getting bounding box and confidence values \n from text detector dnn network output (scores, geometry)\n function takes the number of rows and columns from the scores volume, then\n initializes set of bounding box rectangl... |
def __merge_boxes(self, rects):
'main function to detect text boxes from image\n\n :param rects: list of \n :type rects: numpy array\n :param rectsUsed: image file in numpy array/opencv format\n :type rectsUsed: numpy array\n\n :return: output image with the list of text boxes\n ... | -9,106,895,150,870,533,000 | main function to detect text boxes from image
:param rects: list of
:type rects: numpy array
:param rectsUsed: image file in numpy array/opencv format
:type rectsUsed: numpy array
:return: output image with the list of text boxes
:rtype: file, list | Katna/image_filters/text_detector.py | __merge_boxes | jibinmathew69/katna | python | def __merge_boxes(self, rects):
'main function to detect text boxes from image\n\n :param rects: list of \n :type rects: numpy array\n :param rectsUsed: image file in numpy array/opencv format\n :type rectsUsed: numpy array\n\n :return: output image with the list of text boxes\n ... |
def __detect_text(self):
'Internal function to detect text bounding boxes from input image.\n Returns list of bounding boxes of each detected text field in input image.\n\n :param image: image file in numpy array/opencv format\n :type image: numpy array\n :param output_image: image file ... | -8,224,508,995,595,900,000 | Internal function to detect text bounding boxes from input image.
Returns list of bounding boxes of each detected text field in input image.
:param image: image file in numpy array/opencv format
:type image: numpy array
:param output_image: image file in numpy array/opencv format
:type output_image: numpy array
:retu... | Katna/image_filters/text_detector.py | __detect_text | jibinmathew69/katna | python | def __detect_text(self):
'Internal function to detect text bounding boxes from input image.\n Returns list of bounding boxes of each detected text field in input image.\n\n :param image: image file in numpy array/opencv format\n :type image: numpy array\n :param output_image: image file ... |
def set_image(self, image):
'Public set_image function, This will detect all text boxes in input image and\n will saves them as internal list of text_rect to be used in get_filter_result\n\n :param image: input image from which needs to be cropped\n :type image: numpy array(opencv)\n '
... | -6,723,038,099,207,040,000 | Public set_image function, This will detect all text boxes in input image and
will saves them as internal list of text_rect to be used in get_filter_result
:param image: input image from which needs to be cropped
:type image: numpy array(opencv) | Katna/image_filters/text_detector.py | set_image | jibinmathew69/katna | python | def set_image(self, image):
'Public set_image function, This will detect all text boxes in input image and\n will saves them as internal list of text_rect to be used in get_filter_result\n\n :param image: input image from which needs to be cropped\n :type image: numpy array(opencv)\n '
... |
def get_filter_result(self, crop):
'Main public function of TextDetector filter class,\n this filter Returns false if crop contains no text, additionally\n checks for overlap between input crop rectangle and the detected\n text bounding box, returns True if No overlap (Filter will not discard i... | 9,027,545,007,575,559,000 | Main public function of TextDetector filter class,
this filter Returns false if crop contains no text, additionally
checks for overlap between input crop rectangle and the detected
text bounding box, returns True if No overlap (Filter will not discard input crop)
otherwise returns False (signal for discarding input cro... | Katna/image_filters/text_detector.py | get_filter_result | jibinmathew69/katna | python | def get_filter_result(self, crop):
'Main public function of TextDetector filter class,\n this filter Returns false if crop contains no text, additionally\n checks for overlap between input crop rectangle and the detected\n text bounding box, returns True if No overlap (Filter will not discard i... |
def english_filter(tokens):
'\n Given a list of tokens, remove a small list of English stopwords.\n '
non_stopwords = [token for token in tokens if (token not in STOPWORDS)]
while (non_stopwords and (non_stopwords[0] in DROP_FIRST)):
non_stopwords = non_stopwords[1:]
if non_stopwords:
... | -5,594,310,101,230,834,000 | Given a list of tokens, remove a small list of English stopwords. | lightning_conceptnet/nodes.py | english_filter | ldtoolkit/lightning-conceptnet | python | def english_filter(tokens):
'\n \n '
non_stopwords = [token for token in tokens if (token not in STOPWORDS)]
while (non_stopwords and (non_stopwords[0] in DROP_FIRST)):
non_stopwords = non_stopwords[1:]
if non_stopwords:
return non_stopwords
else:
return tokens |
def standardized_concept_uri(lang, text, *more):
"\n Make the appropriate URI for a concept in a particular language, including\n removing English stopwords, normalizing the text in a way appropriate\n to that language (using the text normalization from wordfreq), and joining\n its tokens with underscor... | -705,133,688,007,534,700 | Make the appropriate URI for a concept in a particular language, including
removing English stopwords, normalizing the text in a way appropriate
to that language (using the text normalization from wordfreq), and joining
its tokens with underscores in a concept URI.
This text normalization can smooth over some writing ... | lightning_conceptnet/nodes.py | standardized_concept_uri | ldtoolkit/lightning-conceptnet | python | def standardized_concept_uri(lang, text, *more):
"\n Make the appropriate URI for a concept in a particular language, including\n removing English stopwords, normalizing the text in a way appropriate\n to that language (using the text normalization from wordfreq), and joining\n its tokens with underscor... |
def get_sources_string_names(sources):
'\n For the specified list of @sources which can be strings, Files, or targets,\n get all the output basenames.\n '
names = []
for s in sources:
if hasattr(s, 'held_object'):
s = s.held_object
if isinstance(s, str):
name... | -1,150,719,354,015,871,500 | For the specified list of @sources which can be strings, Files, or targets,
get all the output basenames. | mesonbuild/build.py | get_sources_string_names | jmesmon/meson | python | def get_sources_string_names(sources):
'\n For the specified list of @sources which can be strings, Files, or targets,\n get all the output basenames.\n '
names = []
for s in sources:
if hasattr(s, 'held_object'):
s = s.held_object
if isinstance(s, str):
name... |
@staticmethod
def construct_id_from_path(subdir, name, type_suffix):
'Construct target ID from subdir, name and type suffix.\n\n This helper function is made public mostly for tests.'
name_part = name.replace('/', '@').replace('\\', '@')
assert (not has_path_sep(type_suffix))
my_id = (name_part +... | 30,134,380,908,118,936 | Construct target ID from subdir, name and type suffix.
This helper function is made public mostly for tests. | mesonbuild/build.py | construct_id_from_path | jmesmon/meson | python | @staticmethod
def construct_id_from_path(subdir, name, type_suffix):
'Construct target ID from subdir, name and type suffix.\n\n This helper function is made public mostly for tests.'
name_part = name.replace('/', '@').replace('\\', '@')
assert (not has_path_sep(type_suffix))
my_id = (name_part +... |
def process_compilers_late(self):
"Processes additional compilers after kwargs have been evaluated.\n\n This can add extra compilers that might be required by keyword\n arguments, such as link_with or dependencies. It will also try to guess\n which compiler to use if one hasn't been selected al... | -5,047,288,703,176,062,000 | Processes additional compilers after kwargs have been evaluated.
This can add extra compilers that might be required by keyword
arguments, such as link_with or dependencies. It will also try to guess
which compiler to use if one hasn't been selected already. | mesonbuild/build.py | process_compilers_late | jmesmon/meson | python | def process_compilers_late(self):
"Processes additional compilers after kwargs have been evaluated.\n\n This can add extra compilers that might be required by keyword\n arguments, such as link_with or dependencies. It will also try to guess\n which compiler to use if one hasn't been selected al... |
def process_compilers(self):
'\n Populate self.compilers, which is the list of compilers that this\n target will use for compiling all its sources.\n We also add compilers that were used by extracted objects to simplify\n dynamic linker determination.\n '
if ((not self.sources... | 5,489,087,880,487,695,000 | Populate self.compilers, which is the list of compilers that this
target will use for compiling all its sources.
We also add compilers that were used by extracted objects to simplify
dynamic linker determination. | mesonbuild/build.py | process_compilers | jmesmon/meson | python | def process_compilers(self):
'\n Populate self.compilers, which is the list of compilers that this\n target will use for compiling all its sources.\n We also add compilers that were used by extracted objects to simplify\n dynamic linker determination.\n '
if ((not self.sources... |
def process_link_depends(self, sources, environment):
"Process the link_depends keyword argument.\n\n This is designed to handle strings, Files, and the output of Custom\n Targets. Notably it doesn't handle generator() returned objects, since\n adding them as a link depends would inherently cau... | 6,275,296,070,609,094,000 | Process the link_depends keyword argument.
This is designed to handle strings, Files, and the output of Custom
Targets. Notably it doesn't handle generator() returned objects, since
adding them as a link depends would inherently cause them to be
generated twice, since the output needs to be passed to the ld_args and
l... | mesonbuild/build.py | process_link_depends | jmesmon/meson | python | def process_link_depends(self, sources, environment):
"Process the link_depends keyword argument.\n\n This is designed to handle strings, Files, and the output of Custom\n Targets. Notably it doesn't handle generator() returned objects, since\n adding them as a link depends would inherently cau... |
def get_langs_used_by_deps(self):
'\n Sometimes you want to link to a C++ library that exports C API, which\n means the linker must link in the C++ stdlib, and we must use a C++\n compiler for linking. The same is also applicable for objc/objc++, etc,\n so we can keep using clink_langs f... | 5,184,799,372,204,265,000 | Sometimes you want to link to a C++ library that exports C API, which
means the linker must link in the C++ stdlib, and we must use a C++
compiler for linking. The same is also applicable for objc/objc++, etc,
so we can keep using clink_langs for the priority order.
See: https://github.com/mesonbuild/meson/issues/1653 | mesonbuild/build.py | get_langs_used_by_deps | jmesmon/meson | python | def get_langs_used_by_deps(self):
'\n Sometimes you want to link to a C++ library that exports C API, which\n means the linker must link in the C++ stdlib, and we must use a C++\n compiler for linking. The same is also applicable for objc/objc++, etc,\n so we can keep using clink_langs f... |
def get_clink_dynamic_linker_and_stdlibs(self):
"\n We use the order of languages in `clink_langs` to determine which\n linker to use in case the target has sources compiled with multiple\n compilers. All languages other than those in this list have their own\n linker.\n Note that... | 8,917,164,519,977,908,000 | We use the order of languages in `clink_langs` to determine which
linker to use in case the target has sources compiled with multiple
compilers. All languages other than those in this list have their own
linker.
Note that Vala outputs C code, so Vala sources can use any linker
that can link compiled C. We don't actuall... | mesonbuild/build.py | get_clink_dynamic_linker_and_stdlibs | jmesmon/meson | python | def get_clink_dynamic_linker_and_stdlibs(self):
"\n We use the order of languages in `clink_langs` to determine which\n linker to use in case the target has sources compiled with multiple\n compilers. All languages other than those in this list have their own\n linker.\n Note that... |
def get_using_msvc(self):
"\n Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,\n and SharedLibrary for deciding when to use MSVC-specific file naming\n and debug filenames.\n\n If at least some code is built with MSVC and the final library is\n linked with M... | 5,777,500,192,533,684,000 | Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,
and SharedLibrary for deciding when to use MSVC-specific file naming
and debug filenames.
If at least some code is built with MSVC and the final library is
linked with MSVC, we can be sure that some debug info will be
generated. We only check the ... | mesonbuild/build.py | get_using_msvc | jmesmon/meson | python | def get_using_msvc(self):
"\n Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,\n and SharedLibrary for deciding when to use MSVC-specific file naming\n and debug filenames.\n\n If at least some code is built with MSVC and the final library is\n linked with M... |
def check_module_linking(self):
'\n Warn if shared modules are linked with target: (link_with) #2865\n '
for link_target in self.link_targets:
if isinstance(link_target, SharedModule):
if for_darwin(self.is_cross, self.environment):
raise MesonException('target ... | -970,886,122,344,748,200 | Warn if shared modules are linked with target: (link_with) #2865 | mesonbuild/build.py | check_module_linking | jmesmon/meson | python | def check_module_linking(self):
'\n \n '
for link_target in self.link_targets:
if isinstance(link_target, SharedModule):
if for_darwin(self.is_cross, self.environment):
raise MesonException('target links against shared modules.\nThis is not permitted on OSX')
... |
def description(self):
'Human friendly description of the executable'
return self.name | 4,660,257,787,278,046,000 | Human friendly description of the executable | mesonbuild/build.py | description | jmesmon/meson | python | def description(self):
return self.name |
def get_import_filename(self):
'\n The name of the import library that will be outputted by the compiler\n\n Returns None if there is no import library required for this platform\n '
return self.import_filename | -6,530,916,317,056,780,000 | The name of the import library that will be outputted by the compiler
Returns None if there is no import library required for this platform | mesonbuild/build.py | get_import_filename | jmesmon/meson | python | def get_import_filename(self):
'\n The name of the import library that will be outputted by the compiler\n\n Returns None if there is no import library required for this platform\n '
return self.import_filename |
def determine_filenames(self, is_cross, env):
'\n See https://github.com/mesonbuild/meson/pull/417 for details.\n\n First we determine the filename template (self.filename_tpl), then we\n set the output filename (self.filename).\n\n The template is needed while creating aliases (self.get... | -7,801,708,533,714,602,000 | See https://github.com/mesonbuild/meson/pull/417 for details.
First we determine the filename template (self.filename_tpl), then we
set the output filename (self.filename).
The template is needed while creating aliases (self.get_aliases),
which are needed while generating .so shared libraries for Linux.
Besides this... | mesonbuild/build.py | determine_filenames | jmesmon/meson | python | def determine_filenames(self, is_cross, env):
'\n See https://github.com/mesonbuild/meson/pull/417 for details.\n\n First we determine the filename template (self.filename_tpl), then we\n set the output filename (self.filename).\n\n The template is needed while creating aliases (self.get... |
def get_import_filename(self):
'\n The name of the import library that will be outputted by the compiler\n\n Returns None if there is no import library required for this platform\n '
return self.import_filename | -6,530,916,317,056,780,000 | The name of the import library that will be outputted by the compiler
Returns None if there is no import library required for this platform | mesonbuild/build.py | get_import_filename | jmesmon/meson | python | def get_import_filename(self):
'\n The name of the import library that will be outputted by the compiler\n\n Returns None if there is no import library required for this platform\n '
return self.import_filename |
def get_aliases(self):
'\n If the versioned library name is libfoo.so.0.100.0, aliases are:\n * libfoo.so.0 (soversion) -> libfoo.so.0.100.0\n * libfoo.so (unversioned; for linking) -> libfoo.so.0\n Same for dylib:\n * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib\n ... | -5,496,365,589,624,999,000 | If the versioned library name is libfoo.so.0.100.0, aliases are:
* libfoo.so.0 (soversion) -> libfoo.so.0.100.0
* libfoo.so (unversioned; for linking) -> libfoo.so.0
Same for dylib:
* libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib | mesonbuild/build.py | get_aliases | jmesmon/meson | python | def get_aliases(self):
'\n If the versioned library name is libfoo.so.0.100.0, aliases are:\n * libfoo.so.0 (soversion) -> libfoo.so.0.100.0\n * libfoo.so (unversioned; for linking) -> libfoo.so.0\n Same for dylib:\n * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib\n ... |
def get_transitive_build_target_deps(self):
'\n Recursively fetch the build targets that this custom target depends on,\n whether through `command:`, `depends:`, or `sources:` The recursion is\n only performed on custom targets.\n This is useful for setting PATH on Windows for finding re... | 8,326,607,069,530,100,000 | Recursively fetch the build targets that this custom target depends on,
whether through `command:`, `depends:`, or `sources:` The recursion is
only performed on custom targets.
This is useful for setting PATH on Windows for finding required DLLs.
F.ex, if you have a python script that loads a C module that links to
oth... | mesonbuild/build.py | get_transitive_build_target_deps | jmesmon/meson | python | def get_transitive_build_target_deps(self):
'\n Recursively fetch the build targets that this custom target depends on,\n whether through `command:`, `depends:`, or `sources:` The recursion is\n only performed on custom targets.\n This is useful for setting PATH on Windows for finding re... |
def oauth_url(client_id: Union[(int, str)], *, permissions: Permissions=MISSING, guild: Snowflake=MISSING, redirect_uri: str=MISSING, scopes: Iterable[str]=MISSING, disable_guild_select: bool=False) -> str:
"A helper function that returns the OAuth2 URL for inviting the bot\n into guilds.\n\n Parameters\n ... | -5,366,905,059,735,044,000 | A helper function that returns the OAuth2 URL for inviting the bot
into guilds.
Parameters
-----------
client_id: Union[:class:`int`, :class:`str`]
The client ID for your bot.
permissions: :class:`~discord.Permissions`
The permissions you're requesting. If not given then you won't be requesting any
permiss... | discord/utils.py | oauth_url | Astrea49/enhanced-discord.py | python | def oauth_url(client_id: Union[(int, str)], *, permissions: Permissions=MISSING, guild: Snowflake=MISSING, redirect_uri: str=MISSING, scopes: Iterable[str]=MISSING, disable_guild_select: bool=False) -> str:
"A helper function that returns the OAuth2 URL for inviting the bot\n into guilds.\n\n Parameters\n ... |
def snowflake_time(id: int) -> datetime.datetime:
'\n Parameters\n -----------\n id: :class:`int`\n The snowflake ID.\n\n Returns\n --------\n :class:`datetime.datetime`\n An aware datetime in UTC representing the creation time of the snowflake.\n '
timestamp = (((id >> 22) + ... | -8,368,037,869,531,534,000 | Parameters
-----------
id: :class:`int`
The snowflake ID.
Returns
--------
:class:`datetime.datetime`
An aware datetime in UTC representing the creation time of the snowflake. | discord/utils.py | snowflake_time | Astrea49/enhanced-discord.py | python | def snowflake_time(id: int) -> datetime.datetime:
'\n Parameters\n -----------\n id: :class:`int`\n The snowflake ID.\n\n Returns\n --------\n :class:`datetime.datetime`\n An aware datetime in UTC representing the creation time of the snowflake.\n '
timestamp = (((id >> 22) + ... |
def time_snowflake(dt: datetime.datetime, high: bool=False) -> int:
'Returns a numeric snowflake pretending to be created at the given date.\n\n When using as the lower end of a range, use ``time_snowflake(high=False) - 1``\n to be inclusive, ``high=True`` to be exclusive.\n\n When using as the higher end ... | -2,900,649,015,111,074,300 | Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use ``time_snowflake(high=False) - 1``
to be inclusive, ``high=True`` to be exclusive.
When using as the higher end of a range, use ``time_snowflake(high=True) + 1``
to be inclusive, ``high=False`` to be ex... | discord/utils.py | time_snowflake | Astrea49/enhanced-discord.py | python | def time_snowflake(dt: datetime.datetime, high: bool=False) -> int:
'Returns a numeric snowflake pretending to be created at the given date.\n\n When using as the lower end of a range, use ``time_snowflake(high=False) - 1``\n to be inclusive, ``high=True`` to be exclusive.\n\n When using as the higher end ... |
def find(predicate: Callable[([T], Any)], seq: Iterable[T]) -> Optional[T]:
"A helper to return the first element found in the sequence\n that meets the predicate. For example: ::\n\n member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)\n\n would find the first :class:`~disc... | 8,747,360,362,780,973,000 | A helper to return the first element found in the sequence
that meets the predicate. For example: ::
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
would find the first :class:`~discord.Member` whose name is 'Mighty' and return it.
If an entry is not found, then ``None`` is retur... | discord/utils.py | find | Astrea49/enhanced-discord.py | python | def find(predicate: Callable[([T], Any)], seq: Iterable[T]) -> Optional[T]:
"A helper to return the first element found in the sequence\n that meets the predicate. For example: ::\n\n member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)\n\n would find the first :class:`~disc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.