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 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
44,800 | snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.get_vm | def get_vm(self, name, path=""):
"""Get a VirtualMachine object"""
if path:
return self.get_obj([vim.VirtualMachine], name, path=path)
else:
return self.get_obj([vim.VirtualMachine], name) | python | def get_vm(self, name, path=""):
"""Get a VirtualMachine object"""
if path:
return self.get_obj([vim.VirtualMachine], name, path=path)
else:
return self.get_obj([vim.VirtualMachine], name) | [
"def",
"get_vm",
"(",
"self",
",",
"name",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"path",
":",
"return",
"self",
".",
"get_obj",
"(",
"[",
"vim",
".",
"VirtualMachine",
"]",
",",
"name",
",",
"path",
"=",
"path",
")",
"else",
":",
"return",
"s... | Get a VirtualMachine object | [
"Get",
"a",
"VirtualMachine",
"object"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L856-L861 |
44,801 | snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.get_vm_failfast | def get_vm_failfast(self, name, verbose=False, vm_term='VM', path=""):
"""
Get a VirtualMachine object
fail fast if the object isn't a valid reference
"""
if verbose:
print("Finding VirtualMachine named %s..." % name)
if path:
vm = self.get_vm(name... | python | def get_vm_failfast(self, name, verbose=False, vm_term='VM', path=""):
"""
Get a VirtualMachine object
fail fast if the object isn't a valid reference
"""
if verbose:
print("Finding VirtualMachine named %s..." % name)
if path:
vm = self.get_vm(name... | [
"def",
"get_vm_failfast",
"(",
"self",
",",
"name",
",",
"verbose",
"=",
"False",
",",
"vm_term",
"=",
"'VM'",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Finding VirtualMachine named %s...\"",
"%",
"name",
")",
"if",
"path",... | Get a VirtualMachine object
fail fast if the object isn't a valid reference | [
"Get",
"a",
"VirtualMachine",
"object",
"fail",
"fast",
"if",
"the",
"object",
"isn",
"t",
"a",
"valid",
"reference"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L863-L881 |
44,802 | snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.WaitForVirtualMachineShutdown | def WaitForVirtualMachineShutdown(
self,
vm_to_poll,
timeout_seconds,
sleep_period=5
):
"""
Guest shutdown requests do not run a task we can wait for.
So, we must poll and wait for status to be poweredOff.
Returns True if shutdown, Fal... | python | def WaitForVirtualMachineShutdown(
self,
vm_to_poll,
timeout_seconds,
sleep_period=5
):
"""
Guest shutdown requests do not run a task we can wait for.
So, we must poll and wait for status to be poweredOff.
Returns True if shutdown, Fal... | [
"def",
"WaitForVirtualMachineShutdown",
"(",
"self",
",",
"vm_to_poll",
",",
"timeout_seconds",
",",
"sleep_period",
"=",
"5",
")",
":",
"seconds_waited",
"=",
"0",
"# wait counter",
"while",
"seconds_waited",
"<",
"timeout_seconds",
":",
"# sleep first, since nothing s... | Guest shutdown requests do not run a task we can wait for.
So, we must poll and wait for status to be poweredOff.
Returns True if shutdown, False if poll expired. | [
"Guest",
"shutdown",
"requests",
"do",
"not",
"run",
"a",
"task",
"we",
"can",
"wait",
"for",
".",
"So",
"we",
"must",
"poll",
"and",
"wait",
"for",
"status",
"to",
"be",
"poweredOff",
"."
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L935-L958 |
44,803 | ipapi-co/ipapi-python | ipapi/ipapi.py | location | def location(ip=None, key=None, field=None):
''' Get geolocation data for a given IP address
If field is specified, get specific field as text
Else get complete location data as JSON
'''
if field and (field not in field_list):
return 'Invalid field'
if field:
if ip:
... | python | def location(ip=None, key=None, field=None):
''' Get geolocation data for a given IP address
If field is specified, get specific field as text
Else get complete location data as JSON
'''
if field and (field not in field_list):
return 'Invalid field'
if field:
if ip:
... | [
"def",
"location",
"(",
"ip",
"=",
"None",
",",
"key",
"=",
"None",
",",
"field",
"=",
"None",
")",
":",
"if",
"field",
"and",
"(",
"field",
"not",
"in",
"field_list",
")",
":",
"return",
"'Invalid field'",
"if",
"field",
":",
"if",
"ip",
":",
"url... | Get geolocation data for a given IP address
If field is specified, get specific field as text
Else get complete location data as JSON | [
"Get",
"geolocation",
"data",
"for",
"a",
"given",
"IP",
"address",
"If",
"field",
"is",
"specified",
"get",
"specific",
"field",
"as",
"text",
"Else",
"get",
"complete",
"location",
"data",
"as",
"JSON"
] | 45896291d5e6a70fc6234c9e070dc9077ef45ccc | https://github.com/ipapi-co/ipapi-python/blob/45896291d5e6a70fc6234c9e070dc9077ef45ccc/ipapi/ipapi.py#L19-L47 |
44,804 | kellerza/pysma | example.py | main | def main():
"""Main example."""
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
parser = argparse.ArgumentParser(
description='Test the SMA webconnect library.')
parser.add_argument(
'ip', type=str, help='IP address of the Webconnect module')
parser.add_argument(
... | python | def main():
"""Main example."""
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
parser = argparse.ArgumentParser(
description='Test the SMA webconnect library.')
parser.add_argument(
'ip', type=str, help='IP address of the Webconnect module')
parser.add_argument(
... | [
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"stream",
"=",
"sys",
".",
"stdout",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Test the SMA webconnect libra... | Main example. | [
"Main",
"example",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/example.py#L55-L80 |
44,805 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubCachedAPI.data | def data(self):
"""
Get a cached post-processed result of a GitHub API call. Uses Trac cache
to avoid constant querying of the remote API. If a previous API call did
not succeed, automatically retries after a timeout.
"""
if self._next_update and datetime.now() > self._ne... | python | def data(self):
"""
Get a cached post-processed result of a GitHub API call. Uses Trac cache
to avoid constant querying of the remote API. If a previous API call did
not succeed, automatically retries after a timeout.
"""
if self._next_update and datetime.now() > self._ne... | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_next_update",
"and",
"datetime",
".",
"now",
"(",
")",
">",
"self",
".",
"_next_update",
":",
"self",
".",
"update",
"(",
")",
"return",
"self",
".",
"_data"
] | Get a cached post-processed result of a GitHub API call. Uses Trac cache
to avoid constant querying of the remote API. If a previous API call did
not succeed, automatically retries after a timeout. | [
"Get",
"a",
"cached",
"post",
"-",
"processed",
"result",
"of",
"a",
"GitHub",
"API",
"call",
".",
"Uses",
"Trac",
"cache",
"to",
"avoid",
"constant",
"querying",
"of",
"the",
"remote",
"API",
".",
"If",
"a",
"previous",
"API",
"call",
"did",
"not",
"s... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L431-L439 |
44,806 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubOrg.teams | def teams(self):
"""
Return a sequence of `GitHubTeam` objects, one for each team in this
org.
"""
teams = self._teamlist.teams()
# find out which teams have been added or removed since the last sync
current_teams = set(self._teamobjects.keys())
new_teams... | python | def teams(self):
"""
Return a sequence of `GitHubTeam` objects, one for each team in this
org.
"""
teams = self._teamlist.teams()
# find out which teams have been added or removed since the last sync
current_teams = set(self._teamobjects.keys())
new_teams... | [
"def",
"teams",
"(",
"self",
")",
":",
"teams",
"=",
"self",
".",
"_teamlist",
".",
"teams",
"(",
")",
"# find out which teams have been added or removed since the last sync",
"current_teams",
"=",
"set",
"(",
"self",
".",
"_teamobjects",
".",
"keys",
"(",
")",
... | Return a sequence of `GitHubTeam` objects, one for each team in this
org. | [
"Return",
"a",
"sequence",
"of",
"GitHubTeam",
"objects",
"one",
"for",
"each",
"team",
"in",
"this",
"org",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L548-L566 |
44,807 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubOrg.members | def members(self):
"""
Return a list of all users in this organization. Users are identified
by their login name. Note that this is computed from the teams in the
organization, because GitHub does not currently offer a WebHook for
organization membership, so converting org member... | python | def members(self):
"""
Return a list of all users in this organization. Users are identified
by their login name. Note that this is computed from the teams in the
organization, because GitHub does not currently offer a WebHook for
organization membership, so converting org member... | [
"def",
"members",
"(",
"self",
")",
":",
"allmembers",
"=",
"set",
"(",
")",
"for",
"team",
"in",
"self",
".",
"teams",
"(",
")",
":",
"allmembers",
".",
"update",
"(",
"team",
".",
"members",
"(",
")",
")",
"return",
"sorted",
"(",
"allmembers",
"... | Return a list of all users in this organization. Users are identified
by their login name. Note that this is computed from the teams in the
organization, because GitHub does not currently offer a WebHook for
organization membership, so converting org membership would lead to
stale data. | [
"Return",
"a",
"list",
"of",
"all",
"users",
"in",
"this",
"organization",
".",
"Users",
"are",
"identified",
"by",
"their",
"login",
"name",
".",
"Note",
"that",
"this",
"is",
"computed",
"from",
"the",
"teams",
"in",
"the",
"organization",
"because",
"Gi... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L588-L599 |
44,808 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubOrg.update_team | def update_team(self, slug):
"""
Trigger an update and cache invalidation for the team identified by the
given `slug`. Returns `True` on success, `False` otherwise.
:param slug: The GitHub 'slug' that identifies the team in URLs
"""
if slug not in self._teamobjects:
... | python | def update_team(self, slug):
"""
Trigger an update and cache invalidation for the team identified by the
given `slug`. Returns `True` on success, `False` otherwise.
:param slug: The GitHub 'slug' that identifies the team in URLs
"""
if slug not in self._teamobjects:
... | [
"def",
"update_team",
"(",
"self",
",",
"slug",
")",
":",
"if",
"slug",
"not",
"in",
"self",
".",
"_teamobjects",
":",
"# This case is checked and handled further up, but better be safe",
"# than sorry.",
"return",
"False",
"# pragma: no cover",
"return",
"self",
".",
... | Trigger an update and cache invalidation for the team identified by the
given `slug`. Returns `True` on success, `False` otherwise.
:param slug: The GitHub 'slug' that identifies the team in URLs | [
"Trigger",
"an",
"update",
"and",
"cache",
"invalidation",
"for",
"the",
"team",
"identified",
"by",
"the",
"given",
"slug",
".",
"Returns",
"True",
"on",
"success",
"False",
"otherwise",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L610-L621 |
44,809 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.github_api | def github_api(self, url, *args):
"""
Connect to the given GitHub API URL template by replacing all
placeholders with the given parameters and return the decoded JSON
result on success. On error, return `None`.
:param url: The path to request from the GitHub API. Contains format... | python | def github_api(self, url, *args):
"""
Connect to the given GitHub API URL template by replacing all
placeholders with the given parameters and return the decoded JSON
result on success. On error, return `None`.
:param url: The path to request from the GitHub API. Contains format... | [
"def",
"github_api",
"(",
"self",
",",
"url",
",",
"*",
"args",
")",
":",
"import",
"requests",
"import",
"urllib",
"github_api_url",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"TRAC_GITHUB_API_URL\"",
",",
"\"https://api.github.com/\"",
")",
"formatted_url",... | Connect to the given GitHub API URL template by replacing all
placeholders with the given parameters and return the decoded JSON
result on success. On error, return `None`.
:param url: The path to request from the GitHub API. Contains format
string placeholders that will be ... | [
"Connect",
"to",
"the",
"given",
"GitHub",
"API",
"URL",
"template",
"by",
"replacing",
"all",
"placeholders",
"with",
"the",
"given",
"parameters",
"and",
"return",
"the",
"decoded",
"JSON",
"result",
"on",
"success",
".",
"On",
"error",
"return",
"None",
"... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L648-L686 |
44,810 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.update_team | def update_team(self, slug):
"""
Trigger update and cache invalidation for the team identified by the
given `slug`, if any. Returns `True` if the update was successful,
`False` otherwise.
:param slug: GitHub 'slug' name for the team to be updated.
"""
if self._or... | python | def update_team(self, slug):
"""
Trigger update and cache invalidation for the team identified by the
given `slug`, if any. Returns `True` if the update was successful,
`False` otherwise.
:param slug: GitHub 'slug' name for the team to be updated.
"""
if self._or... | [
"def",
"update_team",
"(",
"self",
",",
"slug",
")",
":",
"if",
"self",
".",
"_org",
":",
"if",
"not",
"self",
".",
"_org",
".",
"has_team",
"(",
"slug",
")",
":",
"return",
"self",
".",
"_org",
".",
"update",
"(",
")",
"return",
"self",
".",
"_o... | Trigger update and cache invalidation for the team identified by the
given `slug`, if any. Returns `True` if the update was successful,
`False` otherwise.
:param slug: GitHub 'slug' name for the team to be updated. | [
"Trigger",
"update",
"and",
"cache",
"invalidation",
"for",
"the",
"team",
"identified",
"by",
"the",
"given",
"slug",
"if",
"any",
".",
"Returns",
"True",
"if",
"the",
"update",
"was",
"successful",
"False",
"otherwise",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L719-L734 |
44,811 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.get_permission_groups | def get_permission_groups(self, username):
"""
Return a list of names of the groups that the user with the specified
name is a member of. Implements an `IPermissionGroupProvider` API.
This specific implementation connects to GitHub with a dedicated user,
fetches and caches the t... | python | def get_permission_groups(self, username):
"""
Return a list of names of the groups that the user with the specified
name is a member of. Implements an `IPermissionGroupProvider` API.
This specific implementation connects to GitHub with a dedicated user,
fetches and caches the t... | [
"def",
"get_permission_groups",
"(",
"self",
",",
"username",
")",
":",
"if",
"not",
"self",
".",
"organization",
"or",
"not",
"self",
".",
"username",
"or",
"not",
"self",
".",
"access_token",
":",
"return",
"[",
"]",
"elif",
"(",
"self",
".",
"username... | Return a list of names of the groups that the user with the specified
name is a member of. Implements an `IPermissionGroupProvider` API.
This specific implementation connects to GitHub with a dedicated user,
fetches and caches the teams and their users configured at GitHub and
converts ... | [
"Return",
"a",
"list",
"of",
"names",
"of",
"the",
"groups",
"that",
"the",
"user",
"with",
"the",
"specified",
"name",
"is",
"a",
"member",
"of",
".",
"Implements",
"an",
"IPermissionGroupProvider",
"API",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L737-L757 |
44,812 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.match_request | def match_request(self, req):
"""
Return whether the handler wants to process the given request.
Implements an `IRequestHandler` API.
"""
match = self._request_re.match(req.path_info)
if match:
return True
if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGIN... | python | def match_request(self, req):
"""
Return whether the handler wants to process the given request.
Implements an `IRequestHandler` API.
"""
match = self._request_re.match(req.path_info)
if match:
return True
if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGIN... | [
"def",
"match_request",
"(",
"self",
",",
"req",
")",
":",
"match",
"=",
"self",
".",
"_request_re",
".",
"match",
"(",
"req",
".",
"path_info",
")",
"if",
"match",
":",
"return",
"True",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAC_GITHUB_ENABL... | Return whether the handler wants to process the given request.
Implements an `IRequestHandler` API. | [
"Return",
"whether",
"the",
"handler",
"wants",
"to",
"process",
"the",
"given",
"request",
".",
"Implements",
"an",
"IRequestHandler",
"API",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L763-L774 |
44,813 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.process_debug_request | def process_debug_request(self, req):
"""
Debgging helper used for testing, processes the given request and dumps
the internal state of cached user to group mappings. Note that this is
only callable if TRAC_GITHUB_ENABLE_DEBUGGING is set in the
environment.
"""
re... | python | def process_debug_request(self, req):
"""
Debgging helper used for testing, processes the given request and dumps
the internal state of cached user to group mappings. Note that this is
only callable if TRAC_GITHUB_ENABLE_DEBUGGING is set in the
environment.
"""
re... | [
"def",
"process_debug_request",
"(",
"self",
",",
"req",
")",
":",
"req",
".",
"send",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"_fetch_groups",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"'application/json'",
",",
"200",
")"
] | Debgging helper used for testing, processes the given request and dumps
the internal state of cached user to group mappings. Note that this is
only callable if TRAC_GITHUB_ENABLE_DEBUGGING is set in the
environment. | [
"Debgging",
"helper",
"used",
"for",
"testing",
"processes",
"the",
"given",
"request",
"and",
"dumps",
"the",
"internal",
"state",
"of",
"cached",
"user",
"to",
"group",
"mappings",
".",
"Note",
"that",
"this",
"is",
"only",
"callable",
"if",
"TRAC_GITHUB_ENA... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L776-L783 |
44,814 | trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.process_request | def process_request(self, req):
"""
Process the given request `req`, implements an `IRequestHandler` API.
Normally, `process_request` would return a tuple, but since none of
these requests will return an HTML page, they will all terminate
without a return value and directly send... | python | def process_request(self, req):
"""
Process the given request `req`, implements an `IRequestHandler` API.
Normally, `process_request` would return a tuple, but since none of
these requests will return an HTML page, they will all terminate
without a return value and directly send... | [
"def",
"process_request",
"(",
"self",
",",
"req",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAC_GITHUB_ENABLE_DEBUGGING'",
",",
"None",
")",
"is",
"not",
"None",
":",
"debug_match",
"=",
"self",
".",
"_debug_request_re",
".",
"match",
"(",... | Process the given request `req`, implements an `IRequestHandler` API.
Normally, `process_request` would return a tuple, but since none of
these requests will return an HTML page, they will all terminate
without a return value and directly send a response. | [
"Process",
"the",
"given",
"request",
"req",
"implements",
"an",
"IRequestHandler",
"API",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L785-L841 |
44,815 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_children | def get_content_children(self, content_id, expand=None, parent_version=None, callback=None):
"""
Returns a map of the direct children of a piece of Content. Content can have multiple types of children -
for example a Page can have children that are also Pages, but it can also have Comments and A... | python | def get_content_children(self, content_id, expand=None, parent_version=None, callback=None):
"""
Returns a map of the direct children of a piece of Content. Content can have multiple types of children -
for example a Page can have children that are also Pages, but it can also have Comments and A... | [
"def",
"get_content_children",
"(",
"self",
",",
"content_id",
",",
"expand",
"=",
"None",
",",
"parent_version",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand",
":",
"params",
"[",
"\"expand\"",
"]",
"=",
... | Returns a map of the direct children of a piece of Content. Content can have multiple types of children -
for example a Page can have children that are also Pages, but it can also have Comments and Attachments.
The {@link ContentType}(s) of the children returned is specified by the "expand" query param... | [
"Returns",
"a",
"map",
"of",
"the",
"direct",
"children",
"of",
"a",
"piece",
"of",
"Content",
".",
"Content",
"can",
"have",
"multiple",
"types",
"of",
"children",
"-",
"for",
"example",
"a",
"Page",
"can",
"have",
"children",
"that",
"are",
"also",
"Pa... | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L325-L351 |
44,816 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_descendants | def get_content_descendants(self, content_id, expand=None, callback=None):
"""
Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants -
for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments.
... | python | def get_content_descendants(self, content_id, expand=None, callback=None):
"""
Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants -
for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments.
... | [
"def",
"get_content_descendants",
"(",
"self",
",",
"content_id",
",",
"expand",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand",
":",
"params",
"[",
"\"expand\"",
"]",
"=",
"expand",
"return",
"self",
".",
... | Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants -
for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments.
The {@link ContentType}(s) of the descendants returned is specified by the "expand" query ... | [
"Returns",
"a",
"map",
"of",
"the",
"descendants",
"of",
"a",
"piece",
"of",
"Content",
".",
"Content",
"can",
"have",
"multiple",
"types",
"of",
"descendants",
"-",
"for",
"example",
"a",
"Page",
"can",
"have",
"descendants",
"that",
"are",
"also",
"Pages... | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L385-L406 |
44,817 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_descendants_by_type | def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None,
callback=None):
"""
Returns the direct descendants of a piece of Content, limited to a single descendant type.
The {@link ContentType}(s) of the descend... | python | def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None,
callback=None):
"""
Returns the direct descendants of a piece of Content, limited to a single descendant type.
The {@link ContentType}(s) of the descend... | [
"def",
"get_content_descendants_by_type",
"(",
"self",
",",
"content_id",
",",
"child_type",
",",
"expand",
"=",
"None",
",",
"start",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand"... | Returns the direct descendants of a piece of Content, limited to a single descendant type.
The {@link ContentType}(s) of the descendants returned is specified by the "type" path parameter in the request.
Currently the only supported descendants are comment descendants of non-comment Content.
:... | [
"Returns",
"the",
"direct",
"descendants",
"of",
"a",
"piece",
"of",
"Content",
"limited",
"to",
"a",
"single",
"descendant",
"type",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L408-L437 |
44,818 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_properties | def get_content_properties(self, content_id, expand=None, start=None, limit=None, callback=None):
"""
Returns a paginated list of content properties.
Content properties are a key / value store of properties attached to a piece of Content.
The key is a string, and the value is a JSON-ser... | python | def get_content_properties(self, content_id, expand=None, start=None, limit=None, callback=None):
"""
Returns a paginated list of content properties.
Content properties are a key / value store of properties attached to a piece of Content.
The key is a string, and the value is a JSON-ser... | [
"def",
"get_content_properties",
"(",
"self",
",",
"content_id",
",",
"expand",
"=",
"None",
",",
"start",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand",
":",
"params",
"[",
"\... | Returns a paginated list of content properties.
Content properties are a key / value store of properties attached to a piece of Content.
The key is a string, and the value is a JSON-serializable object.
:param content_id (string): A string containing the id of the property content container.
... | [
"Returns",
"a",
"paginated",
"list",
"of",
"content",
"properties",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L536-L561 |
44,819 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.create_new_attachment_by_content_id | def create_new_attachment_by_content_id(self, content_id, attachments, callback=None):
"""
Add one or more attachments to a Confluence Content entity, with optional comments.
Comments are optional, but if included there must be as many comments as there are files, and the comments must
... | python | def create_new_attachment_by_content_id(self, content_id, attachments, callback=None):
"""
Add one or more attachments to a Confluence Content entity, with optional comments.
Comments are optional, but if included there must be as many comments as there are files, and the comments must
... | [
"def",
"create_new_attachment_by_content_id",
"(",
"self",
",",
"content_id",
",",
"attachments",
",",
"callback",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"attachments",
",",
"list",
")",
":",
"assert",
"all",
"(",
"isinstance",
"(",
"at",
",",
"dict... | Add one or more attachments to a Confluence Content entity, with optional comments.
Comments are optional, but if included there must be as many comments as there are files, and the comments must
be in the same order as the files.
:param content_id (string): A string containing the id of the at... | [
"Add",
"one",
"or",
"more",
"attachments",
"to",
"a",
"Confluence",
"Content",
"entity",
"with",
"optional",
"comments",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L797-L821 |
44,820 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.create_new_space | def create_new_space(self, space_definition, callback=None):
"""
Creates a new Space.
The incoming Space does not include an id, but must include a Key and Name, and should include a Description.
:param space_definition (dict): The dictionary describing the new space. Must include keys ... | python | def create_new_space(self, space_definition, callback=None):
"""
Creates a new Space.
The incoming Space does not include an id, but must include a Key and Name, and should include a Description.
:param space_definition (dict): The dictionary describing the new space. Must include keys ... | [
"def",
"create_new_space",
"(",
"self",
",",
"space_definition",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"space_definition",
",",
"dict",
")",
"and",
"{",
"\"key\"",
",",
"\"name\"",
",",
"\"description\"",
"}",
"<=",
"set",
"(",... | Creates a new Space.
The incoming Space does not include an id, but must include a Key and Name, and should include a Description.
:param space_definition (dict): The dictionary describing the new space. Must include keys "key", "name",
and "description".
... | [
"Creates",
"a",
"new",
"Space",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L892-L918 |
44,821 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_content_by_id | def update_content_by_id(self, content_data, content_id, callback=None):
"""
Updates a piece of Content, or restores if it is trashed.
The body contains the representation of the content. Must include the new version number.
To restore a piece of content that has the status of trashed ... | python | def update_content_by_id(self, content_data, content_id, callback=None):
"""
Updates a piece of Content, or restores if it is trashed.
The body contains the representation of the content. Must include the new version number.
To restore a piece of content that has the status of trashed ... | [
"def",
"update_content_by_id",
"(",
"self",
",",
"content_data",
",",
"content_id",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"content_data",
",",
"dict",
")",
"and",
"set",
"(",
"content_data",
".",
"keys",
"(",
")",
")",
">=",
... | Updates a piece of Content, or restores if it is trashed.
The body contains the representation of the content. Must include the new version number.
To restore a piece of content that has the status of trashed the content must have it's version incremented,
and status set to current. No other f... | [
"Updates",
"a",
"piece",
"of",
"Content",
"or",
"restores",
"if",
"it",
"is",
"trashed",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L948-L990 |
44,822 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_attachment_metadata | def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None):
"""
Update the non-binary data of an Attachment.
This resource can be used to update an attachment's filename, media-type, comment, and parent container.
:param content_id (string): A string co... | python | def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None):
"""
Update the non-binary data of an Attachment.
This resource can be used to update an attachment's filename, media-type, comment, and parent container.
:param content_id (string): A string co... | [
"def",
"update_attachment_metadata",
"(",
"self",
",",
"content_id",
",",
"attachment_id",
",",
"new_metadata",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"new_metadata",
",",
"dict",
")",
"and",
"set",
"(",
"new_metadata",
".",
"keys... | Update the non-binary data of an Attachment.
This resource can be used to update an attachment's filename, media-type, comment, and parent container.
:param content_id (string): A string containing the ID of the attachments content container.
:param attachment_id (string): The ID of the attachm... | [
"Update",
"the",
"non",
"-",
"binary",
"data",
"of",
"an",
"Attachment",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L992-L1020 |
44,823 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_attachment | def update_attachment(self, content_id, attachment_id, attachment, callback=None):
"""
Update the binary data of an Attachment, and optionally the comment and the minor edit field.
This adds a new version of the attachment, containing the new binary data, filename, and content-type.
Wh... | python | def update_attachment(self, content_id, attachment_id, attachment, callback=None):
"""
Update the binary data of an Attachment, and optionally the comment and the minor edit field.
This adds a new version of the attachment, containing the new binary data, filename, and content-type.
Wh... | [
"def",
"update_attachment",
"(",
"self",
",",
"content_id",
",",
"attachment_id",
",",
"attachment",
",",
"callback",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"attachment",
",",
"dict",
")",
":",
"assert",
"\"file\"",
"in",
"list",
"(",
"attachment",
... | Update the binary data of an Attachment, and optionally the comment and the minor edit field.
This adds a new version of the attachment, containing the new binary data, filename, and content-type.
When updating the binary data of an attachment, the comment related to it together with the field that
... | [
"Update",
"the",
"binary",
"data",
"of",
"an",
"Attachment",
"and",
"optionally",
"the",
"comment",
"and",
"the",
"minor",
"edit",
"field",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1022-L1049 |
44,824 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_property | def update_property(self, content_id, property_key, new_property_data, callback=None):
"""
Updates a content property.
The body contains the representation of the content property. Must include the property id, and the new version
number. Attempts to create a new content property if the... | python | def update_property(self, content_id, property_key, new_property_data, callback=None):
"""
Updates a content property.
The body contains the representation of the content property. Must include the property id, and the new version
number. Attempts to create a new content property if the... | [
"def",
"update_property",
"(",
"self",
",",
"content_id",
",",
"property_key",
",",
"new_property_data",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"new_property_data",
",",
"dict",
")",
"and",
"{",
"\"key\"",
",",
"\"value\"",
",",
... | Updates a content property.
The body contains the representation of the content property. Must include the property id, and the new version
number. Attempts to create a new content property if the given version number is 1, just like
{@link #create(com.atlassian.confluence.api.model.content.id.... | [
"Updates",
"a",
"content",
"property",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1051-L1083 |
44,825 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_space | def update_space(self, space_key, space_definition, callback=None):
"""
Updates a Space.
Currently only the Space name, description and homepage can be updated.
:param space_key (string): The key of the space to update.
:param space_definition (dict): The dictionary describing t... | python | def update_space(self, space_key, space_definition, callback=None):
"""
Updates a Space.
Currently only the Space name, description and homepage can be updated.
:param space_key (string): The key of the space to update.
:param space_definition (dict): The dictionary describing t... | [
"def",
"update_space",
"(",
"self",
",",
"space_key",
",",
"space_definition",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"space_definition",
",",
"dict",
")",
"and",
"{",
"\"key\"",
",",
"\"name\"",
",",
"\"description\"",
"}",
"<=... | Updates a Space.
Currently only the Space name, description and homepage can be updated.
:param space_key (string): The key of the space to update.
:param space_definition (dict): The dictionary describing the updated space metadata. This should include
"... | [
"Updates",
"a",
"Space",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1085-L1113 |
44,826 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.convert_contentbody_to_new_type | def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None):
"""
Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destinatio... | python | def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None):
"""
Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destinatio... | [
"def",
"convert_contentbody_to_new_type",
"(",
"self",
",",
"content_data",
",",
"old_representation",
",",
"new_representation",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"{",
"old_representation",
",",
"new_representation",
"}",
"<",
"{",
"\"storage\"",
",... | Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destination Representation Supported
--------------------------------------------------------------
"storage" | ... | [
"Converts",
"between",
"content",
"body",
"representations",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1115-L1141 |
44,827 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.delete_label_by_id | def delete_label_by_id(self, content_id, label_name, callback=None):
"""
Deletes a labels to the specified content.
There is an alternative form of this delete method that is not implemented. A DELETE request to
/rest/api/content/{id}/label/{label} will also delete a label, but is more ... | python | def delete_label_by_id(self, content_id, label_name, callback=None):
"""
Deletes a labels to the specified content.
There is an alternative form of this delete method that is not implemented. A DELETE request to
/rest/api/content/{id}/label/{label} will also delete a label, but is more ... | [
"def",
"delete_label_by_id",
"(",
"self",
",",
"content_id",
",",
"label_name",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"name\"",
":",
"label_name",
"}",
"return",
"self",
".",
"_service_delete_request",
"(",
"\"rest/api/content/{id}/label\""... | Deletes a labels to the specified content.
There is an alternative form of this delete method that is not implemented. A DELETE request to
/rest/api/content/{id}/label/{label} will also delete a label, but is more limited in the label name
that can be accepted (and has no real apparent upside).... | [
"Deletes",
"a",
"labels",
"to",
"the",
"specified",
"content",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1160-L1178 |
44,828 | rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.delete_space | def delete_space(self, space_key, callback=None):
"""
Deletes a Space.
The space is deleted in a long running task, so the space cannot be considered deleted when this method returns.
Clients can follow the status link in the response and poll it until the task completes.
:para... | python | def delete_space(self, space_key, callback=None):
"""
Deletes a Space.
The space is deleted in a long running task, so the space cannot be considered deleted when this method returns.
Clients can follow the status link in the response and poll it until the task completes.
:para... | [
"def",
"delete_space",
"(",
"self",
",",
"space_key",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_service_delete_request",
"(",
"\"rest/api/space/{key}\"",
".",
"format",
"(",
"key",
"=",
"space_key",
")",
",",
"callback",
"=",
"callback",... | Deletes a Space.
The space is deleted in a long running task, so the space cannot be considered deleted when this method returns.
Clients can follow the status link in the response and poll it until the task completes.
:param space_key (string): The key of the space to delete.
:param c... | [
"Deletes",
"a",
"Space",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1195-L1209 |
44,829 | kellerza/pysma | pysma/__init__.py | Sensors.add | def add(self, sensor):
"""Add a sensor, warning if it exists."""
if isinstance(sensor, (list, tuple)):
for sss in sensor:
self.add(sss)
return
if not isinstance(sensor, Sensor):
raise TypeError("pysma.Sensor expected")
if sensor.name ... | python | def add(self, sensor):
"""Add a sensor, warning if it exists."""
if isinstance(sensor, (list, tuple)):
for sss in sensor:
self.add(sss)
return
if not isinstance(sensor, Sensor):
raise TypeError("pysma.Sensor expected")
if sensor.name ... | [
"def",
"add",
"(",
"self",
",",
"sensor",
")",
":",
"if",
"isinstance",
"(",
"sensor",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"sss",
"in",
"sensor",
":",
"self",
".",
"add",
"(",
"sss",
")",
"return",
"if",
"not",
"isinstance",
"("... | Add a sensor, warning if it exists. | [
"Add",
"a",
"sensor",
"warning",
"if",
"it",
"exists",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L149-L167 |
44,830 | kellerza/pysma | pysma/__init__.py | SMA._fetch_json | def _fetch_json(self, url, payload):
"""Fetch json data for requests."""
params = {
'data': json.dumps(payload),
'headers': {'content-type': 'application/json'},
'params': {'sid': self.sma_sid} if self.sma_sid else None,
}
for _ in range(3):
... | python | def _fetch_json(self, url, payload):
"""Fetch json data for requests."""
params = {
'data': json.dumps(payload),
'headers': {'content-type': 'application/json'},
'params': {'sid': self.sma_sid} if self.sma_sid else None,
}
for _ in range(3):
... | [
"def",
"_fetch_json",
"(",
"self",
",",
"url",
",",
"payload",
")",
":",
"params",
"=",
"{",
"'data'",
":",
"json",
".",
"dumps",
"(",
"payload",
")",
",",
"'headers'",
":",
"{",
"'content-type'",
":",
"'application/json'",
"}",
",",
"'params'",
":",
"... | Fetch json data for requests. | [
"Fetch",
"json",
"data",
"for",
"requests",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L190-L206 |
44,831 | kellerza/pysma | pysma/__init__.py | SMA.new_session | def new_session(self):
"""Establish a new session."""
body = yield from self._fetch_json(URL_LOGIN, self._new_session_data)
self.sma_sid = jmespath.search('result.sid', body)
if self.sma_sid:
return True
msg = 'Could not start session, %s, got {}'.format(body)
... | python | def new_session(self):
"""Establish a new session."""
body = yield from self._fetch_json(URL_LOGIN, self._new_session_data)
self.sma_sid = jmespath.search('result.sid', body)
if self.sma_sid:
return True
msg = 'Could not start session, %s, got {}'.format(body)
... | [
"def",
"new_session",
"(",
"self",
")",
":",
"body",
"=",
"yield",
"from",
"self",
".",
"_fetch_json",
"(",
"URL_LOGIN",
",",
"self",
".",
"_new_session_data",
")",
"self",
".",
"sma_sid",
"=",
"jmespath",
".",
"search",
"(",
"'result.sid'",
",",
"body",
... | Establish a new session. | [
"Establish",
"a",
"new",
"session",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L209-L225 |
44,832 | kellerza/pysma | pysma/__init__.py | SMA.read | def read(self, sensors):
"""Read a set of keys."""
payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))}
if self.sma_sid is None:
yield from self.new_session()
if self.sma_sid is None:
return False
body = yield from self._fetch_jso... | python | def read(self, sensors):
"""Read a set of keys."""
payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))}
if self.sma_sid is None:
yield from self.new_session()
if self.sma_sid is None:
return False
body = yield from self._fetch_jso... | [
"def",
"read",
"(",
"self",
",",
"sensors",
")",
":",
"payload",
"=",
"{",
"'destDev'",
":",
"[",
"]",
",",
"'keys'",
":",
"list",
"(",
"set",
"(",
"[",
"s",
".",
"key",
"for",
"s",
"in",
"sensors",
"]",
")",
")",
"}",
"if",
"self",
".",
"sma... | Read a set of keys. | [
"Read",
"a",
"set",
"of",
"keys",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L236-L257 |
44,833 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.media | def media(self, uri):
"""Play a media file."""
try:
local_path, _ = urllib.request.urlretrieve(uri)
metadata = mutagen.File(local_path, easy=True)
if metadata.tags:
self._tags = metadata.tags
title = self._tags.get(TAG_TITLE, [])
... | python | def media(self, uri):
"""Play a media file."""
try:
local_path, _ = urllib.request.urlretrieve(uri)
metadata = mutagen.File(local_path, easy=True)
if metadata.tags:
self._tags = metadata.tags
title = self._tags.get(TAG_TITLE, [])
... | [
"def",
"media",
"(",
"self",
",",
"uri",
")",
":",
"try",
":",
"local_path",
",",
"_",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"uri",
")",
"metadata",
"=",
"mutagen",
".",
"File",
"(",
"local_path",
",",
"easy",
"=",
"True",
")",
"i... | Play a media file. | [
"Play",
"a",
"media",
"file",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L99-L124 |
44,834 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.play | def play(self):
"""Change state to playing."""
if self.state == STATE_PAUSED:
self._player.set_state(Gst.State.PLAYING)
self.state = STATE_PLAYING | python | def play(self):
"""Change state to playing."""
if self.state == STATE_PAUSED:
self._player.set_state(Gst.State.PLAYING)
self.state = STATE_PLAYING | [
"def",
"play",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_PAUSED",
":",
"self",
".",
"_player",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"PLAYING",
")",
"self",
".",
"state",
"=",
"STATE_PLAYING"
] | Change state to playing. | [
"Change",
"state",
"to",
"playing",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L126-L130 |
44,835 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.pause | def pause(self):
"""Change state to paused."""
if self.state == STATE_PLAYING:
self._player.set_state(Gst.State.PAUSED)
self.state = STATE_PAUSED | python | def pause(self):
"""Change state to paused."""
if self.state == STATE_PLAYING:
self._player.set_state(Gst.State.PAUSED)
self.state = STATE_PAUSED | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_PLAYING",
":",
"self",
".",
"_player",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"PAUSED",
")",
"self",
".",
"state",
"=",
"STATE_PAUSED"
] | Change state to paused. | [
"Change",
"state",
"to",
"paused",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L132-L136 |
44,836 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.stop | def stop(self):
"""Stop pipeline."""
urllib.request.urlcleanup()
self._player.set_state(Gst.State.NULL)
self.state = STATE_IDLE
self._tags = {} | python | def stop(self):
"""Stop pipeline."""
urllib.request.urlcleanup()
self._player.set_state(Gst.State.NULL)
self.state = STATE_IDLE
self._tags = {} | [
"def",
"stop",
"(",
"self",
")",
":",
"urllib",
".",
"request",
".",
"urlcleanup",
"(",
")",
"self",
".",
"_player",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"NULL",
")",
"self",
".",
"state",
"=",
"STATE_IDLE",
"self",
".",
"_tags",
"=",
"... | Stop pipeline. | [
"Stop",
"pipeline",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L138-L143 |
44,837 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.set_position | def set_position(self, position):
"""Set media position."""
if position > self._duration():
return
position_ns = position * _NANOSEC_MULT
self._manager[ATTR_POSITION] = position
self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns) | python | def set_position(self, position):
"""Set media position."""
if position > self._duration():
return
position_ns = position * _NANOSEC_MULT
self._manager[ATTR_POSITION] = position
self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns) | [
"def",
"set_position",
"(",
"self",
",",
"position",
")",
":",
"if",
"position",
">",
"self",
".",
"_duration",
"(",
")",
":",
"return",
"position_ns",
"=",
"position",
"*",
"_NANOSEC_MULT",
"self",
".",
"_manager",
"[",
"ATTR_POSITION",
"]",
"=",
"positio... | Set media position. | [
"Set",
"media",
"position",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L145-L151 |
44,838 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.state | def state(self, state):
"""Set state."""
self._state = state
self._manager[ATTR_STATE] = state
_LOGGER.info('state changed to %s', state) | python | def state(self, state):
"""Set state."""
self._state = state
self._manager[ATTR_STATE] = state
_LOGGER.info('state changed to %s', state) | [
"def",
"state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_state",
"=",
"state",
"self",
".",
"_manager",
"[",
"ATTR_STATE",
"]",
"=",
"state",
"_LOGGER",
".",
"info",
"(",
"'state changed to %s'",
",",
"state",
")"
] | Set state. | [
"Set",
"state",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L165-L169 |
44,839 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess._duration | def _duration(self):
"""Get media duration."""
duration = 0
if self.state != STATE_IDLE:
resp = self._player.query_duration(_FORMAT_TIME)
duration = resp[1] // _NANOSEC_MULT
return duration | python | def _duration(self):
"""Get media duration."""
duration = 0
if self.state != STATE_IDLE:
resp = self._player.query_duration(_FORMAT_TIME)
duration = resp[1] // _NANOSEC_MULT
return duration | [
"def",
"_duration",
"(",
"self",
")",
":",
"duration",
"=",
"0",
"if",
"self",
".",
"state",
"!=",
"STATE_IDLE",
":",
"resp",
"=",
"self",
".",
"_player",
".",
"query_duration",
"(",
"_FORMAT_TIME",
")",
"duration",
"=",
"resp",
"[",
"1",
"]",
"//",
... | Get media duration. | [
"Get",
"media",
"duration",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L171-L177 |
44,840 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess._position | def _position(self):
"""Get media position."""
position = 0
if self.state != STATE_IDLE:
resp = self._player.query_position(_FORMAT_TIME)
position = resp[1] // _NANOSEC_MULT
return position | python | def _position(self):
"""Get media position."""
position = 0
if self.state != STATE_IDLE:
resp = self._player.query_position(_FORMAT_TIME)
position = resp[1] // _NANOSEC_MULT
return position | [
"def",
"_position",
"(",
"self",
")",
":",
"position",
"=",
"0",
"if",
"self",
".",
"state",
"!=",
"STATE_IDLE",
":",
"resp",
"=",
"self",
".",
"_player",
".",
"query_position",
"(",
"_FORMAT_TIME",
")",
"position",
"=",
"resp",
"[",
"1",
"]",
"//",
... | Get media position. | [
"Get",
"media",
"position",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L179-L185 |
44,841 | happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess._on_message | def _on_message(self, bus, message): # pylint: disable=unused-argument
"""When a message is received from Gstreamer."""
if message.type == Gst.MessageType.EOS:
self.stop()
elif message.type == Gst.MessageType.ERROR:
self.stop()
err, _ = message.parse_error()
... | python | def _on_message(self, bus, message): # pylint: disable=unused-argument
"""When a message is received from Gstreamer."""
if message.type == Gst.MessageType.EOS:
self.stop()
elif message.type == Gst.MessageType.ERROR:
self.stop()
err, _ = message.parse_error()
... | [
"def",
"_on_message",
"(",
"self",
",",
"bus",
",",
"message",
")",
":",
"# pylint: disable=unused-argument",
"if",
"message",
".",
"type",
"==",
"Gst",
".",
"MessageType",
".",
"EOS",
":",
"self",
".",
"stop",
"(",
")",
"elif",
"message",
".",
"type",
"... | When a message is received from Gstreamer. | [
"When",
"a",
"message",
"is",
"received",
"from",
"Gstreamer",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L187-L194 |
44,842 | spulec/pep8ify | pep8ify/fixes/fix_whitespace_before_inline_comment.py | get_previous_node | def get_previous_node(node):
"""
Return the node before this node.
"""
if node.prev_sibling:
return node.prev_sibling
if node.parent:
return get_previous_node(node.parent) | python | def get_previous_node(node):
"""
Return the node before this node.
"""
if node.prev_sibling:
return node.prev_sibling
if node.parent:
return get_previous_node(node.parent) | [
"def",
"get_previous_node",
"(",
"node",
")",
":",
"if",
"node",
".",
"prev_sibling",
":",
"return",
"node",
".",
"prev_sibling",
"if",
"node",
".",
"parent",
":",
"return",
"get_previous_node",
"(",
"node",
".",
"parent",
")"
] | Return the node before this node. | [
"Return",
"the",
"node",
"before",
"this",
"node",
"."
] | cf1815f7bad9882027289bdb2f77604b68962ca7 | https://github.com/spulec/pep8ify/blob/cf1815f7bad9882027289bdb2f77604b68962ca7/pep8ify/fixes/fix_whitespace_before_inline_comment.py#L6-L13 |
44,843 | makinacorpus/django-screamshot | screamshot/utils.py | casperjs_command_kwargs | def casperjs_command_kwargs():
""" will construct kwargs for cmd
"""
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
'universal_newlines': True
}
phantom_js_cmd = app_settings['PHANTOMJS_CMD']
if phantom_js_cmd:
path = '{0}:{1}'.format(
... | python | def casperjs_command_kwargs():
""" will construct kwargs for cmd
"""
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
'universal_newlines': True
}
phantom_js_cmd = app_settings['PHANTOMJS_CMD']
if phantom_js_cmd:
path = '{0}:{1}'.format(
... | [
"def",
"casperjs_command_kwargs",
"(",
")",
":",
"kwargs",
"=",
"{",
"'stdout'",
":",
"subprocess",
".",
"PIPE",
",",
"'stderr'",
":",
"subprocess",
".",
"PIPE",
",",
"'universal_newlines'",
":",
"True",
"}",
"phantom_js_cmd",
"=",
"app_settings",
"[",
"'PHANT... | will construct kwargs for cmd | [
"will",
"construct",
"kwargs",
"for",
"cmd"
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L40-L54 |
44,844 | makinacorpus/django-screamshot | screamshot/utils.py | casperjs_capture | def casperjs_capture(stream, url, method=None, width=None, height=None,
selector=None, data=None, waitfor=None, size=None,
crop=None, render='png', wait=None):
"""
Captures web pages using ``casperjs``
"""
if isinstance(stream, six.string_types):
output ... | python | def casperjs_capture(stream, url, method=None, width=None, height=None,
selector=None, data=None, waitfor=None, size=None,
crop=None, render='png', wait=None):
"""
Captures web pages using ``casperjs``
"""
if isinstance(stream, six.string_types):
output ... | [
"def",
"casperjs_capture",
"(",
"stream",
",",
"url",
",",
"method",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"selector",
"=",
"None",
",",
"data",
"=",
"None",
",",
"waitfor",
"=",
"None",
",",
"size",
"=",
"None",
... | Captures web pages using ``casperjs`` | [
"Captures",
"web",
"pages",
"using",
"casperjs"
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L108-L158 |
44,845 | makinacorpus/django-screamshot | screamshot/utils.py | process_casperjs_stdout | def process_casperjs_stdout(stdout):
"""Parse and digest capture script output.
"""
for line in stdout.splitlines():
bits = line.split(':', 1)
if len(bits) < 2:
bits = ('INFO', bits)
level, msg = bits
if level == 'FATAL':
logger.fatal(msg)
... | python | def process_casperjs_stdout(stdout):
"""Parse and digest capture script output.
"""
for line in stdout.splitlines():
bits = line.split(':', 1)
if len(bits) < 2:
bits = ('INFO', bits)
level, msg = bits
if level == 'FATAL':
logger.fatal(msg)
... | [
"def",
"process_casperjs_stdout",
"(",
"stdout",
")",
":",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
":",
"bits",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"bits",
"=",
"... | Parse and digest capture script output. | [
"Parse",
"and",
"digest",
"capture",
"script",
"output",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L161-L176 |
44,846 | makinacorpus/django-screamshot | screamshot/utils.py | parse_url | def parse_url(request, url):
"""Parse url URL parameter."""
try:
validate = URLValidator()
validate(url)
except ValidationError:
if url.startswith('/'):
host = request.get_host()
scheme = 'https' if request.is_secure() else 'http'
url = '{scheme}:/... | python | def parse_url(request, url):
"""Parse url URL parameter."""
try:
validate = URLValidator()
validate(url)
except ValidationError:
if url.startswith('/'):
host = request.get_host()
scheme = 'https' if request.is_secure() else 'http'
url = '{scheme}:/... | [
"def",
"parse_url",
"(",
"request",
",",
"url",
")",
":",
"try",
":",
"validate",
"=",
"URLValidator",
"(",
")",
"validate",
"(",
"url",
")",
"except",
"ValidationError",
":",
"if",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"host",
"=",
"request"... | Parse url URL parameter. | [
"Parse",
"url",
"URL",
"parameter",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L198-L212 |
44,847 | makinacorpus/django-screamshot | screamshot/utils.py | parse_render | def parse_render(render):
"""Parse render URL parameter.
>>> parse_render(None)
'png'
>>> parse_render('html')
'png'
>>> parse_render('png')
'png'
>>> parse_render('jpg')
'jpeg'
>>> parse_render('gif')
'gif'
"""
formats = {
'jpeg': guess_all_extensions('image... | python | def parse_render(render):
"""Parse render URL parameter.
>>> parse_render(None)
'png'
>>> parse_render('html')
'png'
>>> parse_render('png')
'png'
>>> parse_render('jpg')
'jpeg'
>>> parse_render('gif')
'gif'
"""
formats = {
'jpeg': guess_all_extensions('image... | [
"def",
"parse_render",
"(",
"render",
")",
":",
"formats",
"=",
"{",
"'jpeg'",
":",
"guess_all_extensions",
"(",
"'image/jpeg'",
")",
",",
"'png'",
":",
"guess_all_extensions",
"(",
"'image/png'",
")",
",",
"'gif'",
":",
"guess_all_extensions",
"(",
"'image/gif'... | Parse render URL parameter.
>>> parse_render(None)
'png'
>>> parse_render('html')
'png'
>>> parse_render('png')
'png'
>>> parse_render('jpg')
'jpeg'
>>> parse_render('gif')
'gif' | [
"Parse",
"render",
"URL",
"parameter",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L215-L248 |
44,848 | makinacorpus/django-screamshot | screamshot/utils.py | parse_size | def parse_size(size_raw):
""" Parse size URL parameter.
>>> parse_size((100,None))
None
>>> parse_size('300x100')
(300, 100)
>>> parse_size('300x')
None
>>> parse_size('x100')
None
>>> parse_size('x')
None
"""
try:
width_str, height_str = size_raw.lower().spl... | python | def parse_size(size_raw):
""" Parse size URL parameter.
>>> parse_size((100,None))
None
>>> parse_size('300x100')
(300, 100)
>>> parse_size('300x')
None
>>> parse_size('x100')
None
>>> parse_size('x')
None
"""
try:
width_str, height_str = size_raw.lower().spl... | [
"def",
"parse_size",
"(",
"size_raw",
")",
":",
"try",
":",
"width_str",
",",
"height_str",
"=",
"size_raw",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'x'",
")",
"except",
"AttributeError",
":",
"size",
"=",
"None",
"except",
"ValueError",
":",
"size",... | Parse size URL parameter.
>>> parse_size((100,None))
None
>>> parse_size('300x100')
(300, 100)
>>> parse_size('300x')
None
>>> parse_size('x100')
None
>>> parse_size('x')
None | [
"Parse",
"size",
"URL",
"parameter",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L251-L285 |
44,849 | makinacorpus/django-screamshot | screamshot/utils.py | build_absolute_uri | def build_absolute_uri(request, url):
"""
Allow to override printing url, not necessarily on the same
server instance.
"""
if app_settings.get('CAPTURE_ROOT_URL'):
return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url)
return request.build_absolute_uri(url) | python | def build_absolute_uri(request, url):
"""
Allow to override printing url, not necessarily on the same
server instance.
"""
if app_settings.get('CAPTURE_ROOT_URL'):
return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url)
return request.build_absolute_uri(url) | [
"def",
"build_absolute_uri",
"(",
"request",
",",
"url",
")",
":",
"if",
"app_settings",
".",
"get",
"(",
"'CAPTURE_ROOT_URL'",
")",
":",
"return",
"urljoin",
"(",
"app_settings",
".",
"get",
"(",
"'CAPTURE_ROOT_URL'",
")",
",",
"url",
")",
"return",
"reques... | Allow to override printing url, not necessarily on the same
server instance. | [
"Allow",
"to",
"override",
"printing",
"url",
"not",
"necessarily",
"on",
"the",
"same",
"server",
"instance",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L333-L340 |
44,850 | makinacorpus/django-screamshot | screamshot/utils.py | render_template | def render_template(template_name, context, format='png',
output=None, using=None, **options):
"""
Render a template from django project, and return the
file object of the result.
"""
# output stream, as required by casperjs_capture
stream = BytesIO()
out_f = None
# t... | python | def render_template(template_name, context, format='png',
output=None, using=None, **options):
"""
Render a template from django project, and return the
file object of the result.
"""
# output stream, as required by casperjs_capture
stream = BytesIO()
out_f = None
# t... | [
"def",
"render_template",
"(",
"template_name",
",",
"context",
",",
"format",
"=",
"'png'",
",",
"output",
"=",
"None",
",",
"using",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"# output stream, as required by casperjs_capture",
"stream",
"=",
"BytesIO",
... | Render a template from django project, and return the
file object of the result. | [
"Render",
"a",
"template",
"from",
"django",
"project",
"and",
"return",
"the",
"file",
"object",
"of",
"the",
"result",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L343-L399 |
44,851 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | go | def go(fn, *args, **kwargs):
"""Launch an operation on a thread and get a handle to its future result.
>>> from time import sleep
>>> def print_sleep_print(duration):
... sleep(duration)
... print('hello from background thread')
... sleep(duration)
... print('goodbye from ba... | python | def go(fn, *args, **kwargs):
"""Launch an operation on a thread and get a handle to its future result.
>>> from time import sleep
>>> def print_sleep_print(duration):
... sleep(duration)
... print('hello from background thread')
... sleep(duration)
... print('goodbye from ba... | [
"def",
"go",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"callable",
"(",
"fn",
")",
":",
"raise",
"TypeError",
"(",
"'go() requires a function, not %r'",
"%",
"(",
"fn",
",",
")",
")",
"result",
"=",
"[",
"None",
"... | Launch an operation on a thread and get a handle to its future result.
>>> from time import sleep
>>> def print_sleep_print(duration):
... sleep(duration)
... print('hello from background thread')
... sleep(duration)
... print('goodbye from background thread')
... return... | [
"Launch",
"an",
"operation",
"on",
"a",
"thread",
"and",
"get",
"a",
"handle",
"to",
"its",
"future",
"result",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L107-L153 |
44,852 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | going | def going(fn, *args, **kwargs):
"""Launch a thread and wait for its result before exiting the code block.
>>> with going(lambda: 'return value') as future:
... pass
>>> future() # Won't block, the future is ready by now.
'return value'
Or discard the result:
>>> with going(lambda: "do... | python | def going(fn, *args, **kwargs):
"""Launch a thread and wait for its result before exiting the code block.
>>> with going(lambda: 'return value') as future:
... pass
>>> future() # Won't block, the future is ready by now.
'return value'
Or discard the result:
>>> with going(lambda: "do... | [
"def",
"going",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"future",
"=",
"go",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yield",
"future",
"except",
":",
"# We are raising an exception, just try to cl... | Launch a thread and wait for its result before exiting the code block.
>>> with going(lambda: 'return value') as future:
... pass
>>> future() # Won't block, the future is ready by now.
'return value'
Or discard the result:
>>> with going(lambda: "don't care"):
... pass
If an... | [
"Launch",
"a",
"thread",
"and",
"wait",
"for",
"its",
"result",
"before",
"exiting",
"the",
"code",
"block",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L157-L197 |
44,853 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | _get_c_string | def _get_c_string(data, position):
"""Decode a BSON 'C' string to python unicode string."""
end = data.index(b"\x00", position)
return _utf_8_decode(data[position:end], None, True)[0], end + 1 | python | def _get_c_string(data, position):
"""Decode a BSON 'C' string to python unicode string."""
end = data.index(b"\x00", position)
return _utf_8_decode(data[position:end], None, True)[0], end + 1 | [
"def",
"_get_c_string",
"(",
"data",
",",
"position",
")",
":",
"end",
"=",
"data",
".",
"index",
"(",
"b\"\\x00\"",
",",
"position",
")",
"return",
"_utf_8_decode",
"(",
"data",
"[",
"position",
":",
"end",
"]",
",",
"None",
",",
"True",
")",
"[",
"... | Decode a BSON 'C' string to python unicode string. | [
"Decode",
"a",
"BSON",
"C",
"string",
"to",
"python",
"unicode",
"string",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L286-L289 |
44,854 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | _synchronized | def _synchronized(meth):
"""Call method while holding a lock."""
@functools.wraps(meth)
def wrapper(self, *args, **kwargs):
with self._lock:
return meth(self, *args, **kwargs)
return wrapper | python | def _synchronized(meth):
"""Call method while holding a lock."""
@functools.wraps(meth)
def wrapper(self, *args, **kwargs):
with self._lock:
return meth(self, *args, **kwargs)
return wrapper | [
"def",
"_synchronized",
"(",
"meth",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"meth",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_lock",
":",
"return",
"meth",
"(",
"self",
... | Call method while holding a lock. | [
"Call",
"method",
"while",
"holding",
"a",
"lock",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1120-L1128 |
44,855 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | mock_server_receive_request | def mock_server_receive_request(client, server):
"""Take a client socket and return a Request."""
header = mock_server_receive(client, 16)
length = _UNPACK_INT(header[:4])[0]
request_id = _UNPACK_INT(header[4:8])[0]
opcode = _UNPACK_INT(header[12:])[0]
msg_bytes = mock_server_receive(client, len... | python | def mock_server_receive_request(client, server):
"""Take a client socket and return a Request."""
header = mock_server_receive(client, 16)
length = _UNPACK_INT(header[:4])[0]
request_id = _UNPACK_INT(header[4:8])[0]
opcode = _UNPACK_INT(header[12:])[0]
msg_bytes = mock_server_receive(client, len... | [
"def",
"mock_server_receive_request",
"(",
"client",
",",
"server",
")",
":",
"header",
"=",
"mock_server_receive",
"(",
"client",
",",
"16",
")",
"length",
"=",
"_UNPACK_INT",
"(",
"header",
"[",
":",
"4",
"]",
")",
"[",
"0",
"]",
"request_id",
"=",
"_U... | Take a client socket and return a Request. | [
"Take",
"a",
"client",
"socket",
"and",
"return",
"a",
"Request",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1771-L1781 |
44,856 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | mock_server_receive | def mock_server_receive(sock, length):
"""Receive `length` bytes from a socket object."""
msg = b''
while length:
chunk = sock.recv(length)
if chunk == b'':
raise socket.error(errno.ECONNRESET, 'closed')
length -= len(chunk)
msg += chunk
return msg | python | def mock_server_receive(sock, length):
"""Receive `length` bytes from a socket object."""
msg = b''
while length:
chunk = sock.recv(length)
if chunk == b'':
raise socket.error(errno.ECONNRESET, 'closed')
length -= len(chunk)
msg += chunk
return msg | [
"def",
"mock_server_receive",
"(",
"sock",
",",
"length",
")",
":",
"msg",
"=",
"b''",
"while",
"length",
":",
"chunk",
"=",
"sock",
".",
"recv",
"(",
"length",
")",
"if",
"chunk",
"==",
"b''",
":",
"raise",
"socket",
".",
"error",
"(",
"errno",
".",... | Receive `length` bytes from a socket object. | [
"Receive",
"length",
"bytes",
"from",
"a",
"socket",
"object",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1793-L1804 |
44,857 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | make_docs | def make_docs(*args, **kwargs):
"""Make the documents for a `Request` or `Reply`.
Takes a variety of argument styles, returns a list of dicts.
Used by `make_prototype_request` and `make_reply`, which are in turn used by
`MockupDB.receives`, `Request.replies`, and so on. See examples in
tutorial.
... | python | def make_docs(*args, **kwargs):
"""Make the documents for a `Request` or `Reply`.
Takes a variety of argument styles, returns a list of dicts.
Used by `make_prototype_request` and `make_reply`, which are in turn used by
`MockupDB.receives`, `Request.replies`, and so on. See examples in
tutorial.
... | [
"def",
"make_docs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"err_msg",
"=",
"\"Can't interpret args: \"",
"if",
"not",
"args",
"and",
"not",
"kwargs",
":",
"return",
"[",
"]",
"if",
"not",
"args",
":",
"# OpReply(ok=1, ismaster=True).",
"return"... | Make the documents for a `Request` or `Reply`.
Takes a variety of argument styles, returns a list of dicts.
Used by `make_prototype_request` and `make_reply`, which are in turn used by
`MockupDB.receives`, `Request.replies`, and so on. See examples in
tutorial. | [
"Make",
"the",
"documents",
"for",
"a",
"Request",
"or",
"Reply",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1807-L1861 |
44,858 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | make_prototype_request | def make_prototype_request(*args, **kwargs):
"""Make a prototype Request for a Matcher."""
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
... | python | def make_prototype_request(*args, **kwargs):
"""Make a prototype Request for a Matcher."""
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
... | [
"def",
"make_prototype_request",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"and",
"inspect",
".",
"isclass",
"(",
"args",
"[",
"0",
"]",
")",
"and",
"issubclass",
"(",
"args",
"[",
"0",
"]",
",",
"Request",
")",
":",
"reque... | Make a prototype Request for a Matcher. | [
"Make",
"a",
"prototype",
"Request",
"for",
"a",
"Matcher",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1884-L1895 |
44,859 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | docs_repr | def docs_repr(*args):
"""Stringify ordered dicts like a regular ones.
Preserve order, remove 'u'-prefix on unicodes in Python 2:
>>> print(docs_repr(OrderedDict([(u'_id', 2)])))
{"_id": 2}
>>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]),
... OrderedDict([(u'a', 1)]... | python | def docs_repr(*args):
"""Stringify ordered dicts like a regular ones.
Preserve order, remove 'u'-prefix on unicodes in Python 2:
>>> print(docs_repr(OrderedDict([(u'_id', 2)])))
{"_id": 2}
>>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]),
... OrderedDict([(u'a', 1)]... | [
"def",
"docs_repr",
"(",
"*",
"args",
")",
":",
"sio",
"=",
"StringIO",
"(",
")",
"for",
"doc_idx",
",",
"doc",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"doc_idx",
">",
"0",
":",
"sio",
".",
"write",
"(",
"u', '",
")",
"sio",
".",
"write",... | Stringify ordered dicts like a regular ones.
Preserve order, remove 'u'-prefix on unicodes in Python 2:
>>> print(docs_repr(OrderedDict([(u'_id', 2)])))
{"_id": 2}
>>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]),
... OrderedDict([(u'a', 1)])))
{"_id": 2, "a": "b"},... | [
"Stringify",
"ordered",
"dicts",
"like",
"a",
"regular",
"ones",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1926-L1951 |
44,860 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | seq_match | def seq_match(seq0, seq1):
"""True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match(... | python | def seq_match(seq0, seq1):
"""True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match(... | [
"def",
"seq_match",
"(",
"seq0",
",",
"seq1",
")",
":",
"len_seq1",
"=",
"len",
"(",
"seq1",
")",
"if",
"len_seq1",
"<",
"len",
"(",
"seq0",
")",
":",
"return",
"False",
"seq1_idx",
"=",
"0",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"seq0",... | True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match([3], [1, 2, 3])
True
>>> s... | [
"True",
"if",
"seq0",
"is",
"a",
"subset",
"of",
"seq1",
"and",
"their",
"elements",
"are",
"in",
"same",
"order",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1954-L1987 |
44,861 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | raise_args_err | def raise_args_err(message='bad arguments', error_class=TypeError):
"""Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, ... | python | def raise_args_err(message='bad arguments', error_class=TypeError):
"""Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, ... | [
"def",
"raise_args_err",
"(",
"message",
"=",
"'bad arguments'",
",",
"error_class",
"=",
"TypeError",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"raise",
"error_class",
"(",
"message",
"+",
"': '",
"+",
"format_call",
"... | Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, x='y') | [
"Throw",
"an",
"error",
"with",
"standard",
"message",
"displaying",
"function",
"call",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L2000-L2012 |
44,862 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | interactive_server | def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB',
ssl=False, uds_path=None):
"""A `MockupDB` that the mongo shell can connect to.
Call `~.MockupDB.run` on the returned server, and clean it up with
`~.MockupDB.stop`.
If ``all_ok`` is True, replies {o... | python | def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB',
ssl=False, uds_path=None):
"""A `MockupDB` that the mongo shell can connect to.
Call `~.MockupDB.run` on the returned server, and clean it up with
`~.MockupDB.stop`.
If ``all_ok`` is True, replies {o... | [
"def",
"interactive_server",
"(",
"port",
"=",
"27017",
",",
"verbose",
"=",
"True",
",",
"all_ok",
"=",
"False",
",",
"name",
"=",
"'MockupDB'",
",",
"ssl",
"=",
"False",
",",
"uds_path",
"=",
"None",
")",
":",
"if",
"uds_path",
"is",
"not",
"None",
... | A `MockupDB` that the mongo shell can connect to.
Call `~.MockupDB.run` on the returned server, and clean it up with
`~.MockupDB.stop`.
If ``all_ok`` is True, replies {ok: 1} to anything unmatched by a specific
responder. | [
"A",
"MockupDB",
"that",
"the",
"mongo",
"shell",
"can",
"connect",
"to",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L2015-L2043 |
44,863 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | Request.client_port | def client_port(self):
"""Client connection's TCP port."""
address = self._client.getpeername()
if isinstance(address, tuple):
return address[1]
# Maybe a Unix domain socket connection.
return 0 | python | def client_port(self):
"""Client connection's TCP port."""
address = self._client.getpeername()
if isinstance(address, tuple):
return address[1]
# Maybe a Unix domain socket connection.
return 0 | [
"def",
"client_port",
"(",
"self",
")",
":",
"address",
"=",
"self",
".",
"_client",
".",
"getpeername",
"(",
")",
"if",
"isinstance",
"(",
"address",
",",
"tuple",
")",
":",
"return",
"address",
"[",
"1",
"]",
"# Maybe a Unix domain socket connection.",
"re... | Client connection's TCP port. | [
"Client",
"connection",
"s",
"TCP",
"port",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L408-L415 |
44,864 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | Request.command_err | def command_err(self, code=1, errmsg='MockupDB command failure',
*args, **kwargs):
"""Error reply to a command.
Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
"""
kwargs.setdefault('ok', 0)
kwargs['code'] = code
kwargs['errmsg'... | python | def command_err(self, code=1, errmsg='MockupDB command failure',
*args, **kwargs):
"""Error reply to a command.
Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
"""
kwargs.setdefault('ok', 0)
kwargs['code'] = code
kwargs['errmsg'... | [
"def",
"command_err",
"(",
"self",
",",
"code",
"=",
"1",
",",
"errmsg",
"=",
"'MockupDB command failure'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'ok'",
",",
"0",
")",
"kwargs",
"[",
"'code'",
"]",
"=... | Error reply to a command.
Returns True so it is suitable as an `~MockupDB.autoresponds` handler. | [
"Error",
"reply",
"to",
"a",
"command",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L461-L471 |
44,865 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | OpMsg.unpack | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpMsg`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
payload_document = OrderedDict()
flags, = _UNPACK_UINT(msg[:4])
pos =... | python | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpMsg`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
payload_document = OrderedDict()
flags, = _UNPACK_UINT(msg[:4])
pos =... | [
"def",
"unpack",
"(",
"cls",
",",
"msg",
",",
"client",
",",
"server",
",",
"request_id",
")",
":",
"payload_document",
"=",
"OrderedDict",
"(",
")",
"flags",
",",
"=",
"_UNPACK_UINT",
"(",
"msg",
"[",
":",
"4",
"]",
")",
"pos",
"=",
"4",
"if",
"fl... | Parse message and return an `OpMsg`.
Takes the client message as bytes, the client and server socket objects,
and the client request id. | [
"Parse",
"message",
"and",
"return",
"an",
"OpMsg",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L625-L660 |
44,866 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | OpQuery.unpack | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpQuery` or `Command`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
flags, = _UNPACK_INT(msg[:4])
namespace, pos = _get_c_string(m... | python | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpQuery` or `Command`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
flags, = _UNPACK_INT(msg[:4])
namespace, pos = _get_c_string(m... | [
"def",
"unpack",
"(",
"cls",
",",
"msg",
",",
"client",
",",
"server",
",",
"request_id",
")",
":",
"flags",
",",
"=",
"_UNPACK_INT",
"(",
"msg",
"[",
":",
"4",
"]",
")",
"namespace",
",",
"pos",
"=",
"_get_c_string",
"(",
"msg",
",",
"4",
")",
"... | Parse message and return an `OpQuery` or `Command`.
Takes the client message as bytes, the client and server socket objects,
and the client request id. | [
"Parse",
"message",
"and",
"return",
"an",
"OpQuery",
"or",
"Command",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L713-L742 |
44,867 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | OpGetMore.unpack | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpGetMore`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
flags, = _UNPACK_INT(msg[:4])
namespace, pos = _get_c_string(msg, 4)
... | python | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpGetMore`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
flags, = _UNPACK_INT(msg[:4])
namespace, pos = _get_c_string(msg, 4)
... | [
"def",
"unpack",
"(",
"cls",
",",
"msg",
",",
"client",
",",
"server",
",",
"request_id",
")",
":",
"flags",
",",
"=",
"_UNPACK_INT",
"(",
"msg",
"[",
":",
"4",
"]",
")",
"namespace",
",",
"pos",
"=",
"_get_c_string",
"(",
"msg",
",",
"4",
")",
"... | Parse message and return an `OpGetMore`.
Takes the client message as bytes, the client and server socket objects,
and the client request id. | [
"Parse",
"message",
"and",
"return",
"an",
"OpGetMore",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L813-L826 |
44,868 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | OpKillCursors.unpack | def unpack(cls, msg, client, server, _):
"""Parse message and return an `OpKillCursors`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
# Leading 4 bytes are reserved.
num_of_cursor_ids, = _UNPACK_INT(msg[4:8])
... | python | def unpack(cls, msg, client, server, _):
"""Parse message and return an `OpKillCursors`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
# Leading 4 bytes are reserved.
num_of_cursor_ids, = _UNPACK_INT(msg[4:8])
... | [
"def",
"unpack",
"(",
"cls",
",",
"msg",
",",
"client",
",",
"server",
",",
"_",
")",
":",
"# Leading 4 bytes are reserved.",
"num_of_cursor_ids",
",",
"=",
"_UNPACK_INT",
"(",
"msg",
"[",
"4",
":",
"8",
"]",
")",
"cursor_ids",
"=",
"[",
"]",
"pos",
"=... | Parse message and return an `OpKillCursors`.
Takes the client message as bytes, the client and server socket objects,
and the client request id. | [
"Parse",
"message",
"and",
"return",
"an",
"OpKillCursors",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L848-L862 |
44,869 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | OpInsert.unpack | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpInsert`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
flags, = _UNPACK_INT(msg[:4])
namespace, pos = _get_c_string(msg, 4)
... | python | def unpack(cls, msg, client, server, request_id):
"""Parse message and return an `OpInsert`.
Takes the client message as bytes, the client and server socket objects,
and the client request id.
"""
flags, = _UNPACK_INT(msg[:4])
namespace, pos = _get_c_string(msg, 4)
... | [
"def",
"unpack",
"(",
"cls",
",",
"msg",
",",
"client",
",",
"server",
",",
"request_id",
")",
":",
"flags",
",",
"=",
"_UNPACK_INT",
"(",
"msg",
"[",
":",
"4",
"]",
")",
"namespace",
",",
"pos",
"=",
"_get_c_string",
"(",
"msg",
",",
"4",
")",
"... | Parse message and return an `OpInsert`.
Takes the client message as bytes, the client and server socket objects,
and the client request id. | [
"Parse",
"message",
"and",
"return",
"an",
"OpInsert",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L887-L897 |
44,870 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | OpReply.reply_bytes | def reply_bytes(self, request):
"""Take a `Request` and return an OP_REPLY message as bytes."""
flags = struct.pack("<i", self._flags)
cursor_id = struct.pack("<q", self._cursor_id)
starting_from = struct.pack("<i", self._starting_from)
number_returned = struct.pack("<i", len(sel... | python | def reply_bytes(self, request):
"""Take a `Request` and return an OP_REPLY message as bytes."""
flags = struct.pack("<i", self._flags)
cursor_id = struct.pack("<q", self._cursor_id)
starting_from = struct.pack("<i", self._starting_from)
number_returned = struct.pack("<i", len(sel... | [
"def",
"reply_bytes",
"(",
"self",
",",
"request",
")",
":",
"flags",
"=",
"struct",
".",
"pack",
"(",
"\"<i\"",
",",
"self",
".",
"_flags",
")",
"cursor_id",
"=",
"struct",
".",
"pack",
"(",
"\"<q\"",
",",
"self",
".",
"_cursor_id",
")",
"starting_fro... | Take a `Request` and return an OP_REPLY message as bytes. | [
"Take",
"a",
"Request",
"and",
"return",
"an",
"OP_REPLY",
"message",
"as",
"bytes",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L998-L1014 |
44,871 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | OpMsgReply.reply_bytes | def reply_bytes(self, request):
"""Take a `Request` and return an OP_MSG message as bytes."""
flags = struct.pack("<I", self._flags)
payload_type = struct.pack("<b", 0)
payload_data = bson.BSON.encode(self.doc)
data = b''.join([flags, payload_type, payload_data])
reply_i... | python | def reply_bytes(self, request):
"""Take a `Request` and return an OP_MSG message as bytes."""
flags = struct.pack("<I", self._flags)
payload_type = struct.pack("<b", 0)
payload_data = bson.BSON.encode(self.doc)
data = b''.join([flags, payload_type, payload_data])
reply_i... | [
"def",
"reply_bytes",
"(",
"self",
",",
"request",
")",
":",
"flags",
"=",
"struct",
".",
"pack",
"(",
"\"<I\"",
",",
"self",
".",
"_flags",
")",
"payload_type",
"=",
"struct",
".",
"pack",
"(",
"\"<b\"",
",",
"0",
")",
"payload_data",
"=",
"bson",
"... | Take a `Request` and return an OP_MSG message as bytes. | [
"Take",
"a",
"Request",
"and",
"return",
"an",
"OP_MSG",
"message",
"as",
"bytes",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1045-L1057 |
44,872 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB.run | def run(self):
"""Begin serving. Returns the bound port, or 0 for domain socket."""
self._listening_sock, self._address = (
bind_domain_socket(self._address)
if self._uds_path
else bind_tcp_socket(self._address))
if self._ssl:
certfile = os.path.j... | python | def run(self):
"""Begin serving. Returns the bound port, or 0 for domain socket."""
self._listening_sock, self._address = (
bind_domain_socket(self._address)
if self._uds_path
else bind_tcp_socket(self._address))
if self._ssl:
certfile = os.path.j... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_listening_sock",
",",
"self",
".",
"_address",
"=",
"(",
"bind_domain_socket",
"(",
"self",
".",
"_address",
")",
"if",
"self",
".",
"_uds_path",
"else",
"bind_tcp_socket",
"(",
"self",
".",
"_address",
... | Begin serving. Returns the bound port, or 0 for domain socket. | [
"Begin",
"serving",
".",
"Returns",
"the",
"bound",
"port",
"or",
"0",
"for",
"domain",
"socket",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1264-L1280 |
44,873 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB.stop | def stop(self):
"""Stop serving. Always call this to clean up after yourself."""
self._stopped = True
threads = [self._accept_thread]
threads.extend(self._server_threads)
self._listening_sock.close()
for sock in list(self._server_socks):
try:
s... | python | def stop(self):
"""Stop serving. Always call this to clean up after yourself."""
self._stopped = True
threads = [self._accept_thread]
threads.extend(self._server_threads)
self._listening_sock.close()
for sock in list(self._server_socks):
try:
s... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_stopped",
"=",
"True",
"threads",
"=",
"[",
"self",
".",
"_accept_thread",
"]",
"threads",
".",
"extend",
"(",
"self",
".",
"_server_threads",
")",
"self",
".",
"_listening_sock",
".",
"close",
"(",
... | Stop serving. Always call this to clean up after yourself. | [
"Stop",
"serving",
".",
"Always",
"call",
"this",
"to",
"clean",
"up",
"after",
"yourself",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1283-L1308 |
44,874 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB.receives | def receives(self, *args, **kwargs):
"""Pop the next `Request` and assert it matches.
Returns None if the server is stopped.
Pass a `Request` or request pattern to specify what client request to
expect. See the tutorial for examples. Pass ``timeout`` as a keyword
argument to ov... | python | def receives(self, *args, **kwargs):
"""Pop the next `Request` and assert it matches.
Returns None if the server is stopped.
Pass a `Request` or request pattern to specify what client request to
expect. See the tutorial for examples. Pass ``timeout`` as a keyword
argument to ov... | [
"def",
"receives",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"self",
".",
"_request_timeout",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"matc... | Pop the next `Request` and assert it matches.
Returns None if the server is stopped.
Pass a `Request` or request pattern to specify what client request to
expect. See the tutorial for examples. Pass ``timeout`` as a keyword
argument to override this server's ``request_timeout``. | [
"Pop",
"the",
"next",
"Request",
"and",
"assert",
"it",
"matches",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1310-L1335 |
44,875 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB.autoresponds | def autoresponds(self, matcher, *args, **kwargs):
"""Send a canned reply to all matching client requests.
``matcher`` is a `Matcher` or a command name, or an instance of
`OpInsert`, `OpQuery`, etc.
>>> s = MockupDB()
>>> port = s.run()
>>>
>>> from pymon... | python | def autoresponds(self, matcher, *args, **kwargs):
"""Send a canned reply to all matching client requests.
``matcher`` is a `Matcher` or a command name, or an instance of
`OpInsert`, `OpQuery`, etc.
>>> s = MockupDB()
>>> port = s.run()
>>>
>>> from pymon... | [
"def",
"autoresponds",
"(",
"self",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_insert_responder",
"(",
"\"top\"",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Send a canned reply to all matching client requests.
``matcher`` is a `Matcher` or a command name, or an instance of
`OpInsert`, `OpQuery`, etc.
>>> s = MockupDB()
>>> port = s.run()
>>>
>>> from pymongo import MongoClient
>>> client = MongoClient(s.uri)... | [
"Send",
"a",
"canned",
"reply",
"to",
"all",
"matching",
"client",
"requests",
".",
"matcher",
"is",
"a",
"Matcher",
"or",
"a",
"command",
"name",
"or",
"an",
"instance",
"of",
"OpInsert",
"OpQuery",
"etc",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1401-L1497 |
44,876 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB.append_responder | def append_responder(self, matcher, *args, **kwargs):
"""Add a responder of last resort.
Like `.autoresponds`, but instead of adding a responder to the top of
the stack, add it to the bottom. This responder will be called if no
others match.
"""
return self._insert_respo... | python | def append_responder(self, matcher, *args, **kwargs):
"""Add a responder of last resort.
Like `.autoresponds`, but instead of adding a responder to the top of
the stack, add it to the bottom. This responder will be called if no
others match.
"""
return self._insert_respo... | [
"def",
"append_responder",
"(",
"self",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_insert_responder",
"(",
"\"bottom\"",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Add a responder of last resort.
Like `.autoresponds`, but instead of adding a responder to the top of
the stack, add it to the bottom. This responder will be called if no
others match. | [
"Add",
"a",
"responder",
"of",
"last",
"resort",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1503-L1510 |
44,877 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB.uri | def uri(self):
"""Connection string to pass to `~pymongo.mongo_client.MongoClient`."""
if self._uds_path:
uri = 'mongodb://%s' % (quote_plus(self._uds_path),)
else:
uri = 'mongodb://%s' % (format_addr(self._address),)
return uri + '/?ssl=true' if self._ssl else ur... | python | def uri(self):
"""Connection string to pass to `~pymongo.mongo_client.MongoClient`."""
if self._uds_path:
uri = 'mongodb://%s' % (quote_plus(self._uds_path),)
else:
uri = 'mongodb://%s' % (format_addr(self._address),)
return uri + '/?ssl=true' if self._ssl else ur... | [
"def",
"uri",
"(",
"self",
")",
":",
"if",
"self",
".",
"_uds_path",
":",
"uri",
"=",
"'mongodb://%s'",
"%",
"(",
"quote_plus",
"(",
"self",
".",
"_uds_path",
")",
",",
")",
"else",
":",
"uri",
"=",
"'mongodb://%s'",
"%",
"(",
"format_addr",
"(",
"se... | Connection string to pass to `~pymongo.mongo_client.MongoClient`. | [
"Connection",
"string",
"to",
"pass",
"to",
"~pymongo",
".",
"mongo_client",
".",
"MongoClient",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1557-L1563 |
44,878 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB._accept_loop | def _accept_loop(self):
"""Accept client connections and spawn a thread for each."""
self._listening_sock.setblocking(0)
while not self._stopped and not _shutting_down:
try:
# Wait a short time to accept.
if select.select([self._listening_sock.fileno()... | python | def _accept_loop(self):
"""Accept client connections and spawn a thread for each."""
self._listening_sock.setblocking(0)
while not self._stopped and not _shutting_down:
try:
# Wait a short time to accept.
if select.select([self._listening_sock.fileno()... | [
"def",
"_accept_loop",
"(",
"self",
")",
":",
"self",
".",
"_listening_sock",
".",
"setblocking",
"(",
"0",
")",
"while",
"not",
"self",
".",
"_stopped",
"and",
"not",
"_shutting_down",
":",
"try",
":",
"# Wait a short time to accept.",
"if",
"select",
".",
... | Accept client connections and spawn a thread for each. | [
"Accept",
"client",
"connections",
"and",
"spawn",
"a",
"thread",
"for",
"each",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1611-L1641 |
44,879 | ajdavis/mongo-mockup-db | mockupdb/__init__.py | MockupDB._server_loop | def _server_loop(self, client, client_addr):
"""Read requests from one client socket, 'client'."""
while not self._stopped and not _shutting_down:
try:
with self._unlock():
request = mock_server_receive_request(client, self)
self._requests... | python | def _server_loop(self, client, client_addr):
"""Read requests from one client socket, 'client'."""
while not self._stopped and not _shutting_down:
try:
with self._unlock():
request = mock_server_receive_request(client, self)
self._requests... | [
"def",
"_server_loop",
"(",
"self",
",",
"client",
",",
"client_addr",
")",
":",
"while",
"not",
"self",
".",
"_stopped",
"and",
"not",
"_shutting_down",
":",
"try",
":",
"with",
"self",
".",
"_unlock",
"(",
")",
":",
"request",
"=",
"mock_server_receive_r... | Read requests from one client socket, 'client'. | [
"Read",
"requests",
"from",
"one",
"client",
"socket",
"client",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1644-L1677 |
44,880 | 02strich/django-auth-kerberos | django_auth_kerberos/backends.py | KrbBackend.check_password | def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
if SUPPORTS_VERIFY:
kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), geta... | python | def check_password(self, username, password):
"""The actual password checking logic. Separated from the authenticate code from Django for easier updating"""
try:
if SUPPORTS_VERIFY:
kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), geta... | [
"def",
"check_password",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"try",
":",
"if",
"SUPPORTS_VERIFY",
":",
"kerberos",
".",
"checkPassword",
"(",
"username",
".",
"lower",
"(",
")",
",",
"password",
",",
"getattr",
"(",
"settings",
",",
... | The actual password checking logic. Separated from the authenticate code from Django for easier updating | [
"The",
"actual",
"password",
"checking",
"logic",
".",
"Separated",
"from",
"the",
"authenticate",
"code",
"from",
"Django",
"for",
"easier",
"updating"
] | 416c2e2fafe6f0dbddf79bef6f6dbb90b04ceedc | https://github.com/02strich/django-auth-kerberos/blob/416c2e2fafe6f0dbddf79bef6f6dbb90b04ceedc/django_auth_kerberos/backends.py#L53-L69 |
44,881 | ajdavis/mongo-mockup-db | mockupdb/__main__.py | main | def main():
"""Start an interactive `MockupDB`.
Use like ``python -m mockupdb``.
"""
from optparse import OptionParser
parser = OptionParser('Start mock MongoDB server')
parser.add_option('-p', '--port', dest='port', default=27017,
help='port on which mock mongod listens')... | python | def main():
"""Start an interactive `MockupDB`.
Use like ``python -m mockupdb``.
"""
from optparse import OptionParser
parser = OptionParser('Start mock MongoDB server')
parser.add_option('-p', '--port', dest='port', default=27017,
help='port on which mock mongod listens')... | [
"def",
"main",
"(",
")",
":",
"from",
"optparse",
"import",
"OptionParser",
"parser",
"=",
"OptionParser",
"(",
"'Start mock MongoDB server'",
")",
"parser",
".",
"add_option",
"(",
"'-p'",
",",
"'--port'",
",",
"dest",
"=",
"'port'",
",",
"default",
"=",
"2... | Start an interactive `MockupDB`.
Use like ``python -m mockupdb``. | [
"Start",
"an",
"interactive",
"MockupDB",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__main__.py#L23-L46 |
44,882 | stephantul/somber | somber/som.py | BaseSom._initialize_distance_grid | def _initialize_distance_grid(self):
"""Initialize the distance grid by calls to _grid_dist."""
p = [self._grid_distance(i) for i in range(self.num_neurons)]
return np.array(p) | python | def _initialize_distance_grid(self):
"""Initialize the distance grid by calls to _grid_dist."""
p = [self._grid_distance(i) for i in range(self.num_neurons)]
return np.array(p) | [
"def",
"_initialize_distance_grid",
"(",
"self",
")",
":",
"p",
"=",
"[",
"self",
".",
"_grid_distance",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_neurons",
")",
"]",
"return",
"np",
".",
"array",
"(",
"p",
")"
] | Initialize the distance grid by calls to _grid_dist. | [
"Initialize",
"the",
"distance",
"grid",
"by",
"calls",
"to",
"_grid_dist",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L94-L97 |
44,883 | stephantul/somber | somber/som.py | BaseSom._grid_distance | def _grid_distance(self, index):
"""
Calculate the distance grid for a single index position.
This is pre-calculated for fast neighborhood calculations
later on (see _calc_influence).
"""
# Take every dimension but the first in reverse
# then reverse that list ag... | python | def _grid_distance(self, index):
"""
Calculate the distance grid for a single index position.
This is pre-calculated for fast neighborhood calculations
later on (see _calc_influence).
"""
# Take every dimension but the first in reverse
# then reverse that list ag... | [
"def",
"_grid_distance",
"(",
"self",
",",
"index",
")",
":",
"# Take every dimension but the first in reverse",
"# then reverse that list again.",
"dimensions",
"=",
"np",
".",
"cumprod",
"(",
"self",
".",
"map_dimensions",
"[",
"1",
":",
":",
"]",
"[",
":",
":",... | Calculate the distance grid for a single index position.
This is pre-calculated for fast neighborhood calculations
later on (see _calc_influence). | [
"Calculate",
"the",
"distance",
"grid",
"for",
"a",
"single",
"index",
"position",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L99-L131 |
44,884 | stephantul/somber | somber/som.py | BaseSom.topographic_error | def topographic_error(self, X, batch_size=1):
"""
Calculate the topographic error.
The topographic error is a measure of the spatial organization of the
map. Maps in which the most similar neurons are also close on the
grid have low topographic error and indicate that a problem ... | python | def topographic_error(self, X, batch_size=1):
"""
Calculate the topographic error.
The topographic error is a measure of the spatial organization of the
map. Maps in which the most similar neurons are also close on the
grid have low topographic error and indicate that a problem ... | [
"def",
"topographic_error",
"(",
"self",
",",
"X",
",",
"batch_size",
"=",
"1",
")",
":",
"dist",
"=",
"self",
".",
"transform",
"(",
"X",
",",
"batch_size",
")",
"# Sort the distances and get the indices of the two smallest distances",
"# for each datapoint.",
"res",... | Calculate the topographic error.
The topographic error is a measure of the spatial organization of the
map. Maps in which the most similar neurons are also close on the
grid have low topographic error and indicate that a problem has been
learned correctly.
Formally, the topogra... | [
"Calculate",
"the",
"topographic",
"error",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L133-L168 |
44,885 | stephantul/somber | somber/som.py | BaseSom.neighbors | def neighbors(self, distance=2.0):
"""Get all neighbors for all neurons."""
dgrid = self.distance_grid.reshape(self.num_neurons, self.num_neurons)
for x, y in zip(*np.nonzero(dgrid <= distance)):
if x != y:
yield x, y | python | def neighbors(self, distance=2.0):
"""Get all neighbors for all neurons."""
dgrid = self.distance_grid.reshape(self.num_neurons, self.num_neurons)
for x, y in zip(*np.nonzero(dgrid <= distance)):
if x != y:
yield x, y | [
"def",
"neighbors",
"(",
"self",
",",
"distance",
"=",
"2.0",
")",
":",
"dgrid",
"=",
"self",
".",
"distance_grid",
".",
"reshape",
"(",
"self",
".",
"num_neurons",
",",
"self",
".",
"num_neurons",
")",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"*",
... | Get all neighbors for all neurons. | [
"Get",
"all",
"neighbors",
"for",
"all",
"neurons",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L170-L175 |
44,886 | stephantul/somber | somber/som.py | BaseSom.neighbor_difference | def neighbor_difference(self):
"""Get the euclidean distance between a node and its neighbors."""
differences = np.zeros(self.num_neurons)
num_neighbors = np.zeros(self.num_neurons)
distance, _ = self.distance_function(self.weights, self.weights)
for x, y in self.neighbors():
... | python | def neighbor_difference(self):
"""Get the euclidean distance between a node and its neighbors."""
differences = np.zeros(self.num_neurons)
num_neighbors = np.zeros(self.num_neurons)
distance, _ = self.distance_function(self.weights, self.weights)
for x, y in self.neighbors():
... | [
"def",
"neighbor_difference",
"(",
"self",
")",
":",
"differences",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"num_neurons",
")",
"num_neighbors",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"num_neurons",
")",
"distance",
",",
"_",
"=",
"self",
".",
"... | Get the euclidean distance between a node and its neighbors. | [
"Get",
"the",
"euclidean",
"distance",
"between",
"a",
"node",
"and",
"its",
"neighbors",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L177-L187 |
44,887 | stephantul/somber | somber/som.py | BaseSom.spread | def spread(self, X):
"""
Calculate the average spread for each node.
The average spread is a measure of how far each neuron is from the
data points which cluster to it.
Parameters
----------
X : numpy array
The input data.
Returns
--... | python | def spread(self, X):
"""
Calculate the average spread for each node.
The average spread is a measure of how far each neuron is from the
data points which cluster to it.
Parameters
----------
X : numpy array
The input data.
Returns
--... | [
"def",
"spread",
"(",
"self",
",",
"X",
")",
":",
"distance",
",",
"_",
"=",
"self",
".",
"distance_function",
"(",
"X",
",",
"self",
".",
"weights",
")",
"dists_per_neuron",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"x",
",",
"y",
"in",
"zip",
... | Calculate the average spread for each node.
The average spread is a measure of how far each neuron is from the
data points which cluster to it.
Parameters
----------
X : numpy array
The input data.
Returns
-------
spread : numpy array
... | [
"Calculate",
"the",
"average",
"spread",
"for",
"each",
"node",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L189-L218 |
44,888 | stephantul/somber | somber/som.py | BaseSom.receptive_field | def receptive_field(self,
X,
identities,
max_len=10,
threshold=0.9,
batch_size=1):
"""
Calculate the receptive field of the SOM on some data.
The receptive field is the common... | python | def receptive_field(self,
X,
identities,
max_len=10,
threshold=0.9,
batch_size=1):
"""
Calculate the receptive field of the SOM on some data.
The receptive field is the common... | [
"def",
"receptive_field",
"(",
"self",
",",
"X",
",",
"identities",
",",
"max_len",
"=",
"10",
",",
"threshold",
"=",
"0.9",
",",
"batch_size",
"=",
"1",
")",
":",
"receptive_fields",
"=",
"defaultdict",
"(",
"list",
")",
"predictions",
"=",
"self",
".",... | Calculate the receptive field of the SOM on some data.
The receptive field is the common ending of all sequences which
lead to the activation of a given BMU. If a SOM is well-tuned to
specific sequences, it will have longer receptive fields, and therefore
gives a better description of t... | [
"Calculate",
"the",
"receptive",
"field",
"of",
"the",
"SOM",
"on",
"some",
"data",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L220-L287 |
44,889 | stephantul/somber | somber/som.py | BaseSom.invert_projection | def invert_projection(self, X, identities):
"""
Calculate the inverted projection.
The inverted projectio of a SOM is created by association each weight
with the input which matches it the most, thus giving a good
approximation of the "influence" of each input item.
Wor... | python | def invert_projection(self, X, identities):
"""
Calculate the inverted projection.
The inverted projectio of a SOM is created by association each weight
with the input which matches it the most, thus giving a good
approximation of the "influence" of each input item.
Wor... | [
"def",
"invert_projection",
"(",
"self",
",",
"X",
",",
"identities",
")",
":",
"distances",
"=",
"self",
".",
"transform",
"(",
"X",
")",
"if",
"len",
"(",
"distances",
")",
"!=",
"len",
"(",
"identities",
")",
":",
"raise",
"ValueError",
"(",
"\"X an... | Calculate the inverted projection.
The inverted projectio of a SOM is created by association each weight
with the input which matches it the most, thus giving a good
approximation of the "influence" of each input item.
Works best for symbolic (instead of continuous) input data.
... | [
"Calculate",
"the",
"inverted",
"projection",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L289-L324 |
44,890 | stephantul/somber | somber/som.py | BaseSom.map_weights | def map_weights(self):
"""
Reshaped weights for visualization.
The weights are reshaped as
(W.shape[0], prod(W.shape[1:-1]), W.shape[2]).
This allows one to easily see patterns, even for hyper-dimensional
soms.
For one-dimensional SOMs, the returned array is of ... | python | def map_weights(self):
"""
Reshaped weights for visualization.
The weights are reshaped as
(W.shape[0], prod(W.shape[1:-1]), W.shape[2]).
This allows one to easily see patterns, even for hyper-dimensional
soms.
For one-dimensional SOMs, the returned array is of ... | [
"def",
"map_weights",
"(",
"self",
")",
":",
"first_dim",
"=",
"self",
".",
"map_dimensions",
"[",
"0",
"]",
"if",
"len",
"(",
"self",
".",
"map_dimensions",
")",
"!=",
"1",
":",
"second_dim",
"=",
"np",
".",
"prod",
"(",
"self",
".",
"map_dimensions",... | Reshaped weights for visualization.
The weights are reshaped as
(W.shape[0], prod(W.shape[1:-1]), W.shape[2]).
This allows one to easily see patterns, even for hyper-dimensional
soms.
For one-dimensional SOMs, the returned array is of shape
(W.shape[0], 1, W.shape[2])
... | [
"Reshaped",
"weights",
"for",
"visualization",
"."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L326-L354 |
44,891 | stephantul/somber | somber/som.py | Som.load | def load(cls, path):
"""
Load a SOM from a JSON file saved with this package..
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class.
"""
data = json.load... | python | def load(cls, path):
"""
Load a SOM from a JSON file saved with this package..
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class.
"""
data = json.load... | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"data",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"path",
")",
")",
"weights",
"=",
"data",
"[",
"'weights'",
"]",
"weights",
"=",
"np",
".",
"asarray",
"(",
"weights",
",",
"dtype",
"=",
"np",
... | Load a SOM from a JSON file saved with this package..
Parameters
----------
path : str
The path to the JSON file.
Returns
-------
s : cls
A som of the specified class. | [
"Load",
"a",
"SOM",
"from",
"a",
"JSON",
"file",
"saved",
"with",
"this",
"package",
".."
] | b7a13e646239500cc393668c01a7169c3e50b7b5 | https://github.com/stephantul/somber/blob/b7a13e646239500cc393668c01a7169c3e50b7b5/somber/som.py#L447-L477 |
44,892 | cloudnull/turbolift | turbolift/methods/__init__.py | BaseMethod.remove_dirs | def remove_dirs(self, directory):
"""Delete a directory recursively.
:param directory: $PATH to directory.
:type directory: ``str``
"""
LOG.info('Removing directory [ %s ]', directory)
local_files = self._drectory_local_files(directory=directory)
for file_name i... | python | def remove_dirs(self, directory):
"""Delete a directory recursively.
:param directory: $PATH to directory.
:type directory: ``str``
"""
LOG.info('Removing directory [ %s ]', directory)
local_files = self._drectory_local_files(directory=directory)
for file_name i... | [
"def",
"remove_dirs",
"(",
"self",
",",
"directory",
")",
":",
"LOG",
".",
"info",
"(",
"'Removing directory [ %s ]'",
",",
"directory",
")",
"local_files",
"=",
"self",
".",
"_drectory_local_files",
"(",
"directory",
"=",
"directory",
")",
"for",
"file_name",
... | Delete a directory recursively.
:param directory: $PATH to directory.
:type directory: ``str`` | [
"Delete",
"a",
"directory",
"recursively",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/methods/__init__.py#L139-L167 |
44,893 | cloudnull/turbolift | turbolift/methods/__init__.py | BaseMethod._return_container_objects | def _return_container_objects(self):
"""Return a list of objects to delete.
The return tuple will indicate if it was a userd efined list of objects
as True of False.
The list of objects is a list of dictionaries with the key being
"container_object".
:returns: tuple (`... | python | def _return_container_objects(self):
"""Return a list of objects to delete.
The return tuple will indicate if it was a userd efined list of objects
as True of False.
The list of objects is a list of dictionaries with the key being
"container_object".
:returns: tuple (`... | [
"def",
"_return_container_objects",
"(",
"self",
")",
":",
"container_objects",
"=",
"self",
".",
"job_args",
".",
"get",
"(",
"'object'",
")",
"if",
"container_objects",
":",
"return",
"True",
",",
"[",
"{",
"'container_object'",
":",
"i",
"}",
"for",
"i",
... | Return a list of objects to delete.
The return tuple will indicate if it was a userd efined list of objects
as True of False.
The list of objects is a list of dictionaries with the key being
"container_object".
:returns: tuple (``bol``, ``list``) | [
"Return",
"a",
"list",
"of",
"objects",
"to",
"delete",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/methods/__init__.py#L342-L383 |
44,894 | cloudnull/turbolift | turbolift/methods/__init__.py | BaseMethod._index_fs | def _index_fs(self):
"""Returns a deque object full of local file system items.
:returns: ``deque``
"""
indexed_objects = self._return_deque()
directory = self.job_args.get('directory')
if directory:
indexed_objects = self._return_deque(
deq... | python | def _index_fs(self):
"""Returns a deque object full of local file system items.
:returns: ``deque``
"""
indexed_objects = self._return_deque()
directory = self.job_args.get('directory')
if directory:
indexed_objects = self._return_deque(
deq... | [
"def",
"_index_fs",
"(",
"self",
")",
":",
"indexed_objects",
"=",
"self",
".",
"_return_deque",
"(",
")",
"directory",
"=",
"self",
".",
"job_args",
".",
"get",
"(",
"'directory'",
")",
"if",
"directory",
":",
"indexed_objects",
"=",
"self",
".",
"_return... | Returns a deque object full of local file system items.
:returns: ``deque`` | [
"Returns",
"a",
"deque",
"object",
"full",
"of",
"local",
"file",
"system",
"items",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/methods/__init__.py#L497-L523 |
44,895 | cloudnull/turbolift | turbolift/methods/__init__.py | BaseMethod.match_filter | def match_filter(self, idx_list, pattern, dict_type=False,
dict_key='name'):
"""Return Matched items in indexed files.
:param idx_list:
:return list
"""
if dict_type is False:
return self._return_deque([
obj for obj in idx_list
... | python | def match_filter(self, idx_list, pattern, dict_type=False,
dict_key='name'):
"""Return Matched items in indexed files.
:param idx_list:
:return list
"""
if dict_type is False:
return self._return_deque([
obj for obj in idx_list
... | [
"def",
"match_filter",
"(",
"self",
",",
"idx_list",
",",
"pattern",
",",
"dict_type",
"=",
"False",
",",
"dict_key",
"=",
"'name'",
")",
":",
"if",
"dict_type",
"is",
"False",
":",
"return",
"self",
".",
"_return_deque",
"(",
"[",
"obj",
"for",
"obj",
... | Return Matched items in indexed files.
:param idx_list:
:return list | [
"Return",
"Matched",
"items",
"in",
"indexed",
"files",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/methods/__init__.py#L580-L599 |
44,896 | cloudnull/turbolift | turbolift/methods/__init__.py | BaseMethod.print_horiz_table | def print_horiz_table(self, data):
"""Print a horizontal pretty table from data."""
# Build list of returned objects
return_objects = list()
fields = self.job_args.get('fields')
if not fields:
fields = set()
for item_dict in data:
for fiel... | python | def print_horiz_table(self, data):
"""Print a horizontal pretty table from data."""
# Build list of returned objects
return_objects = list()
fields = self.job_args.get('fields')
if not fields:
fields = set()
for item_dict in data:
for fiel... | [
"def",
"print_horiz_table",
"(",
"self",
",",
"data",
")",
":",
"# Build list of returned objects",
"return_objects",
"=",
"list",
"(",
")",
"fields",
"=",
"self",
".",
"job_args",
".",
"get",
"(",
"'fields'",
")",
"if",
"not",
"fields",
":",
"fields",
"=",
... | Print a horizontal pretty table from data. | [
"Print",
"a",
"horizontal",
"pretty",
"table",
"from",
"data",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/methods/__init__.py#L601-L632 |
44,897 | cloudnull/turbolift | turbolift/methods/__init__.py | BaseMethod.print_virt_table | def print_virt_table(self, data):
"""Print a vertical pretty table from data."""
table = prettytable.PrettyTable()
keys = sorted(data.keys())
table.add_column('Keys', keys)
table.add_column('Values', [data.get(i) for i in keys])
for tbl in table.align.keys():
... | python | def print_virt_table(self, data):
"""Print a vertical pretty table from data."""
table = prettytable.PrettyTable()
keys = sorted(data.keys())
table.add_column('Keys', keys)
table.add_column('Values', [data.get(i) for i in keys])
for tbl in table.align.keys():
... | [
"def",
"print_virt_table",
"(",
"self",
",",
"data",
")",
":",
"table",
"=",
"prettytable",
".",
"PrettyTable",
"(",
")",
"keys",
"=",
"sorted",
"(",
"data",
".",
"keys",
"(",
")",
")",
"table",
".",
"add_column",
"(",
"'Keys'",
",",
"keys",
")",
"ta... | Print a vertical pretty table from data. | [
"Print",
"a",
"vertical",
"pretty",
"table",
"from",
"data",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/methods/__init__.py#L634-L644 |
44,898 | cloudnull/turbolift | turbolift/methods/__init__.py | BaseMethod.printer | def printer(self, message, color_level='info'):
"""Print Messages and Log it.
:param message: item to print to screen
"""
if self.job_args.get('colorized'):
print(cloud_utils.return_colorized(msg=message, color=color_level))
else:
print(message) | python | def printer(self, message, color_level='info'):
"""Print Messages and Log it.
:param message: item to print to screen
"""
if self.job_args.get('colorized'):
print(cloud_utils.return_colorized(msg=message, color=color_level))
else:
print(message) | [
"def",
"printer",
"(",
"self",
",",
"message",
",",
"color_level",
"=",
"'info'",
")",
":",
"if",
"self",
".",
"job_args",
".",
"get",
"(",
"'colorized'",
")",
":",
"print",
"(",
"cloud_utils",
".",
"return_colorized",
"(",
"msg",
"=",
"message",
",",
... | Print Messages and Log it.
:param message: item to print to screen | [
"Print",
"Messages",
"and",
"Log",
"it",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/methods/__init__.py#L646-L655 |
44,899 | cloudnull/turbolift | turbolift/worker.py | Worker._get_method | def _get_method(method):
"""Return an imported object.
:param method: ``str`` DOT notation for import with Colin used to
separate the class used for the job.
:returns: ``object`` Loaded class object from imported method.
"""
# Split the class out ... | python | def _get_method(method):
"""Return an imported object.
:param method: ``str`` DOT notation for import with Colin used to
separate the class used for the job.
:returns: ``object`` Loaded class object from imported method.
"""
# Split the class out ... | [
"def",
"_get_method",
"(",
"method",
")",
":",
"# Split the class out from the job",
"module",
"=",
"method",
".",
"split",
"(",
"':'",
")",
"# Set the import module",
"_module_import",
"=",
"module",
"[",
"0",
"]",
"# Set the class name to use",
"class_name",
"=",
... | Return an imported object.
:param method: ``str`` DOT notation for import with Colin used to
separate the class used for the job.
:returns: ``object`` Loaded class object from imported method. | [
"Return",
"an",
"imported",
"object",
"."
] | da33034e88959226529ce762e2895e6f6356c448 | https://github.com/cloudnull/turbolift/blob/da33034e88959226529ce762e2895e6f6356c448/turbolift/worker.py#L37-L58 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.