repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
jreese/tasky | tasky/loop.py | Tasky.monitor_tasks | async def monitor_tasks(self, interval: float=1.0) -> None:
'''Monitor all known tasks for run state. Ensure that enabled tasks
are running, and that disabled tasks are stopped.'''
Log.debug('monitor running')
while True:
try:
await asyncio.sleep(interval)
for name, task in self.all_tasks.items():
if self.terminate_on_finish:
if task in self.running_tasks and task.running:
await task.stop()
elif task.enabled:
if task not in self.running_tasks:
Log.debug('task %s enabled, restarting', task.name)
await self.insert(task)
else:
if task in self.running_tasks:
Log.debug('task %s disabled, stopping', task.name)
await task.stop()
if self.terminate_on_finish and not self.running_tasks:
Log.debug('all tasks completed, terminating')
break
except CancelledError:
Log.debug('monitor cancelled')
break
except Exception:
Log.exception('monitoring exception')
self.monitor = None
self.loop.call_later(0, self.terminate) | python | async def monitor_tasks(self, interval: float=1.0) -> None:
'''Monitor all known tasks for run state. Ensure that enabled tasks
are running, and that disabled tasks are stopped.'''
Log.debug('monitor running')
while True:
try:
await asyncio.sleep(interval)
for name, task in self.all_tasks.items():
if self.terminate_on_finish:
if task in self.running_tasks and task.running:
await task.stop()
elif task.enabled:
if task not in self.running_tasks:
Log.debug('task %s enabled, restarting', task.name)
await self.insert(task)
else:
if task in self.running_tasks:
Log.debug('task %s disabled, stopping', task.name)
await task.stop()
if self.terminate_on_finish and not self.running_tasks:
Log.debug('all tasks completed, terminating')
break
except CancelledError:
Log.debug('monitor cancelled')
break
except Exception:
Log.exception('monitoring exception')
self.monitor = None
self.loop.call_later(0, self.terminate) | [
"async",
"def",
"monitor_tasks",
"(",
"self",
",",
"interval",
":",
"float",
"=",
"1.0",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'monitor running'",
")",
"while",
"True",
":",
"try",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"interval",
")... | Monitor all known tasks for run state. Ensure that enabled tasks
are running, and that disabled tasks are stopped. | [
"Monitor",
"all",
"known",
"tasks",
"for",
"run",
"state",
".",
"Ensure",
"that",
"enabled",
"tasks",
"are",
"running",
"and",
"that",
"disabled",
"tasks",
"are",
"stopped",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L240-L276 | train | 53,900 |
jreese/tasky | tasky/loop.py | Tasky.exception | def exception(self, loop: asyncio.BaseEventLoop, context: dict) -> None:
'''Log unhandled exceptions from anywhere in the event loop.'''
Log.error('unhandled exception: %s', context['message'])
Log.error('%s', context)
if 'exception' in context:
Log.error(' %s', context['exception']) | python | def exception(self, loop: asyncio.BaseEventLoop, context: dict) -> None:
'''Log unhandled exceptions from anywhere in the event loop.'''
Log.error('unhandled exception: %s', context['message'])
Log.error('%s', context)
if 'exception' in context:
Log.error(' %s', context['exception']) | [
"def",
"exception",
"(",
"self",
",",
"loop",
":",
"asyncio",
".",
"BaseEventLoop",
",",
"context",
":",
"dict",
")",
"->",
"None",
":",
"Log",
".",
"error",
"(",
"'unhandled exception: %s'",
",",
"context",
"[",
"'message'",
"]",
")",
"Log",
".",
"error... | Log unhandled exceptions from anywhere in the event loop. | [
"Log",
"unhandled",
"exceptions",
"from",
"anywhere",
"in",
"the",
"event",
"loop",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L278-L284 | train | 53,901 |
jreese/tasky | tasky/loop.py | Tasky.sigint | def sigint(self) -> None:
'''Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses.'''
if self.stop_attempts < 1:
Log.info('gracefully stopping tasks')
self.stop_attempts += 1
self.terminate()
elif self.stop_attempts < 2:
Log.info('forcefully cancelling tasks')
self.stop_attempts += 1
self.terminate(force=True)
else:
Log.info('forcefully stopping event loop')
self.loop.stop() | python | def sigint(self) -> None:
'''Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses.'''
if self.stop_attempts < 1:
Log.info('gracefully stopping tasks')
self.stop_attempts += 1
self.terminate()
elif self.stop_attempts < 2:
Log.info('forcefully cancelling tasks')
self.stop_attempts += 1
self.terminate(force=True)
else:
Log.info('forcefully stopping event loop')
self.loop.stop() | [
"def",
"sigint",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"stop_attempts",
"<",
"1",
":",
"Log",
".",
"info",
"(",
"'gracefully stopping tasks'",
")",
"self",
".",
"stop_attempts",
"+=",
"1",
"self",
".",
"terminate",
"(",
")",
"elif",
"... | Handle the user pressing Ctrl-C by stopping tasks nicely at first,
then forcibly upon further presses. | [
"Handle",
"the",
"user",
"pressing",
"Ctrl",
"-",
"C",
"by",
"stopping",
"tasks",
"nicely",
"at",
"first",
"then",
"forcibly",
"upon",
"further",
"presses",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L286-L302 | train | 53,902 |
jreese/tasky | tasky/loop.py | Tasky.sigterm | def sigterm(self) -> None:
'''Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish.'''
if self.stop_attempts < 1:
Log.info('received SIGTERM, gracefully stopping tasks')
self.stop_attempts += 1
self.terminate()
else:
Log.info('received SIGTERM, bravely waiting for tasks') | python | def sigterm(self) -> None:
'''Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish.'''
if self.stop_attempts < 1:
Log.info('received SIGTERM, gracefully stopping tasks')
self.stop_attempts += 1
self.terminate()
else:
Log.info('received SIGTERM, bravely waiting for tasks') | [
"def",
"sigterm",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"stop_attempts",
"<",
"1",
":",
"Log",
".",
"info",
"(",
"'received SIGTERM, gracefully stopping tasks'",
")",
"self",
".",
"stop_attempts",
"+=",
"1",
"self",
".",
"terminate",
"(",
... | Handle SIGTERM from the system by stopping tasks gracefully.
Repeated signals will be ignored while waiting for tasks to finish. | [
"Handle",
"SIGTERM",
"from",
"the",
"system",
"by",
"stopping",
"tasks",
"gracefully",
".",
"Repeated",
"signals",
"will",
"be",
"ignored",
"while",
"waiting",
"for",
"tasks",
"to",
"finish",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/loop.py#L304-L314 | train | 53,903 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | CaseInsensitiveKeyword.parse | def parse(cls, parser, text, pos):
"""Checks if terminal token is a keyword after lower-casing it."""
match = cls.regex.match(text)
if match:
# Check if match is is not in the grammar of the specific keyword class.
if match.group(0).lower() not in cls.grammar:
result = text, SyntaxError(repr(match.group(0)) + " is not a member of " + repr(cls.grammar))
else:
result = text[len(match.group(0)):], cls(match.group(0))
else:
result = text, SyntaxError("expecting " + repr(cls.__name__))
return result | python | def parse(cls, parser, text, pos):
"""Checks if terminal token is a keyword after lower-casing it."""
match = cls.regex.match(text)
if match:
# Check if match is is not in the grammar of the specific keyword class.
if match.group(0).lower() not in cls.grammar:
result = text, SyntaxError(repr(match.group(0)) + " is not a member of " + repr(cls.grammar))
else:
result = text[len(match.group(0)):], cls(match.group(0))
else:
result = text, SyntaxError("expecting " + repr(cls.__name__))
return result | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"match",
"=",
"cls",
".",
"regex",
".",
"match",
"(",
"text",
")",
"if",
"match",
":",
"# Check if match is is not in the grammar of the specific keyword class.",
"if",
"match",
".",... | Checks if terminal token is a keyword after lower-casing it. | [
"Checks",
"if",
"terminal",
"token",
"is",
"a",
"keyword",
"after",
"lower",
"-",
"casing",
"it",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L59-L70 | train | 53,904 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | InspireKeyword.parse | def parse(cls, parser, text, pos):
"""Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed.
"""
try:
remaining_text, keyword = parser.parse(text, cls.grammar)
if keyword.lower() == 'texkey':
parser._parsing_texkey_expression = True
return remaining_text, InspireKeyword(keyword)
except SyntaxError as e:
parser._parsing_texkey_expression = False
return text, e | python | def parse(cls, parser, text, pos):
"""Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed.
"""
try:
remaining_text, keyword = parser.parse(text, cls.grammar)
if keyword.lower() == 'texkey':
parser._parsing_texkey_expression = True
return remaining_text, InspireKeyword(keyword)
except SyntaxError as e:
parser._parsing_texkey_expression = False
return text, e | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"try",
":",
"remaining_text",
",",
"keyword",
"=",
"parser",
".",
"parse",
"(",
"text",
",",
"cls",
".",
"grammar",
")",
"if",
"keyword",
".",
"lower",
"(",
")",
"==",
... | Parse InspireKeyword.
If the keyword is `texkey`, enable the parsing texkey expression flag, since its value contains ':' which
normally isn't allowed. | [
"Parse",
"InspireKeyword",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L209-L222 | train | 53,905 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | SimpleValueUnit.parse_terminal_token | def parse_terminal_token(cls, parser, text):
"""Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g. And, Or, Not, defined above) should
not be recognized as terminals, thus we check if they are in the Keywords table (namespace like structure
handled by PyPeg).
This is done only when we are not parsing a parenthesized SimpleValue.
Also, helps in supporting more implicit-and queries cases (last two checks).
"""
token_regex = cls.token_regex
if parser._parsing_texkey_expression:
token_regex = cls.texkey_token_regex
parser._parsing_texkey_expression = False
match = token_regex.match(text)
if match:
matched_token = match.group(0)
# Check if token is a DSL keyword. Disable this check in the case where the parser isn't parsing a
# parenthesized terminal.
if not parser._parsing_parenthesized_terminal and matched_token.lower() in Keyword.table:
return text, SyntaxError("found DSL keyword: " + matched_token)
remaining_text = text[len(matched_token):]
# Attempt to recognize whether current terminal is followed by a ":", which definitely signifies that
# we are parsing a keyword, and we shouldn't.
if cls.starts_with_colon.match(remaining_text):
return text, \
SyntaxError("parsing a keyword (token followed by \":\"): \"" + repr(matched_token) + "\"")
# Attempt to recognize whether current terminal is a non shortened version of Inspire keywords. This is
# done for supporting implicit-and in case of SPIRES style keyword queries. Using the non shortened version
# of the keywords, makes this recognition not eager.
if not parser._parsing_parenthesized_simple_values_expression \
and matched_token in INSPIRE_KEYWORDS_SET:
return text, SyntaxError("parsing a keyword (non shortened INSPIRE keyword)")
result = remaining_text, matched_token
else:
result = text, SyntaxError("expecting match on " + repr(cls.token_regex.pattern))
return result | python | def parse_terminal_token(cls, parser, text):
"""Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g. And, Or, Not, defined above) should
not be recognized as terminals, thus we check if they are in the Keywords table (namespace like structure
handled by PyPeg).
This is done only when we are not parsing a parenthesized SimpleValue.
Also, helps in supporting more implicit-and queries cases (last two checks).
"""
token_regex = cls.token_regex
if parser._parsing_texkey_expression:
token_regex = cls.texkey_token_regex
parser._parsing_texkey_expression = False
match = token_regex.match(text)
if match:
matched_token = match.group(0)
# Check if token is a DSL keyword. Disable this check in the case where the parser isn't parsing a
# parenthesized terminal.
if not parser._parsing_parenthesized_terminal and matched_token.lower() in Keyword.table:
return text, SyntaxError("found DSL keyword: " + matched_token)
remaining_text = text[len(matched_token):]
# Attempt to recognize whether current terminal is followed by a ":", which definitely signifies that
# we are parsing a keyword, and we shouldn't.
if cls.starts_with_colon.match(remaining_text):
return text, \
SyntaxError("parsing a keyword (token followed by \":\"): \"" + repr(matched_token) + "\"")
# Attempt to recognize whether current terminal is a non shortened version of Inspire keywords. This is
# done for supporting implicit-and in case of SPIRES style keyword queries. Using the non shortened version
# of the keywords, makes this recognition not eager.
if not parser._parsing_parenthesized_simple_values_expression \
and matched_token in INSPIRE_KEYWORDS_SET:
return text, SyntaxError("parsing a keyword (non shortened INSPIRE keyword)")
result = remaining_text, matched_token
else:
result = text, SyntaxError("expecting match on " + repr(cls.token_regex.pattern))
return result | [
"def",
"parse_terminal_token",
"(",
"cls",
",",
"parser",
",",
"text",
")",
":",
"token_regex",
"=",
"cls",
".",
"token_regex",
"if",
"parser",
".",
"_parsing_texkey_expression",
":",
"token_regex",
"=",
"cls",
".",
"texkey_token_regex",
"parser",
".",
"_parsing... | Parses a terminal token that doesn't contain parentheses nor colon symbol.
Note:
Handles a special case of tokens where a ':' is needed (for `texkey` queries).
If we're parsing text not in parentheses, then some DSL keywords (e.g. And, Or, Not, defined above) should
not be recognized as terminals, thus we check if they are in the Keywords table (namespace like structure
handled by PyPeg).
This is done only when we are not parsing a parenthesized SimpleValue.
Also, helps in supporting more implicit-and queries cases (last two checks). | [
"Parses",
"a",
"terminal",
"token",
"that",
"doesn",
"t",
"contain",
"parentheses",
"nor",
"colon",
"symbol",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L255-L300 | train | 53,906 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | SimpleValueUnit.parse | def parse(cls, parser, text, pos):
"""Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_grammar
].
Parses plaintext which matches date specifiers or arxiv_identifier syntax, or is comprised of either 1) simple
terminal (no parentheses) or 2) a parenthesized SimpleValue.
For example, "e(+)" will be parsed in two steps, first, "e" token will be recognized and then "(+)", as a
parenthesized SimpleValue.
"""
found = False
# Attempt to parse date specifier
match = cls.date_specifiers_regex.match(text)
if match:
remaining_text, token, found = text[len(match.group(0)):], match.group(0), True
else:
# Attempt to parse arxiv identifier
match = cls.arxiv_token_regex.match(text)
if match:
remaining_text, token, found = text[len(match.group()):], match.group(2), True
else:
# Attempt to parse a terminal token
remaining_text, token = SimpleValueUnit.parse_terminal_token(parser, text)
if type(token) != SyntaxError:
found = True
else:
# Attempt to parse a terminal with parentheses
try:
# Enable parsing a parenthesized terminal so that we can accept {+, -, |} as terminals.
parser._parsing_parenthesized_terminal = True
remaining_text, token = parser.parse(text, cls.parenthesized_token_grammar, pos)
found = True
except SyntaxError:
pass
except GrammarValueError:
raise
except ValueError:
pass
finally:
parser._parsing_parenthesized_terminal = False
if found:
result = remaining_text, SimpleValueUnit(token)
else:
result = text, SyntaxError("expecting match on " + cls.__name__)
return result | python | def parse(cls, parser, text, pos):
"""Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_grammar
].
Parses plaintext which matches date specifiers or arxiv_identifier syntax, or is comprised of either 1) simple
terminal (no parentheses) or 2) a parenthesized SimpleValue.
For example, "e(+)" will be parsed in two steps, first, "e" token will be recognized and then "(+)", as a
parenthesized SimpleValue.
"""
found = False
# Attempt to parse date specifier
match = cls.date_specifiers_regex.match(text)
if match:
remaining_text, token, found = text[len(match.group(0)):], match.group(0), True
else:
# Attempt to parse arxiv identifier
match = cls.arxiv_token_regex.match(text)
if match:
remaining_text, token, found = text[len(match.group()):], match.group(2), True
else:
# Attempt to parse a terminal token
remaining_text, token = SimpleValueUnit.parse_terminal_token(parser, text)
if type(token) != SyntaxError:
found = True
else:
# Attempt to parse a terminal with parentheses
try:
# Enable parsing a parenthesized terminal so that we can accept {+, -, |} as terminals.
parser._parsing_parenthesized_terminal = True
remaining_text, token = parser.parse(text, cls.parenthesized_token_grammar, pos)
found = True
except SyntaxError:
pass
except GrammarValueError:
raise
except ValueError:
pass
finally:
parser._parsing_parenthesized_terminal = False
if found:
result = remaining_text, SimpleValueUnit(token)
else:
result = text, SyntaxError("expecting match on " + cls.__name__)
return result | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"found",
"=",
"False",
"# Attempt to parse date specifier",
"match",
"=",
"cls",
".",
"date_specifiers_regex",
".",
"match",
"(",
"text",
")",
"if",
"match",
":",
"remaining_text",... | Imitates parsing a list grammar.
Specifically, this
grammar = [
SimpleValueUnit.date_specifiers_regex,
SimpleValueUnit.arxiv_token_regex,
SimpleValueUnit.token_regex,
SimpleValueUnit.parenthesized_token_grammar
].
Parses plaintext which matches date specifiers or arxiv_identifier syntax, or is comprised of either 1) simple
terminal (no parentheses) or 2) a parenthesized SimpleValue.
For example, "e(+)" will be parsed in two steps, first, "e" token will be recognized and then "(+)", as a
parenthesized SimpleValue. | [
"Imitates",
"parsing",
"a",
"list",
"grammar",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L303-L358 | train | 53,907 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | SimpleValue.unconsume_and_reconstruct_input | def unconsume_and_reconstruct_input(remaining_text, recognized_tokens, complex_value_idx):
"""Reconstruct input in case of consuming a keyword query or a value query with ComplexValue as value.
Un-consuming at most 3 elements and specifically (Keyword,) Whitespace and ComplexValue, while also
reconstructing parser's input text.
Example:
Given this query "author foo t 'bar'", r would be:
r = [SimpleValueUnit("foo"), Whitespace(" "), SimpleValueUnit("t"), Whitespace(" "),
SimpleValueUnit("'bar'")]
thus after this method, r would be [SimpleValueUnit("foo"), Whitespace(" ")], while initial text will
have been reconstructed as "t 'bar' rest_of_the_text".
"""
# Default slicing index: i.e. at most 3 elements will be unconsumed, Keyword, Whitespace and ComplexValue.
slicing_start_idx = 2
# Check whether the 3rd element from the end is an InspireKeyword. If not, a Value query with ComplexValue
# was consumed.
if not INSPIRE_PARSER_KEYWORDS.get(recognized_tokens[complex_value_idx - slicing_start_idx].value, None):
slicing_start_idx = 1
reconstructed_terminals = recognized_tokens[:complex_value_idx - slicing_start_idx]
reconstructed_text = '{} {}'.format(
''.join([token.value for token in recognized_tokens[complex_value_idx - slicing_start_idx:]]),
remaining_text
)
return reconstructed_text, reconstructed_terminals | python | def unconsume_and_reconstruct_input(remaining_text, recognized_tokens, complex_value_idx):
"""Reconstruct input in case of consuming a keyword query or a value query with ComplexValue as value.
Un-consuming at most 3 elements and specifically (Keyword,) Whitespace and ComplexValue, while also
reconstructing parser's input text.
Example:
Given this query "author foo t 'bar'", r would be:
r = [SimpleValueUnit("foo"), Whitespace(" "), SimpleValueUnit("t"), Whitespace(" "),
SimpleValueUnit("'bar'")]
thus after this method, r would be [SimpleValueUnit("foo"), Whitespace(" ")], while initial text will
have been reconstructed as "t 'bar' rest_of_the_text".
"""
# Default slicing index: i.e. at most 3 elements will be unconsumed, Keyword, Whitespace and ComplexValue.
slicing_start_idx = 2
# Check whether the 3rd element from the end is an InspireKeyword. If not, a Value query with ComplexValue
# was consumed.
if not INSPIRE_PARSER_KEYWORDS.get(recognized_tokens[complex_value_idx - slicing_start_idx].value, None):
slicing_start_idx = 1
reconstructed_terminals = recognized_tokens[:complex_value_idx - slicing_start_idx]
reconstructed_text = '{} {}'.format(
''.join([token.value for token in recognized_tokens[complex_value_idx - slicing_start_idx:]]),
remaining_text
)
return reconstructed_text, reconstructed_terminals | [
"def",
"unconsume_and_reconstruct_input",
"(",
"remaining_text",
",",
"recognized_tokens",
",",
"complex_value_idx",
")",
":",
"# Default slicing index: i.e. at most 3 elements will be unconsumed, Keyword, Whitespace and ComplexValue.",
"slicing_start_idx",
"=",
"2",
"# Check whether the... | Reconstruct input in case of consuming a keyword query or a value query with ComplexValue as value.
Un-consuming at most 3 elements and specifically (Keyword,) Whitespace and ComplexValue, while also
reconstructing parser's input text.
Example:
Given this query "author foo t 'bar'", r would be:
r = [SimpleValueUnit("foo"), Whitespace(" "), SimpleValueUnit("t"), Whitespace(" "),
SimpleValueUnit("'bar'")]
thus after this method, r would be [SimpleValueUnit("foo"), Whitespace(" ")], while initial text will
have been reconstructed as "t 'bar' rest_of_the_text". | [
"Reconstruct",
"input",
"in",
"case",
"of",
"consuming",
"a",
"keyword",
"query",
"or",
"a",
"value",
"query",
"with",
"ComplexValue",
"as",
"value",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L379-L405 | train | 53,908 |
inspirehep/inspire-query-parser | inspire_query_parser/parser.py | ParenthesizedSimpleValues.parse | def parse(cls, parser, text, pos):
"""Using our own parse to enable the flag below."""
try:
parser._parsing_parenthesized_simple_values_expression = True
remaining_text, recognized_tokens = parser.parse(text, cls.grammar)
return remaining_text, recognized_tokens
except SyntaxError as e:
return text, e
finally:
parser._parsing_parenthesized_simple_values_expression = False | python | def parse(cls, parser, text, pos):
"""Using our own parse to enable the flag below."""
try:
parser._parsing_parenthesized_simple_values_expression = True
remaining_text, recognized_tokens = parser.parse(text, cls.grammar)
return remaining_text, recognized_tokens
except SyntaxError as e:
return text, e
finally:
parser._parsing_parenthesized_simple_values_expression = False | [
"def",
"parse",
"(",
"cls",
",",
"parser",
",",
"text",
",",
"pos",
")",
":",
"try",
":",
"parser",
".",
"_parsing_parenthesized_simple_values_expression",
"=",
"True",
"remaining_text",
",",
"recognized_tokens",
"=",
"parser",
".",
"parse",
"(",
"text",
",",
... | Using our own parse to enable the flag below. | [
"Using",
"our",
"own",
"parse",
"to",
"enable",
"the",
"flag",
"below",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/parser.py#L534-L543 | train | 53,909 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_fieldnames_if_bai_query | def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):
"""Generates new fieldnames in case of BAI query.
Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').
query_bai_field_if_dots_in_name (bool): Whether to query BAI field (in addition to author's name field)
if dots exist in the name and name contains no whitespace.
Returns:
list: Fieldnames to query on, in case of BAI query or None, otherwise.
Raises:
ValueError, if ``field_variation`` is not one of ('search', 'raw').
"""
if bai_field_variation not in (FieldVariations.search, FieldVariations.raw):
raise ValueError('Non supported field variation "{}".'.format(bai_field_variation))
normalized_author_name = normalize_name(node_value).strip('.')
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and \
ElasticSearchVisitor.BAI_REGEX.match(node_value):
return [ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.' + bai_field_variation]
elif not whitespace.search(normalized_author_name) and \
query_bai_field_if_dots_in_name and \
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and \
'.' in normalized_author_name:
# Case of partial BAI, e.g. ``J.Smith``.
return [ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.' + bai_field_variation] + \
force_list(ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'])
else:
return None | python | def _generate_fieldnames_if_bai_query(self, node_value, bai_field_variation, query_bai_field_if_dots_in_name):
"""Generates new fieldnames in case of BAI query.
Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').
query_bai_field_if_dots_in_name (bool): Whether to query BAI field (in addition to author's name field)
if dots exist in the name and name contains no whitespace.
Returns:
list: Fieldnames to query on, in case of BAI query or None, otherwise.
Raises:
ValueError, if ``field_variation`` is not one of ('search', 'raw').
"""
if bai_field_variation not in (FieldVariations.search, FieldVariations.raw):
raise ValueError('Non supported field variation "{}".'.format(bai_field_variation))
normalized_author_name = normalize_name(node_value).strip('.')
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and \
ElasticSearchVisitor.BAI_REGEX.match(node_value):
return [ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.' + bai_field_variation]
elif not whitespace.search(normalized_author_name) and \
query_bai_field_if_dots_in_name and \
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] and \
'.' in normalized_author_name:
# Case of partial BAI, e.g. ``J.Smith``.
return [ElasticSearchVisitor.AUTHORS_BAI_FIELD + '.' + bai_field_variation] + \
force_list(ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'])
else:
return None | [
"def",
"_generate_fieldnames_if_bai_query",
"(",
"self",
",",
"node_value",
",",
"bai_field_variation",
",",
"query_bai_field_if_dots_in_name",
")",
":",
"if",
"bai_field_variation",
"not",
"in",
"(",
"FieldVariations",
".",
"search",
",",
"FieldVariations",
".",
"raw",... | Generates new fieldnames in case of BAI query.
Args:
node_value (six.text_type): The node's value (i.e. author name).
bai_field_variation (six.text_type): Which field variation to query ('search' or 'raw').
query_bai_field_if_dots_in_name (bool): Whether to query BAI field (in addition to author's name field)
if dots exist in the name and name contains no whitespace.
Returns:
list: Fieldnames to query on, in case of BAI query or None, otherwise.
Raises:
ValueError, if ``field_variation`` is not one of ('search', 'raw'). | [
"Generates",
"new",
"fieldnames",
"in",
"case",
"of",
"BAI",
"query",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L156-L189 | train | 53,910 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_author_query | def _generate_author_query(self, author_name):
"""Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" results. E.g. Searching for `Smith, John`
shouldn't return papers of 'Smith, Bob'.
Additionally, doing a ``match`` with ``"operator": "and"`` in order to be even more exact in our search, by
requiring that ``full_name`` field contains both
"""
name_variations = [name_variation.lower()
for name_variation
in generate_minimal_name_variations(author_name)]
# When the query contains sufficient data, i.e. full names, e.g. ``Mele, Salvatore`` (and not ``Mele, S`` or
# ``Mele``) we can improve our filtering in order to filter out results containing records with authors that
# have the same non lastnames prefix, e.g. 'Mele, Samuele'.
if author_name_contains_fullnames(author_name):
specialized_author_filter = [
{
'bool': {
'must': [
{
'term': {ElasticSearchVisitor.AUTHORS_NAME_VARIATIONS_FIELD: names_variation[0]}
},
generate_match_query(
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'],
names_variation[1],
with_operator_and=True
)
]
}
} for names_variation
in product(name_variations, name_variations)
]
else:
# In the case of initials or even single lastname search, filter with only the name variations.
specialized_author_filter = [
{'term': {ElasticSearchVisitor.AUTHORS_NAME_VARIATIONS_FIELD: name_variation}}
for name_variation in name_variations
]
query = {
'bool': {
'filter': {
'bool': {
'should': specialized_author_filter
}
},
'must': {
'match': {
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author']: author_name
}
}
}
}
return generate_nested_query(ElasticSearchVisitor.AUTHORS_NESTED_QUERY_PATH, query) | python | def _generate_author_query(self, author_name):
"""Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" results. E.g. Searching for `Smith, John`
shouldn't return papers of 'Smith, Bob'.
Additionally, doing a ``match`` with ``"operator": "and"`` in order to be even more exact in our search, by
requiring that ``full_name`` field contains both
"""
name_variations = [name_variation.lower()
for name_variation
in generate_minimal_name_variations(author_name)]
# When the query contains sufficient data, i.e. full names, e.g. ``Mele, Salvatore`` (and not ``Mele, S`` or
# ``Mele``) we can improve our filtering in order to filter out results containing records with authors that
# have the same non lastnames prefix, e.g. 'Mele, Samuele'.
if author_name_contains_fullnames(author_name):
specialized_author_filter = [
{
'bool': {
'must': [
{
'term': {ElasticSearchVisitor.AUTHORS_NAME_VARIATIONS_FIELD: names_variation[0]}
},
generate_match_query(
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'],
names_variation[1],
with_operator_and=True
)
]
}
} for names_variation
in product(name_variations, name_variations)
]
else:
# In the case of initials or even single lastname search, filter with only the name variations.
specialized_author_filter = [
{'term': {ElasticSearchVisitor.AUTHORS_NAME_VARIATIONS_FIELD: name_variation}}
for name_variation in name_variations
]
query = {
'bool': {
'filter': {
'bool': {
'should': specialized_author_filter
}
},
'must': {
'match': {
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author']: author_name
}
}
}
}
return generate_nested_query(ElasticSearchVisitor.AUTHORS_NESTED_QUERY_PATH, query) | [
"def",
"_generate_author_query",
"(",
"self",
",",
"author_name",
")",
":",
"name_variations",
"=",
"[",
"name_variation",
".",
"lower",
"(",
")",
"for",
"name_variation",
"in",
"generate_minimal_name_variations",
"(",
"author_name",
")",
"]",
"# When the query contai... | Generates a query handling specifically authors.
Notes:
The match query is generic enough to return many results. Then, using the filter clause we truncate these
so that we imitate legacy's behaviour on returning more "exact" results. E.g. Searching for `Smith, John`
shouldn't return papers of 'Smith, Bob'.
Additionally, doing a ``match`` with ``"operator": "and"`` in order to be even more exact in our search, by
requiring that ``full_name`` field contains both | [
"Generates",
"a",
"query",
"handling",
"specifically",
"authors",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L191-L250 | train | 53,911 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_exact_author_query | def _generate_exact_author_query(self, author_name_or_bai):
"""Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value will be procesed in the same way as the indexed value (i.e. lowercased and normalized
(inspire_utils.normalize_name and then NFKC normalization).
E.g. Searching for 'Smith, J.' is the same as searching for: 'Smith, J', 'smith, j.', 'smith j', 'j smith',
'j. smith', 'J Smith', 'J. Smith'.
"""
if ElasticSearchVisitor.BAI_REGEX.match(author_name_or_bai):
bai = author_name_or_bai.lower()
query = self._generate_term_query(
'.'.join((ElasticSearchVisitor.AUTHORS_BAI_FIELD, FieldVariations.search)),
bai
)
else:
author_name = normalize('NFKC', normalize_name(author_name_or_bai)).lower()
query = self._generate_term_query(
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-author'],
author_name
)
return generate_nested_query(ElasticSearchVisitor.AUTHORS_NESTED_QUERY_PATH, query) | python | def _generate_exact_author_query(self, author_name_or_bai):
"""Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value will be procesed in the same way as the indexed value (i.e. lowercased and normalized
(inspire_utils.normalize_name and then NFKC normalization).
E.g. Searching for 'Smith, J.' is the same as searching for: 'Smith, J', 'smith, j.', 'smith j', 'j smith',
'j. smith', 'J Smith', 'J. Smith'.
"""
if ElasticSearchVisitor.BAI_REGEX.match(author_name_or_bai):
bai = author_name_or_bai.lower()
query = self._generate_term_query(
'.'.join((ElasticSearchVisitor.AUTHORS_BAI_FIELD, FieldVariations.search)),
bai
)
else:
author_name = normalize('NFKC', normalize_name(author_name_or_bai)).lower()
query = self._generate_term_query(
ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-author'],
author_name
)
return generate_nested_query(ElasticSearchVisitor.AUTHORS_NESTED_QUERY_PATH, query) | [
"def",
"_generate_exact_author_query",
"(",
"self",
",",
"author_name_or_bai",
")",
":",
"if",
"ElasticSearchVisitor",
".",
"BAI_REGEX",
".",
"match",
"(",
"author_name_or_bai",
")",
":",
"bai",
"=",
"author_name_or_bai",
".",
"lower",
"(",
")",
"query",
"=",
"s... | Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value will be procesed in the same way as the indexed value (i.e. lowercased and normalized
(inspire_utils.normalize_name and then NFKC normalization).
E.g. Searching for 'Smith, J.' is the same as searching for: 'Smith, J', 'smith, j.', 'smith j', 'j smith',
'j. smith', 'J Smith', 'J. Smith'. | [
"Generates",
"a",
"term",
"query",
"handling",
"authors",
"and",
"BAIs",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L252-L276 | train | 53,912 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_date_with_wildcard_query | def _generate_date_with_wildcard_query(self, date_value):
"""Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservative on what it accepts as valid input. Look into
:meth:`inspire_query_parser.utils.visitor_utils._truncate_wildcard_from_date` for more information.
"""
if date_value.endswith(ast.GenericValue.WILDCARD_TOKEN):
try:
date_value = _truncate_wildcard_from_date(date_value)
except ValueError:
# Drop date query.
return {}
return self._generate_range_queries(self.KEYWORD_TO_ES_FIELDNAME['date'],
{ES_RANGE_EQ_OPERATOR: date_value})
else:
# Drop date query with wildcard not as suffix, e.g. 2000-1*-31
return {} | python | def _generate_date_with_wildcard_query(self, date_value):
"""Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservative on what it accepts as valid input. Look into
:meth:`inspire_query_parser.utils.visitor_utils._truncate_wildcard_from_date` for more information.
"""
if date_value.endswith(ast.GenericValue.WILDCARD_TOKEN):
try:
date_value = _truncate_wildcard_from_date(date_value)
except ValueError:
# Drop date query.
return {}
return self._generate_range_queries(self.KEYWORD_TO_ES_FIELDNAME['date'],
{ES_RANGE_EQ_OPERATOR: date_value})
else:
# Drop date query with wildcard not as suffix, e.g. 2000-1*-31
return {} | [
"def",
"_generate_date_with_wildcard_query",
"(",
"self",
",",
"date_value",
")",
":",
"if",
"date_value",
".",
"endswith",
"(",
"ast",
".",
"GenericValue",
".",
"WILDCARD_TOKEN",
")",
":",
"try",
":",
"date_value",
"=",
"_truncate_wildcard_from_date",
"(",
"date_... | Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservative on what it accepts as valid input. Look into
:meth:`inspire_query_parser.utils.visitor_utils._truncate_wildcard_from_date` for more information. | [
"Helper",
"for",
"generating",
"a",
"date",
"keyword",
"query",
"containing",
"a",
"wildcard",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L278-L298 | train | 53,913 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_queries_for_title_symbols | def _generate_queries_for_title_symbols(title_field, query_value):
"""Generate queries for any symbols in the title against the whitespace tokenized field of titles.
Returns:
(dict): The query or queries for the whitespace tokenized field of titles. If none such tokens exist, then
returns an empty dict.
Notes:
Splits the value stream into tokens according to whitespace.
Heuristically identifies the ones that contain symbol-indicating-characters (examples of those tokens are
"g-2", "SU(2)").
"""
values_tokenized_by_whitespace = query_value.split()
symbol_queries = []
for value in values_tokenized_by_whitespace:
# Heuristic: If there's a symbol-indicating-character in the value, it signifies terms that should be
# queried against the whitespace-tokenized title.
if any(character in value for character in ElasticSearchVisitor.TITLE_SYMBOL_INDICATING_CHARACTER):
symbol_queries.append(
generate_match_query(
'.'.join([title_field, FieldVariations.search]),
value,
with_operator_and=False
)
)
return wrap_queries_in_bool_clauses_if_more_than_one(symbol_queries, use_must_clause=True) | python | def _generate_queries_for_title_symbols(title_field, query_value):
"""Generate queries for any symbols in the title against the whitespace tokenized field of titles.
Returns:
(dict): The query or queries for the whitespace tokenized field of titles. If none such tokens exist, then
returns an empty dict.
Notes:
Splits the value stream into tokens according to whitespace.
Heuristically identifies the ones that contain symbol-indicating-characters (examples of those tokens are
"g-2", "SU(2)").
"""
values_tokenized_by_whitespace = query_value.split()
symbol_queries = []
for value in values_tokenized_by_whitespace:
# Heuristic: If there's a symbol-indicating-character in the value, it signifies terms that should be
# queried against the whitespace-tokenized title.
if any(character in value for character in ElasticSearchVisitor.TITLE_SYMBOL_INDICATING_CHARACTER):
symbol_queries.append(
generate_match_query(
'.'.join([title_field, FieldVariations.search]),
value,
with_operator_and=False
)
)
return wrap_queries_in_bool_clauses_if_more_than_one(symbol_queries, use_must_clause=True) | [
"def",
"_generate_queries_for_title_symbols",
"(",
"title_field",
",",
"query_value",
")",
":",
"values_tokenized_by_whitespace",
"=",
"query_value",
".",
"split",
"(",
")",
"symbol_queries",
"=",
"[",
"]",
"for",
"value",
"in",
"values_tokenized_by_whitespace",
":",
... | Generate queries for any symbols in the title against the whitespace tokenized field of titles.
Returns:
(dict): The query or queries for the whitespace tokenized field of titles. If none such tokens exist, then
returns an empty dict.
Notes:
Splits the value stream into tokens according to whitespace.
Heuristically identifies the ones that contain symbol-indicating-characters (examples of those tokens are
"g-2", "SU(2)"). | [
"Generate",
"queries",
"for",
"any",
"symbols",
"in",
"the",
"title",
"against",
"the",
"whitespace",
"tokenized",
"field",
"of",
"titles",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L301-L327 | train | 53,914 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_type_code_query | def _generate_type_code_query(self, value):
"""Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
See: https://github.com/inspirehep/inspire-query-parser/issues/79
Otherwise, we query both ``document_type`` and ``publication_info``.
"""
mapping_for_value = self.TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING.get(value, None)
if mapping_for_value:
return generate_match_query(*mapping_for_value, with_operator_and=True)
else:
return {
'bool': {
'minimum_should_match': 1,
'should': [
generate_match_query('document_type', value, with_operator_and=True),
generate_match_query('publication_type', value, with_operator_and=True),
]
}
} | python | def _generate_type_code_query(self, value):
"""Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
See: https://github.com/inspirehep/inspire-query-parser/issues/79
Otherwise, we query both ``document_type`` and ``publication_info``.
"""
mapping_for_value = self.TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING.get(value, None)
if mapping_for_value:
return generate_match_query(*mapping_for_value, with_operator_and=True)
else:
return {
'bool': {
'minimum_should_match': 1,
'should': [
generate_match_query('document_type', value, with_operator_and=True),
generate_match_query('publication_type', value, with_operator_and=True),
]
}
} | [
"def",
"_generate_type_code_query",
"(",
"self",
",",
"value",
")",
":",
"mapping_for_value",
"=",
"self",
".",
"TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"mapping_for_value",
":",
"return",
"generate_match_que... | Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
See: https://github.com/inspirehep/inspire-query-parser/issues/79
Otherwise, we query both ``document_type`` and ``publication_info``. | [
"Generate",
"type",
"-",
"code",
"queries",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L339-L361 | train | 53,915 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_range_queries | def _generate_range_queries(self, fieldnames, operator_value_pairs):
"""Generates ElasticSearch range queries.
Args:
fieldnames (list): The fieldnames on which the search is the range query is targeted on,
operator_value_pairs (dict): Contains (range_operator, value) pairs.
The range_operator should be one of those supported by ElasticSearch (e.g. 'gt', 'lt', 'ge', 'le').
The value should be of type int or string.
Notes:
A bool should query with multiple range sub-queries is generated so that even if one of the multiple fields
is missing from a document, ElasticSearch will be able to match some records.
In the case of a 'date' keyword query, it updates date values after normalizing them by using
:meth:`inspire_query_parser.utils.visitor_utils.update_date_value_in_operator_value_pairs_for_fieldname`.
Additionally, in the aforementioned case, if a malformed date has been given, then the the method will
return an empty dictionary.
"""
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
range_queries = []
for fieldname in fieldnames:
updated_operator_value_pairs = \
update_date_value_in_operator_value_pairs_for_fieldname(fieldname, operator_value_pairs)
if not updated_operator_value_pairs:
break # Malformed date
else:
range_query = {
'range': {
fieldname: updated_operator_value_pairs
}
}
range_queries.append(
generate_nested_query(ElasticSearchVisitor.DATE_NESTED_QUERY_PATH, range_query)
if fieldname in ElasticSearchVisitor.DATE_NESTED_FIELDS
else range_query
)
else:
range_queries = [{
'range': {
fieldname: operator_value_pairs
}
}
for fieldname in fieldnames
]
return wrap_queries_in_bool_clauses_if_more_than_one(range_queries, use_must_clause=False) | python | def _generate_range_queries(self, fieldnames, operator_value_pairs):
"""Generates ElasticSearch range queries.
Args:
fieldnames (list): The fieldnames on which the search is the range query is targeted on,
operator_value_pairs (dict): Contains (range_operator, value) pairs.
The range_operator should be one of those supported by ElasticSearch (e.g. 'gt', 'lt', 'ge', 'le').
The value should be of type int or string.
Notes:
A bool should query with multiple range sub-queries is generated so that even if one of the multiple fields
is missing from a document, ElasticSearch will be able to match some records.
In the case of a 'date' keyword query, it updates date values after normalizing them by using
:meth:`inspire_query_parser.utils.visitor_utils.update_date_value_in_operator_value_pairs_for_fieldname`.
Additionally, in the aforementioned case, if a malformed date has been given, then the the method will
return an empty dictionary.
"""
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
range_queries = []
for fieldname in fieldnames:
updated_operator_value_pairs = \
update_date_value_in_operator_value_pairs_for_fieldname(fieldname, operator_value_pairs)
if not updated_operator_value_pairs:
break # Malformed date
else:
range_query = {
'range': {
fieldname: updated_operator_value_pairs
}
}
range_queries.append(
generate_nested_query(ElasticSearchVisitor.DATE_NESTED_QUERY_PATH, range_query)
if fieldname in ElasticSearchVisitor.DATE_NESTED_FIELDS
else range_query
)
else:
range_queries = [{
'range': {
fieldname: operator_value_pairs
}
}
for fieldname in fieldnames
]
return wrap_queries_in_bool_clauses_if_more_than_one(range_queries, use_must_clause=False) | [
"def",
"_generate_range_queries",
"(",
"self",
",",
"fieldnames",
",",
"operator_value_pairs",
")",
":",
"if",
"ElasticSearchVisitor",
".",
"KEYWORD_TO_ES_FIELDNAME",
"[",
"'date'",
"]",
"==",
"fieldnames",
":",
"range_queries",
"=",
"[",
"]",
"for",
"fieldname",
... | Generates ElasticSearch range queries.
Args:
fieldnames (list): The fieldnames on which the search is the range query is targeted on,
operator_value_pairs (dict): Contains (range_operator, value) pairs.
The range_operator should be one of those supported by ElasticSearch (e.g. 'gt', 'lt', 'ge', 'le').
The value should be of type int or string.
Notes:
A bool should query with multiple range sub-queries is generated so that even if one of the multiple fields
is missing from a document, ElasticSearch will be able to match some records.
In the case of a 'date' keyword query, it updates date values after normalizing them by using
:meth:`inspire_query_parser.utils.visitor_utils.update_date_value_in_operator_value_pairs_for_fieldname`.
Additionally, in the aforementioned case, if a malformed date has been given, then the the method will
return an empty dictionary. | [
"Generates",
"ElasticSearch",
"range",
"queries",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L411-L458 | train | 53,916 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor._generate_malformed_query | def _generate_malformed_query(data):
"""Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor.
"""
if isinstance(data, six.text_type):
# Remove colon character (special character for ES)
query_str = data.replace(':', ' ')
else:
query_str = ' '.join([word.strip(':') for word in data.children])
return {
'simple_query_string': {
'fields': ['_all'],
'query': query_str
}
} | python | def _generate_malformed_query(data):
"""Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor.
"""
if isinstance(data, six.text_type):
# Remove colon character (special character for ES)
query_str = data.replace(':', ' ')
else:
query_str = ' '.join([word.strip(':') for word in data.children])
return {
'simple_query_string': {
'fields': ['_all'],
'query': query_str
}
} | [
"def",
"_generate_malformed_query",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"# Remove colon character (special character for ES)",
"query_str",
"=",
"data",
".",
"replace",
"(",
"':'",
",",
"' '",
")",
"els... | Generates a query on the ``_all`` field with all the query content.
Args:
data (six.text_type or list): The query in the format of ``six.text_type`` (when used from parsing driver)
or ``list`` when used from withing the ES visitor. | [
"Generates",
"a",
"query",
"on",
"the",
"_all",
"field",
"with",
"all",
"the",
"query",
"content",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L461-L479 | train | 53,917 |
inspirehep/inspire-query-parser | inspire_query_parser/visitors/elastic_search_visitor.py | ElasticSearchVisitor.visit_partial_match_value | def visit_partial_match_value(self, node, fieldnames=None):
"""Generates a query which looks for a substring of the node's value in the given fieldname."""
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
# Date queries with partial values are transformed into range queries, among the given and the exact
# next date, according to the granularity of the given date.
if node.contains_wildcard:
return self._generate_date_with_wildcard_query(node.value)
return self._generate_range_queries(force_list(fieldnames), {ES_RANGE_EQ_OPERATOR: node.value})
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-author'] == fieldnames:
return self._generate_exact_author_query(node.value)
elif ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['type-code'] == fieldnames:
return self._generate_type_code_query(node.value)
elif ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['journal'] == fieldnames:
return self._generate_journal_nested_queries(node.value)
# Add wildcard token as prefix and suffix.
value = \
('' if node.value.startswith(ast.GenericValue.WILDCARD_TOKEN) else '*') + \
node.value + \
('' if node.value.endswith(ast.GenericValue.WILDCARD_TOKEN) else '*')
bai_fieldnames = self._generate_fieldnames_if_bai_query(
node.value,
bai_field_variation=FieldVariations.search,
query_bai_field_if_dots_in_name=True
)
query = self._generate_query_string_query(value,
fieldnames=bai_fieldnames or fieldnames,
analyze_wildcard=True)
if (bai_fieldnames and ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] in bai_fieldnames) \
or (fieldnames and ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] in fieldnames):
return generate_nested_query(ElasticSearchVisitor.AUTHORS_NESTED_QUERY_PATH, query)
return query | python | def visit_partial_match_value(self, node, fieldnames=None):
"""Generates a query which looks for a substring of the node's value in the given fieldname."""
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['date'] == fieldnames:
# Date queries with partial values are transformed into range queries, among the given and the exact
# next date, according to the granularity of the given date.
if node.contains_wildcard:
return self._generate_date_with_wildcard_query(node.value)
return self._generate_range_queries(force_list(fieldnames), {ES_RANGE_EQ_OPERATOR: node.value})
if ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['exact-author'] == fieldnames:
return self._generate_exact_author_query(node.value)
elif ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['type-code'] == fieldnames:
return self._generate_type_code_query(node.value)
elif ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['journal'] == fieldnames:
return self._generate_journal_nested_queries(node.value)
# Add wildcard token as prefix and suffix.
value = \
('' if node.value.startswith(ast.GenericValue.WILDCARD_TOKEN) else '*') + \
node.value + \
('' if node.value.endswith(ast.GenericValue.WILDCARD_TOKEN) else '*')
bai_fieldnames = self._generate_fieldnames_if_bai_query(
node.value,
bai_field_variation=FieldVariations.search,
query_bai_field_if_dots_in_name=True
)
query = self._generate_query_string_query(value,
fieldnames=bai_fieldnames or fieldnames,
analyze_wildcard=True)
if (bai_fieldnames and ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] in bai_fieldnames) \
or (fieldnames and ElasticSearchVisitor.KEYWORD_TO_ES_FIELDNAME['author'] in fieldnames):
return generate_nested_query(ElasticSearchVisitor.AUTHORS_NESTED_QUERY_PATH, query)
return query | [
"def",
"visit_partial_match_value",
"(",
"self",
",",
"node",
",",
"fieldnames",
"=",
"None",
")",
":",
"if",
"ElasticSearchVisitor",
".",
"KEYWORD_TO_ES_FIELDNAME",
"[",
"'date'",
"]",
"==",
"fieldnames",
":",
"# Date queries with partial values are transformed into rang... | Generates a query which looks for a substring of the node's value in the given fieldname. | [
"Generates",
"a",
"query",
"which",
"looks",
"for",
"a",
"substring",
"of",
"the",
"node",
"s",
"value",
"in",
"the",
"given",
"fieldname",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/inspire_query_parser/visitors/elastic_search_visitor.py#L796-L834 | train | 53,918 |
praekeltfoundation/seed-stage-based-messaging | contentstore/tasks.py | SyncSchedule.run | def run(self, schedule_id, **kwargs):
"""
Synchronises the schedule specified by the ID `schedule_id` to the
scheduler service.
Arguments:
schedule_id {str} -- The ID of the schedule to sync
"""
log = self.get_logger(**kwargs)
try:
schedule = Schedule.objects.get(id=schedule_id)
except Schedule.DoesNotExist:
log.error("Missing Schedule %s", schedule_id, exc_info=True)
if schedule.scheduler_schedule_id is None:
# Create the new schedule
result = self.scheduler.create_schedule(schedule.scheduler_format)
schedule.scheduler_schedule_id = result["id"]
# Disable update signal here to avoid calling twice
post_save.disconnect(schedule_saved, sender=Schedule)
schedule.save(update_fields=("scheduler_schedule_id",))
post_save.connect(schedule_saved, sender=Schedule)
log.info(
"Created schedule %s on scheduler for schedule %s",
schedule.scheduler_schedule_id,
schedule.id,
)
else:
# Update the existing schedule
result = self.scheduler.update_schedule(
str(schedule.scheduler_schedule_id), schedule.scheduler_format
)
log.info(
"Updated schedule %s on scheduler for schedule %s",
schedule.scheduler_schedule_id,
schedule.id,
) | python | def run(self, schedule_id, **kwargs):
"""
Synchronises the schedule specified by the ID `schedule_id` to the
scheduler service.
Arguments:
schedule_id {str} -- The ID of the schedule to sync
"""
log = self.get_logger(**kwargs)
try:
schedule = Schedule.objects.get(id=schedule_id)
except Schedule.DoesNotExist:
log.error("Missing Schedule %s", schedule_id, exc_info=True)
if schedule.scheduler_schedule_id is None:
# Create the new schedule
result = self.scheduler.create_schedule(schedule.scheduler_format)
schedule.scheduler_schedule_id = result["id"]
# Disable update signal here to avoid calling twice
post_save.disconnect(schedule_saved, sender=Schedule)
schedule.save(update_fields=("scheduler_schedule_id",))
post_save.connect(schedule_saved, sender=Schedule)
log.info(
"Created schedule %s on scheduler for schedule %s",
schedule.scheduler_schedule_id,
schedule.id,
)
else:
# Update the existing schedule
result = self.scheduler.update_schedule(
str(schedule.scheduler_schedule_id), schedule.scheduler_format
)
log.info(
"Updated schedule %s on scheduler for schedule %s",
schedule.scheduler_schedule_id,
schedule.id,
) | [
"def",
"run",
"(",
"self",
",",
"schedule_id",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"try",
":",
"schedule",
"=",
"Schedule",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"schedule_id... | Synchronises the schedule specified by the ID `schedule_id` to the
scheduler service.
Arguments:
schedule_id {str} -- The ID of the schedule to sync | [
"Synchronises",
"the",
"schedule",
"specified",
"by",
"the",
"ID",
"schedule_id",
"to",
"the",
"scheduler",
"service",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/tasks.py#L106-L144 | train | 53,919 |
praekeltfoundation/seed-stage-based-messaging | contentstore/tasks.py | DeactivateSchedule.run | def run(self, scheduler_schedule_id, **kwargs):
"""
Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate
"""
log = self.get_logger(**kwargs)
self.scheduler.update_schedule(scheduler_schedule_id, {"active": False})
log.info(
"Deactivated schedule %s in the scheduler service", scheduler_schedule_id
) | python | def run(self, scheduler_schedule_id, **kwargs):
"""
Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate
"""
log = self.get_logger(**kwargs)
self.scheduler.update_schedule(scheduler_schedule_id, {"active": False})
log.info(
"Deactivated schedule %s in the scheduler service", scheduler_schedule_id
) | [
"def",
"run",
"(",
"self",
",",
"scheduler_schedule_id",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"scheduler",
".",
"update_schedule",
"(",
"scheduler_schedule_id",
",",
"{",
"\"... | Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate | [
"Deactivates",
"the",
"schedule",
"specified",
"by",
"the",
"ID",
"scheduler_schedule_id",
"in",
"the",
"scheduler",
"service",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/tasks.py#L158-L171 | train | 53,920 |
bitlabstudio/django-multilingual-tags | multilingual_tags/models.py | TagManager.get_for_queryset | def get_for_queryset(self, obj_queryset):
"""Returns all tags for a whole queryset of objects."""
qs = Tag.objects.language(get_language())
if obj_queryset.count() == 0:
return qs.none()
qs = qs.filter(
tagged_items__object_id__in=[
obj.id for obj in obj_queryset],
tagged_items__content_type=ctype_models.ContentType.objects.get_for_model(obj_queryset[0])) # NOQA
return qs.distinct() | python | def get_for_queryset(self, obj_queryset):
"""Returns all tags for a whole queryset of objects."""
qs = Tag.objects.language(get_language())
if obj_queryset.count() == 0:
return qs.none()
qs = qs.filter(
tagged_items__object_id__in=[
obj.id for obj in obj_queryset],
tagged_items__content_type=ctype_models.ContentType.objects.get_for_model(obj_queryset[0])) # NOQA
return qs.distinct() | [
"def",
"get_for_queryset",
"(",
"self",
",",
"obj_queryset",
")",
":",
"qs",
"=",
"Tag",
".",
"objects",
".",
"language",
"(",
"get_language",
"(",
")",
")",
"if",
"obj_queryset",
".",
"count",
"(",
")",
"==",
"0",
":",
"return",
"qs",
".",
"none",
"... | Returns all tags for a whole queryset of objects. | [
"Returns",
"all",
"tags",
"for",
"a",
"whole",
"queryset",
"of",
"objects",
"."
] | c3040d8c6275b1617b99023ce3388365190cfcbd | https://github.com/bitlabstudio/django-multilingual-tags/blob/c3040d8c6275b1617b99023ce3388365190cfcbd/multilingual_tags/models.py#L27-L36 | train | 53,921 |
praekeltfoundation/seed-stage-based-messaging | subscriptions/tasks.py | post_send_process | def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[messageset] = serializers.deserialize("json", context["messageset"])
messageset = messageset.object
# Get set max
set_max = messageset.messages.filter(lang=subscription.lang).count()
logger.debug("set_max calculated - %s" % set_max)
# Compare user position to max
if subscription.next_sequence_number == set_max:
with transaction.atomic():
# Mark current as completed
logger.debug("marking current subscription as complete")
subscription.completed = True
subscription.active = False
subscription.process_status = 2 # Completed
deserialized_subscription.save(
update_fields=("completed", "active", "process_status")
)
# If next set defined create new subscription
if messageset.next_set:
logger.info("Creating new subscription for next set")
newsub = Subscription.objects.create(
identity=subscription.identity,
lang=subscription.lang,
messageset=messageset.next_set,
schedule=messageset.next_set.default_schedule,
)
logger.debug("Created Subscription <%s>" % newsub.id)
else:
# More in this set so increment by one
logger.debug("incrementing next_sequence_number")
subscription.next_sequence_number = F("next_sequence_number") + 1
logger.debug("setting process status back to 0")
subscription.process_status = 0
logger.debug("saving subscription")
deserialized_subscription.save(
update_fields=("next_sequence_number", "process_status")
)
# return response
return "Subscription for %s updated" % str(subscription.id) | python | def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[messageset] = serializers.deserialize("json", context["messageset"])
messageset = messageset.object
# Get set max
set_max = messageset.messages.filter(lang=subscription.lang).count()
logger.debug("set_max calculated - %s" % set_max)
# Compare user position to max
if subscription.next_sequence_number == set_max:
with transaction.atomic():
# Mark current as completed
logger.debug("marking current subscription as complete")
subscription.completed = True
subscription.active = False
subscription.process_status = 2 # Completed
deserialized_subscription.save(
update_fields=("completed", "active", "process_status")
)
# If next set defined create new subscription
if messageset.next_set:
logger.info("Creating new subscription for next set")
newsub = Subscription.objects.create(
identity=subscription.identity,
lang=subscription.lang,
messageset=messageset.next_set,
schedule=messageset.next_set.default_schedule,
)
logger.debug("Created Subscription <%s>" % newsub.id)
else:
# More in this set so increment by one
logger.debug("incrementing next_sequence_number")
subscription.next_sequence_number = F("next_sequence_number") + 1
logger.debug("setting process status back to 0")
subscription.process_status = 0
logger.debug("saving subscription")
deserialized_subscription.save(
update_fields=("next_sequence_number", "process_status")
)
# return response
return "Subscription for %s updated" % str(subscription.id) | [
"def",
"post_send_process",
"(",
"context",
")",
":",
"if",
"\"error\"",
"in",
"context",
":",
"return",
"context",
"[",
"deserialized_subscription",
"]",
"=",
"serializers",
".",
"deserialize",
"(",
"\"json\"",
",",
"context",
"[",
"\"subscription\"",
"]",
")",... | Task to ensure subscription is bumped or converted | [
"Task",
"to",
"ensure",
"subscription",
"is",
"bumped",
"or",
"converted"
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/tasks.py#L337-L387 | train | 53,922 |
praekeltfoundation/seed-stage-based-messaging | subscriptions/tasks.py | calculate_subscription_lifecycle | def calculate_subscription_lifecycle(subscription_id):
"""
Calculates the expected lifecycle position the subscription in
subscription_ids, and creates a BehindSubscription entry for them.
Args:
subscription_id (str): ID of subscription to calculate lifecycle for
"""
subscription = Subscription.objects.select_related("messageset", "schedule").get(
id=subscription_id
)
behind = subscription.messages_behind()
if behind == 0:
return
current_messageset = subscription.messageset
current_sequence_number = subscription.next_sequence_number
end_subscription = Subscription.fast_forward_lifecycle(subscription, save=False)[-1]
BehindSubscription.objects.create(
subscription=subscription,
messages_behind=behind,
current_messageset=current_messageset,
current_sequence_number=current_sequence_number,
expected_messageset=end_subscription.messageset,
expected_sequence_number=end_subscription.next_sequence_number,
) | python | def calculate_subscription_lifecycle(subscription_id):
"""
Calculates the expected lifecycle position the subscription in
subscription_ids, and creates a BehindSubscription entry for them.
Args:
subscription_id (str): ID of subscription to calculate lifecycle for
"""
subscription = Subscription.objects.select_related("messageset", "schedule").get(
id=subscription_id
)
behind = subscription.messages_behind()
if behind == 0:
return
current_messageset = subscription.messageset
current_sequence_number = subscription.next_sequence_number
end_subscription = Subscription.fast_forward_lifecycle(subscription, save=False)[-1]
BehindSubscription.objects.create(
subscription=subscription,
messages_behind=behind,
current_messageset=current_messageset,
current_sequence_number=current_sequence_number,
expected_messageset=end_subscription.messageset,
expected_sequence_number=end_subscription.next_sequence_number,
) | [
"def",
"calculate_subscription_lifecycle",
"(",
"subscription_id",
")",
":",
"subscription",
"=",
"Subscription",
".",
"objects",
".",
"select_related",
"(",
"\"messageset\"",
",",
"\"schedule\"",
")",
".",
"get",
"(",
"id",
"=",
"subscription_id",
")",
"behind",
... | Calculates the expected lifecycle position the subscription in
subscription_ids, and creates a BehindSubscription entry for them.
Args:
subscription_id (str): ID of subscription to calculate lifecycle for | [
"Calculates",
"the",
"expected",
"lifecycle",
"position",
"the",
"subscription",
"in",
"subscription_ids",
"and",
"creates",
"a",
"BehindSubscription",
"entry",
"for",
"them",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/tasks.py#L597-L622 | train | 53,923 |
praekeltfoundation/seed-stage-based-messaging | subscriptions/tasks.py | find_behind_subscriptions | def find_behind_subscriptions():
"""
Finds any subscriptions that are behind according to where they should be,
and creates a BehindSubscription entry for them.
"""
subscriptions = Subscription.objects.filter(
active=True, completed=False, process_status=0
).values_list("id", flat=True)
for subscription_id in subscriptions.iterator():
calculate_subscription_lifecycle.delay(str(subscription_id)) | python | def find_behind_subscriptions():
"""
Finds any subscriptions that are behind according to where they should be,
and creates a BehindSubscription entry for them.
"""
subscriptions = Subscription.objects.filter(
active=True, completed=False, process_status=0
).values_list("id", flat=True)
for subscription_id in subscriptions.iterator():
calculate_subscription_lifecycle.delay(str(subscription_id)) | [
"def",
"find_behind_subscriptions",
"(",
")",
":",
"subscriptions",
"=",
"Subscription",
".",
"objects",
".",
"filter",
"(",
"active",
"=",
"True",
",",
"completed",
"=",
"False",
",",
"process_status",
"=",
"0",
")",
".",
"values_list",
"(",
"\"id\"",
",",
... | Finds any subscriptions that are behind according to where they should be,
and creates a BehindSubscription entry for them. | [
"Finds",
"any",
"subscriptions",
"that",
"are",
"behind",
"according",
"to",
"where",
"they",
"should",
"be",
"and",
"creates",
"a",
"BehindSubscription",
"entry",
"for",
"them",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/tasks.py#L626-L635 | train | 53,924 |
praekeltfoundation/seed-stage-based-messaging | contentstore/views.py | ScheduleViewSet.send | def send(self, request, pk=None):
"""
Sends all the subscriptions for the specified schedule
"""
schedule = self.get_object()
queue_subscription_send.delay(str(schedule.id))
return Response({}, status=status.HTTP_202_ACCEPTED) | python | def send(self, request, pk=None):
"""
Sends all the subscriptions for the specified schedule
"""
schedule = self.get_object()
queue_subscription_send.delay(str(schedule.id))
return Response({}, status=status.HTTP_202_ACCEPTED) | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
")",
":",
"schedule",
"=",
"self",
".",
"get_object",
"(",
")",
"queue_subscription_send",
".",
"delay",
"(",
"str",
"(",
"schedule",
".",
"id",
")",
")",
"return",
"Response",
"(",
... | Sends all the subscriptions for the specified schedule | [
"Sends",
"all",
"the",
"subscriptions",
"for",
"the",
"specified",
"schedule"
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/views.py#L37-L44 | train | 53,925 |
jreese/tasky | tasky/config.py | Config.get | def get(self, key: Any, default: Any=None) -> Any:
'''Return the configured value for the given key name, or `default` if
no value is available or key is invalid.'''
return self.data.get(key, default) | python | def get(self, key: Any, default: Any=None) -> Any:
'''Return the configured value for the given key name, or `default` if
no value is available or key is invalid.'''
return self.data.get(key, default) | [
"def",
"get",
"(",
"self",
",",
"key",
":",
"Any",
",",
"default",
":",
"Any",
"=",
"None",
")",
"->",
"Any",
":",
"return",
"self",
".",
"data",
".",
"get",
"(",
"key",
",",
"default",
")"
] | Return the configured value for the given key name, or `default` if
no value is available or key is invalid. | [
"Return",
"the",
"configured",
"value",
"for",
"the",
"given",
"key",
"name",
"or",
"default",
"if",
"no",
"value",
"is",
"available",
"or",
"key",
"is",
"invalid",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/config.py#L28-L32 | train | 53,926 |
jreese/tasky | tasky/config.py | Config.task_config | def task_config(self, task: Task) -> Any:
'''Return the task-specific configuration.'''
return self.get(task.__class__.__name__) | python | def task_config(self, task: Task) -> Any:
'''Return the task-specific configuration.'''
return self.get(task.__class__.__name__) | [
"def",
"task_config",
"(",
"self",
",",
"task",
":",
"Task",
")",
"->",
"Any",
":",
"return",
"self",
".",
"get",
"(",
"task",
".",
"__class__",
".",
"__name__",
")"
] | Return the task-specific configuration. | [
"Return",
"the",
"task",
"-",
"specific",
"configuration",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/config.py#L39-L42 | train | 53,927 |
jreese/tasky | tasky/config.py | JsonConfig.init | async def init(self) -> None:
'''Load configuration in JSON format from either a file or
a raw data string.'''
if self.data:
return
if self.json_data:
try:
self.data = json.loads(self.json_data)
except Exception:
Log.exception('Falied to load raw configuration')
else:
try:
with open(self.json_path, 'r') as f:
self.data = json.load(f)
except Exception:
Log.exception('Failed to load configuration from %s',
self.json_path)
self.data = {} | python | async def init(self) -> None:
'''Load configuration in JSON format from either a file or
a raw data string.'''
if self.data:
return
if self.json_data:
try:
self.data = json.loads(self.json_data)
except Exception:
Log.exception('Falied to load raw configuration')
else:
try:
with open(self.json_path, 'r') as f:
self.data = json.load(f)
except Exception:
Log.exception('Failed to load configuration from %s',
self.json_path)
self.data = {} | [
"async",
"def",
"init",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"data",
":",
"return",
"if",
"self",
".",
"json_data",
":",
"try",
":",
"self",
".",
"data",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"json_data",
")",
"except",
... | Load configuration in JSON format from either a file or
a raw data string. | [
"Load",
"configuration",
"in",
"JSON",
"format",
"from",
"either",
"a",
"file",
"or",
"a",
"raw",
"data",
"string",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/config.py#L72-L94 | train | 53,928 |
jreese/tasky | tasky/tasks/timer.py | TimerTask.reset | def reset(self) -> None:
'''Reset task execution to `DELAY` seconds from now.'''
Log.debug('resetting timer task %s')
self.target = self.time() + self.DELAY | python | def reset(self) -> None:
'''Reset task execution to `DELAY` seconds from now.'''
Log.debug('resetting timer task %s')
self.target = self.time() + self.DELAY | [
"def",
"reset",
"(",
"self",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'resetting timer task %s'",
")",
"self",
".",
"target",
"=",
"self",
".",
"time",
"(",
")",
"+",
"self",
".",
"DELAY"
] | Reset task execution to `DELAY` seconds from now. | [
"Reset",
"task",
"execution",
"to",
"DELAY",
"seconds",
"from",
"now",
"."
] | 681f4e5a9a60a0eb838b89f320309cfb45a56242 | https://github.com/jreese/tasky/blob/681f4e5a9a60a0eb838b89f320309cfb45a56242/tasky/tasks/timer.py#L55-L59 | train | 53,929 |
praekeltfoundation/seed-stage-based-messaging | seed_stage_based_messaging/decorators.py | internal_only | def internal_only(view_func):
"""
A view decorator which blocks access for requests coming through the load balancer.
"""
@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):
forwards = request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")
# The nginx in the docker container adds the loadbalancer IP to the list inside
# X-Forwarded-For, so if the list contains more than a single item, we know
# that it went through our loadbalancer
if len(forwards) > 1:
raise PermissionDenied()
return view_func(request, *args, **kwargs)
return wrapper | python | def internal_only(view_func):
"""
A view decorator which blocks access for requests coming through the load balancer.
"""
@functools.wraps(view_func)
def wrapper(request, *args, **kwargs):
forwards = request.META.get("HTTP_X_FORWARDED_FOR", "").split(",")
# The nginx in the docker container adds the loadbalancer IP to the list inside
# X-Forwarded-For, so if the list contains more than a single item, we know
# that it went through our loadbalancer
if len(forwards) > 1:
raise PermissionDenied()
return view_func(request, *args, **kwargs)
return wrapper | [
"def",
"internal_only",
"(",
"view_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"view_func",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"forwards",
"=",
"request",
".",
"META",
".",
"get",
"("... | A view decorator which blocks access for requests coming through the load balancer. | [
"A",
"view",
"decorator",
"which",
"blocks",
"access",
"for",
"requests",
"coming",
"through",
"the",
"load",
"balancer",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/seed_stage_based_messaging/decorators.py#L6-L21 | train | 53,930 |
praekeltfoundation/seed-stage-based-messaging | subscriptions/views.py | SubscriptionRequest.post | def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Subscription message
"""
# Ensure that we check for the 'data' key in the request object before
# attempting to reference it
if "data" in request.data:
# This is a workaround for JSONField not liking blank/null refs
if "metadata" not in request.data["data"]:
request.data["data"]["metadata"] = {}
if "initial_sequence_number" not in request.data["data"]:
request.data["data"]["initial_sequence_number"] = request.data[
"data"
].get("next_sequence_number")
subscription = SubscriptionSerializer(data=request.data["data"])
if subscription.is_valid():
subscription.save()
# Return
status = 201
accepted = {"accepted": True}
return Response(accepted, status=status)
else:
status = 400
return Response(subscription.errors, status=status)
else:
status = 400
message = {"data": ["This field is required."]}
return Response(message, status=status) | python | def post(self, request, *args, **kwargs):
""" Validates subscription data before creating Subscription message
"""
# Ensure that we check for the 'data' key in the request object before
# attempting to reference it
if "data" in request.data:
# This is a workaround for JSONField not liking blank/null refs
if "metadata" not in request.data["data"]:
request.data["data"]["metadata"] = {}
if "initial_sequence_number" not in request.data["data"]:
request.data["data"]["initial_sequence_number"] = request.data[
"data"
].get("next_sequence_number")
subscription = SubscriptionSerializer(data=request.data["data"])
if subscription.is_valid():
subscription.save()
# Return
status = 201
accepted = {"accepted": True}
return Response(accepted, status=status)
else:
status = 400
return Response(subscription.errors, status=status)
else:
status = 400
message = {"data": ["This field is required."]}
return Response(message, status=status) | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Ensure that we check for the 'data' key in the request object before",
"# attempting to reference it",
"if",
"\"data\"",
"in",
"request",
".",
"data",
":",
"# This is a... | Validates subscription data before creating Subscription message | [
"Validates",
"subscription",
"data",
"before",
"creating",
"Subscription",
"message"
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/views.py#L125-L153 | train | 53,931 |
praekeltfoundation/seed-stage-based-messaging | subscriptions/views.py | BehindSubscriptionViewSet.find_behind_subscriptions | def find_behind_subscriptions(self, request):
"""
Starts a celery task that looks through active subscriptions to find
and subscriptions that are behind where they should be, and adds a
BehindSubscription for them.
"""
task_id = find_behind_subscriptions.delay()
return Response(
{"accepted": True, "task_id": str(task_id)}, status=status.HTTP_202_ACCEPTED
) | python | def find_behind_subscriptions(self, request):
"""
Starts a celery task that looks through active subscriptions to find
and subscriptions that are behind where they should be, and adds a
BehindSubscription for them.
"""
task_id = find_behind_subscriptions.delay()
return Response(
{"accepted": True, "task_id": str(task_id)}, status=status.HTTP_202_ACCEPTED
) | [
"def",
"find_behind_subscriptions",
"(",
"self",
",",
"request",
")",
":",
"task_id",
"=",
"find_behind_subscriptions",
".",
"delay",
"(",
")",
"return",
"Response",
"(",
"{",
"\"accepted\"",
":",
"True",
",",
"\"task_id\"",
":",
"str",
"(",
"task_id",
")",
... | Starts a celery task that looks through active subscriptions to find
and subscriptions that are behind where they should be, and adds a
BehindSubscription for them. | [
"Starts",
"a",
"celery",
"task",
"that",
"looks",
"through",
"active",
"subscriptions",
"to",
"find",
"and",
"subscriptions",
"that",
"are",
"behind",
"where",
"they",
"should",
"be",
"and",
"adds",
"a",
"BehindSubscription",
"for",
"them",
"."
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/subscriptions/views.py#L290-L300 | train | 53,932 |
inspirehep/inspire-query-parser | examples/demo_parser.py | repl | def repl():
"""Read-Eval-Print-Loop for reading the query, printing it and its parse tree.
Exit the loop either with an interrupt or "quit".
"""
while True:
try:
sys.stdout.write("Type in next query: \n> ")
import locale
query_str = raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))
except KeyboardInterrupt:
break
if u'quit' in query_str:
break
print_query_and_parse_tree(query_str) | python | def repl():
"""Read-Eval-Print-Loop for reading the query, printing it and its parse tree.
Exit the loop either with an interrupt or "quit".
"""
while True:
try:
sys.stdout.write("Type in next query: \n> ")
import locale
query_str = raw_input().decode(sys.stdin.encoding or locale.getpreferredencoding(True))
except KeyboardInterrupt:
break
if u'quit' in query_str:
break
print_query_and_parse_tree(query_str) | [
"def",
"repl",
"(",
")",
":",
"while",
"True",
":",
"try",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Type in next query: \\n> \"",
")",
"import",
"locale",
"query_str",
"=",
"raw_input",
"(",
")",
".",
"decode",
"(",
"sys",
".",
"stdin",
".",
"e... | Read-Eval-Print-Loop for reading the query, printing it and its parse tree.
Exit the loop either with an interrupt or "quit". | [
"Read",
"-",
"Eval",
"-",
"Print",
"-",
"Loop",
"for",
"reading",
"the",
"query",
"printing",
"it",
"and",
"its",
"parse",
"tree",
"."
] | 9dde20d7caef89a48bb419b866f4535c88cfc00d | https://github.com/inspirehep/inspire-query-parser/blob/9dde20d7caef89a48bb419b866f4535c88cfc00d/examples/demo_parser.py#L33-L49 | train | 53,933 |
praekeltfoundation/seed-stage-based-messaging | contentstore/signals.py | schedule_saved | def schedule_saved(sender, instance, **kwargs):
"""
Fires off the celery task to ensure that this schedule is in the scheduler
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the Schedule that we want to sync
"""
from contentstore.tasks import sync_schedule
sync_schedule.delay(str(instance.id)) | python | def schedule_saved(sender, instance, **kwargs):
"""
Fires off the celery task to ensure that this schedule is in the scheduler
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the Schedule that we want to sync
"""
from contentstore.tasks import sync_schedule
sync_schedule.delay(str(instance.id)) | [
"def",
"schedule_saved",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"contentstore",
".",
"tasks",
"import",
"sync_schedule",
"sync_schedule",
".",
"delay",
"(",
"str",
"(",
"instance",
".",
"id",
")",
")"
] | Fires off the celery task to ensure that this schedule is in the scheduler
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the Schedule that we want to sync | [
"Fires",
"off",
"the",
"celery",
"task",
"to",
"ensure",
"that",
"this",
"schedule",
"is",
"in",
"the",
"scheduler"
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/signals.py#L12-L23 | train | 53,934 |
praekeltfoundation/seed-stage-based-messaging | contentstore/signals.py | schedule_deleted | def schedule_deleted(sender, instance, **kwargs):
"""
Fires off the celery task to ensure that this schedule is deactivated
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the schedule that we want to deactivate
"""
from contentstore.tasks import deactivate_schedule
deactivate_schedule.delay(str(instance.scheduler_schedule_id)) | python | def schedule_deleted(sender, instance, **kwargs):
"""
Fires off the celery task to ensure that this schedule is deactivated
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the schedule that we want to deactivate
"""
from contentstore.tasks import deactivate_schedule
deactivate_schedule.delay(str(instance.scheduler_schedule_id)) | [
"def",
"schedule_deleted",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"contentstore",
".",
"tasks",
"import",
"deactivate_schedule",
"deactivate_schedule",
".",
"delay",
"(",
"str",
"(",
"instance",
".",
"scheduler_schedule_id",
"... | Fires off the celery task to ensure that this schedule is deactivated
Arguments:
sender {class} -- The model class, always Schedule
instance {Schedule} --
The instance of the schedule that we want to deactivate | [
"Fires",
"off",
"the",
"celery",
"task",
"to",
"ensure",
"that",
"this",
"schedule",
"is",
"deactivated"
] | 6f0cacf0727ac2ed19877de214d58009c685b8fa | https://github.com/praekeltfoundation/seed-stage-based-messaging/blob/6f0cacf0727ac2ed19877de214d58009c685b8fa/contentstore/signals.py#L27-L38 | train | 53,935 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | group_by | def group_by(keys, values=None, reduction=None, axis=0):
"""construct a grouping object on the given keys, optionally performing the given reduction on the given values
Parameters
----------
keys : indexable object
keys to group by
values : array_like, optional
sequence of values, of the same length as keys
if a reduction function is provided, the given values are reduced by key
if no reduction is provided, the given values are grouped and split by key
reduction : lambda, optional
reduction function to apply to the values in each group
axis : int, optional
axis to regard as the key-sequence, in case keys is multi-dimensional
Returns
-------
iterable
if values is None, a GroupBy object of the given keys object
if reduction is None, an tuple of a sequence of unique keys and a sequence of grouped values
else, a sequence of tuples of unique keys and reductions of values over that key-group
See Also
--------
numpy_indexed.as_index : for information regarding the casting rules to a valid Index object
"""
g = GroupBy(keys, axis)
if values is None:
return g
groups = g.split(values)
if reduction is None:
return g.unique, groups
return [(key, reduction(group)) for key, group in zip(g.unique, groups)] | python | def group_by(keys, values=None, reduction=None, axis=0):
"""construct a grouping object on the given keys, optionally performing the given reduction on the given values
Parameters
----------
keys : indexable object
keys to group by
values : array_like, optional
sequence of values, of the same length as keys
if a reduction function is provided, the given values are reduced by key
if no reduction is provided, the given values are grouped and split by key
reduction : lambda, optional
reduction function to apply to the values in each group
axis : int, optional
axis to regard as the key-sequence, in case keys is multi-dimensional
Returns
-------
iterable
if values is None, a GroupBy object of the given keys object
if reduction is None, an tuple of a sequence of unique keys and a sequence of grouped values
else, a sequence of tuples of unique keys and reductions of values over that key-group
See Also
--------
numpy_indexed.as_index : for information regarding the casting rules to a valid Index object
"""
g = GroupBy(keys, axis)
if values is None:
return g
groups = g.split(values)
if reduction is None:
return g.unique, groups
return [(key, reduction(group)) for key, group in zip(g.unique, groups)] | [
"def",
"group_by",
"(",
"keys",
",",
"values",
"=",
"None",
",",
"reduction",
"=",
"None",
",",
"axis",
"=",
"0",
")",
":",
"g",
"=",
"GroupBy",
"(",
"keys",
",",
"axis",
")",
"if",
"values",
"is",
"None",
":",
"return",
"g",
"groups",
"=",
"g",
... | construct a grouping object on the given keys, optionally performing the given reduction on the given values
Parameters
----------
keys : indexable object
keys to group by
values : array_like, optional
sequence of values, of the same length as keys
if a reduction function is provided, the given values are reduced by key
if no reduction is provided, the given values are grouped and split by key
reduction : lambda, optional
reduction function to apply to the values in each group
axis : int, optional
axis to regard as the key-sequence, in case keys is multi-dimensional
Returns
-------
iterable
if values is None, a GroupBy object of the given keys object
if reduction is None, an tuple of a sequence of unique keys and a sequence of grouped values
else, a sequence of tuples of unique keys and reductions of values over that key-group
See Also
--------
numpy_indexed.as_index : for information regarding the casting rules to a valid Index object | [
"construct",
"a",
"grouping",
"object",
"on",
"the",
"given",
"keys",
"optionally",
"performing",
"the",
"given",
"reduction",
"on",
"the",
"given",
"values"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L576-L609 | train | 53,936 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.split_iterable_as_iterable | def split_iterable_as_iterable(self, values):
"""Group iterable into iterables, in the order of the keys
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
Memory consumption depends on the amount of sorting required
Worst case, if index.sorter[-1] = 0, we need to consume the entire value iterable,
before we can start yielding any output
But to the extent that the keys are already sorted, the grouping is lazy
"""
values = iter(enumerate(values))
cache = dict()
def get_value(ti):
try:
return cache.pop(ti)
except:
while True:
i, v = next(values)
if i==ti:
return v
cache[i] = v
s = iter(self.index.sorter)
for c in self.count:
yield (get_value(i) for i in itertools.islice(s, int(c))) | python | def split_iterable_as_iterable(self, values):
"""Group iterable into iterables, in the order of the keys
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
Memory consumption depends on the amount of sorting required
Worst case, if index.sorter[-1] = 0, we need to consume the entire value iterable,
before we can start yielding any output
But to the extent that the keys are already sorted, the grouping is lazy
"""
values = iter(enumerate(values))
cache = dict()
def get_value(ti):
try:
return cache.pop(ti)
except:
while True:
i, v = next(values)
if i==ti:
return v
cache[i] = v
s = iter(self.index.sorter)
for c in self.count:
yield (get_value(i) for i in itertools.islice(s, int(c))) | [
"def",
"split_iterable_as_iterable",
"(",
"self",
",",
"values",
")",
":",
"values",
"=",
"iter",
"(",
"enumerate",
"(",
"values",
")",
")",
"cache",
"=",
"dict",
"(",
")",
"def",
"get_value",
"(",
"ti",
")",
":",
"try",
":",
"return",
"cache",
".",
... | Group iterable into iterables, in the order of the keys
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
Memory consumption depends on the amount of sorting required
Worst case, if index.sorter[-1] = 0, we need to consume the entire value iterable,
before we can start yielding any output
But to the extent that the keys are already sorted, the grouping is lazy | [
"Group",
"iterable",
"into",
"iterables",
"in",
"the",
"order",
"of",
"the",
"keys"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L57-L89 | train | 53,937 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.split_iterable_as_unordered_iterable | def split_iterable_as_unordered_iterable(self, values):
"""Group iterable into iterables, without regard for the ordering of self.index.unique
key-group tuples are yielded as soon as they are complete
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
tuple of key, and a list of corresponding items in values
Notes
-----
This approach is lazy, insofar as grouped values are close in their iterable
"""
from collections import defaultdict
cache = defaultdict(list)
count = self.count
unique = self.unique
key = (lambda i: unique[i]) if isinstance(unique, np.ndarray) else (lambda i: tuple(c[i] for c in unique))
for i,v in zip(self.inverse, values):
cache[i].append(v)
if len(cache[i]) == count[i]:
yield key(i), cache.pop(i) | python | def split_iterable_as_unordered_iterable(self, values):
"""Group iterable into iterables, without regard for the ordering of self.index.unique
key-group tuples are yielded as soon as they are complete
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
tuple of key, and a list of corresponding items in values
Notes
-----
This approach is lazy, insofar as grouped values are close in their iterable
"""
from collections import defaultdict
cache = defaultdict(list)
count = self.count
unique = self.unique
key = (lambda i: unique[i]) if isinstance(unique, np.ndarray) else (lambda i: tuple(c[i] for c in unique))
for i,v in zip(self.inverse, values):
cache[i].append(v)
if len(cache[i]) == count[i]:
yield key(i), cache.pop(i) | [
"def",
"split_iterable_as_unordered_iterable",
"(",
"self",
",",
"values",
")",
":",
"from",
"collections",
"import",
"defaultdict",
"cache",
"=",
"defaultdict",
"(",
"list",
")",
"count",
"=",
"self",
".",
"count",
"unique",
"=",
"self",
".",
"unique",
"key",... | Group iterable into iterables, without regard for the ordering of self.index.unique
key-group tuples are yielded as soon as they are complete
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
tuple of key, and a list of corresponding items in values
Notes
-----
This approach is lazy, insofar as grouped values are close in their iterable | [
"Group",
"iterable",
"into",
"iterables",
"without",
"regard",
"for",
"the",
"ordering",
"of",
"self",
".",
"index",
".",
"unique",
"key",
"-",
"group",
"tuples",
"are",
"yielded",
"as",
"soon",
"as",
"they",
"are",
"complete"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L91-L116 | train | 53,938 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.split_sequence_as_iterable | def split_sequence_as_iterable(self, values):
"""Group sequence into iterables
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
This is the preferred method if values has random access, but we dont want it completely in memory.
Like a big memory mapped file, for instance
"""
print(self.count)
s = iter(self.index.sorter)
for c in self.count:
yield (values[i] for i in itertools.islice(s, int(c))) | python | def split_sequence_as_iterable(self, values):
"""Group sequence into iterables
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
This is the preferred method if values has random access, but we dont want it completely in memory.
Like a big memory mapped file, for instance
"""
print(self.count)
s = iter(self.index.sorter)
for c in self.count:
yield (values[i] for i in itertools.islice(s, int(c))) | [
"def",
"split_sequence_as_iterable",
"(",
"self",
",",
"values",
")",
":",
"print",
"(",
"self",
".",
"count",
")",
"s",
"=",
"iter",
"(",
"self",
".",
"index",
".",
"sorter",
")",
"for",
"c",
"in",
"self",
".",
"count",
":",
"yield",
"(",
"values",
... | Group sequence into iterables
Parameters
----------
values : iterable of length equal to keys
iterable of values to be grouped
Yields
------
iterable of items in values
Notes
-----
This is the preferred method if values has random access, but we dont want it completely in memory.
Like a big memory mapped file, for instance | [
"Group",
"sequence",
"into",
"iterables"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L118-L138 | train | 53,939 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.split_array_as_array | def split_array_as_array(self, values):
"""Group ndarray into ndarray by means of reshaping
Parameters
----------
values : ndarray_like, [index.size, ...]
Returns
-------
ndarray, [groups, group_size, ...]
values grouped by key
Raises
------
AssertionError
This operation is only possible if index.uniform==True
"""
if not self.index.uniform:
raise ValueError("Array can only be split as array if all groups have the same size")
values = np.asarray(values)
values = values[self.index.sorter]
return values.reshape(self.groups, -1, *values.shape[1:]) | python | def split_array_as_array(self, values):
"""Group ndarray into ndarray by means of reshaping
Parameters
----------
values : ndarray_like, [index.size, ...]
Returns
-------
ndarray, [groups, group_size, ...]
values grouped by key
Raises
------
AssertionError
This operation is only possible if index.uniform==True
"""
if not self.index.uniform:
raise ValueError("Array can only be split as array if all groups have the same size")
values = np.asarray(values)
values = values[self.index.sorter]
return values.reshape(self.groups, -1, *values.shape[1:]) | [
"def",
"split_array_as_array",
"(",
"self",
",",
"values",
")",
":",
"if",
"not",
"self",
".",
"index",
".",
"uniform",
":",
"raise",
"ValueError",
"(",
"\"Array can only be split as array if all groups have the same size\"",
")",
"values",
"=",
"np",
".",
"asarray"... | Group ndarray into ndarray by means of reshaping
Parameters
----------
values : ndarray_like, [index.size, ...]
Returns
-------
ndarray, [groups, group_size, ...]
values grouped by key
Raises
------
AssertionError
This operation is only possible if index.uniform==True | [
"Group",
"ndarray",
"into",
"ndarray",
"by",
"means",
"of",
"reshaping"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L140-L161 | train | 53,940 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.split_array_as_list | def split_array_as_list(self, values):
"""Group values as a list of arrays, or a jagged-array
Parameters
----------
values : ndarray, [keys, ...]
Returns
-------
list of length self.groups of ndarray, [key_count, ...]
"""
values = np.asarray(values)
values = values[self.index.sorter]
return np.split(values, self.index.slices[1:-1], axis=0) | python | def split_array_as_list(self, values):
"""Group values as a list of arrays, or a jagged-array
Parameters
----------
values : ndarray, [keys, ...]
Returns
-------
list of length self.groups of ndarray, [key_count, ...]
"""
values = np.asarray(values)
values = values[self.index.sorter]
return np.split(values, self.index.slices[1:-1], axis=0) | [
"def",
"split_array_as_list",
"(",
"self",
",",
"values",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"values",
"=",
"values",
"[",
"self",
".",
"index",
".",
"sorter",
"]",
"return",
"np",
".",
"split",
"(",
"values",
",",
"se... | Group values as a list of arrays, or a jagged-array
Parameters
----------
values : ndarray, [keys, ...]
Returns
-------
list of length self.groups of ndarray, [key_count, ...] | [
"Group",
"values",
"as",
"a",
"list",
"of",
"arrays",
"or",
"a",
"jagged",
"-",
"array"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L163-L176 | train | 53,941 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.reduce | def reduce(self, values, operator=np.add, axis=0, dtype=None):
"""Reduce the values over identical key groups, using the given ufunc
reduction is over the first axis, which should have elements corresponding to the keys
all other axes are treated indepenently for the sake of this reduction
Parameters
----------
values : ndarray, [keys, ...]
values to perform reduction over
operator : numpy.ufunc
a numpy ufunc, such as np.add or np.sum
axis : int, optional
the axis to reduce over
dtype : output dtype
Returns
-------
ndarray, [groups, ...]
values reduced by operator over the key-groups
"""
values = np.take(values, self.index.sorter, axis=axis)
return operator.reduceat(values, self.index.start, axis=axis, dtype=dtype) | python | def reduce(self, values, operator=np.add, axis=0, dtype=None):
"""Reduce the values over identical key groups, using the given ufunc
reduction is over the first axis, which should have elements corresponding to the keys
all other axes are treated indepenently for the sake of this reduction
Parameters
----------
values : ndarray, [keys, ...]
values to perform reduction over
operator : numpy.ufunc
a numpy ufunc, such as np.add or np.sum
axis : int, optional
the axis to reduce over
dtype : output dtype
Returns
-------
ndarray, [groups, ...]
values reduced by operator over the key-groups
"""
values = np.take(values, self.index.sorter, axis=axis)
return operator.reduceat(values, self.index.start, axis=axis, dtype=dtype) | [
"def",
"reduce",
"(",
"self",
",",
"values",
",",
"operator",
"=",
"np",
".",
"add",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"None",
")",
":",
"values",
"=",
"np",
".",
"take",
"(",
"values",
",",
"self",
".",
"index",
".",
"sorter",
",",
"ax... | Reduce the values over identical key groups, using the given ufunc
reduction is over the first axis, which should have elements corresponding to the keys
all other axes are treated indepenently for the sake of this reduction
Parameters
----------
values : ndarray, [keys, ...]
values to perform reduction over
operator : numpy.ufunc
a numpy ufunc, such as np.add or np.sum
axis : int, optional
the axis to reduce over
dtype : output dtype
Returns
-------
ndarray, [groups, ...]
values reduced by operator over the key-groups | [
"Reduce",
"the",
"values",
"over",
"identical",
"key",
"groups",
"using",
"the",
"given",
"ufunc",
"reduction",
"is",
"over",
"the",
"first",
"axis",
"which",
"should",
"have",
"elements",
"corresponding",
"to",
"the",
"keys",
"all",
"other",
"axes",
"are",
... | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L192-L213 | train | 53,942 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.sum | def sum(self, values, axis=0, dtype=None):
"""compute the sum over each group
Parameters
----------
values : array_like, [keys, ...]
values to sum per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, dtype=dtype) | python | def sum(self, values, axis=0, dtype=None):
"""compute the sum over each group
Parameters
----------
values : array_like, [keys, ...]
values to sum per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, dtype=dtype) | [
"def",
"sum",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"None",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"return",
"self",
".",
"unique",
",",
"self",
".",
"reduce",
"(",
"values",
",",
"axis"... | compute the sum over each group
Parameters
----------
values : array_like, [keys, ...]
values to sum per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"compute",
"the",
"sum",
"over",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L216-L235 | train | 53,943 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.prod | def prod(self, values, axis=0, dtype=None):
"""compute the product over each group
Parameters
----------
values : array_like, [keys, ...]
values to multiply per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, dtype=dtype, operator=np.multiply) | python | def prod(self, values, axis=0, dtype=None):
"""compute the product over each group
Parameters
----------
values : array_like, [keys, ...]
values to multiply per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, dtype=dtype, operator=np.multiply) | [
"def",
"prod",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"None",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"return",
"self",
".",
"unique",
",",
"self",
".",
"reduce",
"(",
"values",
",",
"axis... | compute the product over each group
Parameters
----------
values : array_like, [keys, ...]
values to multiply per group
axis : int, optional
alternative reduction axis for values
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"compute",
"the",
"product",
"over",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L237-L256 | train | 53,944 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.mean | def mean(self, values, axis=0, weights=None, dtype=None):
"""compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for each value
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
if weights is None:
result = self.reduce(values, axis=axis, dtype=dtype)
shape = [1] * values.ndim
shape[axis] = self.groups
weights = self.count.reshape(shape)
else:
weights = np.asarray(weights)
result = self.reduce(values * weights, axis=axis, dtype=dtype)
weights = self.reduce(weights, axis=axis, dtype=dtype)
return self.unique, result / weights | python | def mean(self, values, axis=0, weights=None, dtype=None):
"""compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for each value
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
if weights is None:
result = self.reduce(values, axis=axis, dtype=dtype)
shape = [1] * values.ndim
shape[axis] = self.groups
weights = self.count.reshape(shape)
else:
weights = np.asarray(weights)
result = self.reduce(values * weights, axis=axis, dtype=dtype)
weights = self.reduce(weights, axis=axis, dtype=dtype)
return self.unique, result / weights | [
"def",
"mean",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"if",
"weights",
"is",
"None",
":",
"result",
"=",
"self"... | compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for each value
dtype : output dtype
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"compute",
"the",
"mean",
"over",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L258-L288 | train | 53,945 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.var | def var(self, values, axis=0, weights=None, dtype=None):
"""compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
unique, mean = self.mean(values, axis, weights, dtype)
err = values - mean.take(self.inverse, axis)
if weights is None:
shape = [1] * values.ndim
shape[axis] = self.groups
group_weights = self.count.reshape(shape)
var = self.reduce(err ** 2, axis=axis, dtype=dtype)
else:
weights = np.asarray(weights)
group_weights = self.reduce(weights, axis=axis, dtype=dtype)
var = self.reduce(weights * err ** 2, axis=axis, dtype=dtype)
return unique, var / group_weights | python | def var(self, values, axis=0, weights=None, dtype=None):
"""compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
unique, mean = self.mean(values, axis, weights, dtype)
err = values - mean.take(self.inverse, axis)
if weights is None:
shape = [1] * values.ndim
shape[axis] = self.groups
group_weights = self.count.reshape(shape)
var = self.reduce(err ** 2, axis=axis, dtype=dtype)
else:
weights = np.asarray(weights)
group_weights = self.reduce(weights, axis=axis, dtype=dtype)
var = self.reduce(weights * err ** 2, axis=axis, dtype=dtype)
return unique, var / group_weights | [
"def",
"var",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"unique",
",",
"mean",
"=",
"self",
".",
"mean",
"(",
"v... | compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"compute",
"the",
"variance",
"over",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L290-L321 | train | 53,946 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.std | def std(self, values, axis=0, weights=None, dtype=None):
"""standard deviation over each group
Parameters
----------
values : array_like, [keys, ...]
values to take standard deviation of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
unique, var = self.var(values, axis, weights, dtype)
return unique, np.sqrt(var) | python | def std(self, values, axis=0, weights=None, dtype=None):
"""standard deviation over each group
Parameters
----------
values : array_like, [keys, ...]
values to take standard deviation of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
unique, var = self.var(values, axis, weights, dtype)
return unique, np.sqrt(var) | [
"def",
"std",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
",",
"weights",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"unique",
",",
"var",
"=",
"self",
".",
"var",
"(",
"values",
",",
"axis",
",",
"weights",
",",
"dtype",
")",
"re... | standard deviation over each group
Parameters
----------
values : array_like, [keys, ...]
values to take standard deviation of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"standard",
"deviation",
"over",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L323-L341 | train | 53,947 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.median | def median(self, values, axis=0, average=True):
"""compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
average : bool, optional
when average is true, the average of the two central values is taken for groups with an even key-count
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
mid_2 = self.index.start + self.index.stop
hi = (mid_2 ) // 2
lo = (mid_2 - 1) // 2
#need this indirection for lex-index compatibility
sorted_group_rank_per_key = self.index.sorted_group_rank_per_key
def median1d(slc):
#place values at correct keys; preconditions the upcoming lexsort
slc = slc[self.index.sorter]
#refine value sorting within each keygroup
sorter = np.lexsort((slc, sorted_group_rank_per_key))
slc = slc[sorter]
return (slc[lo]+slc[hi]) / 2 if average else slc[hi]
values = np.asarray(values)
if values.ndim>1: #is trying to skip apply_along_axis somewhat premature optimization?
values = np.apply_along_axis(median1d, axis, values)
else:
values = median1d(values)
return self.unique, values | python | def median(self, values, axis=0, average=True):
"""compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
average : bool, optional
when average is true, the average of the two central values is taken for groups with an even key-count
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
mid_2 = self.index.start + self.index.stop
hi = (mid_2 ) // 2
lo = (mid_2 - 1) // 2
#need this indirection for lex-index compatibility
sorted_group_rank_per_key = self.index.sorted_group_rank_per_key
def median1d(slc):
#place values at correct keys; preconditions the upcoming lexsort
slc = slc[self.index.sorter]
#refine value sorting within each keygroup
sorter = np.lexsort((slc, sorted_group_rank_per_key))
slc = slc[sorter]
return (slc[lo]+slc[hi]) / 2 if average else slc[hi]
values = np.asarray(values)
if values.ndim>1: #is trying to skip apply_along_axis somewhat premature optimization?
values = np.apply_along_axis(median1d, axis, values)
else:
values = median1d(values)
return self.unique, values | [
"def",
"median",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
",",
"average",
"=",
"True",
")",
":",
"mid_2",
"=",
"self",
".",
"index",
".",
"start",
"+",
"self",
".",
"index",
".",
"stop",
"hi",
"=",
"(",
"mid_2",
")",
"//",
"2",
"lo",
... | compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
average : bool, optional
when average is true, the average of the two central values is taken for groups with an even key-count
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"compute",
"the",
"median",
"value",
"over",
"each",
"group",
"."
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L343-L382 | train | 53,948 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.mode | def mode(self, values, weights=None):
"""compute the mode within each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the mode of per group
weights : array_like, [keys], float, optional
optional weight associated with each entry in values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
if weights is None:
unique, weights = npi.count((self.index.sorted_group_rank_per_key, values))
else:
unique, weights = npi.group_by((self.index.sorted_group_rank_per_key, values)).sum(weights)
x, bin = npi.group_by(unique[0]).argmax(weights)
return x, unique[1][bin] | python | def mode(self, values, weights=None):
"""compute the mode within each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the mode of per group
weights : array_like, [keys], float, optional
optional weight associated with each entry in values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
if weights is None:
unique, weights = npi.count((self.index.sorted_group_rank_per_key, values))
else:
unique, weights = npi.group_by((self.index.sorted_group_rank_per_key, values)).sum(weights)
x, bin = npi.group_by(unique[0]).argmax(weights)
return x, unique[1][bin] | [
"def",
"mode",
"(",
"self",
",",
"values",
",",
"weights",
"=",
"None",
")",
":",
"if",
"weights",
"is",
"None",
":",
"unique",
",",
"weights",
"=",
"npi",
".",
"count",
"(",
"(",
"self",
".",
"index",
".",
"sorted_group_rank_per_key",
",",
"values",
... | compute the mode within each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the mode of per group
weights : array_like, [keys], float, optional
optional weight associated with each entry in values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"compute",
"the",
"mode",
"within",
"each",
"group",
"."
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L384-L407 | train | 53,949 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.min | def min(self, values, axis=0):
"""return the minimum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take minimum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, np.minimum, axis) | python | def min(self, values, axis=0):
"""return the minimum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take minimum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, np.minimum, axis) | [
"def",
"min",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"return",
"self",
".",
"unique",
",",
"self",
".",
"reduce",
"(",
"values",
",",
"np",
".",
"minimum",
",",
"axis"... | return the minimum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take minimum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"return",
"the",
"minimum",
"within",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L409-L427 | train | 53,950 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.max | def max(self, values, axis=0):
"""return the maximum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take maximum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, np.maximum, axis) | python | def max(self, values, axis=0):
"""return the maximum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take maximum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, np.maximum, axis) | [
"def",
"max",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"return",
"self",
".",
"unique",
",",
"self",
".",
"reduce",
"(",
"values",
",",
"np",
".",
"maximum",
",",
"axis"... | return the maximum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take maximum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"return",
"the",
"maximum",
"within",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L429-L447 | train | 53,951 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.first | def first(self, values, axis=0):
"""return values at first occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the first value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, np.take(values, self.index.sorter[self.index.start], axis) | python | def first(self, values, axis=0):
"""return values at first occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the first value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, np.take(values, self.index.sorter[self.index.start], axis) | [
"def",
"first",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"return",
"self",
".",
"unique",
",",
"np",
".",
"take",
"(",
"values",
",",
"self",
".",
"index",
".",
"sorter"... | return values at first occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the first value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"return",
"values",
"at",
"first",
"occurance",
"of",
"its",
"associated",
"key"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L449-L467 | train | 53,952 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.last | def last(self, values, axis=0):
"""return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, np.take(values, self.index.sorter[self.index.stop-1], axis) | python | def last(self, values, axis=0):
"""return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, np.take(values, self.index.sorter[self.index.stop-1], axis) | [
"def",
"last",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"return",
"self",
".",
"unique",
",",
"np",
".",
"take",
"(",
"values",
",",
"self",
".",
"index",
".",
"sorter",... | return values at last occurance of its associated key
Parameters
----------
values : array_like, [keys, ...]
values to pick the last value of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups | [
"return",
"values",
"at",
"last",
"occurance",
"of",
"its",
"associated",
"key"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L469-L487 | train | 53,953 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.any | def any(self, values, axis=0):
"""compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...], np.bool
value array, reduced over groups
"""
values = np.asarray(values)
if not values.dtype == np.bool:
values = values != 0
return self.unique, self.reduce(values, axis=axis) > 0 | python | def any(self, values, axis=0):
"""compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...], np.bool
value array, reduced over groups
"""
values = np.asarray(values)
if not values.dtype == np.bool:
values = values != 0
return self.unique, self.reduce(values, axis=axis) > 0 | [
"def",
"any",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"if",
"not",
"values",
".",
"dtype",
"==",
"np",
".",
"bool",
":",
"values",
"=",
"values",
"!=",
"0",
"return",
... | compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...], np.bool
value array, reduced over groups | [
"compute",
"if",
"any",
"item",
"evaluates",
"to",
"true",
"in",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L489-L509 | train | 53,954 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.all | def all(self, values, axis=0):
"""compute if all items evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...], np.bool
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, operator=np.multiply) != 0 | python | def all(self, values, axis=0):
"""compute if all items evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...], np.bool
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, axis=axis, operator=np.multiply) != 0 | [
"def",
"all",
"(",
"self",
",",
"values",
",",
"axis",
"=",
"0",
")",
":",
"values",
"=",
"np",
".",
"asarray",
"(",
"values",
")",
"return",
"self",
".",
"unique",
",",
"self",
".",
"reduce",
"(",
"values",
",",
"axis",
"=",
"axis",
",",
"operat... | compute if all items evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...], np.bool
value array, reduced over groups | [
"compute",
"if",
"all",
"items",
"evaluates",
"to",
"true",
"in",
"each",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L511-L529 | train | 53,955 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.argmin | def argmin(self, values):
"""return the index into values corresponding to the minimum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmin of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmin : ndarray, [groups]
index into value array, representing the argmin per group
"""
keys, minima = self.min(values)
minima = minima[self.inverse]
# select the first occurence of the minimum in each group
index = as_index((self.inverse, values == minima))
return keys, index.sorter[index.start[-self.groups:]] | python | def argmin(self, values):
"""return the index into values corresponding to the minimum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmin of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmin : ndarray, [groups]
index into value array, representing the argmin per group
"""
keys, minima = self.min(values)
minima = minima[self.inverse]
# select the first occurence of the minimum in each group
index = as_index((self.inverse, values == minima))
return keys, index.sorter[index.start[-self.groups:]] | [
"def",
"argmin",
"(",
"self",
",",
"values",
")",
":",
"keys",
",",
"minima",
"=",
"self",
".",
"min",
"(",
"values",
")",
"minima",
"=",
"minima",
"[",
"self",
".",
"inverse",
"]",
"# select the first occurence of the minimum in each group",
"index",
"=",
"... | return the index into values corresponding to the minimum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmin of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmin : ndarray, [groups]
index into value array, representing the argmin per group | [
"return",
"the",
"index",
"into",
"values",
"corresponding",
"to",
"the",
"minimum",
"value",
"of",
"the",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L531-L550 | train | 53,956 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/grouping.py | GroupBy.argmax | def argmax(self, values):
"""return the index into values corresponding to the maximum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmax of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmax : ndarray, [groups]
index into value array, representing the argmax per group
"""
keys, maxima = self.max(values)
maxima = maxima[self.inverse]
# select the first occurence of the maximum in each group
index = as_index((self.inverse, values == maxima))
return keys, index.sorter[index.start[-self.groups:]] | python | def argmax(self, values):
"""return the index into values corresponding to the maximum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmax of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmax : ndarray, [groups]
index into value array, representing the argmax per group
"""
keys, maxima = self.max(values)
maxima = maxima[self.inverse]
# select the first occurence of the maximum in each group
index = as_index((self.inverse, values == maxima))
return keys, index.sorter[index.start[-self.groups:]] | [
"def",
"argmax",
"(",
"self",
",",
"values",
")",
":",
"keys",
",",
"maxima",
"=",
"self",
".",
"max",
"(",
"values",
")",
"maxima",
"=",
"maxima",
"[",
"self",
".",
"inverse",
"]",
"# select the first occurence of the maximum in each group",
"index",
"=",
"... | return the index into values corresponding to the maximum value of the group
Parameters
----------
values : array_like, [keys]
values to pick the argmax of per group
Returns
-------
unique: ndarray, [groups]
unique keys
argmax : ndarray, [groups]
index into value array, representing the argmax per group | [
"return",
"the",
"index",
"into",
"values",
"corresponding",
"to",
"the",
"maximum",
"value",
"of",
"the",
"group"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L552-L571 | train | 53,957 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/index.py | as_index | def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False):
"""
casting rules for a keys object to an index object
the preferred semantics is that keys is a sequence of key objects,
except when keys is an instance of tuple,
in which case the zipped elements of the tuple are the key objects
the axis keyword specifies the axis which enumerates the keys
if axis is None, the keys array is flattened
if axis is 0, the first axis enumerates the keys
which of these two is the default depends on whether backwards_compatible == True
if base==True, the most basic index possible is constructed.
this avoids an indirect sort; if it isnt required, this has better performance
"""
if isinstance(keys, Index):
if type(keys) is BaseIndex and base==False:
keys = keys.keys #need to upcast to an indirectly sorted index type
else:
return keys #already done here
if isinstance(keys, tuple):
if lex_as_struct:
keys = as_struct_array(*keys)
else:
return LexIndex(keys, stable)
try:
keys = np.asarray(keys)
except:
raise TypeError('Given object does not form a valid set of keys')
if axis is None:
keys = keys.flatten()
if keys.ndim==1:
if base:
return BaseIndex(keys)
else:
return Index(keys, stable=stable)
else:
return ObjectIndex(keys, axis, stable=stable) | python | def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False):
"""
casting rules for a keys object to an index object
the preferred semantics is that keys is a sequence of key objects,
except when keys is an instance of tuple,
in which case the zipped elements of the tuple are the key objects
the axis keyword specifies the axis which enumerates the keys
if axis is None, the keys array is flattened
if axis is 0, the first axis enumerates the keys
which of these two is the default depends on whether backwards_compatible == True
if base==True, the most basic index possible is constructed.
this avoids an indirect sort; if it isnt required, this has better performance
"""
if isinstance(keys, Index):
if type(keys) is BaseIndex and base==False:
keys = keys.keys #need to upcast to an indirectly sorted index type
else:
return keys #already done here
if isinstance(keys, tuple):
if lex_as_struct:
keys = as_struct_array(*keys)
else:
return LexIndex(keys, stable)
try:
keys = np.asarray(keys)
except:
raise TypeError('Given object does not form a valid set of keys')
if axis is None:
keys = keys.flatten()
if keys.ndim==1:
if base:
return BaseIndex(keys)
else:
return Index(keys, stable=stable)
else:
return ObjectIndex(keys, axis, stable=stable) | [
"def",
"as_index",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
",",
"base",
"=",
"False",
",",
"stable",
"=",
"True",
",",
"lex_as_struct",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"keys",
",",
"Index",
")",
":",
"if",
"t... | casting rules for a keys object to an index object
the preferred semantics is that keys is a sequence of key objects,
except when keys is an instance of tuple,
in which case the zipped elements of the tuple are the key objects
the axis keyword specifies the axis which enumerates the keys
if axis is None, the keys array is flattened
if axis is 0, the first axis enumerates the keys
which of these two is the default depends on whether backwards_compatible == True
if base==True, the most basic index possible is constructed.
this avoids an indirect sort; if it isnt required, this has better performance | [
"casting",
"rules",
"for",
"a",
"keys",
"object",
"to",
"an",
"index",
"object"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/index.py#L288-L327 | train | 53,958 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/index.py | LexIndex.unique | def unique(self):
"""returns a tuple of unique key columns"""
return tuple(
(array_as_typed(s, k.dtype, k.shape) if k.ndim>1 else s)[self.start]
for s, k in zip(self.sorted, self._keys)) | python | def unique(self):
"""returns a tuple of unique key columns"""
return tuple(
(array_as_typed(s, k.dtype, k.shape) if k.ndim>1 else s)[self.start]
for s, k in zip(self.sorted, self._keys)) | [
"def",
"unique",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"(",
"array_as_typed",
"(",
"s",
",",
"k",
".",
"dtype",
",",
"k",
".",
"shape",
")",
"if",
"k",
".",
"ndim",
">",
"1",
"else",
"s",
")",
"[",
"self",
".",
"start",
"]",
"for",
"... | returns a tuple of unique key columns | [
"returns",
"a",
"tuple",
"of",
"unique",
"key",
"columns"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/index.py#L236-L240 | train | 53,959 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/utility.py | as_struct_array | def as_struct_array(*columns):
"""pack a sequence of columns into a recarray
Parameters
----------
columns : sequence of key objects
Returns
-------
data : recarray
recarray containing the input columns as struct fields
"""
columns = [np.asarray(c) for c in columns]
rows = len(columns[0])
names = ['f'+str(i) for i in range(len(columns))]
dtype = [(names[i], c.dtype, c.shape[1:]) for i, c in enumerate(columns)]
data = np.empty(rows, dtype)
for i, c in enumerate(columns):
data[names[i]] = c
return data | python | def as_struct_array(*columns):
"""pack a sequence of columns into a recarray
Parameters
----------
columns : sequence of key objects
Returns
-------
data : recarray
recarray containing the input columns as struct fields
"""
columns = [np.asarray(c) for c in columns]
rows = len(columns[0])
names = ['f'+str(i) for i in range(len(columns))]
dtype = [(names[i], c.dtype, c.shape[1:]) for i, c in enumerate(columns)]
data = np.empty(rows, dtype)
for i, c in enumerate(columns):
data[names[i]] = c
return data | [
"def",
"as_struct_array",
"(",
"*",
"columns",
")",
":",
"columns",
"=",
"[",
"np",
".",
"asarray",
"(",
"c",
")",
"for",
"c",
"in",
"columns",
"]",
"rows",
"=",
"len",
"(",
"columns",
"[",
"0",
"]",
")",
"names",
"=",
"[",
"'f'",
"+",
"str",
"... | pack a sequence of columns into a recarray
Parameters
----------
columns : sequence of key objects
Returns
-------
data : recarray
recarray containing the input columns as struct fields | [
"pack",
"a",
"sequence",
"of",
"columns",
"into",
"a",
"recarray"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/utility.py#L11-L31 | train | 53,960 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/utility.py | axis_as_object | def axis_as_object(arr, axis=-1):
"""cast the given axis of an array to a void object
if the axis to be cast is contiguous, a view is returned, otherwise a copy is made
this is useful for efficiently sorting by the content of an axis, for instance
Parameters
----------
arr : ndarray
array to view as void object type
axis : int
axis to view as a void object type
Returns
-------
ndarray
array with the given axis viewed as a void object
"""
shape = arr.shape
# make axis to be viewed as a void object as contiguous items
arr = np.ascontiguousarray(np.rollaxis(arr, axis, arr.ndim))
# number of bytes in each void object
nbytes = arr.dtype.itemsize * shape[axis]
# void type with the correct number of bytes
voidtype = np.dtype((np.void, nbytes))
# return the view as such, with the reduced shape
return arr.view(voidtype).reshape(np.delete(shape, axis)) | python | def axis_as_object(arr, axis=-1):
"""cast the given axis of an array to a void object
if the axis to be cast is contiguous, a view is returned, otherwise a copy is made
this is useful for efficiently sorting by the content of an axis, for instance
Parameters
----------
arr : ndarray
array to view as void object type
axis : int
axis to view as a void object type
Returns
-------
ndarray
array with the given axis viewed as a void object
"""
shape = arr.shape
# make axis to be viewed as a void object as contiguous items
arr = np.ascontiguousarray(np.rollaxis(arr, axis, arr.ndim))
# number of bytes in each void object
nbytes = arr.dtype.itemsize * shape[axis]
# void type with the correct number of bytes
voidtype = np.dtype((np.void, nbytes))
# return the view as such, with the reduced shape
return arr.view(voidtype).reshape(np.delete(shape, axis)) | [
"def",
"axis_as_object",
"(",
"arr",
",",
"axis",
"=",
"-",
"1",
")",
":",
"shape",
"=",
"arr",
".",
"shape",
"# make axis to be viewed as a void object as contiguous items",
"arr",
"=",
"np",
".",
"ascontiguousarray",
"(",
"np",
".",
"rollaxis",
"(",
"arr",
"... | cast the given axis of an array to a void object
if the axis to be cast is contiguous, a view is returned, otherwise a copy is made
this is useful for efficiently sorting by the content of an axis, for instance
Parameters
----------
arr : ndarray
array to view as void object type
axis : int
axis to view as a void object type
Returns
-------
ndarray
array with the given axis viewed as a void object | [
"cast",
"the",
"given",
"axis",
"of",
"an",
"array",
"to",
"a",
"void",
"object",
"if",
"the",
"axis",
"to",
"be",
"cast",
"is",
"contiguous",
"a",
"view",
"is",
"returned",
"otherwise",
"a",
"copy",
"is",
"made",
"this",
"is",
"useful",
"for",
"effici... | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/utility.py#L34-L59 | train | 53,961 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/utility.py | object_as_axis | def object_as_axis(arr, dtype, axis=-1):
"""
cast an array of void objects to a typed axis
Parameters
----------
arr : ndarray, [ndim], void
array of type np.void
dtype : numpy dtype object
the output dtype to cast the input array to
axis : int
position to insert the newly formed axis into
Returns
-------
ndarray, [ndim+1], dtype
output array cast to given dtype
"""
# view the void objects as typed elements
arr = arr.view(dtype).reshape(arr.shape + (-1,))
# put the axis in the specified location
return np.rollaxis(arr, -1, axis) | python | def object_as_axis(arr, dtype, axis=-1):
"""
cast an array of void objects to a typed axis
Parameters
----------
arr : ndarray, [ndim], void
array of type np.void
dtype : numpy dtype object
the output dtype to cast the input array to
axis : int
position to insert the newly formed axis into
Returns
-------
ndarray, [ndim+1], dtype
output array cast to given dtype
"""
# view the void objects as typed elements
arr = arr.view(dtype).reshape(arr.shape + (-1,))
# put the axis in the specified location
return np.rollaxis(arr, -1, axis) | [
"def",
"object_as_axis",
"(",
"arr",
",",
"dtype",
",",
"axis",
"=",
"-",
"1",
")",
":",
"# view the void objects as typed elements",
"arr",
"=",
"arr",
".",
"view",
"(",
"dtype",
")",
".",
"reshape",
"(",
"arr",
".",
"shape",
"+",
"(",
"-",
"1",
",",
... | cast an array of void objects to a typed axis
Parameters
----------
arr : ndarray, [ndim], void
array of type np.void
dtype : numpy dtype object
the output dtype to cast the input array to
axis : int
position to insert the newly formed axis into
Returns
-------
ndarray, [ndim+1], dtype
output array cast to given dtype | [
"cast",
"an",
"array",
"of",
"void",
"objects",
"to",
"a",
"typed",
"axis"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/utility.py#L62-L83 | train | 53,962 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | binning | def binning(keys, start, end, count, axes=None):
"""Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10)
"""
if isinstance(keys, tuple):
n_keys = len(keys)
else:
n_keys = 1
bins = np.linspace(start, end, count+1, endpoint=True)
idx = np.searchsorted(bins, keys)
if axes is None:
axes = [-1] | python | def binning(keys, start, end, count, axes=None):
"""Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10)
"""
if isinstance(keys, tuple):
n_keys = len(keys)
else:
n_keys = 1
bins = np.linspace(start, end, count+1, endpoint=True)
idx = np.searchsorted(bins, keys)
if axes is None:
axes = [-1] | [
"def",
"binning",
"(",
"keys",
",",
"start",
",",
"end",
",",
"count",
",",
"axes",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"keys",
",",
"tuple",
")",
":",
"n_keys",
"=",
"len",
"(",
"keys",
")",
"else",
":",
"n_keys",
"=",
"1",
"bins",
... | Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10) | [
"Perform",
"binning",
"over",
"the",
"given",
"axes",
"of",
"the",
"keys"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L73-L92 | train | 53,963 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | multiplicity | def multiplicity(keys, axis=semantics.axis_default):
"""return the multiplicity of each key, or how often it occurs in the set
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
the number of times each input item occurs in the set
"""
index = as_index(keys, axis)
return index.count[index.inverse] | python | def multiplicity(keys, axis=semantics.axis_default):
"""return the multiplicity of each key, or how often it occurs in the set
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
the number of times each input item occurs in the set
"""
index = as_index(keys, axis)
return index.count[index.inverse] | [
"def",
"multiplicity",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"index",
".",
"count",
"[",
"index",
".",
"inverse",
"]"
] | return the multiplicity of each key, or how often it occurs in the set
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
the number of times each input item occurs in the set | [
"return",
"the",
"multiplicity",
"of",
"each",
"key",
"or",
"how",
"often",
"it",
"occurs",
"in",
"the",
"set"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L183-L196 | train | 53,964 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | rank | def rank(keys, axis=semantics.axis_default):
"""where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys
"""
index = as_index(keys, axis)
return index.rank | python | def rank(keys, axis=semantics.axis_default):
"""where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys
"""
index = as_index(keys, axis)
return index.rank | [
"def",
"rank",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"index",
".",
"rank"
] | where each item is in the pecking order.
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
unique integers, ranking the sorting order
Notes
-----
we should have that index.sorted[index.rank] == keys | [
"where",
"each",
"item",
"is",
"in",
"the",
"pecking",
"order",
"."
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L199-L216 | train | 53,965 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | mode | def mode(keys, axis=semantics.axis_default, weights=None, return_indices=False):
"""compute the mode, or most frequent occuring key in a set
Parameters
----------
keys : ndarray, [n_keys, ...]
input array. elements of 'keys' can have arbitrary shape or dtype
weights : ndarray, [n_keys], optional
if given, the contribution of each key to the mode is weighted by the given weights
return_indices : bool
if True, return all indices such that keys[indices]==mode holds
Returns
-------
mode : ndarray, [...]
the most frequently occuring key in the key sequence
indices : ndarray, [mode_multiplicity], int, optional
if return_indices is True, all indices such that points[indices]==mode holds
"""
index = as_index(keys, axis)
if weights is None:
unique, weights = count(index)
else:
unique, weights = group_by(index).sum(weights)
bin = np.argmax(weights)
_mode = unique[bin] # FIXME: replace with index.take for lexindex compatibility?
if return_indices:
indices = index.sorter[index.start[bin]: index.stop[bin]]
return _mode, indices
else:
return _mode | python | def mode(keys, axis=semantics.axis_default, weights=None, return_indices=False):
"""compute the mode, or most frequent occuring key in a set
Parameters
----------
keys : ndarray, [n_keys, ...]
input array. elements of 'keys' can have arbitrary shape or dtype
weights : ndarray, [n_keys], optional
if given, the contribution of each key to the mode is weighted by the given weights
return_indices : bool
if True, return all indices such that keys[indices]==mode holds
Returns
-------
mode : ndarray, [...]
the most frequently occuring key in the key sequence
indices : ndarray, [mode_multiplicity], int, optional
if return_indices is True, all indices such that points[indices]==mode holds
"""
index = as_index(keys, axis)
if weights is None:
unique, weights = count(index)
else:
unique, weights = group_by(index).sum(weights)
bin = np.argmax(weights)
_mode = unique[bin] # FIXME: replace with index.take for lexindex compatibility?
if return_indices:
indices = index.sorter[index.start[bin]: index.stop[bin]]
return _mode, indices
else:
return _mode | [
"def",
"mode",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
",",
"weights",
"=",
"None",
",",
"return_indices",
"=",
"False",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"if",
"weights",
"is",
"None",
":",
"... | compute the mode, or most frequent occuring key in a set
Parameters
----------
keys : ndarray, [n_keys, ...]
input array. elements of 'keys' can have arbitrary shape or dtype
weights : ndarray, [n_keys], optional
if given, the contribution of each key to the mode is weighted by the given weights
return_indices : bool
if True, return all indices such that keys[indices]==mode holds
Returns
-------
mode : ndarray, [...]
the most frequently occuring key in the key sequence
indices : ndarray, [mode_multiplicity], int, optional
if return_indices is True, all indices such that points[indices]==mode holds | [
"compute",
"the",
"mode",
"or",
"most",
"frequent",
"occuring",
"key",
"in",
"a",
"set"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L219-L249 | train | 53,966 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | incidence | def incidence(boundary):
"""
given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib
"""
return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1]) | python | def incidence(boundary):
"""
given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib
"""
return GroupBy(boundary).split(np.arange(boundary.size) // boundary.shape[1]) | [
"def",
"incidence",
"(",
"boundary",
")",
":",
"return",
"GroupBy",
"(",
"boundary",
")",
".",
"split",
"(",
"np",
".",
"arange",
"(",
"boundary",
".",
"size",
")",
"//",
"boundary",
".",
"shape",
"[",
"1",
"]",
")"
] | given an Nxm matrix containing boundary info between simplices,
compute indidence info matrix
not very reusable; should probably not be in this lib | [
"given",
"an",
"Nxm",
"matrix",
"containing",
"boundary",
"info",
"between",
"simplices",
"compute",
"indidence",
"info",
"matrix",
"not",
"very",
"reusable",
";",
"should",
"probably",
"not",
"be",
"in",
"this",
"lib"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L267-L273 | train | 53,967 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | all_unique | def all_unique(keys, axis=semantics.axis_default):
"""Returns true if all keys are unique"""
index = as_index(keys, axis)
return index.groups == index.size | python | def all_unique(keys, axis=semantics.axis_default):
"""Returns true if all keys are unique"""
index = as_index(keys, axis)
return index.groups == index.size | [
"def",
"all_unique",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"index",
".",
"groups",
"==",
"index",
".",
"size"
] | Returns true if all keys are unique | [
"Returns",
"true",
"if",
"all",
"keys",
"are",
"unique"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L276-L279 | train | 53,968 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | any_unique | def any_unique(keys, axis=semantics.axis_default):
"""returns true if any of the keys is unique"""
index = as_index(keys, axis)
return np.any(index.count == 1) | python | def any_unique(keys, axis=semantics.axis_default):
"""returns true if any of the keys is unique"""
index = as_index(keys, axis)
return np.any(index.count == 1) | [
"def",
"any_unique",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"np",
".",
"any",
"(",
"index",
".",
"count",
"==",
"1",
")"
] | returns true if any of the keys is unique | [
"returns",
"true",
"if",
"any",
"of",
"the",
"keys",
"is",
"unique"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L282-L285 | train | 53,969 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | all_equal | def all_equal(keys, axis=semantics.axis_default):
"""returns true of all keys are equal"""
index = as_index(keys, axis)
return index.groups == 1 | python | def all_equal(keys, axis=semantics.axis_default):
"""returns true of all keys are equal"""
index = as_index(keys, axis)
return index.groups == 1 | [
"def",
"all_equal",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"index",
".",
"groups",
"==",
"1"
] | returns true of all keys are equal | [
"returns",
"true",
"of",
"all",
"keys",
"are",
"equal"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L293-L296 | train | 53,970 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | is_uniform | def is_uniform(keys, axis=semantics.axis_default):
"""returns true if all keys have equal multiplicity"""
index = as_index(keys, axis)
return index.uniform | python | def is_uniform(keys, axis=semantics.axis_default):
"""returns true if all keys have equal multiplicity"""
index = as_index(keys, axis)
return index.uniform | [
"def",
"is_uniform",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"index",
"=",
"as_index",
"(",
"keys",
",",
"axis",
")",
"return",
"index",
".",
"uniform"
] | returns true if all keys have equal multiplicity | [
"returns",
"true",
"if",
"all",
"keys",
"have",
"equal",
"multiplicity"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L299-L302 | train | 53,971 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/funcs.py | Table.unique | def unique(self, values):
"""Place each entry in a table, while asserting that each entry occurs once"""
_, count = self.count()
if not np.array_equiv(count, 1):
raise ValueError("Not every entry in the table is assigned a unique value")
return self.sum(values) | python | def unique(self, values):
"""Place each entry in a table, while asserting that each entry occurs once"""
_, count = self.count()
if not np.array_equiv(count, 1):
raise ValueError("Not every entry in the table is assigned a unique value")
return self.sum(values) | [
"def",
"unique",
"(",
"self",
",",
"values",
")",
":",
"_",
",",
"count",
"=",
"self",
".",
"count",
"(",
")",
"if",
"not",
"np",
".",
"array_equiv",
"(",
"count",
",",
"1",
")",
":",
"raise",
"ValueError",
"(",
"\"Not every entry in the table is assigne... | Place each entry in a table, while asserting that each entry occurs once | [
"Place",
"each",
"entry",
"in",
"a",
"table",
"while",
"asserting",
"that",
"each",
"entry",
"occurs",
"once"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/funcs.py#L175-L180 | train | 53,972 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | unique | def unique(keys, axis=semantics.axis_default, return_index=False, return_inverse=False, return_count=False):
"""compute the set of unique keys
Parameters
----------
keys : indexable key object
keys object to find unique keys within
axis : int
if keys is a multi-dimensional array, the axis to regard as the sequence of key objects
return_index : bool
if True, return indexes such that keys[index] == unique
return_inverse : bool
if True, return the indices such that unique[inverse] == keys
return_count : bool
if True, return the number of times each unique key occurs in the input
Notes
-----
The kwargs are there to provide a backwards compatible interface to numpy.unique, but arguably,
it is cleaner to call index and its properties directly, should more than unique values be desired as output
"""
stable = return_index or return_inverse
index = as_index(keys, axis, base = not stable, stable = stable)
ret = index.unique,
if return_index:
ret = ret + (index.index,)
if return_inverse:
ret = ret + (index.inverse,)
if return_count:
ret = ret + (index.count,)
return ret[0] if len(ret) == 1 else ret | python | def unique(keys, axis=semantics.axis_default, return_index=False, return_inverse=False, return_count=False):
"""compute the set of unique keys
Parameters
----------
keys : indexable key object
keys object to find unique keys within
axis : int
if keys is a multi-dimensional array, the axis to regard as the sequence of key objects
return_index : bool
if True, return indexes such that keys[index] == unique
return_inverse : bool
if True, return the indices such that unique[inverse] == keys
return_count : bool
if True, return the number of times each unique key occurs in the input
Notes
-----
The kwargs are there to provide a backwards compatible interface to numpy.unique, but arguably,
it is cleaner to call index and its properties directly, should more than unique values be desired as output
"""
stable = return_index or return_inverse
index = as_index(keys, axis, base = not stable, stable = stable)
ret = index.unique,
if return_index:
ret = ret + (index.index,)
if return_inverse:
ret = ret + (index.inverse,)
if return_count:
ret = ret + (index.count,)
return ret[0] if len(ret) == 1 else ret | [
"def",
"unique",
"(",
"keys",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
",",
"return_index",
"=",
"False",
",",
"return_inverse",
"=",
"False",
",",
"return_count",
"=",
"False",
")",
":",
"stable",
"=",
"return_index",
"or",
"return_inverse",
"ind... | compute the set of unique keys
Parameters
----------
keys : indexable key object
keys object to find unique keys within
axis : int
if keys is a multi-dimensional array, the axis to regard as the sequence of key objects
return_index : bool
if True, return indexes such that keys[index] == unique
return_inverse : bool
if True, return the indices such that unique[inverse] == keys
return_count : bool
if True, return the number of times each unique key occurs in the input
Notes
-----
The kwargs are there to provide a backwards compatible interface to numpy.unique, but arguably,
it is cleaner to call index and its properties directly, should more than unique values be desired as output | [
"compute",
"the",
"set",
"of",
"unique",
"keys"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L19-L50 | train | 53,973 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | contains | def contains(this, that, axis=semantics.axis_default):
"""Returns bool for each element of `that`, indicating if it is contained in `this`
Parameters
----------
this : indexable key sequence
sequence of items to test against
that : indexable key sequence
sequence of items to test for
Returns
-------
ndarray, [that.size], bool
returns a bool for each element in `that`, indicating if it is contained in `this`
Notes
-----
Reads as 'this contains that'
Similar to 'that in this', but with different performance characteristics
"""
this = as_index(this, axis=axis, lex_as_struct=True, base=True)
that = as_index(that, axis=axis, lex_as_struct=True)
left = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='left')
right = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='right')
flags = np.zeros(that.size + 1, dtype=np.int)
np.add.at(flags, left, 1)
np.add.at(flags, right, -1)
return np.cumsum(flags)[:-1].astype(np.bool)[that.rank] | python | def contains(this, that, axis=semantics.axis_default):
"""Returns bool for each element of `that`, indicating if it is contained in `this`
Parameters
----------
this : indexable key sequence
sequence of items to test against
that : indexable key sequence
sequence of items to test for
Returns
-------
ndarray, [that.size], bool
returns a bool for each element in `that`, indicating if it is contained in `this`
Notes
-----
Reads as 'this contains that'
Similar to 'that in this', but with different performance characteristics
"""
this = as_index(this, axis=axis, lex_as_struct=True, base=True)
that = as_index(that, axis=axis, lex_as_struct=True)
left = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='left')
right = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='right')
flags = np.zeros(that.size + 1, dtype=np.int)
np.add.at(flags, left, 1)
np.add.at(flags, right, -1)
return np.cumsum(flags)[:-1].astype(np.bool)[that.rank] | [
"def",
"contains",
"(",
"this",
",",
"that",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"this",
"=",
"as_index",
"(",
"this",
",",
"axis",
"=",
"axis",
",",
"lex_as_struct",
"=",
"True",
",",
"base",
"=",
"True",
")",
"that",
"=",
... | Returns bool for each element of `that`, indicating if it is contained in `this`
Parameters
----------
this : indexable key sequence
sequence of items to test against
that : indexable key sequence
sequence of items to test for
Returns
-------
ndarray, [that.size], bool
returns a bool for each element in `that`, indicating if it is contained in `this`
Notes
-----
Reads as 'this contains that'
Similar to 'that in this', but with different performance characteristics | [
"Returns",
"bool",
"for",
"each",
"element",
"of",
"that",
"indicating",
"if",
"it",
"is",
"contained",
"in",
"this"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L53-L83 | train | 53,974 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | in_ | def in_(this, that, axis=semantics.axis_default):
"""Returns bool for each element of `this`, indicating if it is present in `that`
Parameters
----------
this : indexable key sequence
sequence of items to test for
that : indexable key sequence
sequence of items to test against
Returns
-------
ndarray, [that.size], bool
returns a bool for each element in `this`, indicating if it is present in `that`
Notes
-----
Reads as 'this in that'
Similar to 'that contains this', but with different performance characteristics
"""
this = as_index(this, axis=axis, lex_as_struct=True, base=True)
that = as_index(that, axis=axis, lex_as_struct=True)
left = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='left')
right = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='right')
return left != right | python | def in_(this, that, axis=semantics.axis_default):
"""Returns bool for each element of `this`, indicating if it is present in `that`
Parameters
----------
this : indexable key sequence
sequence of items to test for
that : indexable key sequence
sequence of items to test against
Returns
-------
ndarray, [that.size], bool
returns a bool for each element in `this`, indicating if it is present in `that`
Notes
-----
Reads as 'this in that'
Similar to 'that contains this', but with different performance characteristics
"""
this = as_index(this, axis=axis, lex_as_struct=True, base=True)
that = as_index(that, axis=axis, lex_as_struct=True)
left = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='left')
right = np.searchsorted(that._keys, this._keys, sorter=that.sorter, side='right')
return left != right | [
"def",
"in_",
"(",
"this",
",",
"that",
",",
"axis",
"=",
"semantics",
".",
"axis_default",
")",
":",
"this",
"=",
"as_index",
"(",
"this",
",",
"axis",
"=",
"axis",
",",
"lex_as_struct",
"=",
"True",
",",
"base",
"=",
"True",
")",
"that",
"=",
"as... | Returns bool for each element of `this`, indicating if it is present in `that`
Parameters
----------
this : indexable key sequence
sequence of items to test for
that : indexable key sequence
sequence of items to test against
Returns
-------
ndarray, [that.size], bool
returns a bool for each element in `this`, indicating if it is present in `that`
Notes
-----
Reads as 'this in that'
Similar to 'that contains this', but with different performance characteristics | [
"Returns",
"bool",
"for",
"each",
"element",
"of",
"this",
"indicating",
"if",
"it",
"is",
"present",
"in",
"that"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L86-L112 | train | 53,975 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | _set_preprocess | def _set_preprocess(sets, **kwargs):
"""upcasts a sequence of indexable objects to Index objets according to the given kwargs
Parameters
----------
sets : iterable of indexable objects
axis : int, optional
axis to view as item sequence
assume_unique : bool, optional
if we should assume the items sequence does not contain duplicates
Returns
-------
list of Index objects
Notes
-----
common preprocessing for all set operations
"""
axis = kwargs.get('axis', semantics.axis_default)
assume_unique = kwargs.get('assume_unique', False)
if assume_unique:
sets = [as_index(s, axis=axis).unique for s in sets]
else:
sets = [as_index(s, axis=axis).unique for s in sets]
return sets | python | def _set_preprocess(sets, **kwargs):
"""upcasts a sequence of indexable objects to Index objets according to the given kwargs
Parameters
----------
sets : iterable of indexable objects
axis : int, optional
axis to view as item sequence
assume_unique : bool, optional
if we should assume the items sequence does not contain duplicates
Returns
-------
list of Index objects
Notes
-----
common preprocessing for all set operations
"""
axis = kwargs.get('axis', semantics.axis_default)
assume_unique = kwargs.get('assume_unique', False)
if assume_unique:
sets = [as_index(s, axis=axis).unique for s in sets]
else:
sets = [as_index(s, axis=axis).unique for s in sets]
return sets | [
"def",
"_set_preprocess",
"(",
"sets",
",",
"*",
"*",
"kwargs",
")",
":",
"axis",
"=",
"kwargs",
".",
"get",
"(",
"'axis'",
",",
"semantics",
".",
"axis_default",
")",
"assume_unique",
"=",
"kwargs",
".",
"get",
"(",
"'assume_unique'",
",",
"False",
")",... | upcasts a sequence of indexable objects to Index objets according to the given kwargs
Parameters
----------
sets : iterable of indexable objects
axis : int, optional
axis to view as item sequence
assume_unique : bool, optional
if we should assume the items sequence does not contain duplicates
Returns
-------
list of Index objects
Notes
-----
common preprocessing for all set operations | [
"upcasts",
"a",
"sequence",
"of",
"indexable",
"objects",
"to",
"Index",
"objets",
"according",
"to",
"the",
"given",
"kwargs"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L208-L234 | train | 53,976 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | _set_concatenate | def _set_concatenate(sets):
"""concatenate indexable objects.
Parameters
----------
sets : iterable of indexable objects
Returns
-------
indexable object
handles both arrays and tuples of arrays
"""
def con(set):
# if not all():
# raise ValueError('concatenated keys must have the same dtype')
try:
return np.concatenate([s for s in sets if len(s)])
except ValueError:
return set[0]
if any(not isinstance(s, tuple) for s in sets):
#assume all arrays
return con(sets)
else:
#assume all tuples
return tuple(con(s) for s in zip(*sets)) | python | def _set_concatenate(sets):
"""concatenate indexable objects.
Parameters
----------
sets : iterable of indexable objects
Returns
-------
indexable object
handles both arrays and tuples of arrays
"""
def con(set):
# if not all():
# raise ValueError('concatenated keys must have the same dtype')
try:
return np.concatenate([s for s in sets if len(s)])
except ValueError:
return set[0]
if any(not isinstance(s, tuple) for s in sets):
#assume all arrays
return con(sets)
else:
#assume all tuples
return tuple(con(s) for s in zip(*sets)) | [
"def",
"_set_concatenate",
"(",
"sets",
")",
":",
"def",
"con",
"(",
"set",
")",
":",
"# if not all():",
"# raise ValueError('concatenated keys must have the same dtype')",
"try",
":",
"return",
"np",
".",
"concatenate",
"(",
"[",
"s",
"for",
"s",
"in",
"sets"... | concatenate indexable objects.
Parameters
----------
sets : iterable of indexable objects
Returns
-------
indexable object
handles both arrays and tuples of arrays | [
"concatenate",
"indexable",
"objects",
"."
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L237-L263 | train | 53,977 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | _set_count | def _set_count(sets, n, **kwargs):
"""return the elements which occur n times over the sequence of sets
Parameters
----------
sets : iterable of indexable objects
n : int
number of sets the element should occur in
Returns
-------
indexable
indexable with all elements that occured in n of the sets
Notes
-----
used by both exclusive and intersection
"""
sets = _set_preprocess(sets, **kwargs)
i = as_index(_set_concatenate(sets), axis=0, base=True)
# FIXME : this does not work for lex-keys
return i.unique[i.count == n] | python | def _set_count(sets, n, **kwargs):
"""return the elements which occur n times over the sequence of sets
Parameters
----------
sets : iterable of indexable objects
n : int
number of sets the element should occur in
Returns
-------
indexable
indexable with all elements that occured in n of the sets
Notes
-----
used by both exclusive and intersection
"""
sets = _set_preprocess(sets, **kwargs)
i = as_index(_set_concatenate(sets), axis=0, base=True)
# FIXME : this does not work for lex-keys
return i.unique[i.count == n] | [
"def",
"_set_count",
"(",
"sets",
",",
"n",
",",
"*",
"*",
"kwargs",
")",
":",
"sets",
"=",
"_set_preprocess",
"(",
"sets",
",",
"*",
"*",
"kwargs",
")",
"i",
"=",
"as_index",
"(",
"_set_concatenate",
"(",
"sets",
")",
",",
"axis",
"=",
"0",
",",
... | return the elements which occur n times over the sequence of sets
Parameters
----------
sets : iterable of indexable objects
n : int
number of sets the element should occur in
Returns
-------
indexable
indexable with all elements that occured in n of the sets
Notes
-----
used by both exclusive and intersection | [
"return",
"the",
"elements",
"which",
"occur",
"n",
"times",
"over",
"the",
"sequence",
"of",
"sets"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L266-L287 | train | 53,978 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | union | def union(*sets, **kwargs):
"""all unique items which occur in any one of the sets
Parameters
----------
sets : tuple of indexable objects
Returns
-------
union of all items in all sets
"""
sets = _set_preprocess(sets, **kwargs)
return as_index( _set_concatenate(sets), axis=0, base=True).unique | python | def union(*sets, **kwargs):
"""all unique items which occur in any one of the sets
Parameters
----------
sets : tuple of indexable objects
Returns
-------
union of all items in all sets
"""
sets = _set_preprocess(sets, **kwargs)
return as_index( _set_concatenate(sets), axis=0, base=True).unique | [
"def",
"union",
"(",
"*",
"sets",
",",
"*",
"*",
"kwargs",
")",
":",
"sets",
"=",
"_set_preprocess",
"(",
"sets",
",",
"*",
"*",
"kwargs",
")",
"return",
"as_index",
"(",
"_set_concatenate",
"(",
"sets",
")",
",",
"axis",
"=",
"0",
",",
"base",
"="... | all unique items which occur in any one of the sets
Parameters
----------
sets : tuple of indexable objects
Returns
-------
union of all items in all sets | [
"all",
"unique",
"items",
"which",
"occur",
"in",
"any",
"one",
"of",
"the",
"sets"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L290-L302 | train | 53,979 |
EelcoHoogendoorn/Numpy_arraysetops_EP | numpy_indexed/arraysetops.py | difference | def difference(*sets, **kwargs):
"""subtracts all tail sets from the head set
Parameters
----------
sets : tuple of indexable objects
first set is the head, from which we subtract
other items form the tail, which are subtracted from head
Returns
-------
items which are in the head but not in any of the tail sets
Notes
-----
alt implementation: compute union of tail, then union with head, then use set_count(1)
"""
head, tail = sets[0], sets[1:]
idx = as_index(head, **kwargs)
lhs = idx.unique
rhs = [intersection(idx, s, **kwargs) for s in tail]
return exclusive(lhs, *rhs, axis=0, assume_unique=True) | python | def difference(*sets, **kwargs):
"""subtracts all tail sets from the head set
Parameters
----------
sets : tuple of indexable objects
first set is the head, from which we subtract
other items form the tail, which are subtracted from head
Returns
-------
items which are in the head but not in any of the tail sets
Notes
-----
alt implementation: compute union of tail, then union with head, then use set_count(1)
"""
head, tail = sets[0], sets[1:]
idx = as_index(head, **kwargs)
lhs = idx.unique
rhs = [intersection(idx, s, **kwargs) for s in tail]
return exclusive(lhs, *rhs, axis=0, assume_unique=True) | [
"def",
"difference",
"(",
"*",
"sets",
",",
"*",
"*",
"kwargs",
")",
":",
"head",
",",
"tail",
"=",
"sets",
"[",
"0",
"]",
",",
"sets",
"[",
"1",
":",
"]",
"idx",
"=",
"as_index",
"(",
"head",
",",
"*",
"*",
"kwargs",
")",
"lhs",
"=",
"idx",
... | subtracts all tail sets from the head set
Parameters
----------
sets : tuple of indexable objects
first set is the head, from which we subtract
other items form the tail, which are subtracted from head
Returns
-------
items which are in the head but not in any of the tail sets
Notes
-----
alt implementation: compute union of tail, then union with head, then use set_count(1) | [
"subtracts",
"all",
"tail",
"sets",
"from",
"the",
"head",
"set"
] | 84dc8114bf8a79c3acb3f7f59128247b9fc97243 | https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/arraysetops.py#L339-L360 | train | 53,980 |
gtnx/pandas-highcharts | pandas_highcharts/display.py | _generate_div_id_chart | def _generate_div_id_chart(prefix="chart_id", digits=8):
"""Generate a random id for div chart.
"""
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) | python | def _generate_div_id_chart(prefix="chart_id", digits=8):
"""Generate a random id for div chart.
"""
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) | [
"def",
"_generate_div_id_chart",
"(",
"prefix",
"=",
"\"chart_id\"",
",",
"digits",
"=",
"8",
")",
":",
"choices",
"=",
"(",
"random",
".",
"randrange",
"(",
"0",
",",
"52",
")",
"for",
"_",
"in",
"range",
"(",
"digits",
")",
")",
"return",
"prefix",
... | Generate a random id for div chart. | [
"Generate",
"a",
"random",
"id",
"for",
"div",
"chart",
"."
] | bf449b7db8b6966bcf95a0280bf2e4518f3e2419 | https://github.com/gtnx/pandas-highcharts/blob/bf449b7db8b6966bcf95a0280bf2e4518f3e2419/pandas_highcharts/display.py#L36-L40 | train | 53,981 |
Skyscanner/skyscanner-python-sdk | skyscanner/skyscanner.py | Transport.get_additional_params | def get_additional_params(self, **params):
"""
Filter to get the additional params needed for polling
"""
# TODO: Move these params to their own vertical if needed.
polling_params = [
'locationschema',
'carrierschema',
'sorttype',
'sortorder',
'originairports',
'destinationairports',
'stops',
'outbounddeparttime',
'outbounddepartstarttime',
'outbounddepartendtime',
'inbounddeparttime',
'inbounddepartstarttime',
'inbounddepartendtime',
'duration',
'includecarriers',
'excludecarriers'
]
additional_params = dict(
(key, value) for key, value in params.items()
if key in polling_params
)
return additional_params | python | def get_additional_params(self, **params):
"""
Filter to get the additional params needed for polling
"""
# TODO: Move these params to their own vertical if needed.
polling_params = [
'locationschema',
'carrierschema',
'sorttype',
'sortorder',
'originairports',
'destinationairports',
'stops',
'outbounddeparttime',
'outbounddepartstarttime',
'outbounddepartendtime',
'inbounddeparttime',
'inbounddepartstarttime',
'inbounddepartendtime',
'duration',
'includecarriers',
'excludecarriers'
]
additional_params = dict(
(key, value) for key, value in params.items()
if key in polling_params
)
return additional_params | [
"def",
"get_additional_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"# TODO: Move these params to their own vertical if needed.",
"polling_params",
"=",
"[",
"'locationschema'",
",",
"'carrierschema'",
",",
"'sorttype'",
",",
"'sortorder'",
",",
"'originairpor... | Filter to get the additional params needed for polling | [
"Filter",
"to",
"get",
"the",
"additional",
"params",
"needed",
"for",
"polling"
] | 26ce4a563f538a689f2a29063f3604731703ddac | https://github.com/Skyscanner/skyscanner-python-sdk/blob/26ce4a563f538a689f2a29063f3604731703ddac/skyscanner/skyscanner.py#L102-L132 | train | 53,982 |
Skyscanner/skyscanner-python-sdk | skyscanner/skyscanner.py | Transport.get_result | def get_result(self, errors=GRACEFUL, **params):
"""
Get all results, no filtering, etc. by creating and polling the
session.
"""
additional_params = self.get_additional_params(**params)
return self.poll_session(
self.create_session(**params),
errors=errors,
**additional_params
) | python | def get_result(self, errors=GRACEFUL, **params):
"""
Get all results, no filtering, etc. by creating and polling the
session.
"""
additional_params = self.get_additional_params(**params)
return self.poll_session(
self.create_session(**params),
errors=errors,
**additional_params
) | [
"def",
"get_result",
"(",
"self",
",",
"errors",
"=",
"GRACEFUL",
",",
"*",
"*",
"params",
")",
":",
"additional_params",
"=",
"self",
".",
"get_additional_params",
"(",
"*",
"*",
"params",
")",
"return",
"self",
".",
"poll_session",
"(",
"self",
".",
"c... | Get all results, no filtering, etc. by creating and polling the
session. | [
"Get",
"all",
"results",
"no",
"filtering",
"etc",
".",
"by",
"creating",
"and",
"polling",
"the",
"session",
"."
] | 26ce4a563f538a689f2a29063f3604731703ddac | https://github.com/Skyscanner/skyscanner-python-sdk/blob/26ce4a563f538a689f2a29063f3604731703ddac/skyscanner/skyscanner.py#L134-L144 | train | 53,983 |
Skyscanner/skyscanner-python-sdk | skyscanner/skyscanner.py | Transport.make_request | def make_request(self, service_url, method='get', headers=None, data=None,
callback=None, errors=GRACEFUL, **params):
"""
Reusable method for performing requests.
:param service_url - URL to request
:param method - request method, default is 'get'
:param headers - request headers
:param data - post data
:param callback - callback to be applied to response,
default callback will parse response as json object.
:param errors - specifies communication errors handling mode,
possible values are:
* strict (default) - throw an error as soon as one
occurred
* graceful - ignore certain errors, e.g. EmptyResponse
* ignore - ignore all errors and return a result in
any case.
NOTE that it DOES NOT mean that
no exceptions can be raised from
this method, it mostly ignores
communication related errors.
* None or empty string equals to default
:param params - additional query parameters for request
"""
error_modes = (STRICT, GRACEFUL, IGNORE)
error_mode = errors or GRACEFUL
if error_mode.lower() not in error_modes:
raise ValueError(
'Possible values for errors argument are: %s' %
', '.join(error_modes)
)
if callback is None:
callback = self._default_resp_callback
if 'apikey' not in service_url.lower():
params.update({
'apiKey': self.api_key
})
request = getattr(requests, method.lower())
log.debug('* Request URL: %s' % service_url)
log.debug('* Request method: %s' % method)
log.debug('* Request query params: %s' % params)
log.debug('* Request headers: %s' % headers)
r = request(service_url, headers=headers, data=data, params=params)
try:
r.raise_for_status()
return callback(r)
except Exception as e:
return self._with_error_handling(r, e, error_mode,
self.response_format) | python | def make_request(self, service_url, method='get', headers=None, data=None,
callback=None, errors=GRACEFUL, **params):
"""
Reusable method for performing requests.
:param service_url - URL to request
:param method - request method, default is 'get'
:param headers - request headers
:param data - post data
:param callback - callback to be applied to response,
default callback will parse response as json object.
:param errors - specifies communication errors handling mode,
possible values are:
* strict (default) - throw an error as soon as one
occurred
* graceful - ignore certain errors, e.g. EmptyResponse
* ignore - ignore all errors and return a result in
any case.
NOTE that it DOES NOT mean that
no exceptions can be raised from
this method, it mostly ignores
communication related errors.
* None or empty string equals to default
:param params - additional query parameters for request
"""
error_modes = (STRICT, GRACEFUL, IGNORE)
error_mode = errors or GRACEFUL
if error_mode.lower() not in error_modes:
raise ValueError(
'Possible values for errors argument are: %s' %
', '.join(error_modes)
)
if callback is None:
callback = self._default_resp_callback
if 'apikey' not in service_url.lower():
params.update({
'apiKey': self.api_key
})
request = getattr(requests, method.lower())
log.debug('* Request URL: %s' % service_url)
log.debug('* Request method: %s' % method)
log.debug('* Request query params: %s' % params)
log.debug('* Request headers: %s' % headers)
r = request(service_url, headers=headers, data=data, params=params)
try:
r.raise_for_status()
return callback(r)
except Exception as e:
return self._with_error_handling(r, e, error_mode,
self.response_format) | [
"def",
"make_request",
"(",
"self",
",",
"service_url",
",",
"method",
"=",
"'get'",
",",
"headers",
"=",
"None",
",",
"data",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"errors",
"=",
"GRACEFUL",
",",
"*",
"*",
"params",
")",
":",
"error_modes",
... | Reusable method for performing requests.
:param service_url - URL to request
:param method - request method, default is 'get'
:param headers - request headers
:param data - post data
:param callback - callback to be applied to response,
default callback will parse response as json object.
:param errors - specifies communication errors handling mode,
possible values are:
* strict (default) - throw an error as soon as one
occurred
* graceful - ignore certain errors, e.g. EmptyResponse
* ignore - ignore all errors and return a result in
any case.
NOTE that it DOES NOT mean that
no exceptions can be raised from
this method, it mostly ignores
communication related errors.
* None or empty string equals to default
:param params - additional query parameters for request | [
"Reusable",
"method",
"for",
"performing",
"requests",
"."
] | 26ce4a563f538a689f2a29063f3604731703ddac | https://github.com/Skyscanner/skyscanner-python-sdk/blob/26ce4a563f538a689f2a29063f3604731703ddac/skyscanner/skyscanner.py#L146-L200 | train | 53,984 |
Skyscanner/skyscanner-python-sdk | skyscanner/skyscanner.py | Transport._construct_params | def _construct_params(params, required_keys, opt_keys=None):
"""
Construct params list in order of given keys.
"""
try:
params_list = [params.pop(key) for key in required_keys]
except KeyError as e:
raise MissingParameter(
'Missing expected request parameter: %s' % e)
if opt_keys:
params_list.extend([params.pop(key)
for key in opt_keys if key in params])
return '/'.join(str(p) for p in params_list) | python | def _construct_params(params, required_keys, opt_keys=None):
"""
Construct params list in order of given keys.
"""
try:
params_list = [params.pop(key) for key in required_keys]
except KeyError as e:
raise MissingParameter(
'Missing expected request parameter: %s' % e)
if opt_keys:
params_list.extend([params.pop(key)
for key in opt_keys if key in params])
return '/'.join(str(p) for p in params_list) | [
"def",
"_construct_params",
"(",
"params",
",",
"required_keys",
",",
"opt_keys",
"=",
"None",
")",
":",
"try",
":",
"params_list",
"=",
"[",
"params",
".",
"pop",
"(",
"key",
")",
"for",
"key",
"in",
"required_keys",
"]",
"except",
"KeyError",
"as",
"e"... | Construct params list in order of given keys. | [
"Construct",
"params",
"list",
"in",
"order",
"of",
"given",
"keys",
"."
] | 26ce4a563f538a689f2a29063f3604731703ddac | https://github.com/Skyscanner/skyscanner-python-sdk/blob/26ce4a563f538a689f2a29063f3604731703ddac/skyscanner/skyscanner.py#L400-L412 | train | 53,985 |
jlmadurga/django-telegram-bot | telegrambot/bot_views/generic/detail.py | DetailCommandView.get_queryset | def get_queryset(self):
"""
Return the `QuerySet` that will be used to look up the object.
Note that this method is called by the default implementation of
`get_object` and may not be called if `get_object` is overridden.
"""
if self.queryset is None:
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
return self.queryset.all() | python | def get_queryset(self):
"""
Return the `QuerySet` that will be used to look up the object.
Note that this method is called by the default implementation of
`get_object` and may not be called if `get_object` is overridden.
"""
if self.queryset is None:
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured(
"%(cls)s is missing a QuerySet. Define "
"%(cls)s.model, %(cls)s.queryset, or override "
"%(cls)s.get_queryset()." % {
'cls': self.__class__.__name__
}
)
return self.queryset.all() | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"if",
"self",
".",
"queryset",
"is",
"None",
":",
"if",
"self",
".",
"model",
":",
"return",
"self",
".",
"model",
".",
"_default_manager",
".",
"all",
"(",
")",
"else",
":",
"raise",
"ImproperlyConfigured",
... | Return the `QuerySet` that will be used to look up the object.
Note that this method is called by the default implementation of
`get_object` and may not be called if `get_object` is overridden. | [
"Return",
"the",
"QuerySet",
"that",
"will",
"be",
"used",
"to",
"look",
"up",
"the",
"object",
".",
"Note",
"that",
"this",
"method",
"is",
"called",
"by",
"the",
"default",
"implementation",
"of",
"get_object",
"and",
"may",
"not",
"be",
"called",
"if",
... | becbc86a9735c794828eb5da39bd59647104ba34 | https://github.com/jlmadurga/django-telegram-bot/blob/becbc86a9735c794828eb5da39bd59647104ba34/telegrambot/bot_views/generic/detail.py#L20-L37 | train | 53,986 |
jlmadurga/django-telegram-bot | telegrambot/bot_views/decorators.py | login_required | def login_required(view_func):
"""
Decorator for command views that checks that the chat is authenticated,
sends message with link for authenticated if necessary.
"""
@wraps(view_func)
def wrapper(bot, update, **kwargs):
chat = Chat.objects.get(id=update.message.chat.id)
if chat.is_authenticated():
return view_func(bot, update, **kwargs)
from telegrambot.bot_views.login import LoginBotView
login_command_view = LoginBotView.as_command_view()
bot_model = Bot.objects.get(token=bot.token)
kwargs['link'] = reverse('telegrambot:auth', kwargs={'bot': bot_model.user_api.username})
return login_command_view(bot, update, **kwargs)
return wrapper | python | def login_required(view_func):
"""
Decorator for command views that checks that the chat is authenticated,
sends message with link for authenticated if necessary.
"""
@wraps(view_func)
def wrapper(bot, update, **kwargs):
chat = Chat.objects.get(id=update.message.chat.id)
if chat.is_authenticated():
return view_func(bot, update, **kwargs)
from telegrambot.bot_views.login import LoginBotView
login_command_view = LoginBotView.as_command_view()
bot_model = Bot.objects.get(token=bot.token)
kwargs['link'] = reverse('telegrambot:auth', kwargs={'bot': bot_model.user_api.username})
return login_command_view(bot, update, **kwargs)
return wrapper | [
"def",
"login_required",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
")",
"def",
"wrapper",
"(",
"bot",
",",
"update",
",",
"*",
"*",
"kwargs",
")",
":",
"chat",
"=",
"Chat",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"update",
"."... | Decorator for command views that checks that the chat is authenticated,
sends message with link for authenticated if necessary. | [
"Decorator",
"for",
"command",
"views",
"that",
"checks",
"that",
"the",
"chat",
"is",
"authenticated",
"sends",
"message",
"with",
"link",
"for",
"authenticated",
"if",
"necessary",
"."
] | becbc86a9735c794828eb5da39bd59647104ba34 | https://github.com/jlmadurga/django-telegram-bot/blob/becbc86a9735c794828eb5da39bd59647104ba34/telegrambot/bot_views/decorators.py#L6-L21 | train | 53,987 |
0101/pipetools | pipetools/decorators.py | pipe_util | def pipe_util(func):
"""
Decorator that handles X objects and partial application for pipe-utils.
"""
@wraps(func)
def pipe_util_wrapper(function, *args, **kwargs):
if isinstance(function, XObject):
function = ~function
original_function = function
if args or kwargs:
function = xpartial(function, *args, **kwargs)
name = lambda: '%s(%s)' % (get_name(func), ', '.join(
filter(None, (get_name(original_function), repr_args(*args, **kwargs)))))
f = func(function)
result = pipe | set_name(name, f)
# if the util defines an 'attrs' mapping, copy it as attributes
# to the result
attrs = getattr(f, 'attrs', {})
for k, v in dict_items(attrs):
setattr(result, k, v)
return result
return pipe_util_wrapper | python | def pipe_util(func):
"""
Decorator that handles X objects and partial application for pipe-utils.
"""
@wraps(func)
def pipe_util_wrapper(function, *args, **kwargs):
if isinstance(function, XObject):
function = ~function
original_function = function
if args or kwargs:
function = xpartial(function, *args, **kwargs)
name = lambda: '%s(%s)' % (get_name(func), ', '.join(
filter(None, (get_name(original_function), repr_args(*args, **kwargs)))))
f = func(function)
result = pipe | set_name(name, f)
# if the util defines an 'attrs' mapping, copy it as attributes
# to the result
attrs = getattr(f, 'attrs', {})
for k, v in dict_items(attrs):
setattr(result, k, v)
return result
return pipe_util_wrapper | [
"def",
"pipe_util",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"pipe_util_wrapper",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"XObject",
")",
":",
"function",
"=... | Decorator that handles X objects and partial application for pipe-utils. | [
"Decorator",
"that",
"handles",
"X",
"objects",
"and",
"partial",
"application",
"for",
"pipe",
"-",
"utils",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/decorators.py#L10-L39 | train | 53,988 |
0101/pipetools | pipetools/decorators.py | auto_string_formatter | def auto_string_formatter(func):
"""
Decorator that handles automatic string formatting.
By converting a string argument to a function that does formatting on said
string.
"""
@wraps(func)
def auto_string_formatter_wrapper(function, *args, **kwargs):
if isinstance(function, string_types):
function = StringFormatter(function)
return func(function, *args, **kwargs)
return auto_string_formatter_wrapper | python | def auto_string_formatter(func):
"""
Decorator that handles automatic string formatting.
By converting a string argument to a function that does formatting on said
string.
"""
@wraps(func)
def auto_string_formatter_wrapper(function, *args, **kwargs):
if isinstance(function, string_types):
function = StringFormatter(function)
return func(function, *args, **kwargs)
return auto_string_formatter_wrapper | [
"def",
"auto_string_formatter",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"auto_string_formatter_wrapper",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"function",
",",
"string_types",
"... | Decorator that handles automatic string formatting.
By converting a string argument to a function that does formatting on said
string. | [
"Decorator",
"that",
"handles",
"automatic",
"string",
"formatting",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/decorators.py#L42-L56 | train | 53,989 |
0101/pipetools | pipetools/decorators.py | data_structure_builder | def data_structure_builder(func):
"""
Decorator to handle automatic data structure creation for pipe-utils.
"""
@wraps(func)
def ds_builder_wrapper(function, *args, **kwargs):
try:
function = DSBuilder(function)
except NoBuilder:
pass
return func(function, *args, **kwargs)
return ds_builder_wrapper | python | def data_structure_builder(func):
"""
Decorator to handle automatic data structure creation for pipe-utils.
"""
@wraps(func)
def ds_builder_wrapper(function, *args, **kwargs):
try:
function = DSBuilder(function)
except NoBuilder:
pass
return func(function, *args, **kwargs)
return ds_builder_wrapper | [
"def",
"data_structure_builder",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"ds_builder_wrapper",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"function",
"=",
"DSBuilder",
"(",
"function",
")",
"... | Decorator to handle automatic data structure creation for pipe-utils. | [
"Decorator",
"to",
"handle",
"automatic",
"data",
"structure",
"creation",
"for",
"pipe",
"-",
"utils",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/decorators.py#L59-L71 | train | 53,990 |
0101/pipetools | pipetools/decorators.py | regex_condition | def regex_condition(func):
"""
If a condition is given as string instead of a function, it is turned
into a regex-matching function.
"""
@wraps(func)
def regex_condition_wrapper(condition, *args, **kwargs):
if isinstance(condition, string_types):
condition = maybe | partial(re.match, condition)
return func(condition, *args, **kwargs)
return regex_condition_wrapper | python | def regex_condition(func):
"""
If a condition is given as string instead of a function, it is turned
into a regex-matching function.
"""
@wraps(func)
def regex_condition_wrapper(condition, *args, **kwargs):
if isinstance(condition, string_types):
condition = maybe | partial(re.match, condition)
return func(condition, *args, **kwargs)
return regex_condition_wrapper | [
"def",
"regex_condition",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"regex_condition_wrapper",
"(",
"condition",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"condition",
",",
"string_types",
")",
":",... | If a condition is given as string instead of a function, it is turned
into a regex-matching function. | [
"If",
"a",
"condition",
"is",
"given",
"as",
"string",
"instead",
"of",
"a",
"function",
"it",
"is",
"turned",
"into",
"a",
"regex",
"-",
"matching",
"function",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/decorators.py#L74-L84 | train | 53,991 |
0101/pipetools | pipetools/utils.py | sort_by | def sort_by(function):
"""
Sorts an incoming sequence by using the given `function` as key.
>>> range(10) > sort_by(-X)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Supports automatic data-structure creation::
users > sort_by([X.last_name, X.first_name])
There is also a shortcut for ``sort_by(X)`` called ``sort``:
>>> [4, 5, 8, -3, 0] > sort
[-3, 0, 4, 5, 8]
And (as of ``0.2.3``) a shortcut for reversing the sort:
>>> 'asdfaSfa' > sort_by(X.lower()).descending
['s', 'S', 'f', 'f', 'd', 'a', 'a', 'a']
"""
f = partial(sorted, key=function)
f.attrs = {'descending': _descending_sort_by(function)}
return f | python | def sort_by(function):
"""
Sorts an incoming sequence by using the given `function` as key.
>>> range(10) > sort_by(-X)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Supports automatic data-structure creation::
users > sort_by([X.last_name, X.first_name])
There is also a shortcut for ``sort_by(X)`` called ``sort``:
>>> [4, 5, 8, -3, 0] > sort
[-3, 0, 4, 5, 8]
And (as of ``0.2.3``) a shortcut for reversing the sort:
>>> 'asdfaSfa' > sort_by(X.lower()).descending
['s', 'S', 'f', 'f', 'd', 'a', 'a', 'a']
"""
f = partial(sorted, key=function)
f.attrs = {'descending': _descending_sort_by(function)}
return f | [
"def",
"sort_by",
"(",
"function",
")",
":",
"f",
"=",
"partial",
"(",
"sorted",
",",
"key",
"=",
"function",
")",
"f",
".",
"attrs",
"=",
"{",
"'descending'",
":",
"_descending_sort_by",
"(",
"function",
")",
"}",
"return",
"f"
] | Sorts an incoming sequence by using the given `function` as key.
>>> range(10) > sort_by(-X)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Supports automatic data-structure creation::
users > sort_by([X.last_name, X.first_name])
There is also a shortcut for ``sort_by(X)`` called ``sort``:
>>> [4, 5, 8, -3, 0] > sort
[-3, 0, 4, 5, 8]
And (as of ``0.2.3``) a shortcut for reversing the sort:
>>> 'asdfaSfa' > sort_by(X.lower()).descending
['s', 'S', 'f', 'f', 'd', 'a', 'a', 'a'] | [
"Sorts",
"an",
"incoming",
"sequence",
"by",
"using",
"the",
"given",
"function",
"as",
"key",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/utils.py#L76-L99 | train | 53,992 |
0101/pipetools | pipetools/utils.py | drop_first | def drop_first(count):
"""
Assumes an iterable on the input, returns an iterable with identical items
except for the first `count`.
>>> range(10) > drop_first(5) | tuple
(5, 6, 7, 8, 9)
"""
def _drop_first(iterable):
g = (x for x in range(1, count + 1))
return dropwhile(
lambda i: unless(StopIteration, lambda: next(g))(), iterable)
return pipe | set_name('drop_first(%s)' % count, _drop_first) | python | def drop_first(count):
"""
Assumes an iterable on the input, returns an iterable with identical items
except for the first `count`.
>>> range(10) > drop_first(5) | tuple
(5, 6, 7, 8, 9)
"""
def _drop_first(iterable):
g = (x for x in range(1, count + 1))
return dropwhile(
lambda i: unless(StopIteration, lambda: next(g))(), iterable)
return pipe | set_name('drop_first(%s)' % count, _drop_first) | [
"def",
"drop_first",
"(",
"count",
")",
":",
"def",
"_drop_first",
"(",
"iterable",
")",
":",
"g",
"=",
"(",
"x",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"count",
"+",
"1",
")",
")",
"return",
"dropwhile",
"(",
"lambda",
"i",
":",
"unless",
"("... | Assumes an iterable on the input, returns an iterable with identical items
except for the first `count`.
>>> range(10) > drop_first(5) | tuple
(5, 6, 7, 8, 9) | [
"Assumes",
"an",
"iterable",
"on",
"the",
"input",
"returns",
"an",
"iterable",
"with",
"identical",
"items",
"except",
"for",
"the",
"first",
"count",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/utils.py#L177-L189 | train | 53,993 |
0101/pipetools | pipetools/utils.py | unless | def unless(exception_class_or_tuple, func, *args, **kwargs):
"""
When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None
"""
@pipe_util
@auto_string_formatter
@data_structure_builder
def construct_unless(function):
# a wrapper so we can re-use the decorators
def _unless(*args, **kwargs):
try:
return function(*args, **kwargs)
except exception_class_or_tuple:
pass
return _unless
name = lambda: 'unless(%s, %s)' % (exception_class_or_tuple, ', '.join(
filter(None, (get_name(func), repr_args(*args, **kwargs)))))
return set_name(name, construct_unless(func, *args, **kwargs)) | python | def unless(exception_class_or_tuple, func, *args, **kwargs):
"""
When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None
"""
@pipe_util
@auto_string_formatter
@data_structure_builder
def construct_unless(function):
# a wrapper so we can re-use the decorators
def _unless(*args, **kwargs):
try:
return function(*args, **kwargs)
except exception_class_or_tuple:
pass
return _unless
name = lambda: 'unless(%s, %s)' % (exception_class_or_tuple, ', '.join(
filter(None, (get_name(func), repr_args(*args, **kwargs)))))
return set_name(name, construct_unless(func, *args, **kwargs)) | [
"def",
"unless",
"(",
"exception_class_or_tuple",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"@",
"pipe_util",
"@",
"auto_string_formatter",
"@",
"data_structure_builder",
"def",
"construct_unless",
"(",
"function",
")",
":",
"# a wrapper ... | When `exception_class_or_tuple` occurs while executing `func`, it will
be caught and ``None`` will be returned.
>>> f = where(X > 10) | list | unless(IndexError, X[0])
>>> f([5, 8, 12, 4])
12
>>> f([1, 2, 3])
None | [
"When",
"exception_class_or_tuple",
"occurs",
"while",
"executing",
"func",
"it",
"will",
"be",
"caught",
"and",
"None",
"will",
"be",
"returned",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/utils.py#L192-L218 | train | 53,994 |
0101/pipetools | pipetools/utils.py | group_by | def group_by(function):
"""
Groups input sequence by `function`.
Returns an iterator over a sequence of tuples where the first item is a
result of `function` and the second one a list of items matching this
result.
Ordering of the resulting iterator is undefined, but ordering of the items
in the groups is preserved.
>>> [1, 2, 3, 4, 5, 6] > group_by(X % 2) | list
[(0, [2, 4, 6]), (1, [1, 3, 5])]
"""
def _group_by(seq):
result = {}
for item in seq:
result.setdefault(function(item), []).append(item)
return dict_items(result)
return _group_by | python | def group_by(function):
"""
Groups input sequence by `function`.
Returns an iterator over a sequence of tuples where the first item is a
result of `function` and the second one a list of items matching this
result.
Ordering of the resulting iterator is undefined, but ordering of the items
in the groups is preserved.
>>> [1, 2, 3, 4, 5, 6] > group_by(X % 2) | list
[(0, [2, 4, 6]), (1, [1, 3, 5])]
"""
def _group_by(seq):
result = {}
for item in seq:
result.setdefault(function(item), []).append(item)
return dict_items(result)
return _group_by | [
"def",
"group_by",
"(",
"function",
")",
":",
"def",
"_group_by",
"(",
"seq",
")",
":",
"result",
"=",
"{",
"}",
"for",
"item",
"in",
"seq",
":",
"result",
".",
"setdefault",
"(",
"function",
"(",
"item",
")",
",",
"[",
"]",
")",
".",
"append",
"... | Groups input sequence by `function`.
Returns an iterator over a sequence of tuples where the first item is a
result of `function` and the second one a list of items matching this
result.
Ordering of the resulting iterator is undefined, but ordering of the items
in the groups is preserved.
>>> [1, 2, 3, 4, 5, 6] > group_by(X % 2) | list
[(0, [2, 4, 6]), (1, [1, 3, 5])] | [
"Groups",
"input",
"sequence",
"by",
"function",
"."
] | 42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1 | https://github.com/0101/pipetools/blob/42f71af0ecaeacee0f3d64c8706ddb1caacf8bc1/pipetools/utils.py#L254-L274 | train | 53,995 |
pytroll/pyorbital | pyorbital/astronomy.py | gmst | def gmst(utc_time):
"""Greenwich mean sidereal utc_time, in radians.
As defined in the AIAA 2006 implementation:
http://www.celestrak.com/publications/AIAA/2006-6753/
"""
ut1 = jdays2000(utc_time) / 36525.0
theta = 67310.54841 + ut1 * (876600 * 3600 + 8640184.812866 + ut1 *
(0.093104 - ut1 * 6.2 * 10e-6))
return np.deg2rad(theta / 240.0) % (2 * np.pi) | python | def gmst(utc_time):
"""Greenwich mean sidereal utc_time, in radians.
As defined in the AIAA 2006 implementation:
http://www.celestrak.com/publications/AIAA/2006-6753/
"""
ut1 = jdays2000(utc_time) / 36525.0
theta = 67310.54841 + ut1 * (876600 * 3600 + 8640184.812866 + ut1 *
(0.093104 - ut1 * 6.2 * 10e-6))
return np.deg2rad(theta / 240.0) % (2 * np.pi) | [
"def",
"gmst",
"(",
"utc_time",
")",
":",
"ut1",
"=",
"jdays2000",
"(",
"utc_time",
")",
"/",
"36525.0",
"theta",
"=",
"67310.54841",
"+",
"ut1",
"*",
"(",
"876600",
"*",
"3600",
"+",
"8640184.812866",
"+",
"ut1",
"*",
"(",
"0.093104",
"-",
"ut1",
"*... | Greenwich mean sidereal utc_time, in radians.
As defined in the AIAA 2006 implementation:
http://www.celestrak.com/publications/AIAA/2006-6753/ | [
"Greenwich",
"mean",
"sidereal",
"utc_time",
"in",
"radians",
"."
] | 647007934dc827a4c698629cf32a84a5167844b2 | https://github.com/pytroll/pyorbital/blob/647007934dc827a4c698629cf32a84a5167844b2/pyorbital/astronomy.py#L54-L63 | train | 53,996 |
pytroll/pyorbital | pyorbital/astronomy.py | sun_earth_distance_correction | def sun_earth_distance_correction(utc_time):
"""Calculate the sun earth distance correction, relative to 1 AU.
"""
year = 365.256363004
# This is computed from
# http://curious.astro.cornell.edu/question.php?number=582
# AU = 149597870700.0
# a = 149598261000.0
# theta = (jdays2000(utc_time) - 2) * (2 * np.pi) / year
# e = 0.01671123
# r = a*(1-e*e)/(1+e * np.cos(theta))
# corr_me = (r / AU) ** 2
# from known software.
corr = 1 - 0.0334 * np.cos(2 * np.pi * (jdays2000(utc_time) - 2) / year)
return corr | python | def sun_earth_distance_correction(utc_time):
"""Calculate the sun earth distance correction, relative to 1 AU.
"""
year = 365.256363004
# This is computed from
# http://curious.astro.cornell.edu/question.php?number=582
# AU = 149597870700.0
# a = 149598261000.0
# theta = (jdays2000(utc_time) - 2) * (2 * np.pi) / year
# e = 0.01671123
# r = a*(1-e*e)/(1+e * np.cos(theta))
# corr_me = (r / AU) ** 2
# from known software.
corr = 1 - 0.0334 * np.cos(2 * np.pi * (jdays2000(utc_time) - 2) / year)
return corr | [
"def",
"sun_earth_distance_correction",
"(",
"utc_time",
")",
":",
"year",
"=",
"365.256363004",
"# This is computed from",
"# http://curious.astro.cornell.edu/question.php?number=582",
"# AU = 149597870700.0",
"# a = 149598261000.0",
"# theta = (jdays2000(utc_time) - 2) * (2 * np.pi) / ye... | Calculate the sun earth distance correction, relative to 1 AU. | [
"Calculate",
"the",
"sun",
"earth",
"distance",
"correction",
"relative",
"to",
"1",
"AU",
"."
] | 647007934dc827a4c698629cf32a84a5167844b2 | https://github.com/pytroll/pyorbital/blob/647007934dc827a4c698629cf32a84a5167844b2/pyorbital/astronomy.py#L155-L171 | train | 53,997 |
pytroll/pyorbital | pyorbital/astronomy.py | observer_position | def observer_position(time, lon, lat, alt):
"""Calculate observer ECI position.
http://celestrak.com/columns/v02n03/
"""
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
theta = (gmst(time) + lon) % (2 * np.pi)
c = 1 / np.sqrt(1 + F * (F - 2) * np.sin(lat)**2)
sq = c * (1 - F)**2
achcp = (A * c + alt) * np.cos(lat)
x = achcp * np.cos(theta) # kilometers
y = achcp * np.sin(theta)
z = (A * sq + alt) * np.sin(lat)
vx = -MFACTOR * y # kilometers/second
vy = MFACTOR * x
vz = 0
return (x, y, z), (vx, vy, vz) | python | def observer_position(time, lon, lat, alt):
"""Calculate observer ECI position.
http://celestrak.com/columns/v02n03/
"""
lon = np.deg2rad(lon)
lat = np.deg2rad(lat)
theta = (gmst(time) + lon) % (2 * np.pi)
c = 1 / np.sqrt(1 + F * (F - 2) * np.sin(lat)**2)
sq = c * (1 - F)**2
achcp = (A * c + alt) * np.cos(lat)
x = achcp * np.cos(theta) # kilometers
y = achcp * np.sin(theta)
z = (A * sq + alt) * np.sin(lat)
vx = -MFACTOR * y # kilometers/second
vy = MFACTOR * x
vz = 0
return (x, y, z), (vx, vy, vz) | [
"def",
"observer_position",
"(",
"time",
",",
"lon",
",",
"lat",
",",
"alt",
")",
":",
"lon",
"=",
"np",
".",
"deg2rad",
"(",
"lon",
")",
"lat",
"=",
"np",
".",
"deg2rad",
"(",
"lat",
")",
"theta",
"=",
"(",
"gmst",
"(",
"time",
")",
"+",
"lon"... | Calculate observer ECI position.
http://celestrak.com/columns/v02n03/ | [
"Calculate",
"observer",
"ECI",
"position",
"."
] | 647007934dc827a4c698629cf32a84a5167844b2 | https://github.com/pytroll/pyorbital/blob/647007934dc827a4c698629cf32a84a5167844b2/pyorbital/astronomy.py#L174-L196 | train | 53,998 |
pytroll/pyorbital | pyorbital/orbital.py | Orbital.get_last_an_time | def get_last_an_time(self, utc_time):
"""Calculate time of last ascending node relative to the
specified time
"""
# Propagate backwards to ascending node
dt = np.timedelta64(10, 'm')
t_old = utc_time
t_new = t_old - dt
pos0, vel0 = self.get_position(t_old, normalize=False)
pos1, vel1 = self.get_position(t_new, normalize=False)
while not (pos0[2] > 0 and pos1[2] < 0):
pos0 = pos1
t_old = t_new
t_new = t_old - dt
pos1, vel1 = self.get_position(t_new, normalize=False)
# Return if z within 1 km of an
if np.abs(pos0[2]) < 1:
return t_old
elif np.abs(pos1[2]) < 1:
return t_new
# Bisect to z within 1 km
while np.abs(pos1[2]) > 1:
# pos0, vel0 = pos1, vel1
dt = (t_old - t_new) / 2
t_mid = t_old - dt
pos1, vel1 = self.get_position(t_mid, normalize=False)
if pos1[2] > 0:
t_old = t_mid
else:
t_new = t_mid
return t_mid | python | def get_last_an_time(self, utc_time):
"""Calculate time of last ascending node relative to the
specified time
"""
# Propagate backwards to ascending node
dt = np.timedelta64(10, 'm')
t_old = utc_time
t_new = t_old - dt
pos0, vel0 = self.get_position(t_old, normalize=False)
pos1, vel1 = self.get_position(t_new, normalize=False)
while not (pos0[2] > 0 and pos1[2] < 0):
pos0 = pos1
t_old = t_new
t_new = t_old - dt
pos1, vel1 = self.get_position(t_new, normalize=False)
# Return if z within 1 km of an
if np.abs(pos0[2]) < 1:
return t_old
elif np.abs(pos1[2]) < 1:
return t_new
# Bisect to z within 1 km
while np.abs(pos1[2]) > 1:
# pos0, vel0 = pos1, vel1
dt = (t_old - t_new) / 2
t_mid = t_old - dt
pos1, vel1 = self.get_position(t_mid, normalize=False)
if pos1[2] > 0:
t_old = t_mid
else:
t_new = t_mid
return t_mid | [
"def",
"get_last_an_time",
"(",
"self",
",",
"utc_time",
")",
":",
"# Propagate backwards to ascending node",
"dt",
"=",
"np",
".",
"timedelta64",
"(",
"10",
",",
"'m'",
")",
"t_old",
"=",
"utc_time",
"t_new",
"=",
"t_old",
"-",
"dt",
"pos0",
",",
"vel0",
... | Calculate time of last ascending node relative to the
specified time | [
"Calculate",
"time",
"of",
"last",
"ascending",
"node",
"relative",
"to",
"the",
"specified",
"time"
] | 647007934dc827a4c698629cf32a84a5167844b2 | https://github.com/pytroll/pyorbital/blob/647007934dc827a4c698629cf32a84a5167844b2/pyorbital/orbital.py#L172-L206 | train | 53,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.