Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Resource.get_available_hours
(self, start=None, end=None, duration=None, reservation=None, during_closing=False)
Returns hours that the resource is not reserved for a given date range If include_closed=True, will also return hours when the resource is closed, if it is not reserved. This is so that admins can book resources during closing hours. Returns the available hours as a list of dicts. The ...
Returns hours that the resource is not reserved for a given date range
def get_available_hours(self, start=None, end=None, duration=None, reservation=None, during_closing=False): """ Returns hours that the resource is not reserved for a given date range If include_closed=True, will also return hours when the resource is closed, if it is not reserved. This ...
[ "def", "get_available_hours", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ",", "duration", "=", "None", ",", "reservation", "=", "None", ",", "during_closing", "=", "False", ")", ":", "today", "=", "arrow", ".", "get", "(", "timezo...
[ 375, 4 ]
[ 460, 25 ]
python
en
['en', 'error', 'th']
False
Resource.get_opening_hours
(self, begin=None, end=None, opening_hours_cache=None)
:rtype : dict[str, datetime.datetime] :type begin: datetime.date :type end: datetime.date
:rtype : dict[str, datetime.datetime] :type begin: datetime.date :type end: datetime.date
def get_opening_hours(self, begin=None, end=None, opening_hours_cache=None): """ :rtype : dict[str, datetime.datetime] :type begin: datetime.date :type end: datetime.date """ tz = pytz.timezone(self.unit.time_zone) begin, end = determine_hours_time_range(begin, en...
[ "def", "get_opening_hours", "(", "self", ",", "begin", "=", "None", ",", "end", "=", "None", ",", "opening_hours_cache", "=", "None", ")", ":", "tz", "=", "pytz", ".", "timezone", "(", "self", ".", "unit", ".", "time_zone", ")", "begin", ",", "end", ...
[ 462, 4 ]
[ 493, 28 ]
python
en
['en', 'error', 'th']
False
Resource.is_admin
(self, user)
Check if the given user is an administrator of this resource. :type user: users.models.User :rtype: bool
Check if the given user is an administrator of this resource.
def is_admin(self, user): """ Check if the given user is an administrator of this resource. :type user: users.models.User :rtype: bool """ # UserFilterBackend and ReservationFilterSet in resources.api.reservation assume the same behaviour, # so if this is changed...
[ "def", "is_admin", "(", "self", ",", "user", ")", ":", "# UserFilterBackend and ReservationFilterSet in resources.api.reservation assume the same behaviour,", "# so if this is changed those need to be changed as well.", "if", "not", "self", ".", "unit", ":", "return", "is_general_a...
[ 552, 4 ]
[ 563, 39 ]
python
en
['en', 'error', 'th']
False
Resource.is_manager
(self, user)
Check if the given user is a manager of this resource. :type user: users.models.User :rtype: bool
Check if the given user is a manager of this resource.
def is_manager(self, user): """ Check if the given user is a manager of this resource. :type user: users.models.User :rtype: bool """ if not self.unit: return False return self.unit.is_manager(user)
[ "def", "is_manager", "(", "self", ",", "user", ")", ":", "if", "not", "self", ".", "unit", ":", "return", "False", "return", "self", ".", "unit", ".", "is_manager", "(", "user", ")" ]
[ 565, 4 ]
[ 574, 41 ]
python
en
['en', 'error', 'th']
False
Resource.is_viewer
(self, user)
Check if the given user is a viewer of this resource. :type user: users.models.User :rtype: bool
Check if the given user is a viewer of this resource.
def is_viewer(self, user): """ Check if the given user is a viewer of this resource. :type user: users.models.User :rtype: bool """ if not self.unit: return False return self.unit.is_viewer(user)
[ "def", "is_viewer", "(", "self", ",", "user", ")", ":", "if", "not", "self", ".", "unit", ":", "return", "False", "return", "self", ".", "unit", ".", "is_viewer", "(", "user", ")" ]
[ 576, 4 ]
[ 585, 40 ]
python
en
['en', 'error', 'th']
False
ResourceImage._process_image
(self)
Preprocess the uploaded image file, if required. This may transcode the image to a JPEG or PNG if it's not either to begin with. :raises InvalidImage: Exception raised if the uploaded file is not valid.
Preprocess the uploaded image file, if required.
def _process_image(self): """ Preprocess the uploaded image file, if required. This may transcode the image to a JPEG or PNG if it's not either to begin with. :raises InvalidImage: Exception raised if the uploaded file is not valid. """ if not self.image: # No image se...
[ "def", "_process_image", "(", "self", ")", ":", "if", "not", "self", ".", "image", ":", "# No image set - we can't do this right now", "return", "if", "self", ".", "image_format", ":", "# Assume that if image_format is set, no further processing is required", "return", "try...
[ 782, 4 ]
[ 817, 42 ]
python
en
['en', 'error', 'th']
False
is_archive_file
(name)
Return True if `name` is a considered as an archive file.
Return True if `name` is a considered as an archive file.
def is_archive_file(name): # type: (str) -> bool """Return True if `name` is a considered as an archive file.""" ext = splitext(name)[1].lower() if ext in ARCHIVE_EXTENSIONS: return True return False
[ "def", "is_archive_file", "(", "name", ")", ":", "# type: (str) -> bool", "ext", "=", "splitext", "(", "name", ")", "[", "1", "]", ".", "lower", "(", ")", "if", "ext", "in", "ARCHIVE_EXTENSIONS", ":", "return", "True", "return", "False" ]
[ 50, 0 ]
[ 56, 16 ]
python
en
['en', 'en', 'en']
True
parse_editable
(editable_req)
Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra]
Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah
def parse_editable(editable_req): # type: (str) -> Tuple[Optional[str], str, Optional[Set[str]]] """Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirecto...
[ "def", "parse_editable", "(", "editable_req", ")", ":", "# type: (str) -> Tuple[Optional[str], str, Optional[Set[str]]]", "url", "=", "editable_req", "# If a file path is specified with extras, strip off the extras.", "url_no_extras", ",", "extras", "=", "_strip_extras", "(", "url"...
[ 79, 0 ]
[ 151, 34 ]
python
en
['en', 'en', 'en']
True
deduce_helpful_msg
(req)
Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path
Returns helpful msg in case requirements file does not exist, or cannot be parsed.
def deduce_helpful_msg(req): # type: (str) -> str """Returns helpful msg in case requirements file does not exist, or cannot be parsed. :params req: Requirements file path """ msg = "" if os.path.exists(req): msg = " It does exist." # Try to parse and check if it is a requir...
[ "def", "deduce_helpful_msg", "(", "req", ")", ":", "# type: (str) -> str", "msg", "=", "\"\"", "if", "os", ".", "path", ".", "exists", "(", "req", ")", ":", "msg", "=", "\" It does exist.\"", "# Try to parse and check if it is a requirements file.", "try", ":", "w...
[ 154, 0 ]
[ 181, 14 ]
python
en
['en', 'en', 'en']
True
_looks_like_path
(name)
Checks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (either os.path.sep or os.path.altsep); * a dot is found (wh...
Checks whether the string "looks like" a path on the filesystem.
def _looks_like_path(name): # type: (str) -> bool """Checks whether the string "looks like" a path on the filesystem. This does not check whether the target actually exists, only judge from the appearance. Returns true if any of the following conditions is true: * a path separator is found (ei...
[ "def", "_looks_like_path", "(", "name", ")", ":", "# type: (str) -> bool", "if", "os", ".", "path", ".", "sep", "in", "name", ":", "return", "True", "if", "os", ".", "path", ".", "altsep", "is", "not", "None", "and", "os", ".", "path", ".", "altsep", ...
[ 245, 0 ]
[ 262, 16 ]
python
en
['en', 'en', 'en']
True
_get_url_from_path
(path, name)
First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path. If false, check if the path is an archive file (such as a .whl). The function checks if the path is a file. If false, if the path has an @, it will treat it as a PEP 440 URL r...
First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path.
def _get_url_from_path(path, name): # type: (str, str) -> str """ First, it checks whether a provided path is an installable directory (e.g. it has a setup.py). If it is, returns the path. If false, check if the path is an archive file (such as a .whl). The function checks if the path is a file...
[ "def", "_get_url_from_path", "(", "path", ",", "name", ")", ":", "# type: (str, str) -> str", "if", "_looks_like_path", "(", "name", ")", "and", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "is_installable_dir", "(", "path", ")", ":", "ret...
[ 265, 0 ]
[ 296, 28 ]
python
en
['en', 'error', 'th']
False
install_req_from_line
( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: Optional[str] )
Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. :param line_source: An optional string describing where the line is from, for logging purposes in case of an error.
Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL.
def install_req_from_line( name, # type: str comes_from=None, # type: Optional[Union[str, InstallRequirement]] use_pep517=None, # type: Optional[bool] isolated=False, # type: bool options=None, # type: Optional[Dict[str, Any]] constraint=False, # type: bool line_source=None, # type: O...
[ "def", "install_req_from_line", "(", "name", ",", "# type: str", "comes_from", "=", "None", ",", "# type: Optional[Union[str, InstallRequirement]]", "use_pep517", "=", "None", ",", "# type: Optional[bool]", "isolated", "=", "False", ",", "# type: bool", "options", "=", ...
[ 379, 0 ]
[ 405, 5 ]
python
en
['en', 'en', 'en']
True
PushBouncerNotificationTest.test_push_bouncer_api
(self, mock_request: Any)
This is a variant of the below test_push_api, but using the full push notification bouncer flow
This is a variant of the below test_push_api, but using the full push notification bouncer flow
def test_push_bouncer_api(self, mock_request: Any) -> None: """This is a variant of the below test_push_api, but using the full push notification bouncer flow """ mock_request.side_effect = self.bounce_request user = self.example_user("cordelia") self.login_user(user) ...
[ "def", "test_push_bouncer_api", "(", "self", ",", "mock_request", ":", "Any", ")", "->", "None", ":", "mock_request", ".", "side_effect", "=", "self", ".", "bounce_request", "user", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "self", ".", "lo...
[ 300, 4 ]
[ 416, 40 ]
python
en
['en', 'en', 'en']
True
AnalyticsBouncerTest.test_analytics_api
(self, mock_request: Any)
This is a variant of the below test_push_api, but using the full push notification bouncer flow
This is a variant of the below test_push_api, but using the full push notification bouncer flow
def test_analytics_api(self, mock_request: Any) -> None: """This is a variant of the below test_push_api, but using the full push notification bouncer flow """ mock_request.side_effect = self.bounce_request user = self.example_user("hamlet") end_time = self.TIME_ZERO ...
[ "def", "test_analytics_api", "(", "self", ",", "mock_request", ":", "Any", ")", "->", "None", ":", "mock_request", ".", "side_effect", "=", "self", ".", "bounce_request", "user", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "end_time", "=", "sel...
[ 424, 4 ]
[ 584, 13 ]
python
en
['en', 'en', 'en']
True
AnalyticsBouncerTest.test_analytics_api_invalid
(self, mock_request: Any)
This is a variant of the below test_push_api, but using the full push notification bouncer flow
This is a variant of the below test_push_api, but using the full push notification bouncer flow
def test_analytics_api_invalid(self, mock_request: Any) -> None: """This is a variant of the below test_push_api, but using the full push notification bouncer flow """ mock_request.side_effect = self.bounce_request user = self.example_user("hamlet") end_time = self.TIME_Z...
[ "def", "test_analytics_api_invalid", "(", "self", ",", "mock_request", ":", "Any", ")", "->", "None", ":", "mock_request", ".", "side_effect", "=", "self", ".", "bounce_request", "user", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "end_time", "="...
[ 588, 4 ]
[ 607, 61 ]
python
en
['en', 'en', 'en']
True
HandlePushNotificationTest.bounce_request
(self, *args: Any, **kwargs: Any)
This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests.
This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests.
def bounce_request(self, *args: Any, **kwargs: Any) -> HttpResponse: """This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests. """ # args[0] is method, args[1] is URL. local_url = args[1].replace(setting...
[ "def", "bounce_request", "(", "self", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "HttpResponse", ":", "# args[0] is method, args[1] is URL.", "local_url", "=", "args", "[", "1", "]", ".", "replace", "(", "settings", ".", ...
[ 773, 4 ]
[ 785, 21 ]
python
en
['en', 'en', 'en']
True
HandlePushNotificationTest.test_deleted_message
(self)
Simulates the race where message is deleted before handlingx push notifications
Simulates the race where message is deleted before handlingx push notifications
def test_deleted_message(self) -> None: """Simulates the race where message is deleted before handlingx push notifications""" user_profile = self.example_user("hamlet") message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=user_pro...
[ "def", "test_deleted_message", "(", "self", ")", "->", "None", ":", "user_profile", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "message", "=", "self", ".", "get_message", "(", "Recipient", ".", "PERSONAL", ",", "type_id", "=", "1", ")", "Use...
[ 934, 4 ]
[ 961, 50 ]
python
en
['en', 'en', 'en']
True
HandlePushNotificationTest.test_missing_message
(self)
Simulates the race where message is missing when handling push notifications
Simulates the race where message is missing when handling push notifications
def test_missing_message(self) -> None: """Simulates the race where message is missing when handling push notifications""" user_profile = self.example_user("hamlet") message = self.get_message(Recipient.PERSONAL, type_id=1) UserMessage.objects.create( user_profile=user_profil...
[ "def", "test_missing_message", "(", "self", ")", "->", "None", ":", "user_profile", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "message", "=", "self", ".", "get_message", "(", "Recipient", ".", "PERSONAL", ",", "type_id", "=", "1", ")", "Use...
[ 963, 4 ]
[ 994, 13 ]
python
en
['en', 'en', 'en']
True
HandlePushNotificationTest.test_user_message_does_not_exist
(self)
This simulates a condition that should only be an error if the user is not long-term idle; we fake it, though, in the sense that the user should not have received the message in the first place
This simulates a condition that should only be an error if the user is not long-term idle; we fake it, though, in the sense that the user should not have received the message in the first place
def test_user_message_does_not_exist(self) -> None: """This simulates a condition that should only be an error if the user is not long-term idle; we fake it, though, in the sense that the user should not have received the message in the first place""" self.make_stream("public_stream") ...
[ "def", "test_user_message_does_not_exist", "(", "self", ")", "->", "None", ":", "self", ".", "make_stream", "(", "\"public_stream\"", ")", "sender", "=", "self", ".", "example_user", "(", "\"iago\"", ")", "message_id", "=", "self", ".", "send_stream_message", "(...
[ 1162, 4 ]
[ 1179, 56 ]
python
en
['en', 'en', 'en']
True
HandlePushNotificationTest.test_user_message_soft_deactivated
(self)
This simulates a condition that should only be an error if the user is not long-term idle; we fake it, though, in the sense that the user should not have received the message in the first place
This simulates a condition that should only be an error if the user is not long-term idle; we fake it, though, in the sense that the user should not have received the message in the first place
def test_user_message_soft_deactivated(self) -> None: """This simulates a condition that should only be an error if the user is not long-term idle; we fake it, though, in the sense that the user should not have received the message in the first place""" self.setup_apns_tokens() s...
[ "def", "test_user_message_soft_deactivated", "(", "self", ")", "->", "None", ":", "self", ".", "setup_apns_tokens", "(", ")", "self", ".", "setup_gcm_tokens", "(", ")", "self", ".", "make_stream", "(", "\"public_stream\"", ")", "self", ".", "subscribe", "(", "...
[ 1181, 4 ]
[ 1232, 56 ]
python
en
['en', 'en', 'en']
True
TestAPNs.test_get_apns_client
(self)
This test is pretty hacky, and needs to carefully reset the state it modifies in order to avoid leaking state that can lead to nondeterministic results for other tests.
This test is pretty hacky, and needs to carefully reset the state it modifies in order to avoid leaking state that can lead to nondeterministic results for other tests.
def test_get_apns_client(self) -> None: """This test is pretty hacky, and needs to carefully reset the state it modifies in order to avoid leaking state that can lead to nondeterministic results for other tests. """ import zerver.lib.push_notifications zerver.lib.push_no...
[ "def", "test_get_apns_client", "(", "self", ")", "->", "None", ":", "import", "zerver", ".", "lib", ".", "push_notifications", "zerver", ".", "lib", ".", "push_notifications", ".", "_apns_client_initialized", "=", "False", "try", ":", "with", "self", ".", "set...
[ 1270, 4 ]
[ 1288, 61 ]
python
en
['en', 'en', 'en']
True
unpack
(src_dir, dst_dir)
Move everything under `src_dir` to `dst_dir`, and delete the former.
Move everything under `src_dir` to `dst_dir`, and delete the former.
def unpack(src_dir, dst_dir): '''Move everything under `src_dir` to `dst_dir`, and delete the former.''' for dirpath, dirnames, filenames in os.walk(src_dir): subdir = os.path.relpath(dirpath, src_dir) for f in filenames: src = os.path.join(dirpath, f) dst = os.path.join(...
[ "def", "unpack", "(", "src_dir", ",", "dst_dir", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "src_dir", ")", ":", "subdir", "=", "os", ".", "path", ".", "relpath", "(", "dirpath", ",", "src_dir", ")", ...
[ 33, 0 ]
[ 52, 25 ]
python
en
['en', 'en', 'en']
True
Wheel.tags
(self)
List tags (py_version, abi, platform) supported by this wheel.
List tags (py_version, abi, platform) supported by this wheel.
def tags(self): '''List tags (py_version, abi, platform) supported by this wheel.''' return itertools.product( self.py_version.split('.'), self.abi.split('.'), self.platform.split('.'), )
[ "def", "tags", "(", "self", ")", ":", "return", "itertools", ".", "product", "(", "self", ".", "py_version", ".", "split", "(", "'.'", ")", ",", "self", ".", "abi", ".", "split", "(", "'.'", ")", ",", "self", ".", "platform", ".", "split", "(", "...
[ 65, 4 ]
[ 71, 9 ]
python
en
['en', 'en', 'en']
True
Wheel.is_compatible
(self)
Is the wheel is compatible with the current platform?
Is the wheel is compatible with the current platform?
def is_compatible(self): '''Is the wheel is compatible with the current platform?''' supported_tags = set( (t.interpreter, t.abi, t.platform) for t in sys_tags()) return next((True for t in self.tags() if t in supported_tags), False)
[ "def", "is_compatible", "(", "self", ")", ":", "supported_tags", "=", "set", "(", "(", "t", ".", "interpreter", ",", "t", ".", "abi", ",", "t", ".", "platform", ")", "for", "t", "in", "sys_tags", "(", ")", ")", "return", "next", "(", "(", "True", ...
[ 73, 4 ]
[ 77, 78 ]
python
en
['en', 'en', 'en']
True
Wheel.install_as_egg
(self, destination_eggdir)
Install wheel as an egg directory.
Install wheel as an egg directory.
def install_as_egg(self, destination_eggdir): '''Install wheel as an egg directory.''' with zipfile.ZipFile(self.filename) as zf: self._install_as_egg(destination_eggdir, zf)
[ "def", "install_as_egg", "(", "self", ",", "destination_eggdir", ")", ":", "with", "zipfile", ".", "ZipFile", "(", "self", ".", "filename", ")", "as", "zf", ":", "self", ".", "_install_as_egg", "(", "destination_eggdir", ",", "zf", ")" ]
[ 95, 4 ]
[ 98, 56 ]
python
en
['en', 'en', 'en']
True
Wheel._move_data_entries
(destination_eggdir, dist_data)
Move data entries to their correct location.
Move data entries to their correct location.
def _move_data_entries(destination_eggdir, dist_data): """Move data entries to their correct location.""" dist_data = os.path.join(destination_eggdir, dist_data) dist_data_scripts = os.path.join(dist_data, 'scripts') if os.path.exists(dist_data_scripts): egg_info_scripts = os...
[ "def", "_move_data_entries", "(", "destination_eggdir", ",", "dist_data", ")", ":", "dist_data", "=", "os", ".", "path", ".", "join", "(", "destination_eggdir", ",", "dist_data", ")", "dist_data_scripts", "=", "os", ".", "path", ".", "join", "(", "dist_data", ...
[ 175, 4 ]
[ 200, 31 ]
python
en
['en', 'en', 'en']
True
Manifest.__init__
(self, base=None)
Initialise an instance. :param base: The base directory to explore under.
Initialise an instance.
def __init__(self, base=None): """ Initialise an instance. :param base: The base directory to explore under. """ self.base = os.path.abspath(os.path.normpath(base or os.getcwd())) self.prefix = self.base + os.sep self.allfiles = None self.files = set()
[ "def", "__init__", "(", "self", ",", "base", "=", "None", ")", ":", "self", ".", "base", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "normpath", "(", "base", "or", "os", ".", "getcwd", "(", ")", ")", ")", "self", ".", ...
[ 41, 4 ]
[ 50, 26 ]
python
en
['en', 'error', 'th']
False
Manifest.findall
(self)
Find all files under the base and set ``allfiles`` to the absolute pathnames of files found.
Find all files under the base and set ``allfiles`` to the absolute pathnames of files found.
def findall(self): """Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. """ from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles = allfiles = [] root = self.base stack = [root] pop = stack.pop push = ...
[ "def", "findall", "(", "self", ")", ":", "from", "stat", "import", "S_ISREG", ",", "S_ISDIR", ",", "S_ISLNK", "self", ".", "allfiles", "=", "allfiles", "=", "[", "]", "root", "=", "self", ".", "base", "stack", "=", "[", "root", "]", "pop", "=", "st...
[ 56, 4 ]
[ 81, 34 ]
python
en
['en', 'en', 'en']
True
Manifest.add
(self, item)
Add a file to the manifest. :param item: The pathname to add. This can be relative to the base.
Add a file to the manifest.
def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. """ if not item.startswith(self.prefix): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
[ "def", "add", "(", "self", ",", "item", ")", ":", "if", "not", "item", ".", "startswith", "(", "self", ".", "prefix", ")", ":", "item", "=", "os", ".", "path", ".", "join", "(", "self", ".", "base", ",", "item", ")", "self", ".", "files", ".", ...
[ 83, 4 ]
[ 91, 46 ]
python
en
['en', 'error', 'th']
False
Manifest.add_many
(self, items)
Add a list of files to the manifest. :param items: The pathnames to add. These can be relative to the base.
Add a list of files to the manifest.
def add_many(self, items): """ Add a list of files to the manifest. :param items: The pathnames to add. These can be relative to the base. """ for item in items: self.add(item)
[ "def", "add_many", "(", "self", ",", "items", ")", ":", "for", "item", "in", "items", ":", "self", ".", "add", "(", "item", ")" ]
[ 93, 4 ]
[ 100, 26 ]
python
en
['en', 'error', 'th']
False
Manifest.sorted
(self, wantdirs=False)
Return sorted files in directory order
Return sorted files in directory order
def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in...
[ "def", "sorted", "(", "self", ",", "wantdirs", "=", "False", ")", ":", "def", "add_dir", "(", "dirs", ",", "d", ")", ":", "dirs", ".", "add", "(", "d", ")", "logger", ".", "debug", "(", "'add_dir added %s'", ",", "d", ")", "if", "d", "!=", "self"...
[ 102, 4 ]
[ 122, 63 ]
python
en
['en', 'error', 'th']
False
Manifest.clear
(self)
Clear all collected files.
Clear all collected files.
def clear(self): """Clear all collected files.""" self.files = set() self.allfiles = []
[ "def", "clear", "(", "self", ")", ":", "self", ".", "files", "=", "set", "(", ")", "self", ".", "allfiles", "=", "[", "]" ]
[ 124, 4 ]
[ 127, 26 ]
python
en
['en', 'en', 'en']
True
Manifest.process_directive
(self, directive)
Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANIFEST.in`` files: http://docs....
Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``.
def process_directive(self, directive): """ Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANI...
[ "def", "process_directive", "(", "self", ",", "directive", ")", ":", "# Parse the line: split it up, make sure the right number of words", "# is there, and return the relevant words. 'action' is always", "# defined: it's the first word of the line. Which of the other", "# three are defined d...
[ 129, 4 ]
[ 202, 45 ]
python
en
['en', 'error', 'th']
False
Manifest._parse_directive
(self, directive)
Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns
Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns
def _parse_directive(self, directive): """ Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns """ words = directive.split() if len(words) == 1 and words[0] not in ('include', 'exclude', ...
[ "def", "_parse_directive", "(", "self", ",", "directive", ")", ":", "words", "=", "directive", ".", "split", "(", ")", "if", "len", "(", "words", ")", "==", "1", "and", "words", "[", "0", "]", "not", "in", "(", "'include'", ",", "'exclude'", ",", "...
[ 208, 4 ]
[ 253, 52 ]
python
en
['en', 'error', 'th']
False
Manifest._include_pattern
(self, pattern, anchor=True, prefix=None, is_regex=False)
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; co...
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern.
def _include_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' ...
[ "def", "_include_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "# XXX docstring lying about what the special chars are?", "found", "=", "False", "pattern_re", "=", "self", ...
[ 255, 4 ]
[ 294, 20 ]
python
en
['en', 'en', 'en']
True
Manifest._exclude_pattern
(self, pattern, anchor=True, prefix=None, is_regex=False)
Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. ...
Remove strings (presumably filenames) from 'files' that match 'pattern'.
def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place...
[ "def", "_exclude_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "found", "=", "False", "pattern_re", "=", "self", ".", "_translate_pattern", "(", "pattern", ",", "an...
[ 296, 4 ]
[ 314, 20 ]
python
en
['en', 'en', 'en']
True
Manifest._translate_pattern
(self, pattern, anchor=True, prefix=None, is_regex=False)
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object).
Translate a shell-like wildcard pattern to a compiled regular expression.
def _translate_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it'...
[ "def", "_translate_pattern", "(", "self", ",", "pattern", ",", "anchor", "=", "True", ",", "prefix", "=", "None", ",", "is_regex", "=", "False", ")", ":", "if", "is_regex", ":", "if", "isinstance", "(", "pattern", ",", "str", ")", ":", "return", "re", ...
[ 316, 4 ]
[ 369, 37 ]
python
en
['en', 'en', 'en']
True
Manifest._glob_to_re
(self, pattern)
Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific).
Translate a shell-like glob pattern to a regular expression.
def _glob_to_re(self, pattern): """Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = fnmat...
[ "def", "_glob_to_re", "(", "self", ",", "pattern", ")", ":", "pattern_re", "=", "fnmatch", ".", "translate", "(", "pattern", ")", "# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which", "# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,", "#...
[ 371, 4 ]
[ 392, 25 ]
python
en
['en', 'ny', 'en']
True
tostring
(element)
Serialize an element and its child nodes to a string
Serialize an element and its child nodes to a string
def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] def serializeElement(element): if not hasattr(element, "tag"): if element.docinfo.internalDTD: if element.docinfo.doctype: dtd_str = element.docinfo.doctype ...
[ "def", "tostring", "(", "element", ")", ":", "rv", "=", "[", "]", "def", "serializeElement", "(", "element", ")", ":", "if", "not", "hasattr", "(", "element", ",", "\"tag\"", ")", ":", "if", "element", ".", "docinfo", ".", "internalDTD", ":", "if", "...
[ 133, 0 ]
[ 171, 22 ]
python
en
['en', 'en', 'en']
True
DatabaseCreation._destroy_test_db
(self, test_database_name, verbosity=1)
Destroy a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created.
Destroy a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created.
def _destroy_test_db(self, test_database_name, verbosity=1): """ Destroy a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created. """ self.connection.settings_dict['USER'] = self.connection.settings_dict['...
[ "def", "_destroy_test_db", "(", "self", ",", "test_database_name", ",", "verbosity", "=", "1", ")", ":", "self", ".", "connection", ".", "settings_dict", "[", "'USER'", "]", "=", "self", ".", "connection", ".", "settings_dict", "[", "'SAVED_USER'", "]", "sel...
[ 130, 4 ]
[ 148, 31 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._test_settings_get
(self, key, default=None, prefixed=None)
Return a value from the test settings dict, or a given default, or a prefixed entry from the main settings dict
Return a value from the test settings dict, or a given default, or a prefixed entry from the main settings dict
def _test_settings_get(self, key, default=None, prefixed=None): """ Return a value from the test settings dict, or a given default, or a prefixed entry from the main settings dict """ settings_dict = self.connection.settings_dict val = settings_dict['TEST'].get(ke...
[ "def", "_test_settings_get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "prefixed", "=", "None", ")", ":", "settings_dict", "=", "self", ".", "connection", ".", "settings_dict", "val", "=", "settings_dict", "[", "'TEST'", "]", ".", "get", ...
[ 238, 4 ]
[ 248, 18 ]
python
en
['en', 'error', 'th']
False
DatabaseCreation._get_test_db_name
(self)
We need to return the 'production' DB name to get the test DB creation machinery to work. This isn't a great deal in this case because DB names as handled by Django haven't real counterparts in Oracle.
We need to return the 'production' DB name to get the test DB creation machinery to work. This isn't a great deal in this case because DB names as handled by Django haven't real counterparts in Oracle.
def _get_test_db_name(self): """ We need to return the 'production' DB name to get the test DB creation machinery to work. This isn't a great deal in this case because DB names as handled by Django haven't real counterparts in Oracle. """ return self.connection.settings_d...
[ "def", "_get_test_db_name", "(", "self", ")", ":", "return", "self", ".", "connection", ".", "settings_dict", "[", "'NAME'", "]" ]
[ 287, 4 ]
[ 293, 52 ]
python
en
['en', 'error', 'th']
False
FileEntry.stat_regular_file
(path, stat_function)
Wrap `stat_function` to raise appropriate errors if `path` is not a regular file
Wrap `stat_function` to raise appropriate errors if `path` is not a regular file
def stat_regular_file(path, stat_function): """ Wrap `stat_function` to raise appropriate errors if `path` is not a regular file """ try: stat_result = stat_function(path) except KeyError: raise MissingFileError(path) except OSError as e: ...
[ "def", "stat_regular_file", "(", "path", ",", "stat_function", ")", ":", "try", ":", "stat_result", "=", "stat_function", "(", "path", ")", "except", "KeyError", ":", "raise", "MissingFileError", "(", "path", ")", "except", "OSError", "as", "e", ":", "if", ...
[ 223, 4 ]
[ 242, 26 ]
python
en
['en', 'error', 'th']
False
avatar
( request: HttpRequest, user_profile: UserProfile, email_or_id: str, medium: bool = False )
Accepts an email address or user ID and returns the avatar
Accepts an email address or user ID and returns the avatar
def avatar( request: HttpRequest, user_profile: UserProfile, email_or_id: str, medium: bool = False ) -> HttpResponse: """Accepts an email address or user ID and returns the avatar""" is_email = False try: int(email_or_id) except ValueError: is_email = True try: realm = ...
[ "def", "avatar", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "email_or_id", ":", "str", ",", "medium", ":", "bool", "=", "False", ")", "->", "HttpResponse", ":", "is_email", "=", "False", "try", ":", "int", "(", "ema...
[ 214, 0 ]
[ 246, 24 ]
python
en
['en', 'en', 'en']
True
get_members_backend
( request: HttpRequest, user_profile: UserProfile, user_id: Optional[int] = None, include_custom_profile_fields: bool = REQ(json_validator=check_bool, default=False), client_gravatar: bool = REQ(json_validator=check_bool, default=False), )
The client_gravatar field here is set to True if clients can compute their own gravatars, which saves us bandwidth. We want to eventually make this the default behavior, but we have old clients that expect the server to compute this for us.
The client_gravatar field here is set to True if clients can compute their own gravatars, which saves us bandwidth. We want to eventually make this the default behavior, but we have old clients that expect the server to compute this for us.
def get_members_backend( request: HttpRequest, user_profile: UserProfile, user_id: Optional[int] = None, include_custom_profile_fields: bool = REQ(json_validator=check_bool, default=False), client_gravatar: bool = REQ(json_validator=check_bool, default=False), ) -> HttpResponse: """ The clie...
[ "def", "get_members_backend", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "UserProfile", ",", "user_id", ":", "Optional", "[", "int", "]", "=", "None", ",", "include_custom_profile_fields", ":", "bool", "=", "REQ", "(", "json_validator", "=", ...
[ 520, 0 ]
[ 558, 29 ]
python
en
['en', 'error', 'th']
False
ExchangeConfiguration.get_ews_session
(self)
Get a configured EWS session. :rtype: respa_exchange.ews.session.ExchangeSession
Get a configured EWS session.
def get_ews_session(self): """ Get a configured EWS session. :rtype: respa_exchange.ews.session.ExchangeSession """ if hasattr(self, '_ews_session'): return self._ews_session session_class = import_string( getattr(settings, "RESPA_EXCHANGE_EWS_S...
[ "def", "get_ews_session", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_ews_session'", ")", ":", "return", "self", ".", "_ews_session", "session_class", "=", "import_string", "(", "getattr", "(", "settings", ",", "\"RESPA_EXCHANGE_EWS_SESSION_CLASS\...
[ 55, 4 ]
[ 71, 32 ]
python
en
['en', 'error', 'th']
False
ExchangeResource.reservations
(self)
Get a queryset of ExchangeReservations for this resource :rtype: django.db.models.QuerySet[ExchangeReservation]
Get a queryset of ExchangeReservations for this resource
def reservations(self): """ Get a queryset of ExchangeReservations for this resource :rtype: django.db.models.QuerySet[ExchangeReservation] """ return ExchangeReservation.objects.filter(reservation__resource=self.resource)
[ "def", "reservations", "(", "self", ")", ":", "return", "ExchangeReservation", ".", "objects", ".", "filter", "(", "reservation__resource", "=", "self", ".", "resource", ")" ]
[ 128, 4 ]
[ 134, 86 ]
python
en
['en', 'error', 'th']
False
ExchangeReservation.item_id
(self)
Retrieve the ExchangeReservation's related appointment's item ID object :rtype: respa_exchange.objs.ItemID
Retrieve the ExchangeReservation's related appointment's item ID object
def item_id(self): """ Retrieve the ExchangeReservation's related appointment's item ID object :rtype: respa_exchange.objs.ItemID """ return ItemID(id=self._item_id, change_key=self._change_key)
[ "def", "item_id", "(", "self", ")", ":", "return", "ItemID", "(", "id", "=", "self", ".", "_item_id", ",", "change_key", "=", "self", ".", "_change_key", ")" ]
[ 196, 4 ]
[ 202, 68 ]
python
en
['en', 'error', 'th']
False
parse_date
(value)
Parses a string and return a datetime.date. Raises ValueError if the input is well formatted but not a valid date. Returns None if the input isn't well formatted.
Parses a string and return a datetime.date.
def parse_date(value): """Parses a string and return a datetime.date. Raises ValueError if the input is well formatted but not a valid date. Returns None if the input isn't well formatted. """ match = date_re.match(value) if match: kw = dict((k, int(v)) for k, v in six.iteritems(match.g...
[ "def", "parse_date", "(", "value", ")", ":", "match", "=", "date_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "dict", "(", "(", "k", ",", "int", "(", "v", ")", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", ...
[ 30, 0 ]
[ 39, 34 ]
python
en
['en', 'en', 'en']
True
parse_time
(value)
Parses a string and return a datetime.time. This function doesn't support time zone offsets. Raises ValueError if the input is well formatted but not a valid time. Returns None if the input isn't well formatted, in particular if it contains an offset.
Parses a string and return a datetime.time.
def parse_time(value): """Parses a string and return a datetime.time. This function doesn't support time zone offsets. Raises ValueError if the input is well formatted but not a valid time. Returns None if the input isn't well formatted, in particular if it contains an offset. """ match = ...
[ "def", "parse_time", "(", "value", ")", ":", "match", "=", "time_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "match", ".", "groupdict", "(", ")", "if", "kw", "[", "'microsecond'", "]", ":", "kw", "[", "'microsecond'", "]", ...
[ 42, 0 ]
[ 57, 34 ]
python
en
['en', 'en', 'en']
True
parse_datetime
(value)
Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if the input isn't well formatted. ...
Parses a string and return a datetime.datetime.
def parse_datetime(value): """Parses a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raises ValueError if the input is well formatted but not a valid datetime. Returns None if t...
[ "def", "parse_datetime", "(", "value", ")", ":", "match", "=", "datetime_re", ".", "match", "(", "value", ")", "if", "match", ":", "kw", "=", "match", ".", "groupdict", "(", ")", "if", "kw", "[", "'microsecond'", "]", ":", "kw", "[", "'microsecond'", ...
[ 60, 0 ]
[ 85, 38 ]
python
en
['en', 'en', 'en']
True
AnalyticsTestCase.assertTableState
( self, table: Type[BaseCount], arg_keys: List[str], arg_values: List[List[object]] )
Assert that the state of a *Count table is what it should be. Example usage: self.assertTableState(RealmCount, ['property', 'subgroup', 'realm'], [['p1', 4], ['p2', 10, self.alt_realm]]) table -- A *Count table. arg_keys -- List of columns of <tabl...
Assert that the state of a *Count table is what it should be.
def assertTableState( self, table: Type[BaseCount], arg_keys: List[str], arg_values: List[List[object]] ) -> None: """Assert that the state of a *Count table is what it should be. Example usage: self.assertTableState(RealmCount, ['property', 'subgroup', 'realm'], ...
[ "def", "assertTableState", "(", "self", ",", "table", ":", "Type", "[", "BaseCount", "]", ",", "arg_keys", ":", "List", "[", "str", "]", ",", "arg_values", ":", "List", "[", "List", "[", "object", "]", "]", ")", "->", "None", ":", "defaults", "=", ...
[ 177, 4 ]
[ 222, 64 ]
python
en
['en', 'en', 'en']
True
clip_eta
(eta, norm, eps)
Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param norm: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation.
Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param norm: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation.
def clip_eta(eta, norm, eps): """ Helper function to clip the perturbation to epsilon norm ball. :param eta: A tensor with the current perturbation. :param norm: Order of the norm (mimics Numpy). Possible values: np.inf, 1 or 2. :param eps: Epsilon, bound of the perturbation. """...
[ "def", "clip_eta", "(", "eta", ",", "norm", ",", "eps", ")", ":", "# Clipping perturbation eta to self.norm norm ball", "if", "norm", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"norm must be np.inf, 1, or 2....
[ 4, 0 ]
[ 35, 14 ]
python
en
['en', 'error', 'th']
False
random_exponential
(shape, rate=1.0, dtype=tf.float32, seed=None)
Helper function to sample from the exponential distribution, which is not included in core TensorFlow. shape: shape of the sampled tensor. :rate: (optional) rate parameter of the exponential distribution, defaults to 1.0. :dtype: (optional) data type of the sempled tensor, defaults to tf.float32. ...
Helper function to sample from the exponential distribution, which is not included in core TensorFlow.
def random_exponential(shape, rate=1.0, dtype=tf.float32, seed=None): """ Helper function to sample from the exponential distribution, which is not included in core TensorFlow. shape: shape of the sampled tensor. :rate: (optional) rate parameter of the exponential distribution, defaults to 1.0. ...
[ "def", "random_exponential", "(", "shape", ",", "rate", "=", "1.0", ",", "dtype", "=", "tf", ".", "float32", ",", "seed", "=", "None", ")", ":", "return", "tf", ".", "random", ".", "gamma", "(", "shape", ",", "alpha", "=", "1", ",", "beta", "=", ...
[ 38, 0 ]
[ 48, 83 ]
python
en
['en', 'error', 'th']
False
random_laplace
(shape, loc=0.0, scale=1.0, dtype=tf.float32, seed=None)
Helper function to sample from the Laplace distribution, which is not included in core TensorFlow. :shape: shape of the sampled tensor. :loc: (optional) mean of the laplace distribution, defaults to 0.0. :scale: (optional) scale parameter of the laplace diustribution, defaults to 1.0. :dtype: ...
Helper function to sample from the Laplace distribution, which is not included in core TensorFlow.
def random_laplace(shape, loc=0.0, scale=1.0, dtype=tf.float32, seed=None): """ Helper function to sample from the Laplace distribution, which is not included in core TensorFlow. :shape: shape of the sampled tensor. :loc: (optional) mean of the laplace distribution, defaults to 0.0. :scale: (op...
[ "def", "random_laplace", "(", "shape", ",", "loc", "=", "0.0", ",", "scale", "=", "1.0", ",", "dtype", "=", "tf", ".", "float32", ",", "seed", "=", "None", ")", ":", "z1", "=", "random_exponential", "(", "shape", ",", "1.0", "/", "scale", ",", "dty...
[ 51, 0 ]
[ 64, 24 ]
python
en
['en', 'error', 'th']
False
random_lp_vector
(shape, ord, eps, dtype=tf.float32, seed=None)
Helper function to generate uniformly random vectors from a norm ball of radius epsilon. :param shape: Output shape of the random sample. The shape is expected to be of the form `(n, d1, d2, ..., dn)` where `n` is the number of i.i.d. samples that will be drawn from a no...
Helper function to generate uniformly random vectors from a norm ball of radius epsilon. :param shape: Output shape of the random sample. The shape is expected to be of the form `(n, d1, d2, ..., dn)` where `n` is the number of i.i.d. samples that will be drawn from a no...
def random_lp_vector(shape, ord, eps, dtype=tf.float32, seed=None): """ Helper function to generate uniformly random vectors from a norm ball of radius epsilon. :param shape: Output shape of the random sample. The shape is expected to be of the form `(n, d1, d2, ..., dn)` where `n` is ...
[ "def", "random_lp_vector", "(", "shape", ",", "ord", ",", "eps", ",", "dtype", "=", "tf", ".", "float32", ",", "seed", "=", "None", ")", ":", "if", "ord", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", ...
[ 67, 0 ]
[ 116, 12 ]
python
en
['en', 'error', 'th']
False
get_or_guess_labels
(model_fn, x, y=None, targeted=False)
Helper function to get the label to use in generating an adversarial example for x. If 'y' is not None, then use these labels. If 'targeted' is True, then assume it's a targeted attack and y must be set. Otherwise, use the model's prediction as the label and perform an untargeted attack ...
Helper function to get the label to use in generating an adversarial example for x. If 'y' is not None, then use these labels. If 'targeted' is True, then assume it's a targeted attack and y must be set. Otherwise, use the model's prediction as the label and perform an untargeted attack ...
def get_or_guess_labels(model_fn, x, y=None, targeted=False): """ Helper function to get the label to use in generating an adversarial example for x. If 'y' is not None, then use these labels. If 'targeted' is True, then assume it's a targeted attack and y must be set. Otherwise, use the mod...
[ "def", "get_or_guess_labels", "(", "model_fn", ",", "x", ",", "y", "=", "None", ",", "targeted", "=", "False", ")", ":", "if", "targeted", "is", "True", "and", "y", "is", "None", ":", "raise", "ValueError", "(", "\"Must provide y for a targeted attack!\"", "...
[ 119, 0 ]
[ 154, 29 ]
python
en
['en', 'error', 'th']
False
set_with_mask
(x, x_other, mask)
Helper function which returns a tensor similar to x with all the values of x replaced by x_other where the mask evaluates to true.
Helper function which returns a tensor similar to x with all the values of x replaced by x_other where the mask evaluates to true.
def set_with_mask(x, x_other, mask): """Helper function which returns a tensor similar to x with all the values of x replaced by x_other where the mask evaluates to true. """ mask = tf.cast(mask, x.dtype) ones = tf.ones_like(mask, dtype=x.dtype) return x_other * mask + x * (ones - mask)
[ "def", "set_with_mask", "(", "x", ",", "x_other", ",", "mask", ")", ":", "mask", "=", "tf", ".", "cast", "(", "mask", ",", "x", ".", "dtype", ")", "ones", "=", "tf", ".", "ones_like", "(", "mask", ",", "dtype", "=", "x", ".", "dtype", ")", "ret...
[ 157, 0 ]
[ 163, 45 ]
python
en
['en', 'en', 'en']
True
compute_gradient
(model_fn, loss_fn, x, y, targeted)
Computes the gradient of the loss with respect to the input tensor. :param model_fn: a callable that takes an input tensor and returns the model logits. :param loss_fn: loss function that takes (labels, logits) as arguments and returns loss. :param x: input tensor :param y: Tensor with true labels....
Computes the gradient of the loss with respect to the input tensor. :param model_fn: a callable that takes an input tensor and returns the model logits. :param loss_fn: loss function that takes (labels, logits) as arguments and returns loss. :param x: input tensor :param y: Tensor with true labels....
def compute_gradient(model_fn, loss_fn, x, y, targeted): """ Computes the gradient of the loss with respect to the input tensor. :param model_fn: a callable that takes an input tensor and returns the model logits. :param loss_fn: loss function that takes (labels, logits) as arguments and returns loss. ...
[ "def", "compute_gradient", "(", "model_fn", ",", "loss_fn", ",", "x", ",", "y", ",", "targeted", ")", ":", "with", "tf", ".", "GradientTape", "(", ")", "as", "g", ":", "g", ".", "watch", "(", "x", ")", "# Compute loss", "loss", "=", "loss_fn", "(", ...
[ 170, 0 ]
[ 194, 15 ]
python
en
['en', 'error', 'th']
False
optimize_linear
(grad, eps, norm=np.inf)
Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{norm} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of constraint region :param norm: int specifying orde...
Solves for the optimal input to a linear function under a norm constraint.
def optimize_linear(grad, eps, norm=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{norm} < eps} dot(eta, grad) :param grad: tf tensor containing a batch of gradients :param eps: float scalar specifying size of co...
[ "def", "optimize_linear", "(", "grad", ",", "eps", ",", "norm", "=", "np", ".", "inf", ")", ":", "# Convert the iterator returned by `range` into a list.", "axis", "=", "list", "(", "range", "(", "1", ",", "len", "(", "grad", ".", "get_shape", "(", ")", ")...
[ 197, 0 ]
[ 241, 30 ]
python
en
['en', 'error', 'th']
False
Bytecode_compat.__iter__
(self)
Yield '(op,arg)' pair for each operation in code object 'code
Yield '(op,arg)' pair for each operation in code object 'code
def __iter__(self): """Yield '(op,arg)' pair for each operation in code object 'code'""" bytes = array.array('b', self.code.co_code) eof = len(self.code.co_code) ptr = 0 extended_arg = 0 while ptr < eof: op = bytes[ptr] if op >= dis.HAVE_ARGUM...
[ "def", "__iter__", "(", "self", ")", ":", "bytes", "=", "array", ".", "array", "(", "'b'", ",", "self", ".", "code", ".", "co_code", ")", "eof", "=", "len", "(", "self", ".", "code", ".", "co_code", ")", "ptr", "=", "0", "extended_arg", "=", "0",...
[ 21, 4 ]
[ 48, 32 ]
python
en
['en', 'en', 'en']
True
decode_dxt1
(data, alpha=False)
input: one "row" of data (i.e. will produce 4*width pixels)
input: one "row" of data (i.e. will produce 4*width pixels)
def decode_dxt1(data, alpha=False): """ input: one "row" of data (i.e. will produce 4*width pixels) """ blocks = len(data) // 8 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): # Decode next 8-byte block. idx = bl...
[ "def", "decode_dxt1", "(", "data", ",", "alpha", "=", "False", ")", ":", "blocks", "=", "len", "(", "data", ")", "//", "8", "# number of blocks in row", "ret", "=", "(", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", "...
[ 51, 0 ]
[ 103, 14 ]
python
en
['en', 'error', 'th']
False
decode_dxt3
(data)
input: one "row" of data (i.e. will produce 4*width pixels)
input: one "row" of data (i.e. will produce 4*width pixels)
def decode_dxt3(data): """ input: one "row" of data (i.e. will produce 4*width pixels) """ blocks = len(data) // 16 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): idx = block * 16 block = data[idx : idx + 16] ...
[ "def", "decode_dxt3", "(", "data", ")", ":", "blocks", "=", "len", "(", "data", ")", "//", "16", "# number of blocks in row", "ret", "=", "(", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ...
[ 106, 0 ]
[ 156, 14 ]
python
en
['en', 'error', 'th']
False
decode_dxt5
(data)
input: one "row" of data (i.e. will produce 4 * width pixels)
input: one "row" of data (i.e. will produce 4 * width pixels)
def decode_dxt5(data): """ input: one "row" of data (i.e. will produce 4 * width pixels) """ blocks = len(data) // 16 # number of blocks in row ret = (bytearray(), bytearray(), bytearray(), bytearray()) for block in range(blocks): idx = block * 16 block = data[idx : idx + 16] ...
[ "def", "decode_dxt5", "(", "data", ")", ":", "blocks", "=", "len", "(", "data", ")", "//", "16", "# number of blocks in row", "ret", "=", "(", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ",", "bytearray", "(", ")", ...
[ 159, 0 ]
[ 226, 14 ]
python
en
['en', 'error', 'th']
False
hide_file
(path)
Set the hidden attribute on a file or directory. From http://stackoverflow.com/questions/19622133/ `path` must be text.
Set the hidden attribute on a file or directory.
def hide_file(path): """ Set the hidden attribute on a file or directory. From http://stackoverflow.com/questions/19622133/ `path` must be text. """ __import__('ctypes.wintypes') SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW SetFileAttributes.argtypes = ctypes.wintypes....
[ "def", "hide_file", "(", "path", ")", ":", "__import__", "(", "'ctypes.wintypes'", ")", "SetFileAttributes", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "SetFileAttributesW", "SetFileAttributes", ".", "argtypes", "=", "ctypes", ".", "wintypes", ".", "LPW...
[ 11, 0 ]
[ 28, 31 ]
python
en
['en', 'error', 'th']
False
_req_set_item_sorter
( item, # type: Tuple[str, InstallRequirement] weights, # type: Dict[Optional[str], int] )
Key function used to sort install requirements for installation. Based on the "weight" mapping calculated in ``get_installation_order()``. The canonical package name is returned as the second member as a tie- breaker to ensure the result is predictable, which is useful in tests.
Key function used to sort install requirements for installation.
def _req_set_item_sorter( item, # type: Tuple[str, InstallRequirement] weights, # type: Dict[Optional[str], int] ): # type: (...) -> Tuple[int, str] """Key function used to sort install requirements for installation. Based on the "weight" mapping calculated in ``get_installation_order()``. ...
[ "def", "_req_set_item_sorter", "(", "item", ",", "# type: Tuple[str, InstallRequirement]", "weights", ",", "# type: Dict[Optional[str], int]", ")", ":", "# type: (...) -> Tuple[int, str]", "name", "=", "canonicalize_name", "(", "item", "[", "0", "]", ")", "return", "weigh...
[ 161, 0 ]
[ 173, 30 ]
python
en
['en', 'en', 'en']
True
Resolver.get_installation_order
(self, req_set)
Create a list that orders given requirements for installation. The returned list should contain all requirements in ``req_set``, so the caller can loop through it and have a requirement installed before the requiring thing. The current implementation walks the resolved dependency graph...
Create a list that orders given requirements for installation.
def get_installation_order(self, req_set): # type: (RequirementSet) -> List[InstallRequirement] """Create a list that orders given requirements for installation. The returned list should contain all requirements in ``req_set``, so the caller can loop through it and have a requirement in...
[ "def", "get_installation_order", "(", "self", ",", "req_set", ")", ":", "# type: (RequirementSet) -> List[InstallRequirement]", "assert", "self", ".", "_result", "is", "not", "None", ",", "\"must call resolve() first\"", "weights", "=", "{", "}", "# type: Dict[Optional[st...
[ 114, 4 ]
[ 158, 49 ]
python
en
['en', 'en', 'en']
True
GeoQuerySet.area
(self, tolerance=0.05, **kwargs)
Returns the area of the geographic field in an `area` attribute on each element of this GeoQuerySet.
Returns the area of the geographic field in an `area` attribute on each element of this GeoQuerySet.
def area(self, tolerance=0.05, **kwargs): """ Returns the area of the geographic field in an `area` attribute on each element of this GeoQuerySet. """ # Performing setup here rather than in `_spatial_attribute` so that # we can get the units for `AreaField`. proce...
[ "def", "area", "(", "self", ",", "tolerance", "=", "0.05", ",", "*", "*", "kwargs", ")", ":", "# Performing setup here rather than in `_spatial_attribute` so that", "# we can get the units for `AreaField`.", "procedure_args", ",", "geo_field", "=", "self", ".", "_spatial_...
[ 21, 4 ]
[ 49, 59 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.centroid
(self, **kwargs)
Returns the centroid of the geographic field in a `centroid` attribute on each element of this GeoQuerySet.
Returns the centroid of the geographic field in a `centroid` attribute on each element of this GeoQuerySet.
def centroid(self, **kwargs): """ Returns the centroid of the geographic field in a `centroid` attribute on each element of this GeoQuerySet. """ return self._geom_attribute('centroid', **kwargs)
[ "def", "centroid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geom_attribute", "(", "'centroid'", ",", "*", "*", "kwargs", ")" ]
[ 51, 4 ]
[ 56, 57 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.collect
(self, **kwargs)
Performs an aggregate collect operation on the given geometry field. This is analogous to a union operation, but much faster because boundaries are not dissolved.
Performs an aggregate collect operation on the given geometry field. This is analogous to a union operation, but much faster because boundaries are not dissolved.
def collect(self, **kwargs): """ Performs an aggregate collect operation on the given geometry field. This is analogous to a union operation, but much faster because boundaries are not dissolved. """ return self._spatial_aggregate(aggregates.Collect, **kwargs)
[ "def", "collect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_aggregate", "(", "aggregates", ".", "Collect", ",", "*", "*", "kwargs", ")" ]
[ 58, 4 ]
[ 64, 68 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.difference
(self, geom, **kwargs)
Returns the spatial difference of the geographic field in a `difference` attribute on each element of this GeoQuerySet.
Returns the spatial difference of the geographic field in a `difference` attribute on each element of this GeoQuerySet.
def difference(self, geom, **kwargs): """ Returns the spatial difference of the geographic field in a `difference` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('difference', geom, **kwargs)
[ "def", "difference", "(", "self", ",", "geom", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geomset_attribute", "(", "'difference'", ",", "geom", ",", "*", "*", "kwargs", ")" ]
[ 66, 4 ]
[ 71, 68 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.distance
(self, geom, **kwargs)
Returns the distance from the given geographic field name to the given geometry in a `distance` attribute on each element of the GeoQuerySet. Keyword Arguments: `spheroid` => If the geometry field is geodetic and PostGIS is the spatial database, then t...
Returns the distance from the given geographic field name to the given geometry in a `distance` attribute on each element of the GeoQuerySet.
def distance(self, geom, **kwargs): """ Returns the distance from the given geographic field name to the given geometry in a `distance` attribute on each element of the GeoQuerySet. Keyword Arguments: `spheroid` => If the geometry field is geodetic and PostGIS is ...
[ "def", "distance", "(", "self", ",", "geom", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_distance_attribute", "(", "'distance'", ",", "geom", ",", "*", "*", "kwargs", ")" ]
[ 73, 4 ]
[ 89, 67 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.envelope
(self, **kwargs)
Returns a Geometry representing the bounding box of the Geometry field in an `envelope` attribute on each element of the GeoQuerySet.
Returns a Geometry representing the bounding box of the Geometry field in an `envelope` attribute on each element of the GeoQuerySet.
def envelope(self, **kwargs): """ Returns a Geometry representing the bounding box of the Geometry field in an `envelope` attribute on each element of the GeoQuerySet. """ return self._geom_attribute('envelope', **kwargs)
[ "def", "envelope", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geom_attribute", "(", "'envelope'", ",", "*", "*", "kwargs", ")" ]
[ 91, 4 ]
[ 97, 57 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.extent
(self, **kwargs)
Returns the extent (aggregate) of the features in the GeoQuerySet. The extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).
Returns the extent (aggregate) of the features in the GeoQuerySet. The extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).
def extent(self, **kwargs): """ Returns the extent (aggregate) of the features in the GeoQuerySet. The extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax). """ return self._spatial_aggregate(aggregates.Extent, **kwargs)
[ "def", "extent", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_aggregate", "(", "aggregates", ".", "Extent", ",", "*", "*", "kwargs", ")" ]
[ 99, 4 ]
[ 104, 67 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.extent3d
(self, **kwargs)
Returns the aggregate extent, in 3D, of the features in the GeoQuerySet. It is returned as a 6-tuple, comprising: (xmin, ymin, zmin, xmax, ymax, zmax).
Returns the aggregate extent, in 3D, of the features in the GeoQuerySet. It is returned as a 6-tuple, comprising: (xmin, ymin, zmin, xmax, ymax, zmax).
def extent3d(self, **kwargs): """ Returns the aggregate extent, in 3D, of the features in the GeoQuerySet. It is returned as a 6-tuple, comprising: (xmin, ymin, zmin, xmax, ymax, zmax). """ return self._spatial_aggregate(aggregates.Extent3D, **kwargs)
[ "def", "extent3d", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_aggregate", "(", "aggregates", ".", "Extent3D", ",", "*", "*", "kwargs", ")" ]
[ 106, 4 ]
[ 112, 69 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.force_rhr
(self, **kwargs)
Returns a modified version of the Polygon/MultiPolygon in which all of the vertices follow the Right-Hand-Rule. By default, this is attached as the `force_rhr` attribute on each element of the GeoQuerySet.
Returns a modified version of the Polygon/MultiPolygon in which all of the vertices follow the Right-Hand-Rule. By default, this is attached as the `force_rhr` attribute on each element of the GeoQuerySet.
def force_rhr(self, **kwargs): """ Returns a modified version of the Polygon/MultiPolygon in which all of the vertices follow the Right-Hand-Rule. By default, this is attached as the `force_rhr` attribute on each element of the GeoQuerySet. """ return self._geom_...
[ "def", "force_rhr", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geom_attribute", "(", "'force_rhr'", ",", "*", "*", "kwargs", ")" ]
[ 114, 4 ]
[ 121, 58 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.geojson
(self, precision=8, crs=False, bbox=False, **kwargs)
Returns a GeoJSON representation of the geometry field in a `geojson` attribute on each element of the GeoQuerySet. The `crs` and `bbox` keywords may be set to True if the user wants the coordinate reference system and the bounding box to be included in the GeoJSON representati...
Returns a GeoJSON representation of the geometry field in a `geojson` attribute on each element of the GeoQuerySet.
def geojson(self, precision=8, crs=False, bbox=False, **kwargs): """ Returns a GeoJSON representation of the geometry field in a `geojson` attribute on each element of the GeoQuerySet. The `crs` and `bbox` keywords may be set to True if the user wants the coordinate reference sy...
[ "def", "geojson", "(", "self", ",", "precision", "=", "8", ",", "crs", "=", "False", ",", "bbox", "=", "False", ",", "*", "*", "kwargs", ")", ":", "backend", "=", "connections", "[", "self", ".", "db", "]", ".", "ops", "if", "not", "backend", "."...
[ 123, 4 ]
[ 151, 62 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.geohash
(self, precision=20, **kwargs)
Returns a GeoHash representation of the given field in a `geohash` attribute on each element of the GeoQuerySet. The `precision` keyword may be used to custom the number of _characters_ used in the output GeoHash, the default is 20.
Returns a GeoHash representation of the given field in a `geohash` attribute on each element of the GeoQuerySet.
def geohash(self, precision=20, **kwargs): """ Returns a GeoHash representation of the given field in a `geohash` attribute on each element of the GeoQuerySet. The `precision` keyword may be used to custom the number of _characters_ used in the output GeoHash, the default is 20....
[ "def", "geohash", "(", "self", ",", "precision", "=", "20", ",", "*", "*", "kwargs", ")", ":", "s", "=", "{", "'desc'", ":", "'GeoHash'", ",", "'procedure_args'", ":", "{", "'precision'", ":", "precision", "}", ",", "'procedure_fmt'", ":", "'%(geo_col)s,...
[ 153, 4 ]
[ 165, 62 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.gml
(self, precision=8, version=2, **kwargs)
Returns GML representation of the given field in a `gml` attribute on each element of the GeoQuerySet.
Returns GML representation of the given field in a `gml` attribute on each element of the GeoQuerySet.
def gml(self, precision=8, version=2, **kwargs): """ Returns GML representation of the given field in a `gml` attribute on each element of the GeoQuerySet. """ backend = connections[self.db].ops s = {'desc': 'GML', 'procedure_args': {'precision': precision}} if ba...
[ "def", "gml", "(", "self", ",", "precision", "=", "8", ",", "version", "=", "2", ",", "*", "*", "kwargs", ")", ":", "backend", "=", "connections", "[", "self", ".", "db", "]", ".", "ops", "s", "=", "{", "'desc'", ":", "'GML'", ",", "'procedure_ar...
[ 167, 4 ]
[ 180, 58 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.intersection
(self, geom, **kwargs)
Returns the spatial intersection of the Geometry field in an `intersection` attribute on each element of this GeoQuerySet.
Returns the spatial intersection of the Geometry field in an `intersection` attribute on each element of this GeoQuerySet.
def intersection(self, geom, **kwargs): """ Returns the spatial intersection of the Geometry field in an `intersection` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('intersection', geom, **kwargs)
[ "def", "intersection", "(", "self", ",", "geom", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geomset_attribute", "(", "'intersection'", ",", "geom", ",", "*", "*", "kwargs", ")" ]
[ 182, 4 ]
[ 188, 70 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.kml
(self, **kwargs)
Returns KML representation of the geometry field in a `kml` attribute on each element of this GeoQuerySet.
Returns KML representation of the geometry field in a `kml` attribute on each element of this GeoQuerySet.
def kml(self, **kwargs): """ Returns KML representation of the geometry field in a `kml` attribute on each element of this GeoQuerySet. """ s = {'desc': 'KML', 'procedure_fmt': '%(geo_col)s,%(precision)s', 'procedure_args': {'precision': kwargs.pop('prec...
[ "def", "kml", "(", "self", ",", "*", "*", "kwargs", ")", ":", "s", "=", "{", "'desc'", ":", "'KML'", ",", "'procedure_fmt'", ":", "'%(geo_col)s,%(precision)s'", ",", "'procedure_args'", ":", "{", "'precision'", ":", "kwargs", ".", "pop", "(", "'precision'"...
[ 190, 4 ]
[ 199, 58 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.length
(self, **kwargs)
Returns the length of the geometry field as a `Distance` object stored in a `length` attribute on each element of this GeoQuerySet.
Returns the length of the geometry field as a `Distance` object stored in a `length` attribute on each element of this GeoQuerySet.
def length(self, **kwargs): """ Returns the length of the geometry field as a `Distance` object stored in a `length` attribute on each element of this GeoQuerySet. """ return self._distance_attribute('length', None, **kwargs)
[ "def", "length", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_distance_attribute", "(", "'length'", ",", "None", ",", "*", "*", "kwargs", ")" ]
[ 201, 4 ]
[ 206, 65 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.make_line
(self, **kwargs)
Creates a linestring from all of the PointField geometries in the this GeoQuerySet and returns it. This is a spatial aggregate method, and thus returns a geometry rather than a GeoQuerySet.
Creates a linestring from all of the PointField geometries in the this GeoQuerySet and returns it. This is a spatial aggregate method, and thus returns a geometry rather than a GeoQuerySet.
def make_line(self, **kwargs): """ Creates a linestring from all of the PointField geometries in the this GeoQuerySet and returns it. This is a spatial aggregate method, and thus returns a geometry rather than a GeoQuerySet. """ return self._spatial_aggregate(aggregates....
[ "def", "make_line", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_aggregate", "(", "aggregates", ".", "MakeLine", ",", "geo_field_type", "=", "PointField", ",", "*", "*", "kwargs", ")" ]
[ 208, 4 ]
[ 214, 96 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.mem_size
(self, **kwargs)
Returns the memory size (number of bytes) that the geometry field takes in a `mem_size` attribute on each element of this GeoQuerySet.
Returns the memory size (number of bytes) that the geometry field takes in a `mem_size` attribute on each element of this GeoQuerySet.
def mem_size(self, **kwargs): """ Returns the memory size (number of bytes) that the geometry field takes in a `mem_size` attribute on each element of this GeoQuerySet. """ return self._spatial_attribute('mem_size', {}, **kwargs)
[ "def", "mem_size", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_attribute", "(", "'mem_size'", ",", "{", "}", ",", "*", "*", "kwargs", ")" ]
[ 216, 4 ]
[ 221, 64 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.num_geom
(self, **kwargs)
Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None.
Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None.
def num_geom(self, **kwargs): """ Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None. """ return self._spatial_attribute('num_geom', {}, ...
[ "def", "num_geom", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_attribute", "(", "'num_geom'", ",", "{", "}", ",", "*", "*", "kwargs", ")" ]
[ 223, 4 ]
[ 230, 64 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.num_points
(self, **kwargs)
Returns the number of points in the first linestring in the Geometry field in a `num_points` attribute on each element of this GeoQuerySet; otherwise sets with None.
Returns the number of points in the first linestring in the Geometry field in a `num_points` attribute on each element of this GeoQuerySet; otherwise sets with None.
def num_points(self, **kwargs): """ Returns the number of points in the first linestring in the Geometry field in a `num_points` attribute on each element of this GeoQuerySet; otherwise sets with None. """ return self._spatial_attribute('num_points', {}, **kwargs)
[ "def", "num_points", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_attribute", "(", "'num_points'", ",", "{", "}", ",", "*", "*", "kwargs", ")" ]
[ 232, 4 ]
[ 238, 66 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.perimeter
(self, **kwargs)
Returns the perimeter of the geometry field as a `Distance` object stored in a `perimeter` attribute on each element of this GeoQuerySet.
Returns the perimeter of the geometry field as a `Distance` object stored in a `perimeter` attribute on each element of this GeoQuerySet.
def perimeter(self, **kwargs): """ Returns the perimeter of the geometry field as a `Distance` object stored in a `perimeter` attribute on each element of this GeoQuerySet. """ return self._distance_attribute('perimeter', None, **kwargs)
[ "def", "perimeter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_distance_attribute", "(", "'perimeter'", ",", "None", ",", "*", "*", "kwargs", ")" ]
[ 240, 4 ]
[ 245, 68 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.point_on_surface
(self, **kwargs)
Returns a Point geometry guaranteed to lie on the surface of the Geometry field in a `point_on_surface` attribute on each element of this GeoQuerySet; otherwise sets with None.
Returns a Point geometry guaranteed to lie on the surface of the Geometry field in a `point_on_surface` attribute on each element of this GeoQuerySet; otherwise sets with None.
def point_on_surface(self, **kwargs): """ Returns a Point geometry guaranteed to lie on the surface of the Geometry field in a `point_on_surface` attribute on each element of this GeoQuerySet; otherwise sets with None. """ return self._geom_attribute('point_on_surface', *...
[ "def", "point_on_surface", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geom_attribute", "(", "'point_on_surface'", ",", "*", "*", "kwargs", ")" ]
[ 247, 4 ]
[ 253, 65 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.reverse_geom
(self, **kwargs)
Reverses the coordinate order of the geometry, and attaches as a `reverse` attribute on each element of this GeoQuerySet.
Reverses the coordinate order of the geometry, and attaches as a `reverse` attribute on each element of this GeoQuerySet.
def reverse_geom(self, **kwargs): """ Reverses the coordinate order of the geometry, and attaches as a `reverse` attribute on each element of this GeoQuerySet. """ s = {'select_field': GeomField()} kwargs.setdefault('model_att', 'reverse_geom') if connections[self...
[ "def", "reverse_geom", "(", "self", ",", "*", "*", "kwargs", ")", ":", "s", "=", "{", "'select_field'", ":", "GeomField", "(", ")", "}", "kwargs", ".", "setdefault", "(", "'model_att'", ",", "'reverse_geom'", ")", "if", "connections", "[", "self", ".", ...
[ 255, 4 ]
[ 264, 62 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.scale
(self, x, y, z=0.0, **kwargs)
Scales the geometry to a new size by multiplying the ordinates with the given x,y,z scale factors.
Scales the geometry to a new size by multiplying the ordinates with the given x,y,z scale factors.
def scale(self, x, y, z=0.0, **kwargs): """ Scales the geometry to a new size by multiplying the ordinates with the given x,y,z scale factors. """ if connections[self.db].ops.spatialite: if z != 0.0: raise NotImplementedError('SpatiaLite does not suppo...
[ "def", "scale", "(", "self", ",", "x", ",", "y", ",", "z", "=", "0.0", ",", "*", "*", "kwargs", ")", ":", "if", "connections", "[", "self", ".", "db", "]", ".", "ops", ".", "spatialite", ":", "if", "z", "!=", "0.0", ":", "raise", "NotImplemente...
[ 266, 4 ]
[ 283, 60 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.snap_to_grid
(self, *args, **kwargs)
Snap all points of the input geometry to the grid. How the geometry is snapped to the grid depends on how many arguments were given: - 1 argument : A single size to snap both the X and Y grids to. - 2 arguments: X and Y sizes to snap the grid to. - 4 arguments: X,...
Snap all points of the input geometry to the grid. How the geometry is snapped to the grid depends on how many arguments were given: - 1 argument : A single size to snap both the X and Y grids to. - 2 arguments: X and Y sizes to snap the grid to. - 4 arguments: X,...
def snap_to_grid(self, *args, **kwargs): """ Snap all points of the input geometry to the grid. How the geometry is snapped to the grid depends on how many arguments were given: - 1 argument : A single size to snap both the X and Y grids to. - 2 arguments: X and Y si...
[ "def", "snap_to_grid", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "False", "in", "[", "isinstance", "(", "arg", ",", "(", "float", ",", ")", "+", "six", ".", "integer_types", ")", "for", "arg", "in", "args", "]", ":",...
[ 285, 4 ]
[ 319, 67 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.svg
(self, relative=False, precision=8, **kwargs)
Returns SVG representation of the geographic field in a `svg` attribute on each element of this GeoQuerySet. Keyword Arguments: `relative` => If set to True, this will evaluate the path in terms of relative moves (rather than absolute). `precision` =...
Returns SVG representation of the geographic field in a `svg` attribute on each element of this GeoQuerySet.
def svg(self, relative=False, precision=8, **kwargs): """ Returns SVG representation of the geographic field in a `svg` attribute on each element of this GeoQuerySet. Keyword Arguments: `relative` => If set to True, this will evaluate the path in terms ...
[ "def", "svg", "(", "self", ",", "relative", "=", "False", ",", "precision", "=", "8", ",", "*", "*", "kwargs", ")", ":", "relative", "=", "int", "(", "bool", "(", "relative", ")", ")", "if", "not", "isinstance", "(", "precision", ",", "six", ".", ...
[ 321, 4 ]
[ 344, 58 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.sym_difference
(self, geom, **kwargs)
Returns the symmetric difference of the geographic field in a `sym_difference` attribute on each element of this GeoQuerySet.
Returns the symmetric difference of the geographic field in a `sym_difference` attribute on each element of this GeoQuerySet.
def sym_difference(self, geom, **kwargs): """ Returns the symmetric difference of the geographic field in a `sym_difference` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('sym_difference', geom, **kwargs)
[ "def", "sym_difference", "(", "self", ",", "geom", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geomset_attribute", "(", "'sym_difference'", ",", "geom", ",", "*", "*", "kwargs", ")" ]
[ 346, 4 ]
[ 351, 72 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.translate
(self, x, y, z=0.0, **kwargs)
Translates the geometry to a new location using the given numeric parameters as offsets.
Translates the geometry to a new location using the given numeric parameters as offsets.
def translate(self, x, y, z=0.0, **kwargs): """ Translates the geometry to a new location using the given numeric parameters as offsets. """ if connections[self.db].ops.spatialite: if z != 0.0: raise NotImplementedError('SpatiaLite does not support 3D ...
[ "def", "translate", "(", "self", ",", "x", ",", "y", ",", "z", "=", "0.0", ",", "*", "*", "kwargs", ")", ":", "if", "connections", "[", "self", ".", "db", "]", ".", "ops", ".", "spatialite", ":", "if", "z", "!=", "0.0", ":", "raise", "NotImplem...
[ 353, 4 ]
[ 370, 64 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.transform
(self, srid=4326, **kwargs)
Transforms the given geometry field to the given SRID. If no SRID is provided, the transformation will default to using 4326 (WGS84).
Transforms the given geometry field to the given SRID. If no SRID is provided, the transformation will default to using 4326 (WGS84).
def transform(self, srid=4326, **kwargs): """ Transforms the given geometry field to the given SRID. If no SRID is provided, the transformation will default to using 4326 (WGS84). """ if not isinstance(srid, six.integer_types): raise TypeError('An integer SRID must b...
[ "def", "transform", "(", "self", ",", "srid", "=", "4326", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "srid", ",", "six", ".", "integer_types", ")", ":", "raise", "TypeError", "(", "'An integer SRID must be provided.'", ")", "field_...
[ 372, 4 ]
[ 398, 28 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.union
(self, geom, **kwargs)
Returns the union of the geographic field with the given Geometry in a `union` attribute on each element of this GeoQuerySet.
Returns the union of the geographic field with the given Geometry in a `union` attribute on each element of this GeoQuerySet.
def union(self, geom, **kwargs): """ Returns the union of the geographic field with the given Geometry in a `union` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('union', geom, **kwargs)
[ "def", "union", "(", "self", ",", "geom", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_geomset_attribute", "(", "'union'", ",", "geom", ",", "*", "*", "kwargs", ")" ]
[ 400, 4 ]
[ 405, 63 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet.unionagg
(self, **kwargs)
Performs an aggregate union on the given geometry field. Returns None if the GeoQuerySet is empty. The `tolerance` keyword is for Oracle backends only.
Performs an aggregate union on the given geometry field. Returns None if the GeoQuerySet is empty. The `tolerance` keyword is for Oracle backends only.
def unionagg(self, **kwargs): """ Performs an aggregate union on the given geometry field. Returns None if the GeoQuerySet is empty. The `tolerance` keyword is for Oracle backends only. """ return self._spatial_aggregate(aggregates.Union, **kwargs)
[ "def", "unionagg", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_spatial_aggregate", "(", "aggregates", ".", "Union", ",", "*", "*", "kwargs", ")" ]
[ 407, 4 ]
[ 413, 66 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet._spatial_setup
(self, att, desc=None, field_name=None, geo_field_type=None)
Performs set up for executing the spatial function.
Performs set up for executing the spatial function.
def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None): """ Performs set up for executing the spatial function. """ # Does the spatial backend support this? connection = connections[self.db] func = getattr(connection.ops, att, False) if des...
[ "def", "_spatial_setup", "(", "self", ",", "att", ",", "desc", "=", "None", ",", "field_name", "=", "None", ",", "geo_field_type", "=", "None", ")", ":", "# Does the spatial backend support this?", "connection", "=", "connections", "[", "self", ".", "db", "]",...
[ 416, 4 ]
[ 447, 40 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet._spatial_aggregate
(self, aggregate, field_name=None, geo_field_type=None, tolerance=0.05)
DRY routine for calling aggregate spatial stored procedures and returning their result to the caller of the function.
DRY routine for calling aggregate spatial stored procedures and returning their result to the caller of the function.
def _spatial_aggregate(self, aggregate, field_name=None, geo_field_type=None, tolerance=0.05): """ DRY routine for calling aggregate spatial stored procedures and returning their result to the caller of the function. """ # Getting the field the geograph...
[ "def", "_spatial_aggregate", "(", "self", ",", "aggregate", ",", "field_name", "=", "None", ",", "geo_field_type", "=", "None", ",", "tolerance", "=", "0.05", ")", ":", "# Getting the field the geographic aggregate will be called on.", "geo_field", "=", "self", ".", ...
[ 449, 4 ]
[ 476, 80 ]
python
en
['en', 'error', 'th']
False
GeoQuerySet._spatial_attribute
(self, att, settings, field_name=None, model_att=None)
DRY routine for calling a spatial stored procedure on a geometry column and attaching its output as an attribute of the model. Arguments: att: The name of the spatial attribute that holds the spatial SQL function to call. settings: Dictonary of ...
DRY routine for calling a spatial stored procedure on a geometry column and attaching its output as an attribute of the model.
def _spatial_attribute(self, att, settings, field_name=None, model_att=None): """ DRY routine for calling a spatial stored procedure on a geometry column and attaching its output as an attribute of the model. Arguments: att: The name of the spatial attribute that hold...
[ "def", "_spatial_attribute", "(", "self", ",", "att", ",", "settings", ",", "field_name", "=", "None", ",", "model_att", "=", "None", ")", ":", "# Default settings.", "settings", ".", "setdefault", "(", "'desc'", ",", "None", ")", "settings", ".", "setdefaul...
[ 478, 4 ]
[ 557, 66 ]
python
en
['en', 'error', 'th']
False