id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,200 | graphql-python/graphql-core-next | graphql/utilities/find_deprecated_usages.py | find_deprecated_usages | def find_deprecated_usages(
schema: GraphQLSchema, ast: DocumentNode
) -> List[GraphQLError]:
"""Get a list of GraphQLError instances describing each deprecated use."""
type_info = TypeInfo(schema)
visitor = FindDeprecatedUsages(type_info)
visit(ast, TypeInfoVisitor(type_info, visitor))
return visitor.errors | python | def find_deprecated_usages(
schema: GraphQLSchema, ast: DocumentNode
) -> List[GraphQLError]:
type_info = TypeInfo(schema)
visitor = FindDeprecatedUsages(type_info)
visit(ast, TypeInfoVisitor(type_info, visitor))
return visitor.errors | [
"def",
"find_deprecated_usages",
"(",
"schema",
":",
"GraphQLSchema",
",",
"ast",
":",
"DocumentNode",
")",
"->",
"List",
"[",
"GraphQLError",
"]",
":",
"type_info",
"=",
"TypeInfo",
"(",
"schema",
")",
"visitor",
"=",
"FindDeprecatedUsages",
"(",
"type_info",
... | Get a list of GraphQLError instances describing each deprecated use. | [
"Get",
"a",
"list",
"of",
"GraphQLError",
"instances",
"describing",
"each",
"deprecated",
"use",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/find_deprecated_usages.py#L12-L20 |
226,201 | graphql-python/graphql-core-next | graphql/pyutils/convert_case.py | snake_to_camel | def snake_to_camel(s, upper=True):
"""Convert from snake_case to CamelCase
If upper is set, then convert to upper CamelCase, otherwise the first character
keeps its case.
"""
s = _re_snake_to_camel.sub(lambda m: m.group(2).upper(), s)
if upper:
s = s[:1].upper() + s[1:]
return s | python | def snake_to_camel(s, upper=True):
s = _re_snake_to_camel.sub(lambda m: m.group(2).upper(), s)
if upper:
s = s[:1].upper() + s[1:]
return s | [
"def",
"snake_to_camel",
"(",
"s",
",",
"upper",
"=",
"True",
")",
":",
"s",
"=",
"_re_snake_to_camel",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"2",
")",
".",
"upper",
"(",
")",
",",
"s",
")",
"if",
"upper",
":",
"s",
"=",
... | Convert from snake_case to CamelCase
If upper is set, then convert to upper CamelCase, otherwise the first character
keeps its case. | [
"Convert",
"from",
"snake_case",
"to",
"CamelCase"
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/convert_case.py#L16-L25 |
226,202 | graphql-python/graphql-core-next | graphql/validation/rules/values_of_correct_type.py | ValuesOfCorrectTypeRule.is_valid_scalar | def is_valid_scalar(self, node: ValueNode) -> None:
"""Check whether this is a valid scalar.
Any value literal may be a valid representation of a Scalar, depending on that
scalar type.
"""
# Report any error at the full type expected by the location.
location_type = self.context.get_input_type()
if not location_type:
return
type_ = get_named_type(location_type)
if not is_scalar_type(type_):
self.report_error(
GraphQLError(
bad_value_message(
location_type,
print_ast(node),
enum_type_suggestion(type_, node),
),
node,
)
)
return
# Scalars determine if a literal value is valid via `parse_literal()` which may
# throw or return an invalid value to indicate failure.
type_ = cast(GraphQLScalarType, type_)
try:
parse_result = type_.parse_literal(node)
if is_invalid(parse_result):
self.report_error(
GraphQLError(
bad_value_message(location_type, print_ast(node)), node
)
)
except Exception as error:
# Ensure a reference to the original error is maintained.
self.report_error(
GraphQLError(
bad_value_message(location_type, print_ast(node), str(error)),
node,
original_error=error,
)
) | python | def is_valid_scalar(self, node: ValueNode) -> None:
# Report any error at the full type expected by the location.
location_type = self.context.get_input_type()
if not location_type:
return
type_ = get_named_type(location_type)
if not is_scalar_type(type_):
self.report_error(
GraphQLError(
bad_value_message(
location_type,
print_ast(node),
enum_type_suggestion(type_, node),
),
node,
)
)
return
# Scalars determine if a literal value is valid via `parse_literal()` which may
# throw or return an invalid value to indicate failure.
type_ = cast(GraphQLScalarType, type_)
try:
parse_result = type_.parse_literal(node)
if is_invalid(parse_result):
self.report_error(
GraphQLError(
bad_value_message(location_type, print_ast(node)), node
)
)
except Exception as error:
# Ensure a reference to the original error is maintained.
self.report_error(
GraphQLError(
bad_value_message(location_type, print_ast(node), str(error)),
node,
original_error=error,
)
) | [
"def",
"is_valid_scalar",
"(",
"self",
",",
"node",
":",
"ValueNode",
")",
"->",
"None",
":",
"# Report any error at the full type expected by the location.",
"location_type",
"=",
"self",
".",
"context",
".",
"get_input_type",
"(",
")",
"if",
"not",
"location_type",
... | Check whether this is a valid scalar.
Any value literal may be a valid representation of a Scalar, depending on that
scalar type. | [
"Check",
"whether",
"this",
"is",
"a",
"valid",
"scalar",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/values_of_correct_type.py#L145-L190 |
226,203 | graphql-python/graphql-core-next | graphql/utilities/value_from_ast.py | is_missing_variable | def is_missing_variable(
value_node: ValueNode, variables: Dict[str, Any] = None
) -> bool:
"""Check if `value_node` is a variable not defined in the `variables` dict."""
return isinstance(value_node, VariableNode) and (
not variables or is_invalid(variables.get(value_node.name.value, INVALID))
) | python | def is_missing_variable(
value_node: ValueNode, variables: Dict[str, Any] = None
) -> bool:
return isinstance(value_node, VariableNode) and (
not variables or is_invalid(variables.get(value_node.name.value, INVALID))
) | [
"def",
"is_missing_variable",
"(",
"value_node",
":",
"ValueNode",
",",
"variables",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
")",
"->",
"bool",
":",
"return",
"isinstance",
"(",
"value_node",
",",
"VariableNode",
")",
"and",
"(",
"not",
"v... | Check if `value_node` is a variable not defined in the `variables` dict. | [
"Check",
"if",
"value_node",
"is",
"a",
"variable",
"not",
"defined",
"in",
"the",
"variables",
"dict",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/value_from_ast.py#L155-L161 |
226,204 | graphql-python/graphql-core-next | graphql/pyutils/is_integer.py | is_integer | def is_integer(value: Any) -> bool:
"""Return true if a value is an integer number."""
return (isinstance(value, int) and not isinstance(value, bool)) or (
isinstance(value, float) and isfinite(value) and int(value) == value
) | python | def is_integer(value: Any) -> bool:
return (isinstance(value, int) and not isinstance(value, bool)) or (
isinstance(value, float) and isfinite(value) and int(value) == value
) | [
"def",
"is_integer",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"return",
"(",
"isinstance",
"(",
"value",
",",
"int",
")",
"and",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
")",
"or",
"(",
"isinstance",
"(",
"value",
",",
"float",
... | Return true if a value is an integer number. | [
"Return",
"true",
"if",
"a",
"value",
"is",
"an",
"integer",
"number",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/pyutils/is_integer.py#L7-L11 |
226,205 | graphql-python/graphql-core-next | graphql/validation/rules/variables_in_allowed_position.py | allowed_variable_usage | def allowed_variable_usage(
schema: GraphQLSchema,
var_type: GraphQLType,
var_default_value: Optional[ValueNode],
location_type: GraphQLType,
location_default_value: Any,
) -> bool:
"""Check for allowed variable usage.
Returns True if the variable is allowed in the location it was found, which includes
considering if default values exist for either the variable or the location at which
it is located.
"""
if is_non_null_type(location_type) and not is_non_null_type(var_type):
has_non_null_variable_default_value = var_default_value and not isinstance(
var_default_value, NullValueNode
)
has_location_default_value = location_default_value is not INVALID
if not has_non_null_variable_default_value and not has_location_default_value:
return False
location_type = cast(GraphQLNonNull, location_type)
nullable_location_type = location_type.of_type
return is_type_sub_type_of(schema, var_type, nullable_location_type)
return is_type_sub_type_of(schema, var_type, location_type) | python | def allowed_variable_usage(
schema: GraphQLSchema,
var_type: GraphQLType,
var_default_value: Optional[ValueNode],
location_type: GraphQLType,
location_default_value: Any,
) -> bool:
if is_non_null_type(location_type) and not is_non_null_type(var_type):
has_non_null_variable_default_value = var_default_value and not isinstance(
var_default_value, NullValueNode
)
has_location_default_value = location_default_value is not INVALID
if not has_non_null_variable_default_value and not has_location_default_value:
return False
location_type = cast(GraphQLNonNull, location_type)
nullable_location_type = location_type.of_type
return is_type_sub_type_of(schema, var_type, nullable_location_type)
return is_type_sub_type_of(schema, var_type, location_type) | [
"def",
"allowed_variable_usage",
"(",
"schema",
":",
"GraphQLSchema",
",",
"var_type",
":",
"GraphQLType",
",",
"var_default_value",
":",
"Optional",
"[",
"ValueNode",
"]",
",",
"location_type",
":",
"GraphQLType",
",",
"location_default_value",
":",
"Any",
",",
"... | Check for allowed variable usage.
Returns True if the variable is allowed in the location it was found, which includes
considering if default values exist for either the variable or the location at which
it is located. | [
"Check",
"for",
"allowed",
"variable",
"usage",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/validation/rules/variables_in_allowed_position.py#L65-L88 |
226,206 | graphql-python/graphql-core-next | graphql/utilities/schema_printer.py | is_schema_of_common_names | def is_schema_of_common_names(schema: GraphQLSchema) -> bool:
"""Check whether this schema uses the common naming convention.
GraphQL schema define root types for each type of operation. These types are the
same as any other type and can be named in any manner, however there is a common
naming convention:
schema {
query: Query
mutation: Mutation
}
When using this naming convention, the schema description can be omitted.
"""
query_type = schema.query_type
if query_type and query_type.name != "Query":
return False
mutation_type = schema.mutation_type
if mutation_type and mutation_type.name != "Mutation":
return False
subscription_type = schema.subscription_type
if subscription_type and subscription_type.name != "Subscription":
return False
return True | python | def is_schema_of_common_names(schema: GraphQLSchema) -> bool:
query_type = schema.query_type
if query_type and query_type.name != "Query":
return False
mutation_type = schema.mutation_type
if mutation_type and mutation_type.name != "Mutation":
return False
subscription_type = schema.subscription_type
if subscription_type and subscription_type.name != "Subscription":
return False
return True | [
"def",
"is_schema_of_common_names",
"(",
"schema",
":",
"GraphQLSchema",
")",
"->",
"bool",
":",
"query_type",
"=",
"schema",
".",
"query_type",
"if",
"query_type",
"and",
"query_type",
".",
"name",
"!=",
"\"Query\"",
":",
"return",
"False",
"mutation_type",
"="... | Check whether this schema uses the common naming convention.
GraphQL schema define root types for each type of operation. These types are the
same as any other type and can be named in any manner, however there is a common
naming convention:
schema {
query: Query
mutation: Mutation
}
When using this naming convention, the schema description can be omitted. | [
"Check",
"whether",
"this",
"schema",
"uses",
"the",
"common",
"naming",
"convention",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/schema_printer.py#L95-L121 |
226,207 | graphql-python/graphql-core-next | graphql/utilities/schema_printer.py | print_value | def print_value(value: Any, type_: GraphQLInputType) -> str:
"""Convenience function for printing a Python value"""
return print_ast(ast_from_value(value, type_)) | python | def print_value(value: Any, type_: GraphQLInputType) -> str:
return print_ast(ast_from_value(value, type_)) | [
"def",
"print_value",
"(",
"value",
":",
"Any",
",",
"type_",
":",
"GraphQLInputType",
")",
"->",
"str",
":",
"return",
"print_ast",
"(",
"ast_from_value",
"(",
"value",
",",
"type_",
")",
")"
] | Convenience function for printing a Python value | [
"Convenience",
"function",
"for",
"printing",
"a",
"Python",
"value"
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/utilities/schema_printer.py#L306-L308 |
226,208 | graphql-python/graphql-core-next | graphql/language/printer.py | add_description | def add_description(method):
"""Decorator adding the description to the output of a visitor method."""
@wraps(method)
def wrapped(self, node, *args):
return join([node.description, method(self, node, *args)], "\n")
return wrapped | python | def add_description(method):
@wraps(method)
def wrapped(self, node, *args):
return join([node.description, method(self, node, *args)], "\n")
return wrapped | [
"def",
"add_description",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapped",
"(",
"self",
",",
"node",
",",
"*",
"args",
")",
":",
"return",
"join",
"(",
"[",
"node",
".",
"description",
",",
"method",
"(",
"self",
",",
"n... | Decorator adding the description to the output of a visitor method. | [
"Decorator",
"adding",
"the",
"description",
"to",
"the",
"output",
"of",
"a",
"visitor",
"method",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/printer.py#L20-L27 |
226,209 | graphql-python/graphql-core-next | graphql/language/printer.py | join | def join(strings: Optional[Sequence[str]], separator: str = "") -> str:
"""Join strings in a given sequence.
Return an empty string if it is None or empty, otherwise join all items together
separated by separator if provided.
"""
return separator.join(s for s in strings if s) if strings else "" | python | def join(strings: Optional[Sequence[str]], separator: str = "") -> str:
return separator.join(s for s in strings if s) if strings else "" | [
"def",
"join",
"(",
"strings",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
",",
"separator",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"return",
"separator",
".",
"join",
"(",
"s",
"for",
"s",
"in",
"strings",
"if",
"s",
")",
"i... | Join strings in a given sequence.
Return an empty string if it is None or empty, otherwise join all items together
separated by separator if provided. | [
"Join",
"strings",
"in",
"a",
"given",
"sequence",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/printer.py#L305-L311 |
226,210 | graphql-python/graphql-core-next | graphql/language/printer.py | wrap | def wrap(start: str, string: str, end: str = "") -> str:
"""Wrap string inside other strings at start and end.
If the string is not None or empty, then wrap with start and end, otherwise return
an empty string.
"""
return f"{start}{string}{end}" if string else "" | python | def wrap(start: str, string: str, end: str = "") -> str:
return f"{start}{string}{end}" if string else "" | [
"def",
"wrap",
"(",
"start",
":",
"str",
",",
"string",
":",
"str",
",",
"end",
":",
"str",
"=",
"\"\"",
")",
"->",
"str",
":",
"return",
"f\"{start}{string}{end}\"",
"if",
"string",
"else",
"\"\""
] | Wrap string inside other strings at start and end.
If the string is not None or empty, then wrap with start and end, otherwise return
an empty string. | [
"Wrap",
"string",
"inside",
"other",
"strings",
"at",
"start",
"and",
"end",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/printer.py#L323-L329 |
226,211 | graphql-python/graphql-core-next | graphql/language/printer.py | has_multiline_items | def has_multiline_items(maybe_list: Optional[Sequence[str]]):
"""Check whether one of the items in the list has multiple lines."""
return maybe_list and any(is_multiline(item) for item in maybe_list) | python | def has_multiline_items(maybe_list: Optional[Sequence[str]]):
return maybe_list and any(is_multiline(item) for item in maybe_list) | [
"def",
"has_multiline_items",
"(",
"maybe_list",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
")",
":",
"return",
"maybe_list",
"and",
"any",
"(",
"is_multiline",
"(",
"item",
")",
"for",
"item",
"in",
"maybe_list",
")"
] | Check whether one of the items in the list has multiple lines. | [
"Check",
"whether",
"one",
"of",
"the",
"items",
"in",
"the",
"list",
"has",
"multiple",
"lines",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/language/printer.py#L346-L348 |
226,212 | graphql-python/graphql-core-next | graphql/execution/middleware.py | get_middleware_resolvers | def get_middleware_resolvers(middlewares: Tuple[Any, ...]) -> Iterator[Callable]:
"""Get a list of resolver functions from a list of classes or functions."""
for middleware in middlewares:
if isfunction(middleware):
yield middleware
else: # middleware provided as object with 'resolve' method
resolver_func = getattr(middleware, "resolve", None)
if resolver_func is not None:
yield resolver_func | python | def get_middleware_resolvers(middlewares: Tuple[Any, ...]) -> Iterator[Callable]:
for middleware in middlewares:
if isfunction(middleware):
yield middleware
else: # middleware provided as object with 'resolve' method
resolver_func = getattr(middleware, "resolve", None)
if resolver_func is not None:
yield resolver_func | [
"def",
"get_middleware_resolvers",
"(",
"middlewares",
":",
"Tuple",
"[",
"Any",
",",
"...",
"]",
")",
"->",
"Iterator",
"[",
"Callable",
"]",
":",
"for",
"middleware",
"in",
"middlewares",
":",
"if",
"isfunction",
"(",
"middleware",
")",
":",
"yield",
"mi... | Get a list of resolver functions from a list of classes or functions. | [
"Get",
"a",
"list",
"of",
"resolver",
"functions",
"from",
"a",
"list",
"of",
"classes",
"or",
"functions",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/middleware.py#L54-L62 |
226,213 | graphql-python/graphql-core-next | graphql/execution/middleware.py | MiddlewareManager.get_field_resolver | def get_field_resolver(
self, field_resolver: GraphQLFieldResolver
) -> GraphQLFieldResolver:
"""Wrap the provided resolver with the middleware.
Returns a function that chains the middleware functions with the provided
resolver function.
"""
if self._middleware_resolvers is None:
return field_resolver
if field_resolver not in self._cached_resolvers:
self._cached_resolvers[field_resolver] = reduce(
lambda chained_fns, next_fn: partial(next_fn, chained_fns),
self._middleware_resolvers,
field_resolver,
)
return self._cached_resolvers[field_resolver] | python | def get_field_resolver(
self, field_resolver: GraphQLFieldResolver
) -> GraphQLFieldResolver:
if self._middleware_resolvers is None:
return field_resolver
if field_resolver not in self._cached_resolvers:
self._cached_resolvers[field_resolver] = reduce(
lambda chained_fns, next_fn: partial(next_fn, chained_fns),
self._middleware_resolvers,
field_resolver,
)
return self._cached_resolvers[field_resolver] | [
"def",
"get_field_resolver",
"(",
"self",
",",
"field_resolver",
":",
"GraphQLFieldResolver",
")",
"->",
"GraphQLFieldResolver",
":",
"if",
"self",
".",
"_middleware_resolvers",
"is",
"None",
":",
"return",
"field_resolver",
"if",
"field_resolver",
"not",
"in",
"sel... | Wrap the provided resolver with the middleware.
Returns a function that chains the middleware functions with the provided
resolver function. | [
"Wrap",
"the",
"provided",
"resolver",
"with",
"the",
"middleware",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/execution/middleware.py#L35-L51 |
226,214 | graphql-python/graphql-core-next | graphql/type/schema.py | type_map_reducer | def type_map_reducer(map_: TypeMap, type_: GraphQLNamedType = None) -> TypeMap:
"""Reducer function for creating the type map from given types."""
if not type_:
return map_
if is_wrapping_type(type_):
return type_map_reducer(
map_, cast(GraphQLWrappingType[GraphQLNamedType], type_).of_type
)
name = type_.name
if name in map_:
if map_[name] is not type_:
raise TypeError(
"Schema must contain uniquely named types but contains multiple"
f" types named {name!r}."
)
return map_
map_[name] = type_
if is_union_type(type_):
type_ = cast(GraphQLUnionType, type_)
map_ = type_map_reduce(type_.types, map_)
if is_object_type(type_):
type_ = cast(GraphQLObjectType, type_)
map_ = type_map_reduce(type_.interfaces, map_)
if is_object_type(type_) or is_interface_type(type_):
for field in cast(GraphQLInterfaceType, type_).fields.values():
args = field.args
if args:
types = [arg.type for arg in args.values()]
map_ = type_map_reduce(types, map_)
map_ = type_map_reducer(map_, field.type)
if is_input_object_type(type_):
for field in cast(GraphQLInputObjectType, type_).fields.values():
map_ = type_map_reducer(map_, field.type)
return map_ | python | def type_map_reducer(map_: TypeMap, type_: GraphQLNamedType = None) -> TypeMap:
if not type_:
return map_
if is_wrapping_type(type_):
return type_map_reducer(
map_, cast(GraphQLWrappingType[GraphQLNamedType], type_).of_type
)
name = type_.name
if name in map_:
if map_[name] is not type_:
raise TypeError(
"Schema must contain uniquely named types but contains multiple"
f" types named {name!r}."
)
return map_
map_[name] = type_
if is_union_type(type_):
type_ = cast(GraphQLUnionType, type_)
map_ = type_map_reduce(type_.types, map_)
if is_object_type(type_):
type_ = cast(GraphQLObjectType, type_)
map_ = type_map_reduce(type_.interfaces, map_)
if is_object_type(type_) or is_interface_type(type_):
for field in cast(GraphQLInterfaceType, type_).fields.values():
args = field.args
if args:
types = [arg.type for arg in args.values()]
map_ = type_map_reduce(types, map_)
map_ = type_map_reducer(map_, field.type)
if is_input_object_type(type_):
for field in cast(GraphQLInputObjectType, type_).fields.values():
map_ = type_map_reducer(map_, field.type)
return map_ | [
"def",
"type_map_reducer",
"(",
"map_",
":",
"TypeMap",
",",
"type_",
":",
"GraphQLNamedType",
"=",
"None",
")",
"->",
"TypeMap",
":",
"if",
"not",
"type_",
":",
"return",
"map_",
"if",
"is_wrapping_type",
"(",
"type_",
")",
":",
"return",
"type_map_reducer"... | Reducer function for creating the type map from given types. | [
"Reducer",
"function",
"for",
"creating",
"the",
"type",
"map",
"from",
"given",
"types",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/schema.py#L223-L261 |
226,215 | graphql-python/graphql-core-next | graphql/type/schema.py | type_map_directive_reducer | def type_map_directive_reducer(
map_: TypeMap, directive: GraphQLDirective = None
) -> TypeMap:
"""Reducer function for creating the type map from given directives."""
# Directives are not validated until validate_schema() is called.
if not is_directive(directive):
return map_
directive = cast(GraphQLDirective, directive)
return reduce(
lambda prev_map, arg: type_map_reducer(prev_map, arg.type), # type: ignore
directive.args.values(),
map_,
) | python | def type_map_directive_reducer(
map_: TypeMap, directive: GraphQLDirective = None
) -> TypeMap:
# Directives are not validated until validate_schema() is called.
if not is_directive(directive):
return map_
directive = cast(GraphQLDirective, directive)
return reduce(
lambda prev_map, arg: type_map_reducer(prev_map, arg.type), # type: ignore
directive.args.values(),
map_,
) | [
"def",
"type_map_directive_reducer",
"(",
"map_",
":",
"TypeMap",
",",
"directive",
":",
"GraphQLDirective",
"=",
"None",
")",
"->",
"TypeMap",
":",
"# Directives are not validated until validate_schema() is called.",
"if",
"not",
"is_directive",
"(",
"directive",
")",
... | Reducer function for creating the type map from given directives. | [
"Reducer",
"function",
"for",
"creating",
"the",
"type",
"map",
"from",
"given",
"directives",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/schema.py#L264-L276 |
226,216 | graphql-python/graphql-core-next | graphql/type/schema.py | GraphQLSchema.get_possible_types | def get_possible_types(
self, abstract_type: GraphQLAbstractType
) -> Sequence[GraphQLObjectType]:
"""Get list of all possible concrete types for given abstract type."""
if is_union_type(abstract_type):
abstract_type = cast(GraphQLUnionType, abstract_type)
return abstract_type.types
return self._implementations[abstract_type.name] | python | def get_possible_types(
self, abstract_type: GraphQLAbstractType
) -> Sequence[GraphQLObjectType]:
if is_union_type(abstract_type):
abstract_type = cast(GraphQLUnionType, abstract_type)
return abstract_type.types
return self._implementations[abstract_type.name] | [
"def",
"get_possible_types",
"(",
"self",
",",
"abstract_type",
":",
"GraphQLAbstractType",
")",
"->",
"Sequence",
"[",
"GraphQLObjectType",
"]",
":",
"if",
"is_union_type",
"(",
"abstract_type",
")",
":",
"abstract_type",
"=",
"cast",
"(",
"GraphQLUnionType",
","... | Get list of all possible concrete types for given abstract type. | [
"Get",
"list",
"of",
"all",
"possible",
"concrete",
"types",
"for",
"given",
"abstract",
"type",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/schema.py#L179-L186 |
226,217 | graphql-python/graphql-core-next | graphql/type/schema.py | GraphQLSchema.is_possible_type | def is_possible_type(
self, abstract_type: GraphQLAbstractType, possible_type: GraphQLObjectType
) -> bool:
"""Check whether a concrete type is possible for an abstract type."""
possible_type_map = self._possible_type_map
try:
possible_type_names = possible_type_map[abstract_type.name]
except KeyError:
possible_types = self.get_possible_types(abstract_type)
possible_type_names = {type_.name for type_ in possible_types}
possible_type_map[abstract_type.name] = possible_type_names
return possible_type.name in possible_type_names | python | def is_possible_type(
self, abstract_type: GraphQLAbstractType, possible_type: GraphQLObjectType
) -> bool:
possible_type_map = self._possible_type_map
try:
possible_type_names = possible_type_map[abstract_type.name]
except KeyError:
possible_types = self.get_possible_types(abstract_type)
possible_type_names = {type_.name for type_ in possible_types}
possible_type_map[abstract_type.name] = possible_type_names
return possible_type.name in possible_type_names | [
"def",
"is_possible_type",
"(",
"self",
",",
"abstract_type",
":",
"GraphQLAbstractType",
",",
"possible_type",
":",
"GraphQLObjectType",
")",
"->",
"bool",
":",
"possible_type_map",
"=",
"self",
".",
"_possible_type_map",
"try",
":",
"possible_type_names",
"=",
"po... | Check whether a concrete type is possible for an abstract type. | [
"Check",
"whether",
"a",
"concrete",
"type",
"is",
"possible",
"for",
"an",
"abstract",
"type",
"."
] | 073dce3f002f897d40f9348ffd8f107815160540 | https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/type/schema.py#L188-L199 |
226,218 | vsjha18/nsetools | utils.py | byte_adaptor | def byte_adaptor(fbuffer):
""" provides py3 compatibility by converting byte based
file stream to string based file stream
Arguments:
fbuffer: file like objects containing bytes
Returns:
string buffer
"""
if six.PY3:
strings = fbuffer.read().decode('latin-1')
fbuffer = six.StringIO(strings)
return fbuffer
else:
return fbuffer | python | def byte_adaptor(fbuffer):
if six.PY3:
strings = fbuffer.read().decode('latin-1')
fbuffer = six.StringIO(strings)
return fbuffer
else:
return fbuffer | [
"def",
"byte_adaptor",
"(",
"fbuffer",
")",
":",
"if",
"six",
".",
"PY3",
":",
"strings",
"=",
"fbuffer",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'latin-1'",
")",
"fbuffer",
"=",
"six",
".",
"StringIO",
"(",
"strings",
")",
"return",
"fbuffer",
"... | provides py3 compatibility by converting byte based
file stream to string based file stream
Arguments:
fbuffer: file like objects containing bytes
Returns:
string buffer | [
"provides",
"py3",
"compatibility",
"by",
"converting",
"byte",
"based",
"file",
"stream",
"to",
"string",
"based",
"file",
"stream"
] | c306b568471701c19195d2f17e112cc92022d3e0 | https://github.com/vsjha18/nsetools/blob/c306b568471701c19195d2f17e112cc92022d3e0/utils.py#L29-L44 |
226,219 | vsjha18/nsetools | utils.py | js_adaptor | def js_adaptor(buffer):
""" convert javascript objects like true, none, NaN etc. to
quoted word.
Arguments:
buffer: string to be converted
Returns:
string after conversion
"""
buffer = re.sub('true', 'True', buffer)
buffer = re.sub('false', 'False', buffer)
buffer = re.sub('none', 'None', buffer)
buffer = re.sub('NaN', '"NaN"', buffer)
return buffer | python | def js_adaptor(buffer):
buffer = re.sub('true', 'True', buffer)
buffer = re.sub('false', 'False', buffer)
buffer = re.sub('none', 'None', buffer)
buffer = re.sub('NaN', '"NaN"', buffer)
return buffer | [
"def",
"js_adaptor",
"(",
"buffer",
")",
":",
"buffer",
"=",
"re",
".",
"sub",
"(",
"'true'",
",",
"'True'",
",",
"buffer",
")",
"buffer",
"=",
"re",
".",
"sub",
"(",
"'false'",
",",
"'False'",
",",
"buffer",
")",
"buffer",
"=",
"re",
".",
"sub",
... | convert javascript objects like true, none, NaN etc. to
quoted word.
Arguments:
buffer: string to be converted
Returns:
string after conversion | [
"convert",
"javascript",
"objects",
"like",
"true",
"none",
"NaN",
"etc",
".",
"to",
"quoted",
"word",
"."
] | c306b568471701c19195d2f17e112cc92022d3e0 | https://github.com/vsjha18/nsetools/blob/c306b568471701c19195d2f17e112cc92022d3e0/utils.py#L47-L61 |
226,220 | vsjha18/nsetools | nse.py | Nse.get_bhavcopy_url | def get_bhavcopy_url(self, d):
"""take date and return bhavcopy url"""
d = parser.parse(d).date()
day_of_month = d.strftime("%d")
mon = d.strftime("%b").upper()
year = d.year
url = self.bhavcopy_base_url % (year, mon, day_of_month, mon, year)
return url | python | def get_bhavcopy_url(self, d):
d = parser.parse(d).date()
day_of_month = d.strftime("%d")
mon = d.strftime("%b").upper()
year = d.year
url = self.bhavcopy_base_url % (year, mon, day_of_month, mon, year)
return url | [
"def",
"get_bhavcopy_url",
"(",
"self",
",",
"d",
")",
":",
"d",
"=",
"parser",
".",
"parse",
"(",
"d",
")",
".",
"date",
"(",
")",
"day_of_month",
"=",
"d",
".",
"strftime",
"(",
"\"%d\"",
")",
"mon",
"=",
"d",
".",
"strftime",
"(",
"\"%b\"",
")... | take date and return bhavcopy url | [
"take",
"date",
"and",
"return",
"bhavcopy",
"url"
] | c306b568471701c19195d2f17e112cc92022d3e0 | https://github.com/vsjha18/nsetools/blob/c306b568471701c19195d2f17e112cc92022d3e0/nse.py#L417-L424 |
226,221 | vsjha18/nsetools | nse.py | Nse.download_bhavcopy | def download_bhavcopy(self, d):
"""returns bhavcopy as csv file."""
# ex_url = "https://www.nseindia.com/content/historical/EQUITIES/2011/NOV/cm08NOV2011bhav.csv.zip"
url = self.get_bhavcopy_url(d)
filename = self.get_bhavcopy_filename(d)
# response = requests.get(url, headers=self.headers)
response = self.opener.open(Request(url, None, self.headers))
zip_file_handle = io.BytesIO(response.read())
zf = zipfile.ZipFile(zip_file_handle)
try:
result = zf.read(filename)
except KeyError:
result = zf.read(zf.filelist[0].filename)
return result | python | def download_bhavcopy(self, d):
# ex_url = "https://www.nseindia.com/content/historical/EQUITIES/2011/NOV/cm08NOV2011bhav.csv.zip"
url = self.get_bhavcopy_url(d)
filename = self.get_bhavcopy_filename(d)
# response = requests.get(url, headers=self.headers)
response = self.opener.open(Request(url, None, self.headers))
zip_file_handle = io.BytesIO(response.read())
zf = zipfile.ZipFile(zip_file_handle)
try:
result = zf.read(filename)
except KeyError:
result = zf.read(zf.filelist[0].filename)
return result | [
"def",
"download_bhavcopy",
"(",
"self",
",",
"d",
")",
":",
"# ex_url = \"https://www.nseindia.com/content/historical/EQUITIES/2011/NOV/cm08NOV2011bhav.csv.zip\"",
"url",
"=",
"self",
".",
"get_bhavcopy_url",
"(",
"d",
")",
"filename",
"=",
"self",
".",
"get_bhavcopy_filen... | returns bhavcopy as csv file. | [
"returns",
"bhavcopy",
"as",
"csv",
"file",
"."
] | c306b568471701c19195d2f17e112cc92022d3e0 | https://github.com/vsjha18/nsetools/blob/c306b568471701c19195d2f17e112cc92022d3e0/nse.py#L434-L448 |
226,222 | cloudera/impyla | impala/interface.py | _replace_numeric_markers | def _replace_numeric_markers(operation, string_parameters):
"""
Replaces qname, format, and numeric markers in the given operation, from
the string_parameters list.
Raises ProgrammingError on wrong number of parameters or bindings
when using qmark. There is no error checking on numeric parameters.
"""
def replace_markers(marker, op, parameters):
param_count = len(parameters)
marker_index = 0
start_offset = 0
while True:
found_offset = op.find(marker, start_offset)
if not found_offset > -1:
break
if marker_index < param_count:
op = op[:found_offset]+op[found_offset:].replace(marker, parameters[marker_index], 1)
start_offset = found_offset + len(parameters[marker_index])
marker_index += 1
else:
raise ProgrammingError("Incorrect number of bindings "
"supplied. The current statement uses "
"%d or more, and there are %d "
"supplied." % (marker_index + 1,
param_count))
if marker_index != 0 and marker_index != param_count:
raise ProgrammingError("Incorrect number of bindings "
"supplied. The current statement uses "
"%d or more, and there are %d supplied." %
(marker_index + 1, param_count))
return op
# replace qmark parameters and format parameters
operation = replace_markers('?', operation, string_parameters)
operation = replace_markers(r'%s', operation, string_parameters)
# replace numbered parameters
# Go through them backwards so smaller numbers don't replace
# parts of larger ones
for index in range(len(string_parameters), 0, -1):
operation = operation.replace(':' + str(index),
string_parameters[index - 1])
return operation | python | def _replace_numeric_markers(operation, string_parameters):
def replace_markers(marker, op, parameters):
param_count = len(parameters)
marker_index = 0
start_offset = 0
while True:
found_offset = op.find(marker, start_offset)
if not found_offset > -1:
break
if marker_index < param_count:
op = op[:found_offset]+op[found_offset:].replace(marker, parameters[marker_index], 1)
start_offset = found_offset + len(parameters[marker_index])
marker_index += 1
else:
raise ProgrammingError("Incorrect number of bindings "
"supplied. The current statement uses "
"%d or more, and there are %d "
"supplied." % (marker_index + 1,
param_count))
if marker_index != 0 and marker_index != param_count:
raise ProgrammingError("Incorrect number of bindings "
"supplied. The current statement uses "
"%d or more, and there are %d supplied." %
(marker_index + 1, param_count))
return op
# replace qmark parameters and format parameters
operation = replace_markers('?', operation, string_parameters)
operation = replace_markers(r'%s', operation, string_parameters)
# replace numbered parameters
# Go through them backwards so smaller numbers don't replace
# parts of larger ones
for index in range(len(string_parameters), 0, -1):
operation = operation.replace(':' + str(index),
string_parameters[index - 1])
return operation | [
"def",
"_replace_numeric_markers",
"(",
"operation",
",",
"string_parameters",
")",
":",
"def",
"replace_markers",
"(",
"marker",
",",
"op",
",",
"parameters",
")",
":",
"param_count",
"=",
"len",
"(",
"parameters",
")",
"marker_index",
"=",
"0",
"start_offset",... | Replaces qname, format, and numeric markers in the given operation, from
the string_parameters list.
Raises ProgrammingError on wrong number of parameters or bindings
when using qmark. There is no error checking on numeric parameters. | [
"Replaces",
"qname",
"format",
"and",
"numeric",
"markers",
"in",
"the",
"given",
"operation",
"from",
"the",
"string_parameters",
"list",
"."
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/interface.py#L183-L226 |
226,223 | cloudera/impyla | impala/hiveserver2.py | HiveServer2Cursor.execute | def execute(self, operation, parameters=None, configuration=None):
"""Synchronously execute a SQL query.
Blocks until results are available.
Parameters
----------
operation : str
The SQL query to execute.
parameters : str, optional
Parameters to be bound to variables in the SQL query, if any.
Impyla supports all DB API `paramstyle`s, including `qmark`,
`numeric`, `named`, `format`, `pyformat`.
configuration : dict of str keys and values, optional
Configuration overlay for this query.
Returns
-------
NoneType
Results are available through a call to `fetch*`.
"""
# PEP 249
self.execute_async(operation, parameters=parameters,
configuration=configuration)
log.debug('Waiting for query to finish')
self._wait_to_finish() # make execute synchronous
log.debug('Query finished') | python | def execute(self, operation, parameters=None, configuration=None):
# PEP 249
self.execute_async(operation, parameters=parameters,
configuration=configuration)
log.debug('Waiting for query to finish')
self._wait_to_finish() # make execute synchronous
log.debug('Query finished') | [
"def",
"execute",
"(",
"self",
",",
"operation",
",",
"parameters",
"=",
"None",
",",
"configuration",
"=",
"None",
")",
":",
"# PEP 249",
"self",
".",
"execute_async",
"(",
"operation",
",",
"parameters",
"=",
"parameters",
",",
"configuration",
"=",
"confi... | Synchronously execute a SQL query.
Blocks until results are available.
Parameters
----------
operation : str
The SQL query to execute.
parameters : str, optional
Parameters to be bound to variables in the SQL query, if any.
Impyla supports all DB API `paramstyle`s, including `qmark`,
`numeric`, `named`, `format`, `pyformat`.
configuration : dict of str keys and values, optional
Configuration overlay for this query.
Returns
-------
NoneType
Results are available through a call to `fetch*`. | [
"Synchronously",
"execute",
"a",
"SQL",
"query",
"."
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/hiveserver2.py#L287-L313 |
226,224 | cloudera/impyla | impala/hiveserver2.py | HiveServer2Cursor.execute_async | def execute_async(self, operation, parameters=None, configuration=None):
"""Asynchronously execute a SQL query.
Immediately returns after query is sent to the HS2 server. Poll with
`is_executing`. A call to `fetch*` will block.
Parameters
----------
operation : str
The SQL query to execute.
parameters : str, optional
Parameters to be bound to variables in the SQL query, if any.
Impyla supports all DB API `paramstyle`s, including `qmark`,
`numeric`, `named`, `format`, `pyformat`.
configuration : dict of str keys and values, optional
Configuration overlay for this query.
Returns
-------
NoneType
Results are available through a call to `fetch*`.
"""
log.debug('Executing query %s', operation)
def op():
if parameters:
self._last_operation_string = _bind_parameters(operation,
parameters)
else:
self._last_operation_string = operation
op = self.session.execute(self._last_operation_string,
configuration,
run_async=True)
self._last_operation = op
self._execute_async(op) | python | def execute_async(self, operation, parameters=None, configuration=None):
log.debug('Executing query %s', operation)
def op():
if parameters:
self._last_operation_string = _bind_parameters(operation,
parameters)
else:
self._last_operation_string = operation
op = self.session.execute(self._last_operation_string,
configuration,
run_async=True)
self._last_operation = op
self._execute_async(op) | [
"def",
"execute_async",
"(",
"self",
",",
"operation",
",",
"parameters",
"=",
"None",
",",
"configuration",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Executing query %s'",
",",
"operation",
")",
"def",
"op",
"(",
")",
":",
"if",
"parameters",
"... | Asynchronously execute a SQL query.
Immediately returns after query is sent to the HS2 server. Poll with
`is_executing`. A call to `fetch*` will block.
Parameters
----------
operation : str
The SQL query to execute.
parameters : str, optional
Parameters to be bound to variables in the SQL query, if any.
Impyla supports all DB API `paramstyle`s, including `qmark`,
`numeric`, `named`, `format`, `pyformat`.
configuration : dict of str keys and values, optional
Configuration overlay for this query.
Returns
-------
NoneType
Results are available through a call to `fetch*`. | [
"Asynchronously",
"execute",
"a",
"SQL",
"query",
"."
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/hiveserver2.py#L315-L351 |
226,225 | cloudera/impyla | impala/hiveserver2.py | HiveServer2Cursor._get_sleep_interval | def _get_sleep_interval(self, start_time):
"""Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s"""
elapsed = time.time() - start_time
if elapsed < 0.05:
return 0.01
elif elapsed < 1.0:
return 0.05
elif elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
return 0.5
return 1.0 | python | def _get_sleep_interval(self, start_time):
elapsed = time.time() - start_time
if elapsed < 0.05:
return 0.01
elif elapsed < 1.0:
return 0.05
elif elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
return 0.5
return 1.0 | [
"def",
"_get_sleep_interval",
"(",
"self",
",",
"start_time",
")",
":",
"elapsed",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"if",
"elapsed",
"<",
"0.05",
":",
"return",
"0.01",
"elif",
"elapsed",
"<",
"1.0",
":",
"return",
"0.05",
"elif",
... | Returns a step function of time to sleep in seconds before polling
again. Maximum sleep is 1s, minimum is 0.1s | [
"Returns",
"a",
"step",
"function",
"of",
"time",
"to",
"sleep",
"in",
"seconds",
"before",
"polling",
"again",
".",
"Maximum",
"sleep",
"is",
"1s",
"minimum",
"is",
"0",
".",
"1s"
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/hiveserver2.py#L423-L435 |
226,226 | cloudera/impyla | impala/hiveserver2.py | HiveServer2Cursor.fetchcbatch | def fetchcbatch(self):
'''Return a CBatch object of any data currently in the buffer or
if no data currently in buffer then fetch a batch'''
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fetching")
if not self.has_result_set:
raise ProgrammingError(
"Trying to fetch results on an operation with no results.")
if len(self._buffer) > 0:
log.debug('fetchcbatch: buffer has data in. Returning it and wiping buffer')
batch = self._buffer
self._buffer = Batch()
return batch
elif self._last_operation_active:
log.debug('fetchcbatch: buffer empty and op is active => fetching '
'more data')
batch = (self._last_operation.fetch(
self.description,
self.buffersize,
convert_types=self.convert_types))
if len(batch) == 0:
return None
return batch
else:
return None | python | def fetchcbatch(self):
'''Return a CBatch object of any data currently in the buffer or
if no data currently in buffer then fetch a batch'''
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fetching")
if not self.has_result_set:
raise ProgrammingError(
"Trying to fetch results on an operation with no results.")
if len(self._buffer) > 0:
log.debug('fetchcbatch: buffer has data in. Returning it and wiping buffer')
batch = self._buffer
self._buffer = Batch()
return batch
elif self._last_operation_active:
log.debug('fetchcbatch: buffer empty and op is active => fetching '
'more data')
batch = (self._last_operation.fetch(
self.description,
self.buffersize,
convert_types=self.convert_types))
if len(batch) == 0:
return None
return batch
else:
return None | [
"def",
"fetchcbatch",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_last_operation",
".",
"is_columnar",
":",
"raise",
"NotSupportedError",
"(",
"\"Server does not support columnar \"",
"\"fetching\"",
")",
"if",
"not",
"self",
".",
"has_result_set",
":",
"ra... | Return a CBatch object of any data currently in the buffer or
if no data currently in buffer then fetch a batch | [
"Return",
"a",
"CBatch",
"object",
"of",
"any",
"data",
"currently",
"in",
"the",
"buffer",
"or",
"if",
"no",
"data",
"currently",
"in",
"buffer",
"then",
"fetch",
"a",
"batch"
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/hiveserver2.py#L458-L483 |
226,227 | cloudera/impyla | impala/hiveserver2.py | HiveServer2Cursor.fetchcolumnar | def fetchcolumnar(self):
"""Executes a fetchall operation returning a list of CBatches"""
self._wait_to_finish()
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fetching")
batches = []
while True:
batch = (self._last_operation.fetch(
self.description,
self.buffersize,
convert_types=self.convert_types))
if len(batch) == 0:
break
batches.append(batch)
return batches | python | def fetchcolumnar(self):
self._wait_to_finish()
if not self._last_operation.is_columnar:
raise NotSupportedError("Server does not support columnar "
"fetching")
batches = []
while True:
batch = (self._last_operation.fetch(
self.description,
self.buffersize,
convert_types=self.convert_types))
if len(batch) == 0:
break
batches.append(batch)
return batches | [
"def",
"fetchcolumnar",
"(",
"self",
")",
":",
"self",
".",
"_wait_to_finish",
"(",
")",
"if",
"not",
"self",
".",
"_last_operation",
".",
"is_columnar",
":",
"raise",
"NotSupportedError",
"(",
"\"Server does not support columnar \"",
"\"fetching\"",
")",
"batches",... | Executes a fetchall operation returning a list of CBatches | [
"Executes",
"a",
"fetchall",
"operation",
"returning",
"a",
"list",
"of",
"CBatches"
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/hiveserver2.py#L513-L528 |
226,228 | cloudera/impyla | impala/_thrift_gen/fb303/FacebookService.py | Client.setOption | def setOption(self, key, value):
"""
Sets an option
Parameters:
- key
- value
"""
self.send_setOption(key, value)
self.recv_setOption() | python | def setOption(self, key, value):
self.send_setOption(key, value)
self.recv_setOption() | [
"def",
"setOption",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"send_setOption",
"(",
"key",
",",
"value",
")",
"self",
".",
"recv_setOption",
"(",
")"
] | Sets an option
Parameters:
- key
- value | [
"Sets",
"an",
"option"
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/fb303/FacebookService.py#L308-L317 |
226,229 | cloudera/impyla | impala/_thrift_gen/beeswax/BeeswaxService.py | Client.fetch | def fetch(self, query_id, start_over, fetch_size):
"""
Get the results of a query. This is non-blocking. Caller should check
Results.ready to determine if the results are in yet. The call requests
the batch size of fetch.
Parameters:
- query_id
- start_over
- fetch_size
"""
self.send_fetch(query_id, start_over, fetch_size)
return self.recv_fetch() | python | def fetch(self, query_id, start_over, fetch_size):
self.send_fetch(query_id, start_over, fetch_size)
return self.recv_fetch() | [
"def",
"fetch",
"(",
"self",
",",
"query_id",
",",
"start_over",
",",
"fetch_size",
")",
":",
"self",
".",
"send_fetch",
"(",
"query_id",
",",
"start_over",
",",
"fetch_size",
")",
"return",
"self",
".",
"recv_fetch",
"(",
")"
] | Get the results of a query. This is non-blocking. Caller should check
Results.ready to determine if the results are in yet. The call requests
the batch size of fetch.
Parameters:
- query_id
- start_over
- fetch_size | [
"Get",
"the",
"results",
"of",
"a",
"query",
".",
"This",
"is",
"non",
"-",
"blocking",
".",
"Caller",
"should",
"check",
"Results",
".",
"ready",
"to",
"determine",
"if",
"the",
"results",
"are",
"in",
"yet",
".",
"The",
"call",
"requests",
"the",
"ba... | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/beeswax/BeeswaxService.py#L242-L254 |
226,230 | cloudera/impyla | impala/sqlalchemy.py | ImpalaDDLCompiler.post_create_table | def post_create_table(self, table):
"""Build table-level CREATE options."""
table_opts = []
if 'impala_partition_by' in table.kwargs:
table_opts.append('PARTITION BY %s' % table.kwargs.get('impala_partition_by'))
if 'impala_stored_as' in table.kwargs:
table_opts.append('STORED AS %s' % table.kwargs.get('impala_stored_as'))
if 'impala_table_properties' in table.kwargs:
table_properties = ["'{0}' = '{1}'".format(property_, value)
for property_, value
in table.kwargs.get('impala_table_properties', {}).items()]
table_opts.append('TBLPROPERTIES (%s)' % ', '.join(table_properties))
return '\n%s' % '\n'.join(table_opts) | python | def post_create_table(self, table):
table_opts = []
if 'impala_partition_by' in table.kwargs:
table_opts.append('PARTITION BY %s' % table.kwargs.get('impala_partition_by'))
if 'impala_stored_as' in table.kwargs:
table_opts.append('STORED AS %s' % table.kwargs.get('impala_stored_as'))
if 'impala_table_properties' in table.kwargs:
table_properties = ["'{0}' = '{1}'".format(property_, value)
for property_, value
in table.kwargs.get('impala_table_properties', {}).items()]
table_opts.append('TBLPROPERTIES (%s)' % ', '.join(table_properties))
return '\n%s' % '\n'.join(table_opts) | [
"def",
"post_create_table",
"(",
"self",
",",
"table",
")",
":",
"table_opts",
"=",
"[",
"]",
"if",
"'impala_partition_by'",
"in",
"table",
".",
"kwargs",
":",
"table_opts",
".",
"append",
"(",
"'PARTITION BY %s'",
"%",
"table",
".",
"kwargs",
".",
"get",
... | Build table-level CREATE options. | [
"Build",
"table",
"-",
"level",
"CREATE",
"options",
"."
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/sqlalchemy.py#L50-L66 |
226,231 | cloudera/impyla | impala/util.py | _get_table_schema_hack | def _get_table_schema_hack(cursor, table):
"""Get the schema of table by talking to Impala
table must be a string (incl possible db name)
"""
# get the schema of the query result via a LIMIT 0 hack
cursor.execute('SELECT * FROM %s LIMIT 0' % table)
schema = [tup[:2] for tup in cursor.description]
cursor.fetchall() # resets the state of the cursor and closes operation
return schema | python | def _get_table_schema_hack(cursor, table):
# get the schema of the query result via a LIMIT 0 hack
cursor.execute('SELECT * FROM %s LIMIT 0' % table)
schema = [tup[:2] for tup in cursor.description]
cursor.fetchall() # resets the state of the cursor and closes operation
return schema | [
"def",
"_get_table_schema_hack",
"(",
"cursor",
",",
"table",
")",
":",
"# get the schema of the query result via a LIMIT 0 hack",
"cursor",
".",
"execute",
"(",
"'SELECT * FROM %s LIMIT 0'",
"%",
"table",
")",
"schema",
"=",
"[",
"tup",
"[",
":",
"2",
"]",
"for",
... | Get the schema of table by talking to Impala
table must be a string (incl possible db name) | [
"Get",
"the",
"schema",
"of",
"table",
"by",
"talking",
"to",
"Impala"
] | 547fa2ba3b6151e2a98b3544301471a643212dc3 | https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/util.py#L71-L80 |
226,232 | justquick/django-activity-stream | actstream/views.py | respond | def respond(request, code):
"""
Responds to the request with the given response code.
If ``next`` is in the form, it will redirect instead.
"""
redirect = request.GET.get('next', request.POST.get('next'))
if redirect:
return HttpResponseRedirect(redirect)
return type('Response%d' % code, (HttpResponse, ), {'status_code': code})() | python | def respond(request, code):
redirect = request.GET.get('next', request.POST.get('next'))
if redirect:
return HttpResponseRedirect(redirect)
return type('Response%d' % code, (HttpResponse, ), {'status_code': code})() | [
"def",
"respond",
"(",
"request",
",",
"code",
")",
":",
"redirect",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'next'",
",",
"request",
".",
"POST",
".",
"get",
"(",
"'next'",
")",
")",
"if",
"redirect",
":",
"return",
"HttpResponseRedirect",
"(",
... | Responds to the request with the given response code.
If ``next`` is in the form, it will redirect instead. | [
"Responds",
"to",
"the",
"request",
"with",
"the",
"given",
"response",
"code",
".",
"If",
"next",
"is",
"in",
"the",
"form",
"it",
"will",
"redirect",
"instead",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/views.py#L15-L23 |
226,233 | justquick/django-activity-stream | actstream/views.py | follow_unfollow | def follow_unfollow(request, content_type_id, object_id, flag, do_follow=True, actor_only=True):
"""
Creates or deletes the follow relationship between ``request.user`` and the
actor defined by ``content_type_id``, ``object_id``.
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
instance = get_object_or_404(ctype.model_class(), pk=object_id)
# If flag was omitted in url, None will pass to flag keyword argument
flag = flag or ''
if do_follow:
actions.follow(request.user, instance, actor_only=actor_only, flag=flag)
return respond(request, 201) # CREATED
actions.unfollow(request.user, instance, flag=flag)
return respond(request, 204) | python | def follow_unfollow(request, content_type_id, object_id, flag, do_follow=True, actor_only=True):
ctype = get_object_or_404(ContentType, pk=content_type_id)
instance = get_object_or_404(ctype.model_class(), pk=object_id)
# If flag was omitted in url, None will pass to flag keyword argument
flag = flag or ''
if do_follow:
actions.follow(request.user, instance, actor_only=actor_only, flag=flag)
return respond(request, 201) # CREATED
actions.unfollow(request.user, instance, flag=flag)
return respond(request, 204) | [
"def",
"follow_unfollow",
"(",
"request",
",",
"content_type_id",
",",
"object_id",
",",
"flag",
",",
"do_follow",
"=",
"True",
",",
"actor_only",
"=",
"True",
")",
":",
"ctype",
"=",
"get_object_or_404",
"(",
"ContentType",
",",
"pk",
"=",
"content_type_id",
... | Creates or deletes the follow relationship between ``request.user`` and the
actor defined by ``content_type_id``, ``object_id``. | [
"Creates",
"or",
"deletes",
"the",
"follow",
"relationship",
"between",
"request",
".",
"user",
"and",
"the",
"actor",
"defined",
"by",
"content_type_id",
"object_id",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/views.py#L28-L44 |
226,234 | justquick/django-activity-stream | actstream/views.py | followers | def followers(request, content_type_id, object_id, flag):
"""
Creates a listing of ``User``s that follow the actor defined by
``content_type_id``, ``object_id``.
"""
ctype = get_object_or_404(ContentType, pk=content_type_id)
instance = get_object_or_404(ctype.model_class(), pk=object_id)
flag = flag or ''
return render(
request,
'actstream/followers.html',
{
'followers': models.followers(instance, flag=flag),
'actor': instance,
}
) | python | def followers(request, content_type_id, object_id, flag):
ctype = get_object_or_404(ContentType, pk=content_type_id)
instance = get_object_or_404(ctype.model_class(), pk=object_id)
flag = flag or ''
return render(
request,
'actstream/followers.html',
{
'followers': models.followers(instance, flag=flag),
'actor': instance,
}
) | [
"def",
"followers",
"(",
"request",
",",
"content_type_id",
",",
"object_id",
",",
"flag",
")",
":",
"ctype",
"=",
"get_object_or_404",
"(",
"ContentType",
",",
"pk",
"=",
"content_type_id",
")",
"instance",
"=",
"get_object_or_404",
"(",
"ctype",
".",
"model_... | Creates a listing of ``User``s that follow the actor defined by
``content_type_id``, ``object_id``. | [
"Creates",
"a",
"listing",
"of",
"User",
"s",
"that",
"follow",
"the",
"actor",
"defined",
"by",
"content_type_id",
"object_id",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/views.py#L65-L81 |
226,235 | justquick/django-activity-stream | actstream/managers.py | ActionManager.public | def public(self, *args, **kwargs):
"""
Only return public actions
"""
kwargs['public'] = True
return self.filter(*args, **kwargs) | python | def public(self, *args, **kwargs):
kwargs['public'] = True
return self.filter(*args, **kwargs) | [
"def",
"public",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'public'",
"]",
"=",
"True",
"return",
"self",
".",
"filter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Only return public actions | [
"Only",
"return",
"public",
"actions"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L16-L21 |
226,236 | justquick/django-activity-stream | actstream/managers.py | ActionManager.actor | def actor(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the actor.
Keyword arguments will be passed to Action.objects.filter
"""
check(obj)
return obj.actor_actions.public(**kwargs) | python | def actor(self, obj, **kwargs):
check(obj)
return obj.actor_actions.public(**kwargs) | [
"def",
"actor",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"(",
"obj",
")",
"return",
"obj",
".",
"actor_actions",
".",
"public",
"(",
"*",
"*",
"kwargs",
")"
] | Stream of most recent actions where obj is the actor.
Keyword arguments will be passed to Action.objects.filter | [
"Stream",
"of",
"most",
"recent",
"actions",
"where",
"obj",
"is",
"the",
"actor",
".",
"Keyword",
"arguments",
"will",
"be",
"passed",
"to",
"Action",
".",
"objects",
".",
"filter"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L24-L30 |
226,237 | justquick/django-activity-stream | actstream/managers.py | ActionManager.target | def target(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the target.
Keyword arguments will be passed to Action.objects.filter
"""
check(obj)
return obj.target_actions.public(**kwargs) | python | def target(self, obj, **kwargs):
check(obj)
return obj.target_actions.public(**kwargs) | [
"def",
"target",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"(",
"obj",
")",
"return",
"obj",
".",
"target_actions",
".",
"public",
"(",
"*",
"*",
"kwargs",
")"
] | Stream of most recent actions where obj is the target.
Keyword arguments will be passed to Action.objects.filter | [
"Stream",
"of",
"most",
"recent",
"actions",
"where",
"obj",
"is",
"the",
"target",
".",
"Keyword",
"arguments",
"will",
"be",
"passed",
"to",
"Action",
".",
"objects",
".",
"filter"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L33-L39 |
226,238 | justquick/django-activity-stream | actstream/managers.py | ActionManager.action_object | def action_object(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the action_object.
Keyword arguments will be passed to Action.objects.filter
"""
check(obj)
return obj.action_object_actions.public(**kwargs) | python | def action_object(self, obj, **kwargs):
check(obj)
return obj.action_object_actions.public(**kwargs) | [
"def",
"action_object",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"(",
"obj",
")",
"return",
"obj",
".",
"action_object_actions",
".",
"public",
"(",
"*",
"*",
"kwargs",
")"
] | Stream of most recent actions where obj is the action_object.
Keyword arguments will be passed to Action.objects.filter | [
"Stream",
"of",
"most",
"recent",
"actions",
"where",
"obj",
"is",
"the",
"action_object",
".",
"Keyword",
"arguments",
"will",
"be",
"passed",
"to",
"Action",
".",
"objects",
".",
"filter"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L42-L48 |
226,239 | justquick/django-activity-stream | actstream/managers.py | ActionManager.model_actions | def model_actions(self, model, **kwargs):
"""
Stream of most recent actions by any particular model
"""
check(model)
ctype = ContentType.objects.get_for_model(model)
return self.public(
(Q(target_content_type=ctype) |
Q(action_object_content_type=ctype) |
Q(actor_content_type=ctype)),
**kwargs
) | python | def model_actions(self, model, **kwargs):
check(model)
ctype = ContentType.objects.get_for_model(model)
return self.public(
(Q(target_content_type=ctype) |
Q(action_object_content_type=ctype) |
Q(actor_content_type=ctype)),
**kwargs
) | [
"def",
"model_actions",
"(",
"self",
",",
"model",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"(",
"model",
")",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"return",
"self",
".",
"public",
"(",
"(",
"Q",
"(... | Stream of most recent actions by any particular model | [
"Stream",
"of",
"most",
"recent",
"actions",
"by",
"any",
"particular",
"model"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L51-L62 |
226,240 | justquick/django-activity-stream | actstream/managers.py | ActionManager.any | def any(self, obj, **kwargs):
"""
Stream of most recent actions where obj is the actor OR target OR action_object.
"""
check(obj)
ctype = ContentType.objects.get_for_model(obj)
return self.public(
Q(
actor_content_type=ctype,
actor_object_id=obj.pk,
) | Q(
target_content_type=ctype,
target_object_id=obj.pk,
) | Q(
action_object_content_type=ctype,
action_object_object_id=obj.pk,
), **kwargs) | python | def any(self, obj, **kwargs):
check(obj)
ctype = ContentType.objects.get_for_model(obj)
return self.public(
Q(
actor_content_type=ctype,
actor_object_id=obj.pk,
) | Q(
target_content_type=ctype,
target_object_id=obj.pk,
) | Q(
action_object_content_type=ctype,
action_object_object_id=obj.pk,
), **kwargs) | [
"def",
"any",
"(",
"self",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"(",
"obj",
")",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"return",
"self",
".",
"public",
"(",
"Q",
"(",
"actor_content_typ... | Stream of most recent actions where obj is the actor OR target OR action_object. | [
"Stream",
"of",
"most",
"recent",
"actions",
"where",
"obj",
"is",
"the",
"actor",
"OR",
"target",
"OR",
"action_object",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L65-L81 |
226,241 | justquick/django-activity-stream | actstream/managers.py | ActionManager.user | def user(self, obj, with_user_activity=False, follow_flag=None, **kwargs):
"""Create a stream of the most recent actions by objects that the user is following."""
q = Q()
qs = self.public()
if not obj:
return qs.none()
check(obj)
if with_user_activity:
q = q | Q(
actor_content_type=ContentType.objects.get_for_model(obj),
actor_object_id=obj.pk
)
follows = apps.get_model('actstream', 'follow').objects.filter(user=obj)
if follow_flag:
follows = follows.filter(flag=follow_flag)
content_types = ContentType.objects.filter(
pk__in=follows.values('content_type_id')
)
if not (content_types.exists() or with_user_activity):
return qs.none()
for content_type in content_types:
object_ids = follows.filter(content_type=content_type)
q = q | Q(
actor_content_type=content_type,
actor_object_id__in=object_ids.values('object_id')
) | Q(
target_content_type=content_type,
target_object_id__in=object_ids.filter(
actor_only=False).values('object_id')
) | Q(
action_object_content_type=content_type,
action_object_object_id__in=object_ids.filter(
actor_only=False).values('object_id')
)
return qs.filter(q, **kwargs) | python | def user(self, obj, with_user_activity=False, follow_flag=None, **kwargs):
q = Q()
qs = self.public()
if not obj:
return qs.none()
check(obj)
if with_user_activity:
q = q | Q(
actor_content_type=ContentType.objects.get_for_model(obj),
actor_object_id=obj.pk
)
follows = apps.get_model('actstream', 'follow').objects.filter(user=obj)
if follow_flag:
follows = follows.filter(flag=follow_flag)
content_types = ContentType.objects.filter(
pk__in=follows.values('content_type_id')
)
if not (content_types.exists() or with_user_activity):
return qs.none()
for content_type in content_types:
object_ids = follows.filter(content_type=content_type)
q = q | Q(
actor_content_type=content_type,
actor_object_id__in=object_ids.values('object_id')
) | Q(
target_content_type=content_type,
target_object_id__in=object_ids.filter(
actor_only=False).values('object_id')
) | Q(
action_object_content_type=content_type,
action_object_object_id__in=object_ids.filter(
actor_only=False).values('object_id')
)
return qs.filter(q, **kwargs) | [
"def",
"user",
"(",
"self",
",",
"obj",
",",
"with_user_activity",
"=",
"False",
",",
"follow_flag",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"q",
"=",
"Q",
"(",
")",
"qs",
"=",
"self",
".",
"public",
"(",
")",
"if",
"not",
"obj",
":",
"... | Create a stream of the most recent actions by objects that the user is following. | [
"Create",
"a",
"stream",
"of",
"the",
"most",
"recent",
"actions",
"by",
"objects",
"that",
"the",
"user",
"is",
"following",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L84-L126 |
226,242 | justquick/django-activity-stream | actstream/managers.py | FollowManager.for_object | def for_object(self, instance, flag=''):
"""
Filter to a specific instance.
"""
check(instance)
content_type = ContentType.objects.get_for_model(instance).pk
queryset = self.filter(content_type=content_type, object_id=instance.pk)
if flag:
queryset = queryset.filter(flag=flag)
return queryset | python | def for_object(self, instance, flag=''):
check(instance)
content_type = ContentType.objects.get_for_model(instance).pk
queryset = self.filter(content_type=content_type, object_id=instance.pk)
if flag:
queryset = queryset.filter(flag=flag)
return queryset | [
"def",
"for_object",
"(",
"self",
",",
"instance",
",",
"flag",
"=",
"''",
")",
":",
"check",
"(",
"instance",
")",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"instance",
")",
".",
"pk",
"queryset",
"=",
"self",
".",
... | Filter to a specific instance. | [
"Filter",
"to",
"a",
"specific",
"instance",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L134-L143 |
226,243 | justquick/django-activity-stream | actstream/managers.py | FollowManager.is_following | def is_following(self, user, instance, flag=''):
"""
Check if a user is following an instance.
"""
if not user or user.is_anonymous:
return False
queryset = self.for_object(instance)
if flag:
queryset = queryset.filter(flag=flag)
return queryset.filter(user=user).exists() | python | def is_following(self, user, instance, flag=''):
if not user or user.is_anonymous:
return False
queryset = self.for_object(instance)
if flag:
queryset = queryset.filter(flag=flag)
return queryset.filter(user=user).exists() | [
"def",
"is_following",
"(",
"self",
",",
"user",
",",
"instance",
",",
"flag",
"=",
"''",
")",
":",
"if",
"not",
"user",
"or",
"user",
".",
"is_anonymous",
":",
"return",
"False",
"queryset",
"=",
"self",
".",
"for_object",
"(",
"instance",
")",
"if",
... | Check if a user is following an instance. | [
"Check",
"if",
"a",
"user",
"is",
"following",
"an",
"instance",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/managers.py#L145-L155 |
226,244 | justquick/django-activity-stream | actstream/registry.py | setup_generic_relations | def setup_generic_relations(model_class):
"""
Set up GenericRelations for actionable models.
"""
Action = apps.get_model('actstream', 'action')
if Action is None:
raise RegistrationError(
'Unable get actstream.Action. Potential circular imports '
'in initialisation. Try moving actstream app to come after the '
'apps which have models to register in the INSTALLED_APPS setting.'
)
related_attr_name = 'related_query_name'
related_attr_value = 'actions_with_%s' % label(model_class)
relations = {}
for field in ('actor', 'target', 'action_object'):
attr = '%s_actions' % field
attr_value = '%s_as_%s' % (related_attr_value, field)
kwargs = {
'content_type_field': '%s_content_type' % field,
'object_id_field': '%s_object_id' % field,
related_attr_name: attr_value
}
rel = GenericRelation('actstream.Action', **kwargs)
rel.contribute_to_class(model_class, attr)
relations[field] = rel
# @@@ I'm not entirely sure why this works
setattr(Action, attr_value, None)
return relations | python | def setup_generic_relations(model_class):
Action = apps.get_model('actstream', 'action')
if Action is None:
raise RegistrationError(
'Unable get actstream.Action. Potential circular imports '
'in initialisation. Try moving actstream app to come after the '
'apps which have models to register in the INSTALLED_APPS setting.'
)
related_attr_name = 'related_query_name'
related_attr_value = 'actions_with_%s' % label(model_class)
relations = {}
for field in ('actor', 'target', 'action_object'):
attr = '%s_actions' % field
attr_value = '%s_as_%s' % (related_attr_value, field)
kwargs = {
'content_type_field': '%s_content_type' % field,
'object_id_field': '%s_object_id' % field,
related_attr_name: attr_value
}
rel = GenericRelation('actstream.Action', **kwargs)
rel.contribute_to_class(model_class, attr)
relations[field] = rel
# @@@ I'm not entirely sure why this works
setattr(Action, attr_value, None)
return relations | [
"def",
"setup_generic_relations",
"(",
"model_class",
")",
":",
"Action",
"=",
"apps",
".",
"get_model",
"(",
"'actstream'",
",",
"'action'",
")",
"if",
"Action",
"is",
"None",
":",
"raise",
"RegistrationError",
"(",
"'Unable get actstream.Action. Potential circular i... | Set up GenericRelations for actionable models. | [
"Set",
"up",
"GenericRelations",
"for",
"actionable",
"models",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/registry.py#L15-L46 |
226,245 | justquick/django-activity-stream | actstream/decorators.py | stream | def stream(func):
"""
Stream decorator to be applied to methods of an ``ActionManager`` subclass
Syntax::
from actstream.decorators import stream
from actstream.managers import ActionManager
class MyManager(ActionManager):
@stream
def foobar(self, ...):
...
"""
@wraps(func)
def wrapped(manager, *args, **kwargs):
offset, limit = kwargs.pop('_offset', None), kwargs.pop('_limit', None)
qs = func(manager, *args, **kwargs)
if isinstance(qs, dict):
qs = manager.public(**qs)
elif isinstance(qs, (list, tuple)):
qs = manager.public(*qs)
if offset or limit:
qs = qs[offset:limit]
return qs.fetch_generic_relations()
return wrapped | python | def stream(func):
@wraps(func)
def wrapped(manager, *args, **kwargs):
offset, limit = kwargs.pop('_offset', None), kwargs.pop('_limit', None)
qs = func(manager, *args, **kwargs)
if isinstance(qs, dict):
qs = manager.public(**qs)
elif isinstance(qs, (list, tuple)):
qs = manager.public(*qs)
if offset or limit:
qs = qs[offset:limit]
return qs.fetch_generic_relations()
return wrapped | [
"def",
"stream",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"manager",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"offset",
",",
"limit",
"=",
"kwargs",
".",
"pop",
"(",
"'_offset'",
",",
"None",
")",
... | Stream decorator to be applied to methods of an ``ActionManager`` subclass
Syntax::
from actstream.decorators import stream
from actstream.managers import ActionManager
class MyManager(ActionManager):
@stream
def foobar(self, ...):
... | [
"Stream",
"decorator",
"to",
"be",
"applied",
"to",
"methods",
"of",
"an",
"ActionManager",
"subclass"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/decorators.py#L4-L30 |
226,246 | justquick/django-activity-stream | actstream/templatetags/activity_tags.py | follow_url | def follow_url(parser, token):
"""
Renders the URL of the follow view for a particular actor instance
::
<a href="{% follow_url other_user %}">
{% if request.user|is_following:other_user %}
stop following
{% else %}
follow
{% endif %}
</a>
<a href="{% follow_url other_user 'watching' %}">
{% is_following user group "watching" as is_watching %}
{% if is_watching %}
stop watching
{% else %}
watch
{% endif %}
</a>
"""
bits = token.split_contents()
if len(bits) > 3:
raise TemplateSyntaxError("Accepted format {% follow_url [instance] %} or {% follow_url [instance] [flag] %}")
elif len(bits) == 2:
return DisplayActivityFollowUrl(bits[1])
else:
flag = bits[2][1:-1]
return DisplayActivityFollowUrl(bits[1], flag=flag) | python | def follow_url(parser, token):
bits = token.split_contents()
if len(bits) > 3:
raise TemplateSyntaxError("Accepted format {% follow_url [instance] %} or {% follow_url [instance] [flag] %}")
elif len(bits) == 2:
return DisplayActivityFollowUrl(bits[1])
else:
flag = bits[2][1:-1]
return DisplayActivityFollowUrl(bits[1], flag=flag) | [
"def",
"follow_url",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">",
"3",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"Accepted format {% follow_url [instance] %} or {% follow_url [i... | Renders the URL of the follow view for a particular actor instance
::
<a href="{% follow_url other_user %}">
{% if request.user|is_following:other_user %}
stop following
{% else %}
follow
{% endif %}
</a>
<a href="{% follow_url other_user 'watching' %}">
{% is_following user group "watching" as is_watching %}
{% if is_watching %}
stop watching
{% else %}
watch
{% endif %}
</a> | [
"Renders",
"the",
"URL",
"of",
"the",
"follow",
"view",
"for",
"a",
"particular",
"actor",
"instance"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/templatetags/activity_tags.py#L157-L188 |
226,247 | justquick/django-activity-stream | actstream/templatetags/activity_tags.py | follow_all_url | def follow_all_url(parser, token):
"""
Renders the URL to follow an object as both actor and target
::
<a href="{% follow_all_url other_user %}">
{% if request.user|is_following:other_user %}
stop following
{% else %}
follow
{% endif %}
</a>
<a href="{% follow_all_url other_user 'watching' %}">
{% is_following user group "watching" as is_watching %}
{% if is_watching %}
stop watching
{% else %}
watch
{% endif %}
</a>
"""
bits = token.split_contents()
if len(bits) > 3:
raise TemplateSyntaxError(
"Accepted format {% follow_all_url [instance] %} or {% follow_url [instance] [flag] %}"
)
elif len(bits) == 2:
return DisplayActivityFollowUrl(bits[1], actor_only=False)
else:
flag = bits[2][1:-1]
return DisplayActivityFollowUrl(bits[1], actor_only=False, flag=flag) | python | def follow_all_url(parser, token):
bits = token.split_contents()
if len(bits) > 3:
raise TemplateSyntaxError(
"Accepted format {% follow_all_url [instance] %} or {% follow_url [instance] [flag] %}"
)
elif len(bits) == 2:
return DisplayActivityFollowUrl(bits[1], actor_only=False)
else:
flag = bits[2][1:-1]
return DisplayActivityFollowUrl(bits[1], actor_only=False, flag=flag) | [
"def",
"follow_all_url",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">",
"3",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"Accepted format {% follow_all_url [instance] %} or {% follo... | Renders the URL to follow an object as both actor and target
::
<a href="{% follow_all_url other_user %}">
{% if request.user|is_following:other_user %}
stop following
{% else %}
follow
{% endif %}
</a>
<a href="{% follow_all_url other_user 'watching' %}">
{% is_following user group "watching" as is_watching %}
{% if is_watching %}
stop watching
{% else %}
watch
{% endif %}
</a> | [
"Renders",
"the",
"URL",
"to",
"follow",
"an",
"object",
"as",
"both",
"actor",
"and",
"target"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/templatetags/activity_tags.py#L191-L223 |
226,248 | justquick/django-activity-stream | actstream/templatetags/activity_tags.py | actor_url | def actor_url(parser, token):
"""
Renders the URL for a particular actor instance
::
<a href="{% actor_url request.user %}">View your actions</a>
<a href="{% actor_url another_user %}">{{ another_user }}'s actions</a>
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("Accepted format "
"{% actor_url [actor_instance] %}")
else:
return DisplayActivityActorUrl(*bits[1:]) | python | def actor_url(parser, token):
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("Accepted format "
"{% actor_url [actor_instance] %}")
else:
return DisplayActivityActorUrl(*bits[1:]) | [
"def",
"actor_url",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"Accepted format \"",
"\"{% actor_url [actor_instance] %}\"",
... | Renders the URL for a particular actor instance
::
<a href="{% actor_url request.user %}">View your actions</a>
<a href="{% actor_url another_user %}">{{ another_user }}'s actions</a> | [
"Renders",
"the",
"URL",
"for",
"a",
"particular",
"actor",
"instance"
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/templatetags/activity_tags.py#L226-L241 |
226,249 | justquick/django-activity-stream | actstream/templatetags/activity_tags.py | AsNode.handle_token | def handle_token(cls, parser, token):
"""
Class method to parse and return a Node.
"""
tag_error = "Accepted formats {%% %(tagname)s %(args)s %%} or " \
"{%% %(tagname)s %(args)s as [var] %%}"
bits = token.split_contents()
args_count = len(bits) - 1
if args_count >= 2 and bits[-2] == 'as':
as_var = bits[-1]
args_count -= 2
else:
as_var = None
if args_count != cls.args_count:
arg_list = ' '.join(['[arg]' * cls.args_count])
raise TemplateSyntaxError(tag_error % {'tagname': bits[0],
'args': arg_list})
args = [parser.compile_filter(tkn)
for tkn in bits[1:args_count + 1]]
return cls(args, varname=as_var) | python | def handle_token(cls, parser, token):
tag_error = "Accepted formats {%% %(tagname)s %(args)s %%} or " \
"{%% %(tagname)s %(args)s as [var] %%}"
bits = token.split_contents()
args_count = len(bits) - 1
if args_count >= 2 and bits[-2] == 'as':
as_var = bits[-1]
args_count -= 2
else:
as_var = None
if args_count != cls.args_count:
arg_list = ' '.join(['[arg]' * cls.args_count])
raise TemplateSyntaxError(tag_error % {'tagname': bits[0],
'args': arg_list})
args = [parser.compile_filter(tkn)
for tkn in bits[1:args_count + 1]]
return cls(args, varname=as_var) | [
"def",
"handle_token",
"(",
"cls",
",",
"parser",
",",
"token",
")",
":",
"tag_error",
"=",
"\"Accepted formats {%% %(tagname)s %(args)s %%} or \"",
"\"{%% %(tagname)s %(args)s as [var] %%}\"",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"args_count",
"=",
"l... | Class method to parse and return a Node. | [
"Class",
"method",
"to",
"parse",
"and",
"return",
"a",
"Node",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/templatetags/activity_tags.py#L60-L79 |
226,250 | justquick/django-activity-stream | actstream/actions.py | follow | def follow(user, obj, send_action=True, actor_only=True, flag='', **kwargs):
"""
Creates a relationship allowing the object's activities to appear in the
user's stream.
Returns the created ``Follow`` instance.
If ``send_action`` is ``True`` (the default) then a
``<user> started following <object>`` action signal is sent.
Extra keyword arguments are passed to the action.send call.
If ``actor_only`` is ``True`` (the default) then only actions where the
object is the actor will appear in the user's activity stream. Set to
``False`` to also include actions where this object is the action_object or
the target.
If ``flag`` not an empty string then the relationship would marked by this flag.
Example::
follow(request.user, group, actor_only=False)
follow(request.user, group, actor_only=False, flag='liking')
"""
check(obj)
instance, created = apps.get_model('actstream', 'follow').objects.get_or_create(
user=user, object_id=obj.pk, flag=flag,
content_type=ContentType.objects.get_for_model(obj),
actor_only=actor_only
)
if send_action and created:
if not flag:
action.send(user, verb=_('started following'), target=obj, **kwargs)
else:
action.send(user, verb=_('started %s' % flag), target=obj, **kwargs)
return instance | python | def follow(user, obj, send_action=True, actor_only=True, flag='', **kwargs):
check(obj)
instance, created = apps.get_model('actstream', 'follow').objects.get_or_create(
user=user, object_id=obj.pk, flag=flag,
content_type=ContentType.objects.get_for_model(obj),
actor_only=actor_only
)
if send_action and created:
if not flag:
action.send(user, verb=_('started following'), target=obj, **kwargs)
else:
action.send(user, verb=_('started %s' % flag), target=obj, **kwargs)
return instance | [
"def",
"follow",
"(",
"user",
",",
"obj",
",",
"send_action",
"=",
"True",
",",
"actor_only",
"=",
"True",
",",
"flag",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"check",
"(",
"obj",
")",
"instance",
",",
"created",
"=",
"apps",
".",
"get_model... | Creates a relationship allowing the object's activities to appear in the
user's stream.
Returns the created ``Follow`` instance.
If ``send_action`` is ``True`` (the default) then a
``<user> started following <object>`` action signal is sent.
Extra keyword arguments are passed to the action.send call.
If ``actor_only`` is ``True`` (the default) then only actions where the
object is the actor will appear in the user's activity stream. Set to
``False`` to also include actions where this object is the action_object or
the target.
If ``flag`` not an empty string then the relationship would marked by this flag.
Example::
follow(request.user, group, actor_only=False)
follow(request.user, group, actor_only=False, flag='liking') | [
"Creates",
"a",
"relationship",
"allowing",
"the",
"object",
"s",
"activities",
"to",
"appear",
"in",
"the",
"user",
"s",
"stream",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/actions.py#L19-L53 |
226,251 | justquick/django-activity-stream | actstream/actions.py | unfollow | def unfollow(user, obj, send_action=False, flag=''):
"""
Removes a "follow" relationship.
Set ``send_action`` to ``True`` (``False is default) to also send a
``<user> stopped following <object>`` action signal.
Pass a string value to ``flag`` to determine which type of "follow" relationship you want to remove.
Example::
unfollow(request.user, other_user)
unfollow(request.user, other_user, flag='watching')
"""
check(obj)
qs = apps.get_model('actstream', 'follow').objects.filter(
user=user, object_id=obj.pk,
content_type=ContentType.objects.get_for_model(obj)
)
if flag:
qs = qs.filter(flag=flag)
qs.delete()
if send_action:
if not flag:
action.send(user, verb=_('stopped following'), target=obj)
else:
action.send(user, verb=_('stopped %s' % flag), target=obj) | python | def unfollow(user, obj, send_action=False, flag=''):
check(obj)
qs = apps.get_model('actstream', 'follow').objects.filter(
user=user, object_id=obj.pk,
content_type=ContentType.objects.get_for_model(obj)
)
if flag:
qs = qs.filter(flag=flag)
qs.delete()
if send_action:
if not flag:
action.send(user, verb=_('stopped following'), target=obj)
else:
action.send(user, verb=_('stopped %s' % flag), target=obj) | [
"def",
"unfollow",
"(",
"user",
",",
"obj",
",",
"send_action",
"=",
"False",
",",
"flag",
"=",
"''",
")",
":",
"check",
"(",
"obj",
")",
"qs",
"=",
"apps",
".",
"get_model",
"(",
"'actstream'",
",",
"'follow'",
")",
".",
"objects",
".",
"filter",
... | Removes a "follow" relationship.
Set ``send_action`` to ``True`` (``False is default) to also send a
``<user> stopped following <object>`` action signal.
Pass a string value to ``flag`` to determine which type of "follow" relationship you want to remove.
Example::
unfollow(request.user, other_user)
unfollow(request.user, other_user, flag='watching') | [
"Removes",
"a",
"follow",
"relationship",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/actions.py#L56-L84 |
226,252 | justquick/django-activity-stream | actstream/actions.py | is_following | def is_following(user, obj, flag=''):
"""
Checks if a "follow" relationship exists.
Returns True if exists, False otherwise.
Pass a string value to ``flag`` to determine which type of "follow" relationship you want to check.
Example::
is_following(request.user, group)
is_following(request.user, group, flag='liking')
"""
check(obj)
qs = apps.get_model('actstream', 'follow').objects.filter(
user=user, object_id=obj.pk,
content_type=ContentType.objects.get_for_model(obj)
)
if flag:
qs = qs.filter(flag=flag)
return qs.exists() | python | def is_following(user, obj, flag=''):
check(obj)
qs = apps.get_model('actstream', 'follow').objects.filter(
user=user, object_id=obj.pk,
content_type=ContentType.objects.get_for_model(obj)
)
if flag:
qs = qs.filter(flag=flag)
return qs.exists() | [
"def",
"is_following",
"(",
"user",
",",
"obj",
",",
"flag",
"=",
"''",
")",
":",
"check",
"(",
"obj",
")",
"qs",
"=",
"apps",
".",
"get_model",
"(",
"'actstream'",
",",
"'follow'",
")",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
",",... | Checks if a "follow" relationship exists.
Returns True if exists, False otherwise.
Pass a string value to ``flag`` to determine which type of "follow" relationship you want to check.
Example::
is_following(request.user, group)
is_following(request.user, group, flag='liking') | [
"Checks",
"if",
"a",
"follow",
"relationship",
"exists",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/actions.py#L87-L110 |
226,253 | justquick/django-activity-stream | actstream/actions.py | action_handler | def action_handler(verb, **kwargs):
"""
Handler function to create Action instance upon action signal call.
"""
kwargs.pop('signal', None)
actor = kwargs.pop('sender')
# We must store the unstranslated string
# If verb is an ugettext_lazyed string, fetch the original string
if hasattr(verb, '_proxy____args'):
verb = verb._proxy____args[0]
newaction = apps.get_model('actstream', 'action')(
actor_content_type=ContentType.objects.get_for_model(actor),
actor_object_id=actor.pk,
verb=text_type(verb),
public=bool(kwargs.pop('public', True)),
description=kwargs.pop('description', None),
timestamp=kwargs.pop('timestamp', now())
)
for opt in ('target', 'action_object'):
obj = kwargs.pop(opt, None)
if obj is not None:
check(obj)
setattr(newaction, '%s_object_id' % opt, obj.pk)
setattr(newaction, '%s_content_type' % opt,
ContentType.objects.get_for_model(obj))
if settings.USE_JSONFIELD and len(kwargs):
newaction.data = kwargs
newaction.save(force_insert=True)
return newaction | python | def action_handler(verb, **kwargs):
kwargs.pop('signal', None)
actor = kwargs.pop('sender')
# We must store the unstranslated string
# If verb is an ugettext_lazyed string, fetch the original string
if hasattr(verb, '_proxy____args'):
verb = verb._proxy____args[0]
newaction = apps.get_model('actstream', 'action')(
actor_content_type=ContentType.objects.get_for_model(actor),
actor_object_id=actor.pk,
verb=text_type(verb),
public=bool(kwargs.pop('public', True)),
description=kwargs.pop('description', None),
timestamp=kwargs.pop('timestamp', now())
)
for opt in ('target', 'action_object'):
obj = kwargs.pop(opt, None)
if obj is not None:
check(obj)
setattr(newaction, '%s_object_id' % opt, obj.pk)
setattr(newaction, '%s_content_type' % opt,
ContentType.objects.get_for_model(obj))
if settings.USE_JSONFIELD and len(kwargs):
newaction.data = kwargs
newaction.save(force_insert=True)
return newaction | [
"def",
"action_handler",
"(",
"verb",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"pop",
"(",
"'signal'",
",",
"None",
")",
"actor",
"=",
"kwargs",
".",
"pop",
"(",
"'sender'",
")",
"# We must store the unstranslated string",
"# If verb is an ugettext_lazy... | Handler function to create Action instance upon action signal call. | [
"Handler",
"function",
"to",
"create",
"Action",
"instance",
"upon",
"action",
"signal",
"call",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/actions.py#L113-L144 |
226,254 | justquick/django-activity-stream | actstream/feeds.py | AbstractActivityStream.items | def items(self, *args, **kwargs):
"""
Returns a queryset of Actions to use based on the stream method and object.
"""
return self.get_stream()(self.get_object(*args, **kwargs)) | python | def items(self, *args, **kwargs):
return self.get_stream()(self.get_object(*args, **kwargs)) | [
"def",
"items",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_stream",
"(",
")",
"(",
"self",
".",
"get_object",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | Returns a queryset of Actions to use based on the stream method and object. | [
"Returns",
"a",
"queryset",
"of",
"Actions",
"to",
"use",
"based",
"on",
"the",
"stream",
"method",
"and",
"object",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/feeds.py#L40-L44 |
226,255 | justquick/django-activity-stream | actstream/feeds.py | AbstractActivityStream.get_uri | def get_uri(self, action, obj=None, date=None):
"""
Returns an RFC3987 IRI ID for the given object, action and date.
"""
if date is None:
date = action.timestamp
date = datetime_safe.new_datetime(date).strftime('%Y-%m-%d')
return 'tag:%s,%s:%s' % (Site.objects.get_current().domain, date,
self.get_url(action, obj, False)) | python | def get_uri(self, action, obj=None, date=None):
if date is None:
date = action.timestamp
date = datetime_safe.new_datetime(date).strftime('%Y-%m-%d')
return 'tag:%s,%s:%s' % (Site.objects.get_current().domain, date,
self.get_url(action, obj, False)) | [
"def",
"get_uri",
"(",
"self",
",",
"action",
",",
"obj",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"if",
"date",
"is",
"None",
":",
"date",
"=",
"action",
".",
"timestamp",
"date",
"=",
"datetime_safe",
".",
"new_datetime",
"(",
"date",
")",
... | Returns an RFC3987 IRI ID for the given object, action and date. | [
"Returns",
"an",
"RFC3987",
"IRI",
"ID",
"for",
"the",
"given",
"object",
"action",
"and",
"date",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/feeds.py#L46-L54 |
226,256 | justquick/django-activity-stream | actstream/feeds.py | AbstractActivityStream.get_url | def get_url(self, action, obj=None, domain=True):
"""
Returns an RFC3987 IRI for a HTML representation of the given object, action.
If domain is true, the current site's domain will be added.
"""
if not obj:
url = reverse('actstream_detail', None, (action.pk,))
elif hasattr(obj, 'get_absolute_url'):
url = obj.get_absolute_url()
else:
ctype = ContentType.objects.get_for_model(obj)
url = reverse('actstream_actor', None, (ctype.pk, obj.pk))
if domain:
return add_domain(Site.objects.get_current().domain, url)
return url | python | def get_url(self, action, obj=None, domain=True):
if not obj:
url = reverse('actstream_detail', None, (action.pk,))
elif hasattr(obj, 'get_absolute_url'):
url = obj.get_absolute_url()
else:
ctype = ContentType.objects.get_for_model(obj)
url = reverse('actstream_actor', None, (ctype.pk, obj.pk))
if domain:
return add_domain(Site.objects.get_current().domain, url)
return url | [
"def",
"get_url",
"(",
"self",
",",
"action",
",",
"obj",
"=",
"None",
",",
"domain",
"=",
"True",
")",
":",
"if",
"not",
"obj",
":",
"url",
"=",
"reverse",
"(",
"'actstream_detail'",
",",
"None",
",",
"(",
"action",
".",
"pk",
",",
")",
")",
"el... | Returns an RFC3987 IRI for a HTML representation of the given object, action.
If domain is true, the current site's domain will be added. | [
"Returns",
"an",
"RFC3987",
"IRI",
"for",
"a",
"HTML",
"representation",
"of",
"the",
"given",
"object",
"action",
".",
"If",
"domain",
"is",
"true",
"the",
"current",
"site",
"s",
"domain",
"will",
"be",
"added",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/feeds.py#L56-L70 |
226,257 | justquick/django-activity-stream | actstream/feeds.py | AbstractActivityStream.format | def format(self, action):
"""
Returns a formatted dictionary for the given action.
"""
item = {
'id': self.get_uri(action),
'url': self.get_url(action),
'verb': action.verb,
'published': rfc3339_date(action.timestamp),
'actor': self.format_actor(action),
'title': text_type(action),
}
if action.description:
item['content'] = action.description
if action.target:
item['target'] = self.format_target(action)
if action.action_object:
item['object'] = self.format_action_object(action)
return item | python | def format(self, action):
item = {
'id': self.get_uri(action),
'url': self.get_url(action),
'verb': action.verb,
'published': rfc3339_date(action.timestamp),
'actor': self.format_actor(action),
'title': text_type(action),
}
if action.description:
item['content'] = action.description
if action.target:
item['target'] = self.format_target(action)
if action.action_object:
item['object'] = self.format_action_object(action)
return item | [
"def",
"format",
"(",
"self",
",",
"action",
")",
":",
"item",
"=",
"{",
"'id'",
":",
"self",
".",
"get_uri",
"(",
"action",
")",
",",
"'url'",
":",
"self",
".",
"get_url",
"(",
"action",
")",
",",
"'verb'",
":",
"action",
".",
"verb",
",",
"'pub... | Returns a formatted dictionary for the given action. | [
"Returns",
"a",
"formatted",
"dictionary",
"for",
"the",
"given",
"action",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/feeds.py#L72-L90 |
226,258 | justquick/django-activity-stream | actstream/feeds.py | AbstractActivityStream.format_item | def format_item(self, action, item_type='actor'):
"""
Returns a formatted dictionary for an individual item based on the action and item_type.
"""
obj = getattr(action, item_type)
return {
'id': self.get_uri(action, obj),
'url': self.get_url(action, obj),
'objectType': ContentType.objects.get_for_model(obj).name,
'displayName': text_type(obj)
} | python | def format_item(self, action, item_type='actor'):
obj = getattr(action, item_type)
return {
'id': self.get_uri(action, obj),
'url': self.get_url(action, obj),
'objectType': ContentType.objects.get_for_model(obj).name,
'displayName': text_type(obj)
} | [
"def",
"format_item",
"(",
"self",
",",
"action",
",",
"item_type",
"=",
"'actor'",
")",
":",
"obj",
"=",
"getattr",
"(",
"action",
",",
"item_type",
")",
"return",
"{",
"'id'",
":",
"self",
".",
"get_uri",
"(",
"action",
",",
"obj",
")",
",",
"'url'... | Returns a formatted dictionary for an individual item based on the action and item_type. | [
"Returns",
"a",
"formatted",
"dictionary",
"for",
"an",
"individual",
"item",
"based",
"on",
"the",
"action",
"and",
"item_type",
"."
] | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/feeds.py#L92-L102 |
226,259 | justquick/django-activity-stream | actstream/feeds.py | ActivityStreamsBaseFeed.item_extra_kwargs | def item_extra_kwargs(self, action):
"""
Returns an extra keyword arguments dictionary that is used with
the `add_item` call of the feed generator.
Add the 'content' field of the 'Entry' item, to be used by the custom
feed generator.
"""
item = self.format(action)
item.pop('title', None)
item['uri'] = item.pop('url')
item['activity:verb'] = item.pop('verb')
return item | python | def item_extra_kwargs(self, action):
item = self.format(action)
item.pop('title', None)
item['uri'] = item.pop('url')
item['activity:verb'] = item.pop('verb')
return item | [
"def",
"item_extra_kwargs",
"(",
"self",
",",
"action",
")",
":",
"item",
"=",
"self",
".",
"format",
"(",
"action",
")",
"item",
".",
"pop",
"(",
"'title'",
",",
"None",
")",
"item",
"[",
"'uri'",
"]",
"=",
"item",
".",
"pop",
"(",
"'url'",
")",
... | Returns an extra keyword arguments dictionary that is used with
the `add_item` call of the feed generator.
Add the 'content' field of the 'Entry' item, to be used by the custom
feed generator. | [
"Returns",
"an",
"extra",
"keyword",
"arguments",
"dictionary",
"that",
"is",
"used",
"with",
"the",
"add_item",
"call",
"of",
"the",
"feed",
"generator",
".",
"Add",
"the",
"content",
"field",
"of",
"the",
"Entry",
"item",
"to",
"be",
"used",
"by",
"the",... | a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35 | https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/feeds.py#L180-L191 |
226,260 | Netflix-Skunkworks/policyuniverse | policyuniverse/statement.py | Statement._principals | def _principals(self):
"""Extracts all principals from IAM statement.
Should handle these cases:
"Principal": "value"
"Principal": ["value"]
"Principal": { "AWS": "value" }
"Principal": { "AWS": ["value", "value"] }
"Principal": { "Service": "value" }
"Principal": { "Service": ["value", "value"] }
Return: Set of principals
"""
principals = set()
principal = self.statement.get("Principal", None)
if not principal:
# It is possible not to define a principal, AWS ignores these statements.
return principals
if isinstance(principal, dict):
if 'AWS' in principal:
self._add_or_extend(principal['AWS'], principals)
if 'Service' in principal:
self._add_or_extend(principal['Service'], principals)
else:
self._add_or_extend(principal, principals)
return principals | python | def _principals(self):
principals = set()
principal = self.statement.get("Principal", None)
if not principal:
# It is possible not to define a principal, AWS ignores these statements.
return principals
if isinstance(principal, dict):
if 'AWS' in principal:
self._add_or_extend(principal['AWS'], principals)
if 'Service' in principal:
self._add_or_extend(principal['Service'], principals)
else:
self._add_or_extend(principal, principals)
return principals | [
"def",
"_principals",
"(",
"self",
")",
":",
"principals",
"=",
"set",
"(",
")",
"principal",
"=",
"self",
".",
"statement",
".",
"get",
"(",
"\"Principal\"",
",",
"None",
")",
"if",
"not",
"principal",
":",
"# It is possible not to define a principal, AWS ignor... | Extracts all principals from IAM statement.
Should handle these cases:
"Principal": "value"
"Principal": ["value"]
"Principal": { "AWS": "value" }
"Principal": { "AWS": ["value", "value"] }
"Principal": { "Service": "value" }
"Principal": { "Service": ["value", "value"] }
Return: Set of principals | [
"Extracts",
"all",
"principals",
"from",
"IAM",
"statement",
"."
] | f31453219b348549c3d71659660b868dfb9030a3 | https://github.com/Netflix-Skunkworks/policyuniverse/blob/f31453219b348549c3d71659660b868dfb9030a3/policyuniverse/statement.py#L102-L132 |
226,261 | HearthSim/UnityPack | unitypack/utils.py | extract_audioclip_samples | def extract_audioclip_samples(d) -> dict:
"""
Extract all the sample data from an AudioClip and
convert it from FSB5 if needed.
"""
ret = {}
if not d.data:
# eg. StreamedResource not available
return {}
try:
from fsb5 import FSB5
except ImportError as e:
raise RuntimeError("python-fsb5 is required to extract AudioClip")
af = FSB5(d.data)
for i, sample in enumerate(af.samples):
if i > 0:
filename = "%s-%i.%s" % (d.name, i, af.get_sample_extension())
else:
filename = "%s.%s" % (d.name, af.get_sample_extension())
try:
sample = af.rebuild_sample(sample)
except ValueError as e:
print("WARNING: Could not extract %r (%s)" % (d, e))
continue
ret[filename] = sample
return ret | python | def extract_audioclip_samples(d) -> dict:
ret = {}
if not d.data:
# eg. StreamedResource not available
return {}
try:
from fsb5 import FSB5
except ImportError as e:
raise RuntimeError("python-fsb5 is required to extract AudioClip")
af = FSB5(d.data)
for i, sample in enumerate(af.samples):
if i > 0:
filename = "%s-%i.%s" % (d.name, i, af.get_sample_extension())
else:
filename = "%s.%s" % (d.name, af.get_sample_extension())
try:
sample = af.rebuild_sample(sample)
except ValueError as e:
print("WARNING: Could not extract %r (%s)" % (d, e))
continue
ret[filename] = sample
return ret | [
"def",
"extract_audioclip_samples",
"(",
"d",
")",
"->",
"dict",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"d",
".",
"data",
":",
"# eg. StreamedResource not available",
"return",
"{",
"}",
"try",
":",
"from",
"fsb5",
"import",
"FSB5",
"except",
"ImportError",... | Extract all the sample data from an AudioClip and
convert it from FSB5 if needed. | [
"Extract",
"all",
"the",
"sample",
"data",
"from",
"an",
"AudioClip",
"and",
"convert",
"it",
"from",
"FSB5",
"if",
"needed",
"."
] | 9c9d56031cbbc573cc9d7a5fe37f414d482f9152 | https://github.com/HearthSim/UnityPack/blob/9c9d56031cbbc573cc9d7a5fe37f414d482f9152/unitypack/utils.py#L14-L43 |
226,262 | jmcarp/flask-apispec | flask_apispec/annotations.py | use_kwargs | def use_kwargs(args, locations=None, inherit=None, apply=None, **kwargs):
"""Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fields.Str()})
def get_pets(**kwargs):
return Pet.query.filter_by(**kwargs).all()
:param args: Mapping of argument names to :class:`Field <marshmallow.fields.Field>`
objects, :class:`Schema <marshmallow.Schema>`, or a callable which accepts a
request and returns a :class:`Schema <marshmallow.Schema>`
:param locations: Default request locations to parse
:param inherit: Inherit args from parent classes
:param apply: Parse request with specified args
"""
kwargs.update({'locations': locations})
def wrapper(func):
options = {
'args': args,
'kwargs': kwargs,
}
annotate(func, 'args', [options], inherit=inherit, apply=apply)
return activate(func)
return wrapper | python | def use_kwargs(args, locations=None, inherit=None, apply=None, **kwargs):
kwargs.update({'locations': locations})
def wrapper(func):
options = {
'args': args,
'kwargs': kwargs,
}
annotate(func, 'args', [options], inherit=inherit, apply=apply)
return activate(func)
return wrapper | [
"def",
"use_kwargs",
"(",
"args",
",",
"locations",
"=",
"None",
",",
"inherit",
"=",
"None",
",",
"apply",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'locations'",
":",
"locations",
"}",
")",
"def",
"wrapper"... | Inject keyword arguments from the specified webargs arguments into the
decorated view function.
Usage:
.. code-block:: python
from marshmallow import fields
@use_kwargs({'name': fields.Str(), 'category': fields.Str()})
def get_pets(**kwargs):
return Pet.query.filter_by(**kwargs).all()
:param args: Mapping of argument names to :class:`Field <marshmallow.fields.Field>`
objects, :class:`Schema <marshmallow.Schema>`, or a callable which accepts a
request and returns a :class:`Schema <marshmallow.Schema>`
:param locations: Default request locations to parse
:param inherit: Inherit args from parent classes
:param apply: Parse request with specified args | [
"Inject",
"keyword",
"arguments",
"from",
"the",
"specified",
"webargs",
"arguments",
"into",
"the",
"decorated",
"view",
"function",
"."
] | d8cb658fa427f051568e58d6af201b8e9924c325 | https://github.com/jmcarp/flask-apispec/blob/d8cb658fa427f051568e58d6af201b8e9924c325/flask_apispec/annotations.py#L8-L38 |
226,263 | jmcarp/flask-apispec | flask_apispec/annotations.py | marshal_with | def marshal_with(schema, code='default', description='', inherit=None, apply=None):
"""Marshal the return value of the decorated view function using the
specified schema.
Usage:
.. code-block:: python
class PetSchema(Schema):
class Meta:
fields = ('name', 'category')
@marshal_with(PetSchema)
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
:param schema: :class:`Schema <marshmallow.Schema>` class or instance, or `None`
:param code: Optional HTTP response code
:param description: Optional response description
:param inherit: Inherit schemas from parent classes
:param apply: Marshal response with specified schema
"""
def wrapper(func):
options = {
code: {
'schema': schema or {},
'description': description,
},
}
annotate(func, 'schemas', [options], inherit=inherit, apply=apply)
return activate(func)
return wrapper | python | def marshal_with(schema, code='default', description='', inherit=None, apply=None):
def wrapper(func):
options = {
code: {
'schema': schema or {},
'description': description,
},
}
annotate(func, 'schemas', [options], inherit=inherit, apply=apply)
return activate(func)
return wrapper | [
"def",
"marshal_with",
"(",
"schema",
",",
"code",
"=",
"'default'",
",",
"description",
"=",
"''",
",",
"inherit",
"=",
"None",
",",
"apply",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"options",
"=",
"{",
"code",
":",
"{",
"'... | Marshal the return value of the decorated view function using the
specified schema.
Usage:
.. code-block:: python
class PetSchema(Schema):
class Meta:
fields = ('name', 'category')
@marshal_with(PetSchema)
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
:param schema: :class:`Schema <marshmallow.Schema>` class or instance, or `None`
:param code: Optional HTTP response code
:param description: Optional response description
:param inherit: Inherit schemas from parent classes
:param apply: Marshal response with specified schema | [
"Marshal",
"the",
"return",
"value",
"of",
"the",
"decorated",
"view",
"function",
"using",
"the",
"specified",
"schema",
"."
] | d8cb658fa427f051568e58d6af201b8e9924c325 | https://github.com/jmcarp/flask-apispec/blob/d8cb658fa427f051568e58d6af201b8e9924c325/flask_apispec/annotations.py#L41-L72 |
226,264 | jmcarp/flask-apispec | flask_apispec/annotations.py | doc | def doc(inherit=None, **kwargs):
"""Annotate the decorated view function or class with the specified Swagger
attributes.
Usage:
.. code-block:: python
@doc(tags=['pet'], description='a pet store')
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
:param inherit: Inherit Swagger documentation from parent classes
"""
def wrapper(func):
annotate(func, 'docs', [kwargs], inherit=inherit)
return activate(func)
return wrapper | python | def doc(inherit=None, **kwargs):
def wrapper(func):
annotate(func, 'docs', [kwargs], inherit=inherit)
return activate(func)
return wrapper | [
"def",
"doc",
"(",
"inherit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"annotate",
"(",
"func",
",",
"'docs'",
",",
"[",
"kwargs",
"]",
",",
"inherit",
"=",
"inherit",
")",
"return",
"activate",
"(",
... | Annotate the decorated view function or class with the specified Swagger
attributes.
Usage:
.. code-block:: python
@doc(tags=['pet'], description='a pet store')
def get_pet(pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
:param inherit: Inherit Swagger documentation from parent classes | [
"Annotate",
"the",
"decorated",
"view",
"function",
"or",
"class",
"with",
"the",
"specified",
"Swagger",
"attributes",
"."
] | d8cb658fa427f051568e58d6af201b8e9924c325 | https://github.com/jmcarp/flask-apispec/blob/d8cb658fa427f051568e58d6af201b8e9924c325/flask_apispec/annotations.py#L74-L91 |
226,265 | jmcarp/flask-apispec | flask_apispec/annotations.py | wrap_with | def wrap_with(wrapper_cls):
"""Use a custom `Wrapper` to apply annotations to the decorated function.
:param wrapper_cls: Custom `Wrapper` subclass
"""
def wrapper(func):
annotate(func, 'wrapper', [{'wrapper': wrapper_cls}])
return activate(func)
return wrapper | python | def wrap_with(wrapper_cls):
def wrapper(func):
annotate(func, 'wrapper', [{'wrapper': wrapper_cls}])
return activate(func)
return wrapper | [
"def",
"wrap_with",
"(",
"wrapper_cls",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"annotate",
"(",
"func",
",",
"'wrapper'",
",",
"[",
"{",
"'wrapper'",
":",
"wrapper_cls",
"}",
"]",
")",
"return",
"activate",
"(",
"func",
")",
"return",
"wrap... | Use a custom `Wrapper` to apply annotations to the decorated function.
:param wrapper_cls: Custom `Wrapper` subclass | [
"Use",
"a",
"custom",
"Wrapper",
"to",
"apply",
"annotations",
"to",
"the",
"decorated",
"function",
"."
] | d8cb658fa427f051568e58d6af201b8e9924c325 | https://github.com/jmcarp/flask-apispec/blob/d8cb658fa427f051568e58d6af201b8e9924c325/flask_apispec/annotations.py#L93-L101 |
226,266 | viewflow/django-fsm | django_fsm/__init__.py | get_available_FIELD_transitions | def get_available_FIELD_transitions(instance, field):
"""
List of transitions available in current model state
with all conditions met
"""
curr_state = field.get_state(instance)
transitions = field.transitions[instance.__class__]
for name, transition in transitions.items():
meta = transition._django_fsm
if meta.has_transition(curr_state) and meta.conditions_met(instance, curr_state):
yield meta.get_transition(curr_state) | python | def get_available_FIELD_transitions(instance, field):
curr_state = field.get_state(instance)
transitions = field.transitions[instance.__class__]
for name, transition in transitions.items():
meta = transition._django_fsm
if meta.has_transition(curr_state) and meta.conditions_met(instance, curr_state):
yield meta.get_transition(curr_state) | [
"def",
"get_available_FIELD_transitions",
"(",
"instance",
",",
"field",
")",
":",
"curr_state",
"=",
"field",
".",
"get_state",
"(",
"instance",
")",
"transitions",
"=",
"field",
".",
"transitions",
"[",
"instance",
".",
"__class__",
"]",
"for",
"name",
",",
... | List of transitions available in current model state
with all conditions met | [
"List",
"of",
"transitions",
"available",
"in",
"current",
"model",
"state",
"with",
"all",
"conditions",
"met"
] | c86cd3eb949467626ffc68249ad001746333c38e | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L106-L117 |
226,267 | viewflow/django-fsm | django_fsm/__init__.py | get_available_user_FIELD_transitions | def get_available_user_FIELD_transitions(instance, user, field):
"""
List of transitions available in current model state
with all conditions met and user have rights on it
"""
for transition in get_available_FIELD_transitions(instance, field):
if transition.has_perm(instance, user):
yield transition | python | def get_available_user_FIELD_transitions(instance, user, field):
for transition in get_available_FIELD_transitions(instance, field):
if transition.has_perm(instance, user):
yield transition | [
"def",
"get_available_user_FIELD_transitions",
"(",
"instance",
",",
"user",
",",
"field",
")",
":",
"for",
"transition",
"in",
"get_available_FIELD_transitions",
"(",
"instance",
",",
"field",
")",
":",
"if",
"transition",
".",
"has_perm",
"(",
"instance",
",",
... | List of transitions available in current model state
with all conditions met and user have rights on it | [
"List",
"of",
"transitions",
"available",
"in",
"current",
"model",
"state",
"with",
"all",
"conditions",
"met",
"and",
"user",
"have",
"rights",
"on",
"it"
] | c86cd3eb949467626ffc68249ad001746333c38e | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L127-L134 |
226,268 | viewflow/django-fsm | django_fsm/__init__.py | transition | def transition(field, source='*', target=None, on_error=None, conditions=[], permission=None, custom={}):
"""
Method decorator to mark allowed transitions.
Set target to None if current state needs to be validated and
has not changed after the function call.
"""
def inner_transition(func):
wrapper_installed, fsm_meta = True, getattr(func, '_django_fsm', None)
if not fsm_meta:
wrapper_installed = False
fsm_meta = FSMMeta(field=field, method=func)
setattr(func, '_django_fsm', fsm_meta)
if isinstance(source, (list, tuple, set)):
for state in source:
func._django_fsm.add_transition(func, state, target, on_error, conditions, permission, custom)
else:
func._django_fsm.add_transition(func, source, target, on_error, conditions, permission, custom)
@wraps(func)
def _change_state(instance, *args, **kwargs):
return fsm_meta.field.change_state(instance, func, *args, **kwargs)
if not wrapper_installed:
return _change_state
return func
return inner_transition | python | def transition(field, source='*', target=None, on_error=None, conditions=[], permission=None, custom={}):
def inner_transition(func):
wrapper_installed, fsm_meta = True, getattr(func, '_django_fsm', None)
if not fsm_meta:
wrapper_installed = False
fsm_meta = FSMMeta(field=field, method=func)
setattr(func, '_django_fsm', fsm_meta)
if isinstance(source, (list, tuple, set)):
for state in source:
func._django_fsm.add_transition(func, state, target, on_error, conditions, permission, custom)
else:
func._django_fsm.add_transition(func, source, target, on_error, conditions, permission, custom)
@wraps(func)
def _change_state(instance, *args, **kwargs):
return fsm_meta.field.change_state(instance, func, *args, **kwargs)
if not wrapper_installed:
return _change_state
return func
return inner_transition | [
"def",
"transition",
"(",
"field",
",",
"source",
"=",
"'*'",
",",
"target",
"=",
"None",
",",
"on_error",
"=",
"None",
",",
"conditions",
"=",
"[",
"]",
",",
"permission",
"=",
"None",
",",
"custom",
"=",
"{",
"}",
")",
":",
"def",
"inner_transition... | Method decorator to mark allowed transitions.
Set target to None if current state needs to be validated and
has not changed after the function call. | [
"Method",
"decorator",
"to",
"mark",
"allowed",
"transitions",
"."
] | c86cd3eb949467626ffc68249ad001746333c38e | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L493-L522 |
226,269 | viewflow/django-fsm | django_fsm/__init__.py | can_proceed | def can_proceed(bound_method, check_conditions=True):
"""
Returns True if model in state allows to call bound_method
Set ``check_conditions`` argument to ``False`` to skip checking
conditions.
"""
if not hasattr(bound_method, '_django_fsm'):
im_func = getattr(bound_method, 'im_func', getattr(bound_method, '__func__'))
raise TypeError('%s method is not transition' % im_func.__name__)
meta = bound_method._django_fsm
im_self = getattr(bound_method, 'im_self', getattr(bound_method, '__self__'))
current_state = meta.field.get_state(im_self)
return meta.has_transition(current_state) and (
not check_conditions or meta.conditions_met(im_self, current_state)) | python | def can_proceed(bound_method, check_conditions=True):
if not hasattr(bound_method, '_django_fsm'):
im_func = getattr(bound_method, 'im_func', getattr(bound_method, '__func__'))
raise TypeError('%s method is not transition' % im_func.__name__)
meta = bound_method._django_fsm
im_self = getattr(bound_method, 'im_self', getattr(bound_method, '__self__'))
current_state = meta.field.get_state(im_self)
return meta.has_transition(current_state) and (
not check_conditions or meta.conditions_met(im_self, current_state)) | [
"def",
"can_proceed",
"(",
"bound_method",
",",
"check_conditions",
"=",
"True",
")",
":",
"if",
"not",
"hasattr",
"(",
"bound_method",
",",
"'_django_fsm'",
")",
":",
"im_func",
"=",
"getattr",
"(",
"bound_method",
",",
"'im_func'",
",",
"getattr",
"(",
"bo... | Returns True if model in state allows to call bound_method
Set ``check_conditions`` argument to ``False`` to skip checking
conditions. | [
"Returns",
"True",
"if",
"model",
"in",
"state",
"allows",
"to",
"call",
"bound_method"
] | c86cd3eb949467626ffc68249ad001746333c38e | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L525-L541 |
226,270 | viewflow/django-fsm | django_fsm/__init__.py | has_transition_perm | def has_transition_perm(bound_method, user):
"""
Returns True if model in state allows to call bound_method and user have rights on it
"""
if not hasattr(bound_method, '_django_fsm'):
im_func = getattr(bound_method, 'im_func', getattr(bound_method, '__func__'))
raise TypeError('%s method is not transition' % im_func.__name__)
meta = bound_method._django_fsm
im_self = getattr(bound_method, 'im_self', getattr(bound_method, '__self__'))
current_state = meta.field.get_state(im_self)
return (meta.has_transition(current_state) and
meta.conditions_met(im_self, current_state) and
meta.has_transition_perm(im_self, current_state, user)) | python | def has_transition_perm(bound_method, user):
if not hasattr(bound_method, '_django_fsm'):
im_func = getattr(bound_method, 'im_func', getattr(bound_method, '__func__'))
raise TypeError('%s method is not transition' % im_func.__name__)
meta = bound_method._django_fsm
im_self = getattr(bound_method, 'im_self', getattr(bound_method, '__self__'))
current_state = meta.field.get_state(im_self)
return (meta.has_transition(current_state) and
meta.conditions_met(im_self, current_state) and
meta.has_transition_perm(im_self, current_state, user)) | [
"def",
"has_transition_perm",
"(",
"bound_method",
",",
"user",
")",
":",
"if",
"not",
"hasattr",
"(",
"bound_method",
",",
"'_django_fsm'",
")",
":",
"im_func",
"=",
"getattr",
"(",
"bound_method",
",",
"'im_func'",
",",
"getattr",
"(",
"bound_method",
",",
... | Returns True if model in state allows to call bound_method and user have rights on it | [
"Returns",
"True",
"if",
"model",
"in",
"state",
"allows",
"to",
"call",
"bound_method",
"and",
"user",
"have",
"rights",
"on",
"it"
] | c86cd3eb949467626ffc68249ad001746333c38e | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L544-L558 |
226,271 | viewflow/django-fsm | django_fsm/__init__.py | FSMMeta.has_transition | def has_transition(self, state):
"""
Lookup if any transition exists from current model state using current method
"""
if state in self.transitions:
return True
if '*' in self.transitions:
return True
if '+' in self.transitions and self.transitions['+'].target != state:
return True
return False | python | def has_transition(self, state):
if state in self.transitions:
return True
if '*' in self.transitions:
return True
if '+' in self.transitions and self.transitions['+'].target != state:
return True
return False | [
"def",
"has_transition",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"in",
"self",
".",
"transitions",
":",
"return",
"True",
"if",
"'*'",
"in",
"self",
".",
"transitions",
":",
"return",
"True",
"if",
"'+'",
"in",
"self",
".",
"transitions",
"... | Lookup if any transition exists from current model state using current method | [
"Lookup",
"if",
"any",
"transition",
"exists",
"from",
"current",
"model",
"state",
"using",
"current",
"method"
] | c86cd3eb949467626ffc68249ad001746333c38e | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L166-L179 |
226,272 | viewflow/django-fsm | django_fsm/__init__.py | FSMMeta.conditions_met | def conditions_met(self, instance, state):
"""
Check if all conditions have been met
"""
transition = self.get_transition(state)
if transition is None:
return False
elif transition.conditions is None:
return True
else:
return all(map(lambda condition: condition(instance), transition.conditions)) | python | def conditions_met(self, instance, state):
transition = self.get_transition(state)
if transition is None:
return False
elif transition.conditions is None:
return True
else:
return all(map(lambda condition: condition(instance), transition.conditions)) | [
"def",
"conditions_met",
"(",
"self",
",",
"instance",
",",
"state",
")",
":",
"transition",
"=",
"self",
".",
"get_transition",
"(",
"state",
")",
"if",
"transition",
"is",
"None",
":",
"return",
"False",
"elif",
"transition",
".",
"conditions",
"is",
"No... | Check if all conditions have been met | [
"Check",
"if",
"all",
"conditions",
"have",
"been",
"met"
] | c86cd3eb949467626ffc68249ad001746333c38e | https://github.com/viewflow/django-fsm/blob/c86cd3eb949467626ffc68249ad001746333c38e/django_fsm/__init__.py#L181-L192 |
226,273 | droope/droopescan | dscan/plugins/silverstripe.py | Silverstripe._convert_to_folder | def _convert_to_folder(self, packages):
"""
Silverstripe's page contains a list of composer packages. This
function converts those to folder names. These may be different due
to installer-name.
Implemented exponential backoff in order to prevent packager from
being overly sensitive about the number of requests I was making.
@see: https://github.com/composer/installers#custom-install-names
@see: https://github.com/richardsjoqvist/silverstripe-localdate/issues/7
"""
url = 'http://packagist.org/p/%s.json'
with ThreadPoolExecutor(max_workers=12) as executor:
futures = []
for package in packages:
future = executor.submit(self._get, url, package)
futures.append({
'future': future,
'package': package
})
folders = []
for i, future in enumerate(futures, start=1):
r = future['future'].result()
package = future['package']
if not 'installer-name' in r.text:
folder_name = package.split('/')[1]
else:
splat = list(filter(None, re.split(r'[^a-zA-Z0-9-_.,]', r.text)))
folder_name = splat[splat.index('installer-name') + 1]
if not folder_name in folders:
folders.append(folder_name)
else:
print("Folder %s is duplicated (current %s, previous %s)" % (folder_name,
package, folders.index(folder_name)))
if i % 25 == 0:
print("Done %s." % i)
return folders | python | def _convert_to_folder(self, packages):
url = 'http://packagist.org/p/%s.json'
with ThreadPoolExecutor(max_workers=12) as executor:
futures = []
for package in packages:
future = executor.submit(self._get, url, package)
futures.append({
'future': future,
'package': package
})
folders = []
for i, future in enumerate(futures, start=1):
r = future['future'].result()
package = future['package']
if not 'installer-name' in r.text:
folder_name = package.split('/')[1]
else:
splat = list(filter(None, re.split(r'[^a-zA-Z0-9-_.,]', r.text)))
folder_name = splat[splat.index('installer-name') + 1]
if not folder_name in folders:
folders.append(folder_name)
else:
print("Folder %s is duplicated (current %s, previous %s)" % (folder_name,
package, folders.index(folder_name)))
if i % 25 == 0:
print("Done %s." % i)
return folders | [
"def",
"_convert_to_folder",
"(",
"self",
",",
"packages",
")",
":",
"url",
"=",
"'http://packagist.org/p/%s.json'",
"with",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"12",
")",
"as",
"executor",
":",
"futures",
"=",
"[",
"]",
"for",
"package",
"in",
"pac... | Silverstripe's page contains a list of composer packages. This
function converts those to folder names. These may be different due
to installer-name.
Implemented exponential backoff in order to prevent packager from
being overly sensitive about the number of requests I was making.
@see: https://github.com/composer/installers#custom-install-names
@see: https://github.com/richardsjoqvist/silverstripe-localdate/issues/7 | [
"Silverstripe",
"s",
"page",
"contains",
"a",
"list",
"of",
"composer",
"packages",
".",
"This",
"function",
"converts",
"those",
"to",
"folder",
"names",
".",
"These",
"may",
"be",
"different",
"due",
"to",
"installer",
"-",
"name",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/silverstripe.py#L119-L161 |
226,274 | droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | BasePluginInternal._general_init | def _general_init(self, opts, out=None):
"""
Initializes a variety of variables depending on user input.
@return: a tuple containing a boolean value indicating whether
progressbars should be hidden, functionality and enabled
functionality.
"""
self.session = Session()
if out:
self.out = out
else:
self.out = self._output(opts)
is_cms_plugin = self._meta.label != "scan"
if is_cms_plugin:
self.vf = VersionsFile(self.versions_file)
# http://stackoverflow.com/questions/23632794/in-requests-library-how-can-i-avoid-httpconnectionpool-is-full-discarding-con
try:
a = requests.adapters.HTTPAdapter(pool_maxsize=5000)
self.session.mount('http://', a)
self.session.mount('https://', a)
self.session.cookies.set_policy(BlockAll())
except AttributeError:
old_req = """Running a very old version of requests! Please `pip
install -U requests`."""
self.out.warn(old_req)
self.session.verify = False
self.session.headers['User-Agent'] = self.DEFAULT_UA
debug_requests = opts['debug_requests']
if debug_requests:
hide_progressbar = True
opts['threads_identify'] = 1
opts['threads_scan'] = 1
opts['threads_enumerate'] = 1
self.session = RequestsLogger(self.session)
else:
if opts['hide_progressbar']:
hide_progressbar = True
else:
hide_progressbar = False
functionality = self._functionality(opts)
enabled_functionality = self._enabled_functionality(functionality, opts)
return (hide_progressbar, functionality, enabled_functionality) | python | def _general_init(self, opts, out=None):
self.session = Session()
if out:
self.out = out
else:
self.out = self._output(opts)
is_cms_plugin = self._meta.label != "scan"
if is_cms_plugin:
self.vf = VersionsFile(self.versions_file)
# http://stackoverflow.com/questions/23632794/in-requests-library-how-can-i-avoid-httpconnectionpool-is-full-discarding-con
try:
a = requests.adapters.HTTPAdapter(pool_maxsize=5000)
self.session.mount('http://', a)
self.session.mount('https://', a)
self.session.cookies.set_policy(BlockAll())
except AttributeError:
old_req = """Running a very old version of requests! Please `pip
install -U requests`."""
self.out.warn(old_req)
self.session.verify = False
self.session.headers['User-Agent'] = self.DEFAULT_UA
debug_requests = opts['debug_requests']
if debug_requests:
hide_progressbar = True
opts['threads_identify'] = 1
opts['threads_scan'] = 1
opts['threads_enumerate'] = 1
self.session = RequestsLogger(self.session)
else:
if opts['hide_progressbar']:
hide_progressbar = True
else:
hide_progressbar = False
functionality = self._functionality(opts)
enabled_functionality = self._enabled_functionality(functionality, opts)
return (hide_progressbar, functionality, enabled_functionality) | [
"def",
"_general_init",
"(",
"self",
",",
"opts",
",",
"out",
"=",
"None",
")",
":",
"self",
".",
"session",
"=",
"Session",
"(",
")",
"if",
"out",
":",
"self",
".",
"out",
"=",
"out",
"else",
":",
"self",
".",
"out",
"=",
"self",
".",
"_output",... | Initializes a variety of variables depending on user input.
@return: a tuple containing a boolean value indicating whether
progressbars should be hidden, functionality and enabled
functionality. | [
"Initializes",
"a",
"variety",
"of",
"variables",
"depending",
"on",
"user",
"input",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L237-L286 |
226,275 | droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | BasePluginInternal.url_scan | def url_scan(self, url, opts, functionality, enabled_functionality, hide_progressbar):
"""
This is the main function called whenever a URL needs to be scanned.
This is called when a user specifies an individual CMS, or after CMS
identification has taken place. This function is called for individual
hosts specified by `-u` or for individual lines specified by `-U`.
@param url: this parameter can either be a URL or a (url, host_header)
tuple. The url, if a string, can be in the format of url + " " +
host_header.
@param opts: options object as returned by self._options().
@param functionality: as returned by self._general_init.
@param enabled_functionality: as returned by self._general_init.
@param hide_progressbar: whether to hide the progressbar.
@return: results dictionary.
"""
self.out.debug('base_plugin_internal.url_scan -> %s' % str(url))
if isinstance(url, tuple):
url, host_header = url
else:
url, host_header = self._process_host_line(url)
url = common.repair_url(url)
if opts['follow_redirects']:
url, host_header = self.determine_redirect(url, host_header, opts)
need_sm = opts['enumerate'] in ['a', 'p', 't']
if need_sm and (self.can_enumerate_plugins or self.can_enumerate_themes):
scanning_method = opts['method']
if not scanning_method:
scanning_method = self.determine_scanning_method(url,
opts['verb'], opts['timeout'], self._generate_headers(host_header))
else:
scanning_method = None
enumerating_all = opts['enumerate'] == 'a'
result = {}
for enumerate in enabled_functionality:
enum = functionality[enumerate]
if common.shutdown:
continue
# Get the arguments for the function.
kwargs = dict(enum['kwargs'])
kwargs['url'] = url
kwargs['hide_progressbar'] = hide_progressbar
if enumerate in ['themes', 'plugins']:
kwargs['scanning_method'] = scanning_method
kwargs['headers'] = self._generate_headers(host_header)
# Call to the respective functions occurs here.
finds, is_empty = enum['func'](**kwargs)
result[enumerate] = {'finds': finds, 'is_empty': is_empty}
return result | python | def url_scan(self, url, opts, functionality, enabled_functionality, hide_progressbar):
self.out.debug('base_plugin_internal.url_scan -> %s' % str(url))
if isinstance(url, tuple):
url, host_header = url
else:
url, host_header = self._process_host_line(url)
url = common.repair_url(url)
if opts['follow_redirects']:
url, host_header = self.determine_redirect(url, host_header, opts)
need_sm = opts['enumerate'] in ['a', 'p', 't']
if need_sm and (self.can_enumerate_plugins or self.can_enumerate_themes):
scanning_method = opts['method']
if not scanning_method:
scanning_method = self.determine_scanning_method(url,
opts['verb'], opts['timeout'], self._generate_headers(host_header))
else:
scanning_method = None
enumerating_all = opts['enumerate'] == 'a'
result = {}
for enumerate in enabled_functionality:
enum = functionality[enumerate]
if common.shutdown:
continue
# Get the arguments for the function.
kwargs = dict(enum['kwargs'])
kwargs['url'] = url
kwargs['hide_progressbar'] = hide_progressbar
if enumerate in ['themes', 'plugins']:
kwargs['scanning_method'] = scanning_method
kwargs['headers'] = self._generate_headers(host_header)
# Call to the respective functions occurs here.
finds, is_empty = enum['func'](**kwargs)
result[enumerate] = {'finds': finds, 'is_empty': is_empty}
return result | [
"def",
"url_scan",
"(",
"self",
",",
"url",
",",
"opts",
",",
"functionality",
",",
"enabled_functionality",
",",
"hide_progressbar",
")",
":",
"self",
".",
"out",
".",
"debug",
"(",
"'base_plugin_internal.url_scan -> %s'",
"%",
"str",
"(",
"url",
")",
")",
... | This is the main function called whenever a URL needs to be scanned.
This is called when a user specifies an individual CMS, or after CMS
identification has taken place. This function is called for individual
hosts specified by `-u` or for individual lines specified by `-U`.
@param url: this parameter can either be a URL or a (url, host_header)
tuple. The url, if a string, can be in the format of url + " " +
host_header.
@param opts: options object as returned by self._options().
@param functionality: as returned by self._general_init.
@param enabled_functionality: as returned by self._general_init.
@param hide_progressbar: whether to hide the progressbar.
@return: results dictionary. | [
"This",
"is",
"the",
"main",
"function",
"called",
"whenever",
"a",
"URL",
"needs",
"to",
"be",
"scanned",
".",
"This",
"is",
"called",
"when",
"a",
"user",
"specifies",
"an",
"individual",
"CMS",
"or",
"after",
"CMS",
"identification",
"has",
"taken",
"pl... | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L390-L447 |
226,276 | droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | BasePluginInternal._determine_redirect | def _determine_redirect(self, url, verb, timeout=15, headers={}):
"""
Internal redirect function, focuses on HTTP and worries less about
application-y stuff.
@param url: the url to check
@param verb: the verb, e.g. head, or get.
@param timeout: the time, in seconds, that requests should wait
before throwing an exception.
@param headers: a set of headers as expected by requests.
@return: the url that needs to be scanned. It may be equal to the url
parameter if no redirect is needed.
"""
requests_verb = getattr(self.session, verb)
r = requests_verb(url, timeout=timeout, headers=headers, allow_redirects=False)
redirect = 300 <= r.status_code < 400
url_new = url
if redirect:
redirect_url = r.headers['Location']
url_new = redirect_url
relative_redirect = not redirect_url.startswith('http')
if relative_redirect:
url_new = url
base_redir = base_url(redirect_url)
base_supplied = base_url(url)
same_base = base_redir == base_supplied
if same_base:
url_new = url
return url_new | python | def _determine_redirect(self, url, verb, timeout=15, headers={}):
requests_verb = getattr(self.session, verb)
r = requests_verb(url, timeout=timeout, headers=headers, allow_redirects=False)
redirect = 300 <= r.status_code < 400
url_new = url
if redirect:
redirect_url = r.headers['Location']
url_new = redirect_url
relative_redirect = not redirect_url.startswith('http')
if relative_redirect:
url_new = url
base_redir = base_url(redirect_url)
base_supplied = base_url(url)
same_base = base_redir == base_supplied
if same_base:
url_new = url
return url_new | [
"def",
"_determine_redirect",
"(",
"self",
",",
"url",
",",
"verb",
",",
"timeout",
"=",
"15",
",",
"headers",
"=",
"{",
"}",
")",
":",
"requests_verb",
"=",
"getattr",
"(",
"self",
".",
"session",
",",
"verb",
")",
"r",
"=",
"requests_verb",
"(",
"u... | Internal redirect function, focuses on HTTP and worries less about
application-y stuff.
@param url: the url to check
@param verb: the verb, e.g. head, or get.
@param timeout: the time, in seconds, that requests should wait
before throwing an exception.
@param headers: a set of headers as expected by requests.
@return: the url that needs to be scanned. It may be equal to the url
parameter if no redirect is needed. | [
"Internal",
"redirect",
"function",
"focuses",
"on",
"HTTP",
"and",
"worries",
"less",
"about",
"application",
"-",
"y",
"stuff",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L449-L481 |
226,277 | droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | BasePluginInternal.enumerate_version_changelog | def enumerate_version_changelog(self, url, versions_estimated, timeout=15,
headers={}):
"""
If we have a changelog in store for this CMS, this function will be
called, and a changelog will be used for narrowing down which version is
installed. If the changelog's version is outside our estimated range,
it is discarded.
@param url: the url to check against.
@param versions_estimated: the version other checks estimate the
installation is.
@param timeout: the number of seconds to wait before expiring a request.
@param headers: headers to pass to requests.get()
"""
changelogs = self.vf.changelogs_get()
ch_hash = None
for ch_url in changelogs:
try:
ch_hash = self.enumerate_file_hash(url, file_url=ch_url,
timeout=timeout, headers=headers)
except RuntimeError:
pass
ch_version = self.vf.changelog_identify(ch_hash)
if ch_version in versions_estimated:
return [ch_version]
else:
return versions_estimated | python | def enumerate_version_changelog(self, url, versions_estimated, timeout=15,
headers={}):
changelogs = self.vf.changelogs_get()
ch_hash = None
for ch_url in changelogs:
try:
ch_hash = self.enumerate_file_hash(url, file_url=ch_url,
timeout=timeout, headers=headers)
except RuntimeError:
pass
ch_version = self.vf.changelog_identify(ch_hash)
if ch_version in versions_estimated:
return [ch_version]
else:
return versions_estimated | [
"def",
"enumerate_version_changelog",
"(",
"self",
",",
"url",
",",
"versions_estimated",
",",
"timeout",
"=",
"15",
",",
"headers",
"=",
"{",
"}",
")",
":",
"changelogs",
"=",
"self",
".",
"vf",
".",
"changelogs_get",
"(",
")",
"ch_hash",
"=",
"None",
"... | If we have a changelog in store for this CMS, this function will be
called, and a changelog will be used for narrowing down which version is
installed. If the changelog's version is outside our estimated range,
it is discarded.
@param url: the url to check against.
@param versions_estimated: the version other checks estimate the
installation is.
@param timeout: the number of seconds to wait before expiring a request.
@param headers: headers to pass to requests.get() | [
"If",
"we",
"have",
"a",
"changelog",
"in",
"store",
"for",
"this",
"CMS",
"this",
"function",
"will",
"be",
"called",
"and",
"a",
"changelog",
"will",
"be",
"used",
"for",
"narrowing",
"down",
"which",
"version",
"is",
"installed",
".",
"If",
"the",
"ch... | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L821-L847 |
226,278 | droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | BasePluginInternal._enumerate_plugin_if | def _enumerate_plugin_if(self, found_list, verb, threads, imu_list,
hide_progressbar, timeout=15, headers={}):
"""
Finds interesting urls within a plugin folder which respond with 200 OK.
@param found_list: as returned in self.enumerate. E.g. [{'name':
'this_exists', 'url': 'http://adhwuiaihduhaknbacnckajcwnncwkakncw.com/sites/all/modules/this_exists/'}]
@param verb: the verb to use.
@param threads: the number of threads to use.
@param imu_list: Interesting module urls.
@param hide_progressbar: whether to display a progressbar.
@param timeout: timeout in seconds for http requests.
@param headers: custom headers as expected by requests.
"""
if not hide_progressbar:
p = ProgressBar(sys.stderr, len(found_list) *
len(imu_list), name="IMU")
requests_verb = getattr(self.session, verb)
with ThreadPoolExecutor(max_workers=threads) as executor:
futures = []
for i, found in enumerate(found_list):
found_list[i]['imu'] = []
for imu in imu_list:
interesting_url = found['url'] + imu[0]
future = executor.submit(requests_verb, interesting_url,
timeout=timeout, headers=headers)
futures.append({
'url': interesting_url,
'future': future,
'description': imu[1],
'i': i
})
for f in futures:
if common.shutdown:
f['future'].cancel()
continue
r = f['future'].result()
if r.status_code == 200:
found_list[f['i']]['imu'].append({
'url': f['url'],
'description': f['description']
})
if not hide_progressbar:
p.increment_progress()
if not hide_progressbar:
p.hide()
return found_list | python | def _enumerate_plugin_if(self, found_list, verb, threads, imu_list,
hide_progressbar, timeout=15, headers={}):
if not hide_progressbar:
p = ProgressBar(sys.stderr, len(found_list) *
len(imu_list), name="IMU")
requests_verb = getattr(self.session, verb)
with ThreadPoolExecutor(max_workers=threads) as executor:
futures = []
for i, found in enumerate(found_list):
found_list[i]['imu'] = []
for imu in imu_list:
interesting_url = found['url'] + imu[0]
future = executor.submit(requests_verb, interesting_url,
timeout=timeout, headers=headers)
futures.append({
'url': interesting_url,
'future': future,
'description': imu[1],
'i': i
})
for f in futures:
if common.shutdown:
f['future'].cancel()
continue
r = f['future'].result()
if r.status_code == 200:
found_list[f['i']]['imu'].append({
'url': f['url'],
'description': f['description']
})
if not hide_progressbar:
p.increment_progress()
if not hide_progressbar:
p.hide()
return found_list | [
"def",
"_enumerate_plugin_if",
"(",
"self",
",",
"found_list",
",",
"verb",
",",
"threads",
",",
"imu_list",
",",
"hide_progressbar",
",",
"timeout",
"=",
"15",
",",
"headers",
"=",
"{",
"}",
")",
":",
"if",
"not",
"hide_progressbar",
":",
"p",
"=",
"Pro... | Finds interesting urls within a plugin folder which respond with 200 OK.
@param found_list: as returned in self.enumerate. E.g. [{'name':
'this_exists', 'url': 'http://adhwuiaihduhaknbacnckajcwnncwkakncw.com/sites/all/modules/this_exists/'}]
@param verb: the verb to use.
@param threads: the number of threads to use.
@param imu_list: Interesting module urls.
@param hide_progressbar: whether to display a progressbar.
@param timeout: timeout in seconds for http requests.
@param headers: custom headers as expected by requests. | [
"Finds",
"interesting",
"urls",
"within",
"a",
"plugin",
"folder",
"which",
"respond",
"with",
"200",
"OK",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L864-L917 |
226,279 | droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | BasePluginInternal.cms_identify | def cms_identify(self, url, timeout=15, headers={}):
"""
Function called when attempting to determine if a URL is identified
as being this particular CMS.
@param url: the URL to attempt to identify.
@param timeout: number of seconds before a timeout occurs on a http
connection.
@param headers: custom HTTP headers as expected by requests.
@return: a boolean value indiciating whether this CMS is identified
as being this particular CMS.
"""
self.out.debug("cms_identify")
if isinstance(self.regular_file_url, str):
rfu = [self.regular_file_url]
else:
rfu = self.regular_file_url
is_cms = False
for regular_file_url in rfu:
try:
hash = self.enumerate_file_hash(url, regular_file_url, timeout,
headers)
except RuntimeError:
continue
hash_exists = self.vf.has_hash(hash)
if hash_exists:
is_cms = True
break
return is_cms | python | def cms_identify(self, url, timeout=15, headers={}):
self.out.debug("cms_identify")
if isinstance(self.regular_file_url, str):
rfu = [self.regular_file_url]
else:
rfu = self.regular_file_url
is_cms = False
for regular_file_url in rfu:
try:
hash = self.enumerate_file_hash(url, regular_file_url, timeout,
headers)
except RuntimeError:
continue
hash_exists = self.vf.has_hash(hash)
if hash_exists:
is_cms = True
break
return is_cms | [
"def",
"cms_identify",
"(",
"self",
",",
"url",
",",
"timeout",
"=",
"15",
",",
"headers",
"=",
"{",
"}",
")",
":",
"self",
".",
"out",
".",
"debug",
"(",
"\"cms_identify\"",
")",
"if",
"isinstance",
"(",
"self",
".",
"regular_file_url",
",",
"str",
... | Function called when attempting to determine if a URL is identified
as being this particular CMS.
@param url: the URL to attempt to identify.
@param timeout: number of seconds before a timeout occurs on a http
connection.
@param headers: custom HTTP headers as expected by requests.
@return: a boolean value indiciating whether this CMS is identified
as being this particular CMS. | [
"Function",
"called",
"when",
"attempting",
"to",
"determine",
"if",
"a",
"URL",
"is",
"identified",
"as",
"being",
"this",
"particular",
"CMS",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L919-L949 |
226,280 | droope/droopescan | dscan/plugins/internal/base_plugin_internal.py | BasePluginInternal.resume_forward | def resume_forward(self, fh, resume, file_location, error_log):
"""
Forwards `fh` n lines, where n lines is the amount of lines we should
skip in order to resume our previous scan, if resume is required by the
user.
@param fh: fh to advance.
@param file_location: location of the file handler in disk.
@param error_log: location of the error_log in disk.
"""
if resume:
if not error_log:
raise CannotResumeException("--error-log not provided.")
skip_lines = self.resume(file_location, error_log)
for _ in range(skip_lines):
next(fh) | python | def resume_forward(self, fh, resume, file_location, error_log):
if resume:
if not error_log:
raise CannotResumeException("--error-log not provided.")
skip_lines = self.resume(file_location, error_log)
for _ in range(skip_lines):
next(fh) | [
"def",
"resume_forward",
"(",
"self",
",",
"fh",
",",
"resume",
",",
"file_location",
",",
"error_log",
")",
":",
"if",
"resume",
":",
"if",
"not",
"error_log",
":",
"raise",
"CannotResumeException",
"(",
"\"--error-log not provided.\"",
")",
"skip_lines",
"=",
... | Forwards `fh` n lines, where n lines is the amount of lines we should
skip in order to resume our previous scan, if resume is required by the
user.
@param fh: fh to advance.
@param file_location: location of the file handler in disk.
@param error_log: location of the error_log in disk. | [
"Forwards",
"fh",
"n",
"lines",
"where",
"n",
"lines",
"is",
"the",
"amount",
"of",
"lines",
"we",
"should",
"skip",
"in",
"order",
"to",
"resume",
"our",
"previous",
"scan",
"if",
"resume",
"is",
"required",
"by",
"the",
"user",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/plugins/internal/base_plugin_internal.py#L998-L1013 |
226,281 | droope/droopescan | dscan/common/output.py | StandardOutput.result | def result(self, result, functionality):
"""
For the final result of the scan.
@param result: as returned by BasePluginInternal.url_scan
@param functionality: functionality as returned by
BasePluginInternal._general_init
"""
for enumerate in result:
# The host is a special header, we must not attempt to display it.
if enumerate == "host" or enumerate == "cms_name":
continue
result_ind = result[enumerate]
finds = result_ind['finds']
is_empty = result_ind['is_empty']
template_str = functionality[enumerate]['template']
template_params = {
'noun': enumerate,
'Noun': enumerate.capitalize(),
'items': finds,
'empty': is_empty,
}
self.echo(template(template_str, template_params)) | python | def result(self, result, functionality):
for enumerate in result:
# The host is a special header, we must not attempt to display it.
if enumerate == "host" or enumerate == "cms_name":
continue
result_ind = result[enumerate]
finds = result_ind['finds']
is_empty = result_ind['is_empty']
template_str = functionality[enumerate]['template']
template_params = {
'noun': enumerate,
'Noun': enumerate.capitalize(),
'items': finds,
'empty': is_empty,
}
self.echo(template(template_str, template_params)) | [
"def",
"result",
"(",
"self",
",",
"result",
",",
"functionality",
")",
":",
"for",
"enumerate",
"in",
"result",
":",
"# The host is a special header, we must not attempt to display it.",
"if",
"enumerate",
"==",
"\"host\"",
"or",
"enumerate",
"==",
"\"cms_name\"",
":... | For the final result of the scan.
@param result: as returned by BasePluginInternal.url_scan
@param functionality: functionality as returned by
BasePluginInternal._general_init | [
"For",
"the",
"final",
"result",
"of",
"the",
"scan",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/output.py#L82-L107 |
226,282 | droope/droopescan | dscan/common/output.py | StandardOutput.warn | def warn(self, msg, whitespace_strp=True):
"""
For things that have gone seriously wrong but don't merit a program
halt.
Outputs to stderr, so JsonOutput does not need to override.
@param msg: warning to output.
@param whitespace_strp: whether to strip whitespace.
"""
if self.errors_display:
if whitespace_strp:
msg = strip_whitespace(msg)
if not self.log_to_file:
msg = colors['warn'] + "[+] " + msg + colors['endc']
else:
msg = "[" + time.strftime("%c") + "] " + msg
self.print(msg, file=self.error_log) | python | def warn(self, msg, whitespace_strp=True):
if self.errors_display:
if whitespace_strp:
msg = strip_whitespace(msg)
if not self.log_to_file:
msg = colors['warn'] + "[+] " + msg + colors['endc']
else:
msg = "[" + time.strftime("%c") + "] " + msg
self.print(msg, file=self.error_log) | [
"def",
"warn",
"(",
"self",
",",
"msg",
",",
"whitespace_strp",
"=",
"True",
")",
":",
"if",
"self",
".",
"errors_display",
":",
"if",
"whitespace_strp",
":",
"msg",
"=",
"strip_whitespace",
"(",
"msg",
")",
"if",
"not",
"self",
".",
"log_to_file",
":",
... | For things that have gone seriously wrong but don't merit a program
halt.
Outputs to stderr, so JsonOutput does not need to override.
@param msg: warning to output.
@param whitespace_strp: whether to strip whitespace. | [
"For",
"things",
"that",
"have",
"gone",
"seriously",
"wrong",
"but",
"don",
"t",
"merit",
"a",
"program",
"halt",
".",
"Outputs",
"to",
"stderr",
"so",
"JsonOutput",
"does",
"not",
"need",
"to",
"override",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/output.py#L109-L126 |
226,283 | droope/droopescan | dscan/common/output.py | RequestsLogger._print | def _print(self, method, *args, **kwargs):
"""
Output format affects integration tests.
@see: IntegrationTests.mock_output
"""
sess_method = getattr(self._session, method)
try:
headers = kwargs['headers']
except KeyError:
headers = {}
tpl = '[%s] %s %s'
print(tpl % (method, args[0], headers), end=' ')
try:
r = sess_method(*args, **kwargs)
except:
e = sys.exc_info()
e_str = "%s: %s" % (e[0], e[1])
print("FAILED (%s)" % e_str)
raise
if method == "get" and r.status_code == 200:
hsh = hashlib.md5(r.content).hexdigest()
else:
hsh = ""
print(r.status_code, hsh)
return r | python | def _print(self, method, *args, **kwargs):
sess_method = getattr(self._session, method)
try:
headers = kwargs['headers']
except KeyError:
headers = {}
tpl = '[%s] %s %s'
print(tpl % (method, args[0], headers), end=' ')
try:
r = sess_method(*args, **kwargs)
except:
e = sys.exc_info()
e_str = "%s: %s" % (e[0], e[1])
print("FAILED (%s)" % e_str)
raise
if method == "get" and r.status_code == 200:
hsh = hashlib.md5(r.content).hexdigest()
else:
hsh = ""
print(r.status_code, hsh)
return r | [
"def",
"_print",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sess_method",
"=",
"getattr",
"(",
"self",
".",
"_session",
",",
"method",
")",
"try",
":",
"headers",
"=",
"kwargs",
"[",
"'headers'",
"]",
"except",
... | Output format affects integration tests.
@see: IntegrationTests.mock_output | [
"Output",
"format",
"affects",
"integration",
"tests",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/output.py#L163-L193 |
226,284 | droope/droopescan | dscan/common/functions.py | repair_url | def repair_url(url):
"""
Fixes URL.
@param url: url to repair.
@param out: instance of StandardOutput as defined in this lib.
@return: Newline characters are stripped from the URL string.
If the url string parameter does not start with http, it prepends http://
If the url string parameter does not end with a slash, appends a slash.
If the url contains a query string, it gets removed.
"""
url = url.strip('\n')
if not re.match(r"^http", url):
url = "http://" + url
if "?" in url:
url, _ = url.split('?')
if not url.endswith("/"):
return url + "/"
else :
return url | python | def repair_url(url):
url = url.strip('\n')
if not re.match(r"^http", url):
url = "http://" + url
if "?" in url:
url, _ = url.split('?')
if not url.endswith("/"):
return url + "/"
else :
return url | [
"def",
"repair_url",
"(",
"url",
")",
":",
"url",
"=",
"url",
".",
"strip",
"(",
"'\\n'",
")",
"if",
"not",
"re",
".",
"match",
"(",
"r\"^http\"",
",",
"url",
")",
":",
"url",
"=",
"\"http://\"",
"+",
"url",
"if",
"\"?\"",
"in",
"url",
":",
"url"... | Fixes URL.
@param url: url to repair.
@param out: instance of StandardOutput as defined in this lib.
@return: Newline characters are stripped from the URL string.
If the url string parameter does not start with http, it prepends http://
If the url string parameter does not end with a slash, appends a slash.
If the url contains a query string, it gets removed. | [
"Fixes",
"URL",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L22-L42 |
226,285 | droope/droopescan | dscan/common/functions.py | exc_handle | def exc_handle(url, out, testing):
"""
Handle exception. If of a determinate subset, it is stored into a file as a
single type. Otherwise, full stack is stored. Furthermore, if testing, stack
is always shown.
@param url: url which was being scanned when exception was thrown.
@param out: Output object, usually self.out.
@param testing: whether we are currently running unit tests.
"""
quiet_exceptions = [ConnectionError, ReadTimeout, ConnectTimeout,
TooManyRedirects]
type, value, _ = sys.exc_info()
if type not in quiet_exceptions or testing:
exc = traceback.format_exc()
exc_string = ("Line '%s' raised:\n" % url) + exc
out.warn(exc_string, whitespace_strp=False)
if testing:
print(exc)
else:
exc_string = "Line %s '%s: %s'" % (url, type, value)
out.warn(exc_string) | python | def exc_handle(url, out, testing):
quiet_exceptions = [ConnectionError, ReadTimeout, ConnectTimeout,
TooManyRedirects]
type, value, _ = sys.exc_info()
if type not in quiet_exceptions or testing:
exc = traceback.format_exc()
exc_string = ("Line '%s' raised:\n" % url) + exc
out.warn(exc_string, whitespace_strp=False)
if testing:
print(exc)
else:
exc_string = "Line %s '%s: %s'" % (url, type, value)
out.warn(exc_string) | [
"def",
"exc_handle",
"(",
"url",
",",
"out",
",",
"testing",
")",
":",
"quiet_exceptions",
"=",
"[",
"ConnectionError",
",",
"ReadTimeout",
",",
"ConnectTimeout",
",",
"TooManyRedirects",
"]",
"type",
",",
"value",
",",
"_",
"=",
"sys",
".",
"exc_info",
"(... | Handle exception. If of a determinate subset, it is stored into a file as a
single type. Otherwise, full stack is stored. Furthermore, if testing, stack
is always shown.
@param url: url which was being scanned when exception was thrown.
@param out: Output object, usually self.out.
@param testing: whether we are currently running unit tests. | [
"Handle",
"exception",
".",
"If",
"of",
"a",
"determinate",
"subset",
"it",
"is",
"stored",
"into",
"a",
"file",
"as",
"a",
"single",
"type",
".",
"Otherwise",
"full",
"stack",
"is",
"stored",
".",
"Furthermore",
"if",
"testing",
"stack",
"is",
"always",
... | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L223-L244 |
226,286 | droope/droopescan | dscan/common/functions.py | tail | def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
if bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
f.seek(block * BUFSIZ, 2)
# read BUFFER
data.insert(0, f.read(BUFSIZ).decode('utf-8', errors='ignore'))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
data.insert(0, f.read(bytes).decode('utf-8', errors='ignore'))
linesFound = data[0].count('\n')
size -= linesFound
bytes -= BUFSIZ
block -= 1
return ''.join(data).splitlines()[-window:] | python | def tail(f, window=20):
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
if bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
f.seek(block * BUFSIZ, 2)
# read BUFFER
data.insert(0, f.read(BUFSIZ).decode('utf-8', errors='ignore'))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
data.insert(0, f.read(bytes).decode('utf-8', errors='ignore'))
linesFound = data[0].count('\n')
size -= linesFound
bytes -= BUFSIZ
block -= 1
return ''.join(data).splitlines()[-window:] | [
"def",
"tail",
"(",
"f",
",",
"window",
"=",
"20",
")",
":",
"if",
"window",
"==",
"0",
":",
"return",
"[",
"]",
"BUFSIZ",
"=",
"1024",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"bytes",
"=",
"f",
".",
"tell",
"(",
")",
"size",
"=",
"windo... | Returns the last `window` lines of file `f` as a list.
@param window: the number of lines. | [
"Returns",
"the",
"last",
"window",
"lines",
"of",
"file",
"f",
"as",
"a",
"list",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L246-L275 |
226,287 | droope/droopescan | dscan/common/functions.py | process_host_line | def process_host_line(line):
"""
Processes a line and determines whether it is a tab-delimited CSV of
url and host.
Strips all strings.
@param line: the line to analyse.
@param opts: the options dictionary to modify.
@return: a tuple containing url, and host header if any change is
required. Otherwise, line, null is returned.
"""
if not line:
return None, None
host = None
if _line_contains_host(line):
url, host = re.split(SPLIT_PATTERN, line.strip())
else:
url = line.strip()
return url, host | python | def process_host_line(line):
if not line:
return None, None
host = None
if _line_contains_host(line):
url, host = re.split(SPLIT_PATTERN, line.strip())
else:
url = line.strip()
return url, host | [
"def",
"process_host_line",
"(",
"line",
")",
":",
"if",
"not",
"line",
":",
"return",
"None",
",",
"None",
"host",
"=",
"None",
"if",
"_line_contains_host",
"(",
"line",
")",
":",
"url",
",",
"host",
"=",
"re",
".",
"split",
"(",
"SPLIT_PATTERN",
",",... | Processes a line and determines whether it is a tab-delimited CSV of
url and host.
Strips all strings.
@param line: the line to analyse.
@param opts: the options dictionary to modify.
@return: a tuple containing url, and host header if any change is
required. Otherwise, line, null is returned. | [
"Processes",
"a",
"line",
"and",
"determines",
"whether",
"it",
"is",
"a",
"tab",
"-",
"delimited",
"CSV",
"of",
"url",
"and",
"host",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L280-L301 |
226,288 | droope/droopescan | dscan/common/functions.py | instances_get | def instances_get(opts, plugins, url_file_input, out):
"""
Creates and returns an ordered dictionary containing instances for all available
scanning plugins, sort of ordered by popularity.
@param opts: options as returned by self._options.
@param plugins: plugins as returned by plugins_util.plugins_base_get.
@param url_file_input: boolean value which indicates whether we are
scanning an individual URL or a file. This is used to determine
kwargs required.
@param out: self.out
"""
instances = OrderedDict()
preferred_order = ['wordpress', 'joomla', 'drupal']
for cms_name in preferred_order:
for plugin in plugins:
plugin_name = plugin.__name__.lower()
if cms_name == plugin_name:
instances[plugin_name] = instance_get(plugin, opts,
url_file_input, out)
for plugin in plugins:
plugin_name = plugin.__name__.lower()
if plugin_name not in preferred_order:
instances[plugin_name] = instance_get(plugin, opts,
url_file_input, out)
return instances | python | def instances_get(opts, plugins, url_file_input, out):
instances = OrderedDict()
preferred_order = ['wordpress', 'joomla', 'drupal']
for cms_name in preferred_order:
for plugin in plugins:
plugin_name = plugin.__name__.lower()
if cms_name == plugin_name:
instances[plugin_name] = instance_get(plugin, opts,
url_file_input, out)
for plugin in plugins:
plugin_name = plugin.__name__.lower()
if plugin_name not in preferred_order:
instances[plugin_name] = instance_get(plugin, opts,
url_file_input, out)
return instances | [
"def",
"instances_get",
"(",
"opts",
",",
"plugins",
",",
"url_file_input",
",",
"out",
")",
":",
"instances",
"=",
"OrderedDict",
"(",
")",
"preferred_order",
"=",
"[",
"'wordpress'",
",",
"'joomla'",
",",
"'drupal'",
"]",
"for",
"cms_name",
"in",
"preferre... | Creates and returns an ordered dictionary containing instances for all available
scanning plugins, sort of ordered by popularity.
@param opts: options as returned by self._options.
@param plugins: plugins as returned by plugins_util.plugins_base_get.
@param url_file_input: boolean value which indicates whether we are
scanning an individual URL or a file. This is used to determine
kwargs required.
@param out: self.out | [
"Creates",
"and",
"returns",
"an",
"ordered",
"dictionary",
"containing",
"instances",
"for",
"all",
"available",
"scanning",
"plugins",
"sort",
"of",
"ordered",
"by",
"popularity",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L303-L331 |
226,289 | droope/droopescan | dscan/common/functions.py | instance_get | def instance_get(plugin, opts, url_file_input, out):
"""
Return an instance dictionary for an individual plugin.
@see Scan._instances_get.
"""
inst = plugin()
hp, func, enabled_func = inst._general_init(opts, out)
name = inst._meta.label
kwargs = {
'hide_progressbar': hp,
'functionality': func,
'enabled_functionality': enabled_func
}
if url_file_input:
del kwargs['hide_progressbar']
return {
'inst': inst,
'kwargs': kwargs
} | python | def instance_get(plugin, opts, url_file_input, out):
inst = plugin()
hp, func, enabled_func = inst._general_init(opts, out)
name = inst._meta.label
kwargs = {
'hide_progressbar': hp,
'functionality': func,
'enabled_functionality': enabled_func
}
if url_file_input:
del kwargs['hide_progressbar']
return {
'inst': inst,
'kwargs': kwargs
} | [
"def",
"instance_get",
"(",
"plugin",
",",
"opts",
",",
"url_file_input",
",",
"out",
")",
":",
"inst",
"=",
"plugin",
"(",
")",
"hp",
",",
"func",
",",
"enabled_func",
"=",
"inst",
".",
"_general_init",
"(",
"opts",
",",
"out",
")",
"name",
"=",
"in... | Return an instance dictionary for an individual plugin.
@see Scan._instances_get. | [
"Return",
"an",
"instance",
"dictionary",
"for",
"an",
"individual",
"plugin",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L333-L354 |
226,290 | droope/droopescan | dscan/common/functions.py | result_anything_found | def result_anything_found(result):
"""
Interim solution for the fact that sometimes determine_scanning_method can
legitimately return a valid scanning method, but it results that the site
does not belong to a particular CMS.
@param result: the result as passed to Output.result()
@return: whether anything was found.
"""
keys = ['version', 'themes', 'plugins', 'interesting urls']
anything_found = False
for k in keys:
if k not in result:
continue
else:
if not result[k]['is_empty']:
anything_found = True
return anything_found | python | def result_anything_found(result):
keys = ['version', 'themes', 'plugins', 'interesting urls']
anything_found = False
for k in keys:
if k not in result:
continue
else:
if not result[k]['is_empty']:
anything_found = True
return anything_found | [
"def",
"result_anything_found",
"(",
"result",
")",
":",
"keys",
"=",
"[",
"'version'",
",",
"'themes'",
",",
"'plugins'",
",",
"'interesting urls'",
"]",
"anything_found",
"=",
"False",
"for",
"k",
"in",
"keys",
":",
"if",
"k",
"not",
"in",
"result",
":",... | Interim solution for the fact that sometimes determine_scanning_method can
legitimately return a valid scanning method, but it results that the site
does not belong to a particular CMS.
@param result: the result as passed to Output.result()
@return: whether anything was found. | [
"Interim",
"solution",
"for",
"the",
"fact",
"that",
"sometimes",
"determine_scanning_method",
"can",
"legitimately",
"return",
"a",
"valid",
"scanning",
"method",
"but",
"it",
"results",
"that",
"the",
"site",
"does",
"not",
"belong",
"to",
"a",
"particular",
"... | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/functions.py#L356-L373 |
226,291 | droope/droopescan | dscan/common/versions.py | VersionsFile.update | def update(self, sums):
"""
Update self.et with the sums as returned by VersionsX.sums_get
@param sums: {'version': {'file1':'hash1'}}
"""
for version in sums:
hashes = sums[version]
for filename in hashes:
hsh = hashes[filename]
file_xpath = './files/*[@url="%s"]' % filename
try:
file_add = self.root.findall(file_xpath)[0]
except IndexError:
raise ValueError("Attempted to update element '%s' which doesn't exist" % filename)
# Do not add duplicate, equal hashes.
if not self.version_exists(file_add, version, hsh):
new_ver = ET.SubElement(file_add, 'version')
new_ver.attrib = {
'md5': hsh,
'nb': version
} | python | def update(self, sums):
for version in sums:
hashes = sums[version]
for filename in hashes:
hsh = hashes[filename]
file_xpath = './files/*[@url="%s"]' % filename
try:
file_add = self.root.findall(file_xpath)[0]
except IndexError:
raise ValueError("Attempted to update element '%s' which doesn't exist" % filename)
# Do not add duplicate, equal hashes.
if not self.version_exists(file_add, version, hsh):
new_ver = ET.SubElement(file_add, 'version')
new_ver.attrib = {
'md5': hsh,
'nb': version
} | [
"def",
"update",
"(",
"self",
",",
"sums",
")",
":",
"for",
"version",
"in",
"sums",
":",
"hashes",
"=",
"sums",
"[",
"version",
"]",
"for",
"filename",
"in",
"hashes",
":",
"hsh",
"=",
"hashes",
"[",
"filename",
"]",
"file_xpath",
"=",
"'./files/*[@ur... | Update self.et with the sums as returned by VersionsX.sums_get
@param sums: {'version': {'file1':'hash1'}} | [
"Update",
"self",
".",
"et",
"with",
"the",
"sums",
"as",
"returned",
"by",
"VersionsX",
".",
"sums_get"
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/versions.py#L215-L236 |
226,292 | droope/droopescan | dscan/common/update_api.py | github_tags_newer | def github_tags_newer(github_repo, versions_file, update_majors):
"""
Get new tags from a github repository. Cannot use github API because it
doesn't support chronological ordering of tags.
@param github_repo: the github repository, e.g. 'drupal/drupal/'.
@param versions_file: the file path where the versions database can be found.
@param update_majors: major versions to update. If you want to update
the 6.x and 7.x branch, you would supply a list which would look like
['6', '7']
@return: a boolean value indicating whether an update is needed
@raise MissingMajorException: A new version from a newer major branch is
exists, but will not be downloaded due to it not being in majors.
"""
github_repo = _github_normalize(github_repo)
vf = VersionsFile(versions_file)
current_highest = vf.highest_version_major(update_majors)
tags_url = '%s%stags' % (GH, github_repo)
resp = requests.get(tags_url)
bs = BeautifulSoup(resp.text, 'lxml')
gh_versions = []
for header in bs.find_all('h4'):
tag = header.findChild('a')
if not tag:
continue # Ignore learn more header.
gh_versions.append(tag.text.strip())
newer = _newer_tags_get(current_highest, gh_versions)
return len(newer) > 0 | python | def github_tags_newer(github_repo, versions_file, update_majors):
github_repo = _github_normalize(github_repo)
vf = VersionsFile(versions_file)
current_highest = vf.highest_version_major(update_majors)
tags_url = '%s%stags' % (GH, github_repo)
resp = requests.get(tags_url)
bs = BeautifulSoup(resp.text, 'lxml')
gh_versions = []
for header in bs.find_all('h4'):
tag = header.findChild('a')
if not tag:
continue # Ignore learn more header.
gh_versions.append(tag.text.strip())
newer = _newer_tags_get(current_highest, gh_versions)
return len(newer) > 0 | [
"def",
"github_tags_newer",
"(",
"github_repo",
",",
"versions_file",
",",
"update_majors",
")",
":",
"github_repo",
"=",
"_github_normalize",
"(",
"github_repo",
")",
"vf",
"=",
"VersionsFile",
"(",
"versions_file",
")",
"current_highest",
"=",
"vf",
".",
"highes... | Get new tags from a github repository. Cannot use github API because it
doesn't support chronological ordering of tags.
@param github_repo: the github repository, e.g. 'drupal/drupal/'.
@param versions_file: the file path where the versions database can be found.
@param update_majors: major versions to update. If you want to update
the 6.x and 7.x branch, you would supply a list which would look like
['6', '7']
@return: a boolean value indicating whether an update is needed
@raise MissingMajorException: A new version from a newer major branch is
exists, but will not be downloaded due to it not being in majors. | [
"Get",
"new",
"tags",
"from",
"a",
"github",
"repository",
".",
"Cannot",
"use",
"github",
"API",
"because",
"it",
"doesn",
"t",
"support",
"chronological",
"ordering",
"of",
"tags",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L23-L53 |
226,293 | droope/droopescan | dscan/common/update_api.py | _check_newer_major | def _check_newer_major(current_highest, versions):
"""
Utility function for checking whether a new version exists and is not going
to be updated. This is undesirable because it could result in new versions
existing and not being updated. Raising is prefering to adding the new
version manually because that allows maintainers to check whether the new
version works.
@param current_highest: as returned by VersionsFile.highest_version_major()
@param versions: a list of versions.
@return: void
@raise MissingMajorException: A new version from a newer major branch is
exists, but will not be downloaded due to it not being in majors.
"""
for tag in versions:
update_majors = list(current_highest.keys())
example_version_str = current_highest[update_majors[0]]
if _tag_is_rubbish(tag, example_version_str):
continue
major = tag[0:len(update_majors[0])]
if major not in current_highest:
higher_version_present = False
for major_highest in current_highest:
if version_gt(major_highest, major):
higher_version_present = True
break
if not higher_version_present:
msg = 'Failed updating: Major %s has a new version and is not going to be updated.' % major
raise MissingMajorException(msg) | python | def _check_newer_major(current_highest, versions):
for tag in versions:
update_majors = list(current_highest.keys())
example_version_str = current_highest[update_majors[0]]
if _tag_is_rubbish(tag, example_version_str):
continue
major = tag[0:len(update_majors[0])]
if major not in current_highest:
higher_version_present = False
for major_highest in current_highest:
if version_gt(major_highest, major):
higher_version_present = True
break
if not higher_version_present:
msg = 'Failed updating: Major %s has a new version and is not going to be updated.' % major
raise MissingMajorException(msg) | [
"def",
"_check_newer_major",
"(",
"current_highest",
",",
"versions",
")",
":",
"for",
"tag",
"in",
"versions",
":",
"update_majors",
"=",
"list",
"(",
"current_highest",
".",
"keys",
"(",
")",
")",
"example_version_str",
"=",
"current_highest",
"[",
"update_maj... | Utility function for checking whether a new version exists and is not going
to be updated. This is undesirable because it could result in new versions
existing and not being updated. Raising is prefering to adding the new
version manually because that allows maintainers to check whether the new
version works.
@param current_highest: as returned by VersionsFile.highest_version_major()
@param versions: a list of versions.
@return: void
@raise MissingMajorException: A new version from a newer major branch is
exists, but will not be downloaded due to it not being in majors. | [
"Utility",
"function",
"for",
"checking",
"whether",
"a",
"new",
"version",
"exists",
"and",
"is",
"not",
"going",
"to",
"be",
"updated",
".",
"This",
"is",
"undesirable",
"because",
"it",
"could",
"result",
"in",
"new",
"versions",
"existing",
"and",
"not",... | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L65-L94 |
226,294 | droope/droopescan | dscan/common/update_api.py | _newer_tags_get | def _newer_tags_get(current_highest, versions):
"""
Returns versions from versions which are greater than than the highest
version in each major. If a newer major is present in versions which is
not present on current_highest, an exception will be raised.
@param current_highest: as returned by VersionsFile.highest_version_major()
@param versions: a list of versions.
@return: a list of versions.
@raise MissingMajorException: A new version from a newer major branch is
exists, but will not be downloaded due to it not being in majors.
"""
newer = []
for major in current_highest:
highest_version = current_highest[major]
for version in versions:
version = version.lstrip('v')
if version.startswith(major) and version_gt(version,
highest_version):
newer.append(version)
_check_newer_major(current_highest, versions)
return newer | python | def _newer_tags_get(current_highest, versions):
newer = []
for major in current_highest:
highest_version = current_highest[major]
for version in versions:
version = version.lstrip('v')
if version.startswith(major) and version_gt(version,
highest_version):
newer.append(version)
_check_newer_major(current_highest, versions)
return newer | [
"def",
"_newer_tags_get",
"(",
"current_highest",
",",
"versions",
")",
":",
"newer",
"=",
"[",
"]",
"for",
"major",
"in",
"current_highest",
":",
"highest_version",
"=",
"current_highest",
"[",
"major",
"]",
"for",
"version",
"in",
"versions",
":",
"version",... | Returns versions from versions which are greater than than the highest
version in each major. If a newer major is present in versions which is
not present on current_highest, an exception will be raised.
@param current_highest: as returned by VersionsFile.highest_version_major()
@param versions: a list of versions.
@return: a list of versions.
@raise MissingMajorException: A new version from a newer major branch is
exists, but will not be downloaded due to it not being in majors. | [
"Returns",
"versions",
"from",
"versions",
"which",
"are",
"greater",
"than",
"than",
"the",
"highest",
"version",
"in",
"each",
"major",
".",
"If",
"a",
"newer",
"major",
"is",
"present",
"in",
"versions",
"which",
"is",
"not",
"present",
"on",
"current_hig... | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L96-L118 |
226,295 | droope/droopescan | dscan/common/update_api.py | github_repo_new | def github_repo_new(repo_url, plugin_name, versions_file, update_majors):
"""
Convenience method which creates GitRepo and returns the created
instance, as well as a VersionsFile and tags which need to be updated.
@param repo_url: the github repository path, e.g. 'drupal/drupal/'
@param plugin_name: the current plugin's name (for namespace purposes).
@param versions_file: the path in disk to this plugin's versions.xml. Note
that this path must be relative to the directory where the droopescan module
is installed.
@param update_majors: major versions to update. If you want to update
the 6.x and 7.x branch, you would supply a list which would look like
['6', '7']
@return: a tuple containing (GitRepo, VersionsFile, GitRepo.tags_newer())
"""
gr = github_repo(repo_url, plugin_name)
vf = v.VersionsFile(versions_file)
new_tags = gr.tags_newer(vf, update_majors)
return gr, vf, new_tags | python | def github_repo_new(repo_url, plugin_name, versions_file, update_majors):
gr = github_repo(repo_url, plugin_name)
vf = v.VersionsFile(versions_file)
new_tags = gr.tags_newer(vf, update_majors)
return gr, vf, new_tags | [
"def",
"github_repo_new",
"(",
"repo_url",
",",
"plugin_name",
",",
"versions_file",
",",
"update_majors",
")",
":",
"gr",
"=",
"github_repo",
"(",
"repo_url",
",",
"plugin_name",
")",
"vf",
"=",
"v",
".",
"VersionsFile",
"(",
"versions_file",
")",
"new_tags",... | Convenience method which creates GitRepo and returns the created
instance, as well as a VersionsFile and tags which need to be updated.
@param repo_url: the github repository path, e.g. 'drupal/drupal/'
@param plugin_name: the current plugin's name (for namespace purposes).
@param versions_file: the path in disk to this plugin's versions.xml. Note
that this path must be relative to the directory where the droopescan module
is installed.
@param update_majors: major versions to update. If you want to update
the 6.x and 7.x branch, you would supply a list which would look like
['6', '7']
@return: a tuple containing (GitRepo, VersionsFile, GitRepo.tags_newer()) | [
"Convenience",
"method",
"which",
"creates",
"GitRepo",
"and",
"returns",
"the",
"created",
"instance",
"as",
"well",
"as",
"a",
"VersionsFile",
"and",
"tags",
"which",
"need",
"to",
"be",
"updated",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L139-L157 |
226,296 | droope/droopescan | dscan/common/update_api.py | hashes_get | def hashes_get(versions_file, base_path):
"""
Gets hashes for currently checked out version.
@param versions_file: a common.VersionsFile instance to check against.
@param base_path: where to look for files. e.g. './.update-workspace/silverstripe/'
@return: checksums {'file1': 'hash1'}
"""
files = versions_file.files_get_all()
result = {}
for f in files:
try:
result[f] = functions.md5_file(base_path + f)
except IOError:
# Not all files exist for all versions.
pass
return result | python | def hashes_get(versions_file, base_path):
files = versions_file.files_get_all()
result = {}
for f in files:
try:
result[f] = functions.md5_file(base_path + f)
except IOError:
# Not all files exist for all versions.
pass
return result | [
"def",
"hashes_get",
"(",
"versions_file",
",",
"base_path",
")",
":",
"files",
"=",
"versions_file",
".",
"files_get_all",
"(",
")",
"result",
"=",
"{",
"}",
"for",
"f",
"in",
"files",
":",
"try",
":",
"result",
"[",
"f",
"]",
"=",
"functions",
".",
... | Gets hashes for currently checked out version.
@param versions_file: a common.VersionsFile instance to check against.
@param base_path: where to look for files. e.g. './.update-workspace/silverstripe/'
@return: checksums {'file1': 'hash1'} | [
"Gets",
"hashes",
"for",
"currently",
"checked",
"out",
"version",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L159-L175 |
226,297 | droope/droopescan | dscan/common/update_api.py | file_mtime | def file_mtime(file_path):
"""
Returns the file modified time. This is with regards to the last
modification the file has had in the droopescan repo, rather than actual
file modification time in the filesystem.
@param file_path: file path relative to the executable.
@return datetime.datetime object.
"""
if not os.path.isfile(file_path):
raise IOError('File "%s" does not exist.' % file_path)
ut = subprocess.check_output(['git', 'log', '-1', '--format=%ct',
file_path]).strip()
return datetime.fromtimestamp(int(ut)) | python | def file_mtime(file_path):
if not os.path.isfile(file_path):
raise IOError('File "%s" does not exist.' % file_path)
ut = subprocess.check_output(['git', 'log', '-1', '--format=%ct',
file_path]).strip()
return datetime.fromtimestamp(int(ut)) | [
"def",
"file_mtime",
"(",
"file_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"raise",
"IOError",
"(",
"'File \"%s\" does not exist.'",
"%",
"file_path",
")",
"ut",
"=",
"subprocess",
".",
"check_output",
"(",
... | Returns the file modified time. This is with regards to the last
modification the file has had in the droopescan repo, rather than actual
file modification time in the filesystem.
@param file_path: file path relative to the executable.
@return datetime.datetime object. | [
"Returns",
"the",
"file",
"modified",
"time",
".",
"This",
"is",
"with",
"regards",
"to",
"the",
"last",
"modification",
"the",
"file",
"has",
"had",
"in",
"the",
"droopescan",
"repo",
"rather",
"than",
"actual",
"file",
"modification",
"time",
"in",
"the",
... | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L177-L191 |
226,298 | droope/droopescan | dscan/common/update_api.py | modules_get | def modules_get(url_tpl, per_page, css, max_modules=2000, pagination_type=PT.normal):
"""
Gets a list of modules. Note that this function can also be used to get
themes.
@param url_tpl: a string such as
https://drupal.org/project/project_module?page=%s. %s will be replaced with
the page number.
@param per_page: how many items there are per page.
@param css: the elements matched by this selector will be returned by the
iterator.
@param max_modules: absolute maximum modules we will attempt to request.
@param pagination_type: type of pagination. See the PaginationType enum
for more information.
@return: bs4.element.Tag
@see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors
@see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#tag
"""
page = 0
elements = False
done_so_far = 0
max_potential_pages = max_modules / per_page
print("Maximum pages: %s." % max_potential_pages)
stop = False
while elements == False or len(elements) == per_page:
url = url_tpl % page
r = requests.get(url)
bs = BeautifulSoup(r.text, 'lxml')
elements = bs.select(css)
for element in elements:
yield element
done_so_far += 1
if done_so_far >= max_modules:
stop = True
break
if stop:
break
if pagination_type == PT.normal:
print('Finished parsing page %s.' % page)
page += 1
elif pagination_type == PT.skip:
print('Finished parsing page %s.' % (page / per_page))
page += per_page
else:
assert False | python | def modules_get(url_tpl, per_page, css, max_modules=2000, pagination_type=PT.normal):
page = 0
elements = False
done_so_far = 0
max_potential_pages = max_modules / per_page
print("Maximum pages: %s." % max_potential_pages)
stop = False
while elements == False or len(elements) == per_page:
url = url_tpl % page
r = requests.get(url)
bs = BeautifulSoup(r.text, 'lxml')
elements = bs.select(css)
for element in elements:
yield element
done_so_far += 1
if done_so_far >= max_modules:
stop = True
break
if stop:
break
if pagination_type == PT.normal:
print('Finished parsing page %s.' % page)
page += 1
elif pagination_type == PT.skip:
print('Finished parsing page %s.' % (page / per_page))
page += per_page
else:
assert False | [
"def",
"modules_get",
"(",
"url_tpl",
",",
"per_page",
",",
"css",
",",
"max_modules",
"=",
"2000",
",",
"pagination_type",
"=",
"PT",
".",
"normal",
")",
":",
"page",
"=",
"0",
"elements",
"=",
"False",
"done_so_far",
"=",
"0",
"max_potential_pages",
"=",... | Gets a list of modules. Note that this function can also be used to get
themes.
@param url_tpl: a string such as
https://drupal.org/project/project_module?page=%s. %s will be replaced with
the page number.
@param per_page: how many items there are per page.
@param css: the elements matched by this selector will be returned by the
iterator.
@param max_modules: absolute maximum modules we will attempt to request.
@param pagination_type: type of pagination. See the PaginationType enum
for more information.
@return: bs4.element.Tag
@see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors
@see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#tag | [
"Gets",
"a",
"list",
"of",
"modules",
".",
"Note",
"that",
"this",
"function",
"can",
"also",
"be",
"used",
"to",
"get",
"themes",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L207-L257 |
226,299 | droope/droopescan | dscan/common/update_api.py | GitRepo.init | def init(self):
"""
Performs a clone or a fetch, depending on whether the repository has
been previously cloned or not.
"""
if os.path.isdir(self.path):
self.fetch()
else:
self.clone() | python | def init(self):
if os.path.isdir(self.path):
self.fetch()
else:
self.clone() | [
"def",
"init",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"path",
")",
":",
"self",
".",
"fetch",
"(",
")",
"else",
":",
"self",
".",
"clone",
"(",
")"
] | Performs a clone or a fetch, depending on whether the repository has
been previously cloned or not. | [
"Performs",
"a",
"clone",
"or",
"a",
"fetch",
"depending",
"on",
"whether",
"the",
"repository",
"has",
"been",
"previously",
"cloned",
"or",
"not",
"."
] | 424c48a0f9d12b4536dbef5a786f0fbd4ce9519a | https://github.com/droope/droopescan/blob/424c48a0f9d12b4536dbef5a786f0fbd4ce9519a/dscan/common/update_api.py#L307-L315 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.