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
partition
stringclasses
1 value
szastupov/aiotg
aiotg/chat.py
Chat.send_contact
def send_contact(self, phone_number, first_name, **options): """ Send phone contacts. :param str phone_number: Contact's phone number :param str first_name: Contact's first name :param options: Additional sendContact options (see https://core.telegram.org/bots/api#sendcontact) """ return self.bot.api_call( "sendContact", chat_id=self.id, phone_number=phone_number, first_name=first_name, **options )
python
def send_contact(self, phone_number, first_name, **options): """ Send phone contacts. :param str phone_number: Contact's phone number :param str first_name: Contact's first name :param options: Additional sendContact options (see https://core.telegram.org/bots/api#sendcontact) """ return self.bot.api_call( "sendContact", chat_id=self.id, phone_number=phone_number, first_name=first_name, **options )
[ "def", "send_contact", "(", "self", ",", "phone_number", ",", "first_name", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendContact\"", ",", "chat_id", "=", "self", ".", "id", ",", "phone_number", "=", "phone_number", ",", "first_name", "=", "first_name", ",", "*", "*", "options", ")" ]
Send phone contacts. :param str phone_number: Contact's phone number :param str first_name: Contact's first name :param options: Additional sendContact options (see https://core.telegram.org/bots/api#sendcontact)
[ "Send", "phone", "contacts", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L243-L258
train
szastupov/aiotg
aiotg/chat.py
Chat.send_chat_action
def send_chat_action(self, action): """ Send a chat action, to tell the user that something is happening on the bot's side. Available actions: * `typing` for text messages * `upload_photo` for photos * `record_video` and `upload_video` for videos * `record_audio` and `upload_audio` for audio files * `upload_document` for general files * `find_location` for location data :param str action: Type of action to broadcast """ return self.bot.api_call("sendChatAction", chat_id=self.id, action=action)
python
def send_chat_action(self, action): """ Send a chat action, to tell the user that something is happening on the bot's side. Available actions: * `typing` for text messages * `upload_photo` for photos * `record_video` and `upload_video` for videos * `record_audio` and `upload_audio` for audio files * `upload_document` for general files * `find_location` for location data :param str action: Type of action to broadcast """ return self.bot.api_call("sendChatAction", chat_id=self.id, action=action)
[ "def", "send_chat_action", "(", "self", ",", "action", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendChatAction\"", ",", "chat_id", "=", "self", ".", "id", ",", "action", "=", "action", ")" ]
Send a chat action, to tell the user that something is happening on the bot's side. Available actions: * `typing` for text messages * `upload_photo` for photos * `record_video` and `upload_video` for videos * `record_audio` and `upload_audio` for audio files * `upload_document` for general files * `find_location` for location data :param str action: Type of action to broadcast
[ "Send", "a", "chat", "action", "to", "tell", "the", "user", "that", "something", "is", "happening", "on", "the", "bot", "s", "side", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L260-L276
train
szastupov/aiotg
aiotg/chat.py
Chat.send_media_group
def send_media_group( self, media: str, disable_notification: bool = False, reply_to_message_id: int = None, **options ): """ Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :param reply_to_message_id: If the messages are a reply, ID of the original message :param options: Additional sendMediaGroup options (see https://core.telegram.org/bots/api#sendmediagroup) :Example: >>> from json import dumps >>> photos_urls = [ >>> "https://telegram.org/img/t_logo.png", >>> "https://telegram.org/img/SiteAndroid.jpg?1", >>> "https://telegram.org/img/SiteiOs.jpg?1", >>> "https://telegram.org/img/SiteWP.jpg?2" >>> ] >>> tg_album = [] >>> count = len(photos_urls) >>> for i, p in enumerate(photos_urls): >>> { >>> 'type': 'photo', >>> 'media': p, >>> 'caption': f'{i} of {count}' >>> } >>> await chat.send_media_group(dumps(tg_album)) """ return self.bot.api_call( "sendMediaGroup", chat_id=str(self.id), media=media, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, **options )
python
def send_media_group( self, media: str, disable_notification: bool = False, reply_to_message_id: int = None, **options ): """ Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :param reply_to_message_id: If the messages are a reply, ID of the original message :param options: Additional sendMediaGroup options (see https://core.telegram.org/bots/api#sendmediagroup) :Example: >>> from json import dumps >>> photos_urls = [ >>> "https://telegram.org/img/t_logo.png", >>> "https://telegram.org/img/SiteAndroid.jpg?1", >>> "https://telegram.org/img/SiteiOs.jpg?1", >>> "https://telegram.org/img/SiteWP.jpg?2" >>> ] >>> tg_album = [] >>> count = len(photos_urls) >>> for i, p in enumerate(photos_urls): >>> { >>> 'type': 'photo', >>> 'media': p, >>> 'caption': f'{i} of {count}' >>> } >>> await chat.send_media_group(dumps(tg_album)) """ return self.bot.api_call( "sendMediaGroup", chat_id=str(self.id), media=media, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, **options )
[ "def", "send_media_group", "(", "self", ",", "media", ":", "str", ",", "disable_notification", ":", "bool", "=", "False", ",", "reply_to_message_id", ":", "int", "=", "None", ",", "*", "*", "options", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"sendMediaGroup\"", ",", "chat_id", "=", "str", "(", "self", ".", "id", ")", ",", "media", "=", "media", ",", "disable_notification", "=", "disable_notification", ",", "reply_to_message_id", "=", "reply_to_message_id", ",", "*", "*", "options", ")" ]
Send a group of photos or videos as an album :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items :param disable_notification: Sends the messages silently. Users will receive a notification with no sound. :param reply_to_message_id: If the messages are a reply, ID of the original message :param options: Additional sendMediaGroup options (see https://core.telegram.org/bots/api#sendmediagroup) :Example: >>> from json import dumps >>> photos_urls = [ >>> "https://telegram.org/img/t_logo.png", >>> "https://telegram.org/img/SiteAndroid.jpg?1", >>> "https://telegram.org/img/SiteiOs.jpg?1", >>> "https://telegram.org/img/SiteWP.jpg?2" >>> ] >>> tg_album = [] >>> count = len(photos_urls) >>> for i, p in enumerate(photos_urls): >>> { >>> 'type': 'photo', >>> 'media': p, >>> 'caption': f'{i} of {count}' >>> } >>> await chat.send_media_group(dumps(tg_album))
[ "Send", "a", "group", "of", "photos", "or", "videos", "as", "an", "album" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L278-L322
train
szastupov/aiotg
aiotg/chat.py
Chat.forward_message
def forward_message(self, from_chat_id, message_id): """ Forward a message from another chat to this chat. :param int from_chat_id: ID of the chat to forward the message from :param int message_id: ID of the message to forward """ return self.bot.api_call( "forwardMessage", chat_id=self.id, from_chat_id=from_chat_id, message_id=message_id, )
python
def forward_message(self, from_chat_id, message_id): """ Forward a message from another chat to this chat. :param int from_chat_id: ID of the chat to forward the message from :param int message_id: ID of the message to forward """ return self.bot.api_call( "forwardMessage", chat_id=self.id, from_chat_id=from_chat_id, message_id=message_id, )
[ "def", "forward_message", "(", "self", ",", "from_chat_id", ",", "message_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"forwardMessage\"", ",", "chat_id", "=", "self", ".", "id", ",", "from_chat_id", "=", "from_chat_id", ",", "message_id", "=", "message_id", ",", ")" ]
Forward a message from another chat to this chat. :param int from_chat_id: ID of the chat to forward the message from :param int message_id: ID of the message to forward
[ "Forward", "a", "message", "from", "another", "chat", "to", "this", "chat", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L324-L336
train
szastupov/aiotg
aiotg/chat.py
Chat.kick_chat_member
def kick_chat_member(self, user_id): """ Use this method to kick a user from a group or a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("kickChatMember", chat_id=self.id, user_id=user_id)
python
def kick_chat_member(self, user_id): """ Use this method to kick a user from a group or a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("kickChatMember", chat_id=self.id, user_id=user_id)
[ "def", "kick_chat_member", "(", "self", ",", "user_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"kickChatMember\"", ",", "chat_id", "=", "self", ".", "id", ",", "user_id", "=", "user_id", ")" ]
Use this method to kick a user from a group or a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user
[ "Use", "this", "method", "to", "kick", "a", "user", "from", "a", "group", "or", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "group", "for", "this", "to", "work", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L338-L345
train
szastupov/aiotg
aiotg/chat.py
Chat.unban_chat_member
def unban_chat_member(self, user_id): """ Use this method to unban a previously kicked user in a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("unbanChatMember", chat_id=self.id, user_id=user_id)
python
def unban_chat_member(self, user_id): """ Use this method to unban a previously kicked user in a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user """ return self.bot.api_call("unbanChatMember", chat_id=self.id, user_id=user_id)
[ "def", "unban_chat_member", "(", "self", ",", "user_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"unbanChatMember\"", ",", "chat_id", "=", "self", ".", "id", ",", "user_id", "=", "user_id", ")" ]
Use this method to unban a previously kicked user in a supergroup. The bot must be an administrator in the group for this to work. :param int user_id: Unique identifier of the target user
[ "Use", "this", "method", "to", "unban", "a", "previously", "kicked", "user", "in", "a", "supergroup", ".", "The", "bot", "must", "be", "an", "administrator", "in", "the", "group", "for", "this", "to", "work", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L347-L354
train
szastupov/aiotg
aiotg/chat.py
Chat.delete_message
def delete_message(self, message_id): """ Delete message from this chat :param int message_id: ID of the message """ return self.bot.api_call( "deleteMessage", chat_id=self.id, message_id=message_id )
python
def delete_message(self, message_id): """ Delete message from this chat :param int message_id: ID of the message """ return self.bot.api_call( "deleteMessage", chat_id=self.id, message_id=message_id )
[ "def", "delete_message", "(", "self", ",", "message_id", ")", ":", "return", "self", ".", "bot", ".", "api_call", "(", "\"deleteMessage\"", ",", "chat_id", "=", "self", ".", "id", ",", "message_id", "=", "message_id", ")" ]
Delete message from this chat :param int message_id: ID of the message
[ "Delete", "message", "from", "this", "chat" ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L356-L364
train
szastupov/aiotg
aiotg/chat.py
Chat.from_message
def from_message(bot, message): """ Create a ``Chat`` object from a message. :param Bot bot: ``Bot`` object the message and chat belong to :param dict message: Message to base the object on :return: A chat object based on the message """ chat = message["chat"] return Chat(bot, chat["id"], chat["type"], message)
python
def from_message(bot, message): """ Create a ``Chat`` object from a message. :param Bot bot: ``Bot`` object the message and chat belong to :param dict message: Message to base the object on :return: A chat object based on the message """ chat = message["chat"] return Chat(bot, chat["id"], chat["type"], message)
[ "def", "from_message", "(", "bot", ",", "message", ")", ":", "chat", "=", "message", "[", "\"chat\"", "]", "return", "Chat", "(", "bot", ",", "chat", "[", "\"id\"", "]", ",", "chat", "[", "\"type\"", "]", ",", "message", ")" ]
Create a ``Chat`` object from a message. :param Bot bot: ``Bot`` object the message and chat belong to :param dict message: Message to base the object on :return: A chat object based on the message
[ "Create", "a", "Chat", "object", "from", "a", "message", "." ]
eed81a6a728c02120f1d730a6e8b8fe50263c010
https://github.com/szastupov/aiotg/blob/eed81a6a728c02120f1d730a6e8b8fe50263c010/aiotg/chat.py#L386-L395
train
mnubo/kubernetes-py
kubernetes_py/K8sCronJob.py
K8sCronJob.run
def run(self, timeout=POD_RUN_WAIT_TIMEOUT_SECONDS): """ Forces a K8sCronJob to run immediately. - Fail if the K8sCronJob is currently running on-schedule. - Suspend the K8sCronJob. - Spawn a K8sPod. - Unsuspend a K8sCronJob. :param timeout: The timeout, in seconds, after which to kill the K8sPod. :return: None. """ if not isinstance(timeout, int): raise SyntaxError("K8sCronJob.run() timeout: [ {} ] is invalid.") if len(self.active): raise CronJobAlreadyRunningException( "K8sCronJob.run() failed: CronJob: [ {} ] " "has [ {} ] active Jobs currently.".format(self.name, len(self.active))) self.suspend = True self.update() pod = self.pod if timeout: self.POD_RUN_WAIT_TIMEOUT_SECONDS = timeout try: pod.create() start_time = time.time() while pod.phase not in ['Succeeded', 'Failed']: pod.get() time.sleep(2) self._check_timeout(start_time) except Exception as err: raise CronJobRunException("K8sCronJob.run() failed: {}".format(err)) finally: pod.delete() self.suspend = False self.update()
python
def run(self, timeout=POD_RUN_WAIT_TIMEOUT_SECONDS): """ Forces a K8sCronJob to run immediately. - Fail if the K8sCronJob is currently running on-schedule. - Suspend the K8sCronJob. - Spawn a K8sPod. - Unsuspend a K8sCronJob. :param timeout: The timeout, in seconds, after which to kill the K8sPod. :return: None. """ if not isinstance(timeout, int): raise SyntaxError("K8sCronJob.run() timeout: [ {} ] is invalid.") if len(self.active): raise CronJobAlreadyRunningException( "K8sCronJob.run() failed: CronJob: [ {} ] " "has [ {} ] active Jobs currently.".format(self.name, len(self.active))) self.suspend = True self.update() pod = self.pod if timeout: self.POD_RUN_WAIT_TIMEOUT_SECONDS = timeout try: pod.create() start_time = time.time() while pod.phase not in ['Succeeded', 'Failed']: pod.get() time.sleep(2) self._check_timeout(start_time) except Exception as err: raise CronJobRunException("K8sCronJob.run() failed: {}".format(err)) finally: pod.delete() self.suspend = False self.update()
[ "def", "run", "(", "self", ",", "timeout", "=", "POD_RUN_WAIT_TIMEOUT_SECONDS", ")", ":", "if", "not", "isinstance", "(", "timeout", ",", "int", ")", ":", "raise", "SyntaxError", "(", "\"K8sCronJob.run() timeout: [ {} ] is invalid.\"", ")", "if", "len", "(", "self", ".", "active", ")", ":", "raise", "CronJobAlreadyRunningException", "(", "\"K8sCronJob.run() failed: CronJob: [ {} ] \"", "\"has [ {} ] active Jobs currently.\"", ".", "format", "(", "self", ".", "name", ",", "len", "(", "self", ".", "active", ")", ")", ")", "self", ".", "suspend", "=", "True", "self", ".", "update", "(", ")", "pod", "=", "self", ".", "pod", "if", "timeout", ":", "self", ".", "POD_RUN_WAIT_TIMEOUT_SECONDS", "=", "timeout", "try", ":", "pod", ".", "create", "(", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "pod", ".", "phase", "not", "in", "[", "'Succeeded'", ",", "'Failed'", "]", ":", "pod", ".", "get", "(", ")", "time", ".", "sleep", "(", "2", ")", "self", ".", "_check_timeout", "(", "start_time", ")", "except", "Exception", "as", "err", ":", "raise", "CronJobRunException", "(", "\"K8sCronJob.run() failed: {}\"", ".", "format", "(", "err", ")", ")", "finally", ":", "pod", ".", "delete", "(", ")", "self", ".", "suspend", "=", "False", "self", ".", "update", "(", ")" ]
Forces a K8sCronJob to run immediately. - Fail if the K8sCronJob is currently running on-schedule. - Suspend the K8sCronJob. - Spawn a K8sPod. - Unsuspend a K8sCronJob. :param timeout: The timeout, in seconds, after which to kill the K8sPod. :return: None.
[ "Forces", "a", "K8sCronJob", "to", "run", "immediately", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sCronJob.py#L319-L362
train
mnubo/kubernetes-py
kubernetes_py/K8sReplicationController.py
K8sReplicationController.scale
def scale(config=None, name=None, replicas=None): """ Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas: the desired number of replicas. :return: An instance of K8sReplicationController """ rc = K8sReplicationController(config=config, name=name).get() rc.desired_replicas = replicas rc.update() rc._wait_for_desired_replicas() return rc
python
def scale(config=None, name=None, replicas=None): """ Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas: the desired number of replicas. :return: An instance of K8sReplicationController """ rc = K8sReplicationController(config=config, name=name).get() rc.desired_replicas = replicas rc.update() rc._wait_for_desired_replicas() return rc
[ "def", "scale", "(", "config", "=", "None", ",", "name", "=", "None", ",", "replicas", "=", "None", ")", ":", "rc", "=", "K8sReplicationController", "(", "config", "=", "config", ",", "name", "=", "name", ")", ".", "get", "(", ")", "rc", ".", "desired_replicas", "=", "replicas", "rc", ".", "update", "(", ")", "rc", ".", "_wait_for_desired_replicas", "(", ")", "return", "rc" ]
Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas: the desired number of replicas. :return: An instance of K8sReplicationController
[ "Scales", "the", "number", "of", "pods", "in", "the", "specified", "K8sReplicationController", "to", "the", "desired", "replica", "count", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sReplicationController.py#L517-L534
train
mnubo/kubernetes-py
kubernetes_py/K8sReplicationController.py
K8sReplicationController.rolling_update
def rolling_update(config=None, name=None, image=None, container_name=None, rc_new=None): """ Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the same RC name between updates, which is not supported by default by kubectl. :param config: An instance of K8sConfig. If omitted, reads from ~/.kube/config. :param name: The name of the ReplicationController we want to update. :param image: The updated image version we want applied. :param container_name: The name of the container we're targeting for the update. Required if more than one container is present. :param rc_new: An instance of K8sReplicationController with the new configuration to apply. Mutually exclusive with [image, container_name] if specified. :return: """ if name is None: raise SyntaxError( 'K8sReplicationController: name: [ {0} ] cannot be None.'.format(name)) if image is None and rc_new is None: raise SyntaxError( "K8sReplicationController: please specify either 'image' or 'rc_new'") if container_name is not None and image is not None and rc_new is not None: raise SyntaxError( 'K8sReplicationController: rc_new is mutually exclusive with an (container_name, image) pair.') return K8sReplicationController._rolling_update_init( config=config, name=name, image=image, container_name=container_name, rc_new=rc_new)
python
def rolling_update(config=None, name=None, image=None, container_name=None, rc_new=None): """ Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the same RC name between updates, which is not supported by default by kubectl. :param config: An instance of K8sConfig. If omitted, reads from ~/.kube/config. :param name: The name of the ReplicationController we want to update. :param image: The updated image version we want applied. :param container_name: The name of the container we're targeting for the update. Required if more than one container is present. :param rc_new: An instance of K8sReplicationController with the new configuration to apply. Mutually exclusive with [image, container_name] if specified. :return: """ if name is None: raise SyntaxError( 'K8sReplicationController: name: [ {0} ] cannot be None.'.format(name)) if image is None and rc_new is None: raise SyntaxError( "K8sReplicationController: please specify either 'image' or 'rc_new'") if container_name is not None and image is not None and rc_new is not None: raise SyntaxError( 'K8sReplicationController: rc_new is mutually exclusive with an (container_name, image) pair.') return K8sReplicationController._rolling_update_init( config=config, name=name, image=image, container_name=container_name, rc_new=rc_new)
[ "def", "rolling_update", "(", "config", "=", "None", ",", "name", "=", "None", ",", "image", "=", "None", ",", "container_name", "=", "None", ",", "rc_new", "=", "None", ")", ":", "if", "name", "is", "None", ":", "raise", "SyntaxError", "(", "'K8sReplicationController: name: [ {0} ] cannot be None.'", ".", "format", "(", "name", ")", ")", "if", "image", "is", "None", "and", "rc_new", "is", "None", ":", "raise", "SyntaxError", "(", "\"K8sReplicationController: please specify either 'image' or 'rc_new'\"", ")", "if", "container_name", "is", "not", "None", "and", "image", "is", "not", "None", "and", "rc_new", "is", "not", "None", ":", "raise", "SyntaxError", "(", "'K8sReplicationController: rc_new is mutually exclusive with an (container_name, image) pair.'", ")", "return", "K8sReplicationController", ".", "_rolling_update_init", "(", "config", "=", "config", ",", "name", "=", "name", ",", "image", "=", "image", ",", "container_name", "=", "container_name", ",", "rc_new", "=", "rc_new", ")" ]
Performs a simple rolling update of a ReplicationController. See https://github.com/kubernetes/kubernetes/blob/master/docs/design/simple-rolling-update.md for algorithm details. We have modified it slightly to allow for keeping the same RC name between updates, which is not supported by default by kubectl. :param config: An instance of K8sConfig. If omitted, reads from ~/.kube/config. :param name: The name of the ReplicationController we want to update. :param image: The updated image version we want applied. :param container_name: The name of the container we're targeting for the update. Required if more than one container is present. :param rc_new: An instance of K8sReplicationController with the new configuration to apply. Mutually exclusive with [image, container_name] if specified. :return:
[ "Performs", "a", "simple", "rolling", "update", "of", "a", "ReplicationController", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sReplicationController.py#L539-L577
train
mnubo/kubernetes-py
kubernetes_py/K8sReplicationController.py
K8sReplicationController.restart
def restart(self): """ Restart will force a rolling update of the current ReplicationController to the current revision. This essentially spawns a fresh copy of the RC and its pods. Useful when something is misbehaving. """ rc_new = copy.deepcopy(self) return K8sReplicationController.rolling_update( config=self.config, name=self.name, rc_new=rc_new)
python
def restart(self): """ Restart will force a rolling update of the current ReplicationController to the current revision. This essentially spawns a fresh copy of the RC and its pods. Useful when something is misbehaving. """ rc_new = copy.deepcopy(self) return K8sReplicationController.rolling_update( config=self.config, name=self.name, rc_new=rc_new)
[ "def", "restart", "(", "self", ")", ":", "rc_new", "=", "copy", ".", "deepcopy", "(", "self", ")", "return", "K8sReplicationController", ".", "rolling_update", "(", "config", "=", "self", ".", "config", ",", "name", "=", "self", ".", "name", ",", "rc_new", "=", "rc_new", ")" ]
Restart will force a rolling update of the current ReplicationController to the current revision. This essentially spawns a fresh copy of the RC and its pods. Useful when something is misbehaving.
[ "Restart", "will", "force", "a", "rolling", "update", "of", "the", "current", "ReplicationController", "to", "the", "current", "revision", ".", "This", "essentially", "spawns", "a", "fresh", "copy", "of", "the", "RC", "and", "its", "pods", ".", "Useful", "when", "something", "is", "misbehaving", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sReplicationController.py#L711-L721
train
mnubo/kubernetes-py
kubernetes_py/K8sNode.py
K8sNode._has_local_storage
def _has_local_storage(self, pod=None): """ Determines if a K8sPod has any local storage susceptible to be lost. :param pod: The K8sPod we're interested in. :return: a boolean. """ for vol in pod.volumes: if vol.emptyDir is not None: return True return False
python
def _has_local_storage(self, pod=None): """ Determines if a K8sPod has any local storage susceptible to be lost. :param pod: The K8sPod we're interested in. :return: a boolean. """ for vol in pod.volumes: if vol.emptyDir is not None: return True return False
[ "def", "_has_local_storage", "(", "self", ",", "pod", "=", "None", ")", ":", "for", "vol", "in", "pod", ".", "volumes", ":", "if", "vol", ".", "emptyDir", "is", "not", "None", ":", "return", "True", "return", "False" ]
Determines if a K8sPod has any local storage susceptible to be lost. :param pod: The K8sPod we're interested in. :return: a boolean.
[ "Determines", "if", "a", "K8sPod", "has", "any", "local", "storage", "susceptible", "to", "be", "lost", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sNode.py#L268-L280
train
mnubo/kubernetes-py
kubernetes_py/K8sDeployment.py
K8sDeployment.rollback
def rollback(self, revision=None, annotations=None): """ Performs a rollback of the Deployment. If the 'revision' parameter is omitted, we fetch the Deployment's system-generated annotation containing the current revision, and revert to the version immediately preceding the current version. :param revision: The revision to rollback to. :param annotations: Annotations we'd like to update. :return: self """ rollback = DeploymentRollback() rollback.name = self.name rollback_config = RollbackConfig() # to the specified revision if revision is not None: rollback_config.revision = revision # to the revision immediately preceding the current revision else: current_revision = int(self.get_annotation(self.REVISION_ANNOTATION)) rev = max(current_revision - 1, 0) rollback_config.revision = rev rollback.rollback_to = rollback_config if annotations is not None: rollback.updated_annotations = annotations url = '{base}/{name}/rollback'.format(base=self.base_url, name=self.name) state = self.request( method='POST', url=url, data=rollback.serialize()) if not state.get('success'): status = state.get('status', '') reason = state.get('data', dict()).get('message', None) message = 'K8sDeployment: ROLLBACK failed : HTTP {0} : {1}'.format(status, reason) raise BadRequestException(message) time.sleep(0.2) self._wait_for_desired_replicas() self.get() return self
python
def rollback(self, revision=None, annotations=None): """ Performs a rollback of the Deployment. If the 'revision' parameter is omitted, we fetch the Deployment's system-generated annotation containing the current revision, and revert to the version immediately preceding the current version. :param revision: The revision to rollback to. :param annotations: Annotations we'd like to update. :return: self """ rollback = DeploymentRollback() rollback.name = self.name rollback_config = RollbackConfig() # to the specified revision if revision is not None: rollback_config.revision = revision # to the revision immediately preceding the current revision else: current_revision = int(self.get_annotation(self.REVISION_ANNOTATION)) rev = max(current_revision - 1, 0) rollback_config.revision = rev rollback.rollback_to = rollback_config if annotations is not None: rollback.updated_annotations = annotations url = '{base}/{name}/rollback'.format(base=self.base_url, name=self.name) state = self.request( method='POST', url=url, data=rollback.serialize()) if not state.get('success'): status = state.get('status', '') reason = state.get('data', dict()).get('message', None) message = 'K8sDeployment: ROLLBACK failed : HTTP {0} : {1}'.format(status, reason) raise BadRequestException(message) time.sleep(0.2) self._wait_for_desired_replicas() self.get() return self
[ "def", "rollback", "(", "self", ",", "revision", "=", "None", ",", "annotations", "=", "None", ")", ":", "rollback", "=", "DeploymentRollback", "(", ")", "rollback", ".", "name", "=", "self", ".", "name", "rollback_config", "=", "RollbackConfig", "(", ")", "# to the specified revision", "if", "revision", "is", "not", "None", ":", "rollback_config", ".", "revision", "=", "revision", "# to the revision immediately preceding the current revision", "else", ":", "current_revision", "=", "int", "(", "self", ".", "get_annotation", "(", "self", ".", "REVISION_ANNOTATION", ")", ")", "rev", "=", "max", "(", "current_revision", "-", "1", ",", "0", ")", "rollback_config", ".", "revision", "=", "rev", "rollback", ".", "rollback_to", "=", "rollback_config", "if", "annotations", "is", "not", "None", ":", "rollback", ".", "updated_annotations", "=", "annotations", "url", "=", "'{base}/{name}/rollback'", ".", "format", "(", "base", "=", "self", ".", "base_url", ",", "name", "=", "self", ".", "name", ")", "state", "=", "self", ".", "request", "(", "method", "=", "'POST'", ",", "url", "=", "url", ",", "data", "=", "rollback", ".", "serialize", "(", ")", ")", "if", "not", "state", ".", "get", "(", "'success'", ")", ":", "status", "=", "state", ".", "get", "(", "'status'", ",", "''", ")", "reason", "=", "state", ".", "get", "(", "'data'", ",", "dict", "(", ")", ")", ".", "get", "(", "'message'", ",", "None", ")", "message", "=", "'K8sDeployment: ROLLBACK failed : HTTP {0} : {1}'", ".", "format", "(", "status", ",", "reason", ")", "raise", "BadRequestException", "(", "message", ")", "time", ".", "sleep", "(", "0.2", ")", "self", ".", "_wait_for_desired_replicas", "(", ")", "self", ".", "get", "(", ")", "return", "self" ]
Performs a rollback of the Deployment. If the 'revision' parameter is omitted, we fetch the Deployment's system-generated annotation containing the current revision, and revert to the version immediately preceding the current version. :param revision: The revision to rollback to. :param annotations: Annotations we'd like to update. :return: self
[ "Performs", "a", "rollback", "of", "the", "Deployment", "." ]
e417946837f7cb06b6ea9f7c20d8c19853fbd1bf
https://github.com/mnubo/kubernetes-py/blob/e417946837f7cb06b6ea9f7c20d8c19853fbd1bf/kubernetes_py/K8sDeployment.py#L363-L411
train
area4lib/area4
extras/sum_roll_dice.py
roll_dice
def roll_dice(): """ Roll a die. :return: None """ sums = 0 # will return the sum of the roll calls. while True: roll = random.randint(1, 6) sums += roll if(input("Enter y or n to continue: ").upper()) == 'N': print(sums) # prints the sum of the roll calls break
python
def roll_dice(): """ Roll a die. :return: None """ sums = 0 # will return the sum of the roll calls. while True: roll = random.randint(1, 6) sums += roll if(input("Enter y or n to continue: ").upper()) == 'N': print(sums) # prints the sum of the roll calls break
[ "def", "roll_dice", "(", ")", ":", "sums", "=", "0", "# will return the sum of the roll calls.", "while", "True", ":", "roll", "=", "random", ".", "randint", "(", "1", ",", "6", ")", "sums", "+=", "roll", "if", "(", "input", "(", "\"Enter y or n to continue: \"", ")", ".", "upper", "(", ")", ")", "==", "'N'", ":", "print", "(", "sums", ")", "# prints the sum of the roll calls", "break" ]
Roll a die. :return: None
[ "Roll", "a", "die", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/extras/sum_roll_dice.py#L6-L18
train
area4lib/area4
area4/util.py
get_raw_file
def get_raw_file(): """ Get the raw divider file in a string array. :return: the array :rtype: str """ with open("{0}/dividers.txt".format( os.path.abspath( os.path.dirname(__file__) ) ), mode="r") as file_handler: lines = file_handler.readlines() lines[35] = str( random.randint(0, 999999999999) ) return lines
python
def get_raw_file(): """ Get the raw divider file in a string array. :return: the array :rtype: str """ with open("{0}/dividers.txt".format( os.path.abspath( os.path.dirname(__file__) ) ), mode="r") as file_handler: lines = file_handler.readlines() lines[35] = str( random.randint(0, 999999999999) ) return lines
[ "def", "get_raw_file", "(", ")", ":", "with", "open", "(", "\"{0}/dividers.txt\"", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ")", ",", "mode", "=", "\"r\"", ")", "as", "file_handler", ":", "lines", "=", "file_handler", ".", "readlines", "(", ")", "lines", "[", "35", "]", "=", "str", "(", "random", ".", "randint", "(", "0", ",", "999999999999", ")", ")", "return", "lines" ]
Get the raw divider file in a string array. :return: the array :rtype: str
[ "Get", "the", "raw", "divider", "file", "in", "a", "string", "array", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/util.py#L13-L29
train
area4lib/area4
area4/util.py
reduce_to_unit
def reduce_to_unit(divider): """ Reduce a repeating divider to the smallest repeating unit possible. Note: this function is used by make-div :param divider: the divider :return: smallest repeating unit possible :rtype: str :Example: 'XxXxXxX' -> 'Xx' """ for unit_size in range(1, len(divider) // 2 + 1): length = len(divider) unit = divider[:unit_size] # Ignores mismatches in final characters: divider_item = divider[:unit_size * (length // unit_size)] if unit * (length // unit_size) == divider_item: return unit return divider
python
def reduce_to_unit(divider): """ Reduce a repeating divider to the smallest repeating unit possible. Note: this function is used by make-div :param divider: the divider :return: smallest repeating unit possible :rtype: str :Example: 'XxXxXxX' -> 'Xx' """ for unit_size in range(1, len(divider) // 2 + 1): length = len(divider) unit = divider[:unit_size] # Ignores mismatches in final characters: divider_item = divider[:unit_size * (length // unit_size)] if unit * (length // unit_size) == divider_item: return unit return divider
[ "def", "reduce_to_unit", "(", "divider", ")", ":", "for", "unit_size", "in", "range", "(", "1", ",", "len", "(", "divider", ")", "//", "2", "+", "1", ")", ":", "length", "=", "len", "(", "divider", ")", "unit", "=", "divider", "[", ":", "unit_size", "]", "# Ignores mismatches in final characters:", "divider_item", "=", "divider", "[", ":", "unit_size", "*", "(", "length", "//", "unit_size", ")", "]", "if", "unit", "*", "(", "length", "//", "unit_size", ")", "==", "divider_item", ":", "return", "unit", "return", "divider" ]
Reduce a repeating divider to the smallest repeating unit possible. Note: this function is used by make-div :param divider: the divider :return: smallest repeating unit possible :rtype: str :Example: 'XxXxXxX' -> 'Xx'
[ "Reduce", "a", "repeating", "divider", "to", "the", "smallest", "repeating", "unit", "possible", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/util.py#L42-L62
train
area4lib/area4
area4/__init__.py
splitter
def splitter(div, *args): """ Split text with dividers easily. :return: newly made value :rtype: str :param div: the divider """ retstr = "" if type(div) is int: div = theArray()[div] if len(args) == 1: return args[0] for s in args: retstr += s retstr += "\n" retstr += div retstr += "\n" return retstr
python
def splitter(div, *args): """ Split text with dividers easily. :return: newly made value :rtype: str :param div: the divider """ retstr = "" if type(div) is int: div = theArray()[div] if len(args) == 1: return args[0] for s in args: retstr += s retstr += "\n" retstr += div retstr += "\n" return retstr
[ "def", "splitter", "(", "div", ",", "*", "args", ")", ":", "retstr", "=", "\"\"", "if", "type", "(", "div", ")", "is", "int", ":", "div", "=", "theArray", "(", ")", "[", "div", "]", "if", "len", "(", "args", ")", "==", "1", ":", "return", "args", "[", "0", "]", "for", "s", "in", "args", ":", "retstr", "+=", "s", "retstr", "+=", "\"\\n\"", "retstr", "+=", "div", "retstr", "+=", "\"\\n\"", "return", "retstr" ]
Split text with dividers easily. :return: newly made value :rtype: str :param div: the divider
[ "Split", "text", "with", "dividers", "easily", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/__init__.py#L54-L72
train
area4lib/area4
area4/__init__.py
area4info
def area4info(): """ Get some info about the package. :return: Package info :rtype: str """ # Info variables: name = "area4" author = "https://github.com/RDIL" author_email = rdillib.get_email() description = "Dividers in Python, the easy way!" return "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}".format( "Name:", name, "Author:", author, "Author Email:", author_email, "Description:", description )
python
def area4info(): """ Get some info about the package. :return: Package info :rtype: str """ # Info variables: name = "area4" author = "https://github.com/RDIL" author_email = rdillib.get_email() description = "Dividers in Python, the easy way!" return "{0}: {1}\n{2}: {3}\n{4}: {5}\n{6}: {7}".format( "Name:", name, "Author:", author, "Author Email:", author_email, "Description:", description )
[ "def", "area4info", "(", ")", ":", "# Info variables:", "name", "=", "\"area4\"", "author", "=", "\"https://github.com/RDIL\"", "author_email", "=", "rdillib", ".", "get_email", "(", ")", "description", "=", "\"Dividers in Python, the easy way!\"", "return", "\"{0}: {1}\\n{2}: {3}\\n{4}: {5}\\n{6}: {7}\"", ".", "format", "(", "\"Name:\"", ",", "name", ",", "\"Author:\"", ",", "author", ",", "\"Author Email:\"", ",", "author_email", ",", "\"Description:\"", ",", "description", ")" ]
Get some info about the package. :return: Package info :rtype: str
[ "Get", "some", "info", "about", "the", "package", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/__init__.py#L75-L92
train
area4lib/area4
area4/__init__.py
make_div
def make_div(unit, length=24, start='', end='', literal_unit=False): """ Generate and return a custom divider. :param unit: str containing a repeating unit :param length: The maximum length (won't be exceeded) (default: 24) :param start: optional starting string :param end: optional ending string :param literal_unit: if True will not try to break unit down into smaller repeating subunits :return: a custom created divider :rtype: str :Example: custom_div = make_div(unit='=-', length=40, start='<', end='=>') note:: The generated string will be terminated at the specified length regardless of whether all the input strings have been fully replicated. A unit > 1 length may not be able to be replicated to extend to the full length. In this situation, the string will be shorter than the specified length. Example: unit of 10 characters and a specified length of 25 will contain 2 units for a total length of 20 characters. """ # Reduce the size if possible to extend closer to full length: if not literal_unit: unit = utils.reduce_to_unit(unit) repeats = (length - len(start + end)) // len(unit) return (start + unit * repeats + end)[0:length]
python
def make_div(unit, length=24, start='', end='', literal_unit=False): """ Generate and return a custom divider. :param unit: str containing a repeating unit :param length: The maximum length (won't be exceeded) (default: 24) :param start: optional starting string :param end: optional ending string :param literal_unit: if True will not try to break unit down into smaller repeating subunits :return: a custom created divider :rtype: str :Example: custom_div = make_div(unit='=-', length=40, start='<', end='=>') note:: The generated string will be terminated at the specified length regardless of whether all the input strings have been fully replicated. A unit > 1 length may not be able to be replicated to extend to the full length. In this situation, the string will be shorter than the specified length. Example: unit of 10 characters and a specified length of 25 will contain 2 units for a total length of 20 characters. """ # Reduce the size if possible to extend closer to full length: if not literal_unit: unit = utils.reduce_to_unit(unit) repeats = (length - len(start + end)) // len(unit) return (start + unit * repeats + end)[0:length]
[ "def", "make_div", "(", "unit", ",", "length", "=", "24", ",", "start", "=", "''", ",", "end", "=", "''", ",", "literal_unit", "=", "False", ")", ":", "# Reduce the size if possible to extend closer to full length:", "if", "not", "literal_unit", ":", "unit", "=", "utils", ".", "reduce_to_unit", "(", "unit", ")", "repeats", "=", "(", "length", "-", "len", "(", "start", "+", "end", ")", ")", "//", "len", "(", "unit", ")", "return", "(", "start", "+", "unit", "*", "repeats", "+", "end", ")", "[", "0", ":", "length", "]" ]
Generate and return a custom divider. :param unit: str containing a repeating unit :param length: The maximum length (won't be exceeded) (default: 24) :param start: optional starting string :param end: optional ending string :param literal_unit: if True will not try to break unit down into smaller repeating subunits :return: a custom created divider :rtype: str :Example: custom_div = make_div(unit='=-', length=40, start='<', end='=>') note:: The generated string will be terminated at the specified length regardless of whether all the input strings have been fully replicated. A unit > 1 length may not be able to be replicated to extend to the full length. In this situation, the string will be shorter than the specified length. Example: unit of 10 characters and a specified length of 25 will contain 2 units for a total length of 20 characters.
[ "Generate", "and", "return", "a", "custom", "divider", "." ]
7f71b58d6b44b1a61284a8a01f26afd3138b9b17
https://github.com/area4lib/area4/blob/7f71b58d6b44b1a61284a8a01f26afd3138b9b17/area4/__init__.py#L95-L127
train
capnproto/pycapnp
buildutils/bundle.py
localpath
def localpath(*args): """construct an absolute path from a list relative to the root pycapnp directory""" plist = [ROOT] + list(args) return os.path.abspath(pjoin(*plist))
python
def localpath(*args): """construct an absolute path from a list relative to the root pycapnp directory""" plist = [ROOT] + list(args) return os.path.abspath(pjoin(*plist))
[ "def", "localpath", "(", "*", "args", ")", ":", "plist", "=", "[", "ROOT", "]", "+", "list", "(", "args", ")", "return", "os", ".", "path", ".", "abspath", "(", "pjoin", "(", "*", "plist", ")", ")" ]
construct an absolute path from a list relative to the root pycapnp directory
[ "construct", "an", "absolute", "path", "from", "a", "list", "relative", "to", "the", "root", "pycapnp", "directory" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/bundle.py#L53-L56
train
capnproto/pycapnp
buildutils/bundle.py
fetch_libcapnp
def fetch_libcapnp(savedir, url=None): """download and extract libcapnp""" is_preconfigured = False if url is None: url = libcapnp_url is_preconfigured = True dest = pjoin(savedir, 'capnproto-c++') if os.path.exists(dest): info("already have %s" % dest) return fname = fetch_archive(savedir, url, libcapnp) tf = tarfile.open(fname) with_version = pjoin(savedir, tf.firstmember.path) tf.extractall(savedir) tf.close() # remove version suffix: if is_preconfigured: shutil.move(with_version, dest) else: cpp_dir = os.path.join(with_version, 'c++') conf = Popen(['autoreconf', '-i'], cwd=cpp_dir) returncode = conf.wait() if returncode != 0: raise RuntimeError('Autoreconf failed. Make sure autotools are installed on your system.') shutil.move(cpp_dir, dest)
python
def fetch_libcapnp(savedir, url=None): """download and extract libcapnp""" is_preconfigured = False if url is None: url = libcapnp_url is_preconfigured = True dest = pjoin(savedir, 'capnproto-c++') if os.path.exists(dest): info("already have %s" % dest) return fname = fetch_archive(savedir, url, libcapnp) tf = tarfile.open(fname) with_version = pjoin(savedir, tf.firstmember.path) tf.extractall(savedir) tf.close() # remove version suffix: if is_preconfigured: shutil.move(with_version, dest) else: cpp_dir = os.path.join(with_version, 'c++') conf = Popen(['autoreconf', '-i'], cwd=cpp_dir) returncode = conf.wait() if returncode != 0: raise RuntimeError('Autoreconf failed. Make sure autotools are installed on your system.') shutil.move(cpp_dir, dest)
[ "def", "fetch_libcapnp", "(", "savedir", ",", "url", "=", "None", ")", ":", "is_preconfigured", "=", "False", "if", "url", "is", "None", ":", "url", "=", "libcapnp_url", "is_preconfigured", "=", "True", "dest", "=", "pjoin", "(", "savedir", ",", "'capnproto-c++'", ")", "if", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "info", "(", "\"already have %s\"", "%", "dest", ")", "return", "fname", "=", "fetch_archive", "(", "savedir", ",", "url", ",", "libcapnp", ")", "tf", "=", "tarfile", ".", "open", "(", "fname", ")", "with_version", "=", "pjoin", "(", "savedir", ",", "tf", ".", "firstmember", ".", "path", ")", "tf", ".", "extractall", "(", "savedir", ")", "tf", ".", "close", "(", ")", "# remove version suffix:", "if", "is_preconfigured", ":", "shutil", ".", "move", "(", "with_version", ",", "dest", ")", "else", ":", "cpp_dir", "=", "os", ".", "path", ".", "join", "(", "with_version", ",", "'c++'", ")", "conf", "=", "Popen", "(", "[", "'autoreconf'", ",", "'-i'", "]", ",", "cwd", "=", "cpp_dir", ")", "returncode", "=", "conf", ".", "wait", "(", ")", "if", "returncode", "!=", "0", ":", "raise", "RuntimeError", "(", "'Autoreconf failed. Make sure autotools are installed on your system.'", ")", "shutil", ".", "move", "(", "cpp_dir", ",", "dest", ")" ]
download and extract libcapnp
[ "download", "and", "extract", "libcapnp" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/bundle.py#L76-L100
train
capnproto/pycapnp
buildutils/bundle.py
stage_platform_hpp
def stage_platform_hpp(capnproot): """stage platform.hpp into libcapnp sources Tries ./configure first (except on Windows), then falls back on included platform.hpp previously generated. """ platform_hpp = pjoin(capnproot, 'src', 'platform.hpp') if os.path.exists(platform_hpp): info("already have platform.hpp") return if os.name == 'nt': # stage msvc platform header platform_dir = pjoin(capnproot, 'builds', 'msvc') else: info("attempting ./configure to generate platform.hpp") p = Popen('./configure', cwd=capnproot, shell=True, stdout=PIPE, stderr=PIPE, ) o,e = p.communicate() if p.returncode: warn("failed to configure libcapnp:\n%s" % e) if sys.platform == 'darwin': platform_dir = pjoin(HERE, 'include_darwin') elif sys.platform.startswith('freebsd'): platform_dir = pjoin(HERE, 'include_freebsd') elif sys.platform.startswith('linux-armv'): platform_dir = pjoin(HERE, 'include_linux-armv') else: platform_dir = pjoin(HERE, 'include_linux') else: return info("staging platform.hpp from: %s" % platform_dir) shutil.copy(pjoin(platform_dir, 'platform.hpp'), platform_hpp)
python
def stage_platform_hpp(capnproot): """stage platform.hpp into libcapnp sources Tries ./configure first (except on Windows), then falls back on included platform.hpp previously generated. """ platform_hpp = pjoin(capnproot, 'src', 'platform.hpp') if os.path.exists(platform_hpp): info("already have platform.hpp") return if os.name == 'nt': # stage msvc platform header platform_dir = pjoin(capnproot, 'builds', 'msvc') else: info("attempting ./configure to generate platform.hpp") p = Popen('./configure', cwd=capnproot, shell=True, stdout=PIPE, stderr=PIPE, ) o,e = p.communicate() if p.returncode: warn("failed to configure libcapnp:\n%s" % e) if sys.platform == 'darwin': platform_dir = pjoin(HERE, 'include_darwin') elif sys.platform.startswith('freebsd'): platform_dir = pjoin(HERE, 'include_freebsd') elif sys.platform.startswith('linux-armv'): platform_dir = pjoin(HERE, 'include_linux-armv') else: platform_dir = pjoin(HERE, 'include_linux') else: return info("staging platform.hpp from: %s" % platform_dir) shutil.copy(pjoin(platform_dir, 'platform.hpp'), platform_hpp)
[ "def", "stage_platform_hpp", "(", "capnproot", ")", ":", "platform_hpp", "=", "pjoin", "(", "capnproot", ",", "'src'", ",", "'platform.hpp'", ")", "if", "os", ".", "path", ".", "exists", "(", "platform_hpp", ")", ":", "info", "(", "\"already have platform.hpp\"", ")", "return", "if", "os", ".", "name", "==", "'nt'", ":", "# stage msvc platform header", "platform_dir", "=", "pjoin", "(", "capnproot", ",", "'builds'", ",", "'msvc'", ")", "else", ":", "info", "(", "\"attempting ./configure to generate platform.hpp\"", ")", "p", "=", "Popen", "(", "'./configure'", ",", "cwd", "=", "capnproot", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", ")", "o", ",", "e", "=", "p", ".", "communicate", "(", ")", "if", "p", ".", "returncode", ":", "warn", "(", "\"failed to configure libcapnp:\\n%s\"", "%", "e", ")", "if", "sys", ".", "platform", "==", "'darwin'", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_darwin'", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'freebsd'", ")", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_freebsd'", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux-armv'", ")", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_linux-armv'", ")", "else", ":", "platform_dir", "=", "pjoin", "(", "HERE", ",", "'include_linux'", ")", "else", ":", "return", "info", "(", "\"staging platform.hpp from: %s\"", "%", "platform_dir", ")", "shutil", ".", "copy", "(", "pjoin", "(", "platform_dir", ",", "'platform.hpp'", ")", ",", "platform_hpp", ")" ]
stage platform.hpp into libcapnp sources Tries ./configure first (except on Windows), then falls back on included platform.hpp previously generated.
[ "stage", "platform", ".", "hpp", "into", "libcapnp", "sources" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/bundle.py#L103-L138
train
capnproto/pycapnp
buildutils/patch.py
_find_library
def _find_library(lib, path): """Find a library""" for d in path[::-1]: real_lib = os.path.join(d, lib) if os.path.exists(real_lib): return real_lib
python
def _find_library(lib, path): """Find a library""" for d in path[::-1]: real_lib = os.path.join(d, lib) if os.path.exists(real_lib): return real_lib
[ "def", "_find_library", "(", "lib", ",", "path", ")", ":", "for", "d", "in", "path", "[", ":", ":", "-", "1", "]", ":", "real_lib", "=", "os", ".", "path", ".", "join", "(", "d", ",", "lib", ")", "if", "os", ".", "path", ".", "exists", "(", "real_lib", ")", ":", "return", "real_lib" ]
Find a library
[ "Find", "a", "library" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/patch.py#L30-L35
train
capnproto/pycapnp
buildutils/misc.py
get_output_error
def get_output_error(cmd): """Return the exit status, stdout, stderr of a command""" if not isinstance(cmd, list): cmd = [cmd] logging.debug("Running: %s", ' '.join(map(quote, cmd))) try: result = Popen(cmd, stdout=PIPE, stderr=PIPE) except IOError as e: return -1, u(''), u('Failed to run %r: %r' % (cmd, e)) so, se = result.communicate() # unicode: so = so.decode('utf8', 'replace') se = se.decode('utf8', 'replace') return result.returncode, so, se
python
def get_output_error(cmd): """Return the exit status, stdout, stderr of a command""" if not isinstance(cmd, list): cmd = [cmd] logging.debug("Running: %s", ' '.join(map(quote, cmd))) try: result = Popen(cmd, stdout=PIPE, stderr=PIPE) except IOError as e: return -1, u(''), u('Failed to run %r: %r' % (cmd, e)) so, se = result.communicate() # unicode: so = so.decode('utf8', 'replace') se = se.decode('utf8', 'replace') return result.returncode, so, se
[ "def", "get_output_error", "(", "cmd", ")", ":", "if", "not", "isinstance", "(", "cmd", ",", "list", ")", ":", "cmd", "=", "[", "cmd", "]", "logging", ".", "debug", "(", "\"Running: %s\"", ",", "' '", ".", "join", "(", "map", "(", "quote", ",", "cmd", ")", ")", ")", "try", ":", "result", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "except", "IOError", "as", "e", ":", "return", "-", "1", ",", "u", "(", "''", ")", ",", "u", "(", "'Failed to run %r: %r'", "%", "(", "cmd", ",", "e", ")", ")", "so", ",", "se", "=", "result", ".", "communicate", "(", ")", "# unicode:", "so", "=", "so", ".", "decode", "(", "'utf8'", ",", "'replace'", ")", "se", "=", "se", ".", "decode", "(", "'utf8'", ",", "'replace'", ")", "return", "result", ".", "returncode", ",", "so", ",", "se" ]
Return the exit status, stdout, stderr of a command
[ "Return", "the", "exit", "status", "stdout", "stderr", "of", "a", "command" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/misc.py#L50-L64
train
capnproto/pycapnp
buildutils/config.py
load_config
def load_config(name, base='conf'): """Load config dict from JSON""" fname = pjoin(base, name + '.json') if not os.path.exists(fname): return {} try: with open(fname) as f: cfg = json.load(f) except Exception as e: warn("Couldn't load %s: %s" % (fname, e)) cfg = {} return cfg
python
def load_config(name, base='conf'): """Load config dict from JSON""" fname = pjoin(base, name + '.json') if not os.path.exists(fname): return {} try: with open(fname) as f: cfg = json.load(f) except Exception as e: warn("Couldn't load %s: %s" % (fname, e)) cfg = {} return cfg
[ "def", "load_config", "(", "name", ",", "base", "=", "'conf'", ")", ":", "fname", "=", "pjoin", "(", "base", ",", "name", "+", "'.json'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "return", "{", "}", "try", ":", "with", "open", "(", "fname", ")", "as", "f", ":", "cfg", "=", "json", ".", "load", "(", "f", ")", "except", "Exception", "as", "e", ":", "warn", "(", "\"Couldn't load %s: %s\"", "%", "(", "fname", ",", "e", ")", ")", "cfg", "=", "{", "}", "return", "cfg" ]
Load config dict from JSON
[ "Load", "config", "dict", "from", "JSON" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L31-L42
train
capnproto/pycapnp
buildutils/config.py
save_config
def save_config(name, data, base='conf'): """Save config dict to JSON""" if not os.path.exists(base): os.mkdir(base) fname = pjoin(base, name+'.json') with open(fname, 'w') as f: json.dump(data, f, indent=2)
python
def save_config(name, data, base='conf'): """Save config dict to JSON""" if not os.path.exists(base): os.mkdir(base) fname = pjoin(base, name+'.json') with open(fname, 'w') as f: json.dump(data, f, indent=2)
[ "def", "save_config", "(", "name", ",", "data", ",", "base", "=", "'conf'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "base", ")", ":", "os", ".", "mkdir", "(", "base", ")", "fname", "=", "pjoin", "(", "base", ",", "name", "+", "'.json'", ")", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ",", "indent", "=", "2", ")" ]
Save config dict to JSON
[ "Save", "config", "dict", "to", "JSON" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L45-L51
train
capnproto/pycapnp
buildutils/config.py
get_eargs
def get_eargs(): """ Look for options in environment vars """ settings = {} zmq = os.environ.get("ZMQ_PREFIX", None) if zmq is not None: debug("Found environ var ZMQ_PREFIX=%s" % zmq) settings['zmq_prefix'] = zmq return settings
python
def get_eargs(): """ Look for options in environment vars """ settings = {} zmq = os.environ.get("ZMQ_PREFIX", None) if zmq is not None: debug("Found environ var ZMQ_PREFIX=%s" % zmq) settings['zmq_prefix'] = zmq return settings
[ "def", "get_eargs", "(", ")", ":", "settings", "=", "{", "}", "zmq", "=", "os", ".", "environ", ".", "get", "(", "\"ZMQ_PREFIX\"", ",", "None", ")", "if", "zmq", "is", "not", "None", ":", "debug", "(", "\"Found environ var ZMQ_PREFIX=%s\"", "%", "zmq", ")", "settings", "[", "'zmq_prefix'", "]", "=", "zmq", "return", "settings" ]
Look for options in environment vars
[ "Look", "for", "options", "in", "environment", "vars" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L58-L68
train
capnproto/pycapnp
buildutils/config.py
cfg2dict
def cfg2dict(cfg): """turn a ConfigParser into a nested dict because ConfigParser objects are dumb. """ d = {} for section in cfg.sections(): d[section] = dict(cfg.items(section)) return d
python
def cfg2dict(cfg): """turn a ConfigParser into a nested dict because ConfigParser objects are dumb. """ d = {} for section in cfg.sections(): d[section] = dict(cfg.items(section)) return d
[ "def", "cfg2dict", "(", "cfg", ")", ":", "d", "=", "{", "}", "for", "section", "in", "cfg", ".", "sections", "(", ")", ":", "d", "[", "section", "]", "=", "dict", "(", "cfg", ".", "items", "(", "section", ")", ")", "return", "d" ]
turn a ConfigParser into a nested dict because ConfigParser objects are dumb.
[ "turn", "a", "ConfigParser", "into", "a", "nested", "dict", "because", "ConfigParser", "objects", "are", "dumb", "." ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L70-L78
train
capnproto/pycapnp
buildutils/config.py
get_cfg_args
def get_cfg_args(): """ Look for options in setup.cfg """ if not os.path.exists('setup.cfg'): return {} cfg = ConfigParser() cfg.read('setup.cfg') cfg = cfg2dict(cfg) g = cfg.setdefault('global', {}) # boolean keys: for key in ['libzmq_extension', 'bundle_libzmq_dylib', 'no_libzmq_extension', 'have_sys_un_h', 'skip_check_zmq', ]: if key in g: g[key] = eval(g[key]) # globals go to top level cfg.update(cfg.pop('global')) return cfg
python
def get_cfg_args(): """ Look for options in setup.cfg """ if not os.path.exists('setup.cfg'): return {} cfg = ConfigParser() cfg.read('setup.cfg') cfg = cfg2dict(cfg) g = cfg.setdefault('global', {}) # boolean keys: for key in ['libzmq_extension', 'bundle_libzmq_dylib', 'no_libzmq_extension', 'have_sys_un_h', 'skip_check_zmq', ]: if key in g: g[key] = eval(g[key]) # globals go to top level cfg.update(cfg.pop('global')) return cfg
[ "def", "get_cfg_args", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "'setup.cfg'", ")", ":", "return", "{", "}", "cfg", "=", "ConfigParser", "(", ")", "cfg", ".", "read", "(", "'setup.cfg'", ")", "cfg", "=", "cfg2dict", "(", "cfg", ")", "g", "=", "cfg", ".", "setdefault", "(", "'global'", ",", "{", "}", ")", "# boolean keys:", "for", "key", "in", "[", "'libzmq_extension'", ",", "'bundle_libzmq_dylib'", ",", "'no_libzmq_extension'", ",", "'have_sys_un_h'", ",", "'skip_check_zmq'", ",", "]", ":", "if", "key", "in", "g", ":", "g", "[", "key", "]", "=", "eval", "(", "g", "[", "key", "]", ")", "# globals go to top level", "cfg", ".", "update", "(", "cfg", ".", "pop", "(", "'global'", ")", ")", "return", "cfg" ]
Look for options in setup.cfg
[ "Look", "for", "options", "in", "setup", ".", "cfg" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L80-L102
train
capnproto/pycapnp
buildutils/config.py
config_from_prefix
def config_from_prefix(prefix): """Get config from zmq prefix""" settings = {} if prefix.lower() in ('default', 'auto', ''): settings['zmq_prefix'] = '' settings['libzmq_extension'] = False settings['no_libzmq_extension'] = False elif prefix.lower() in ('bundled', 'extension'): settings['zmq_prefix'] = '' settings['libzmq_extension'] = True settings['no_libzmq_extension'] = False else: settings['zmq_prefix'] = prefix settings['libzmq_extension'] = False settings['no_libzmq_extension'] = True return settings
python
def config_from_prefix(prefix): """Get config from zmq prefix""" settings = {} if prefix.lower() in ('default', 'auto', ''): settings['zmq_prefix'] = '' settings['libzmq_extension'] = False settings['no_libzmq_extension'] = False elif prefix.lower() in ('bundled', 'extension'): settings['zmq_prefix'] = '' settings['libzmq_extension'] = True settings['no_libzmq_extension'] = False else: settings['zmq_prefix'] = prefix settings['libzmq_extension'] = False settings['no_libzmq_extension'] = True return settings
[ "def", "config_from_prefix", "(", "prefix", ")", ":", "settings", "=", "{", "}", "if", "prefix", ".", "lower", "(", ")", "in", "(", "'default'", ",", "'auto'", ",", "''", ")", ":", "settings", "[", "'zmq_prefix'", "]", "=", "''", "settings", "[", "'libzmq_extension'", "]", "=", "False", "settings", "[", "'no_libzmq_extension'", "]", "=", "False", "elif", "prefix", ".", "lower", "(", ")", "in", "(", "'bundled'", ",", "'extension'", ")", ":", "settings", "[", "'zmq_prefix'", "]", "=", "''", "settings", "[", "'libzmq_extension'", "]", "=", "True", "settings", "[", "'no_libzmq_extension'", "]", "=", "False", "else", ":", "settings", "[", "'zmq_prefix'", "]", "=", "prefix", "settings", "[", "'libzmq_extension'", "]", "=", "False", "settings", "[", "'no_libzmq_extension'", "]", "=", "True", "return", "settings" ]
Get config from zmq prefix
[ "Get", "config", "from", "zmq", "prefix" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L104-L119
train
capnproto/pycapnp
buildutils/config.py
merge
def merge(into, d): """merge two containers into is updated, d has priority """ if isinstance(into, dict): for key in d.keys(): if key not in into: into[key] = d[key] else: into[key] = merge(into[key], d[key]) return into elif isinstance(into, list): return into + d else: return d
python
def merge(into, d): """merge two containers into is updated, d has priority """ if isinstance(into, dict): for key in d.keys(): if key not in into: into[key] = d[key] else: into[key] = merge(into[key], d[key]) return into elif isinstance(into, list): return into + d else: return d
[ "def", "merge", "(", "into", ",", "d", ")", ":", "if", "isinstance", "(", "into", ",", "dict", ")", ":", "for", "key", "in", "d", ".", "keys", "(", ")", ":", "if", "key", "not", "in", "into", ":", "into", "[", "key", "]", "=", "d", "[", "key", "]", "else", ":", "into", "[", "key", "]", "=", "merge", "(", "into", "[", "key", "]", ",", "d", "[", "key", "]", ")", "return", "into", "elif", "isinstance", "(", "into", ",", "list", ")", ":", "return", "into", "+", "d", "else", ":", "return", "d" ]
merge two containers into is updated, d has priority
[ "merge", "two", "containers", "into", "is", "updated", "d", "has", "priority" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L121-L136
train
capnproto/pycapnp
buildutils/config.py
discover_settings
def discover_settings(conf_base=None): """ Discover custom settings for ZMQ path""" settings = { 'zmq_prefix': '', 'libzmq_extension': False, 'no_libzmq_extension': False, 'skip_check_zmq': False, 'build_ext': {}, 'bdist_egg': {}, } if sys.platform.startswith('win'): settings['have_sys_un_h'] = False if conf_base: # lowest priority merge(settings, load_config('config', conf_base)) merge(settings, get_cfg_args()) merge(settings, get_eargs()) return settings
python
def discover_settings(conf_base=None): """ Discover custom settings for ZMQ path""" settings = { 'zmq_prefix': '', 'libzmq_extension': False, 'no_libzmq_extension': False, 'skip_check_zmq': False, 'build_ext': {}, 'bdist_egg': {}, } if sys.platform.startswith('win'): settings['have_sys_un_h'] = False if conf_base: # lowest priority merge(settings, load_config('config', conf_base)) merge(settings, get_cfg_args()) merge(settings, get_eargs()) return settings
[ "def", "discover_settings", "(", "conf_base", "=", "None", ")", ":", "settings", "=", "{", "'zmq_prefix'", ":", "''", ",", "'libzmq_extension'", ":", "False", ",", "'no_libzmq_extension'", ":", "False", ",", "'skip_check_zmq'", ":", "False", ",", "'build_ext'", ":", "{", "}", ",", "'bdist_egg'", ":", "{", "}", ",", "}", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "settings", "[", "'have_sys_un_h'", "]", "=", "False", "if", "conf_base", ":", "# lowest priority", "merge", "(", "settings", ",", "load_config", "(", "'config'", ",", "conf_base", ")", ")", "merge", "(", "settings", ",", "get_cfg_args", "(", ")", ")", "merge", "(", "settings", ",", "get_eargs", "(", ")", ")", "return", "settings" ]
Discover custom settings for ZMQ path
[ "Discover", "custom", "settings", "for", "ZMQ", "path" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/config.py#L138-L157
train
capnproto/pycapnp
examples/calculator_server.py
FunctionImpl.call
def call(self, params, _context, **kwargs): '''Note that we're returning a Promise object here, and bypassing the helper functionality that normally sets the results struct from the returned object. Instead, we set _context.results directly inside of another promise''' assert len(params) == self.paramCount # using setattr because '=' is not allowed inside of lambdas return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
python
def call(self, params, _context, **kwargs): '''Note that we're returning a Promise object here, and bypassing the helper functionality that normally sets the results struct from the returned object. Instead, we set _context.results directly inside of another promise''' assert len(params) == self.paramCount # using setattr because '=' is not allowed inside of lambdas return evaluate_impl(self.body, params).then(lambda value: setattr(_context.results, 'value', value))
[ "def", "call", "(", "self", ",", "params", ",", "_context", ",", "*", "*", "kwargs", ")", ":", "assert", "len", "(", "params", ")", "==", "self", ".", "paramCount", "# using setattr because '=' is not allowed inside of lambdas", "return", "evaluate_impl", "(", "self", ".", "body", ",", "params", ")", ".", "then", "(", "lambda", "value", ":", "setattr", "(", "_context", ".", "results", ",", "'value'", ",", "value", ")", ")" ]
Note that we're returning a Promise object here, and bypassing the helper functionality that normally sets the results struct from the returned object. Instead, we set _context.results directly inside of another promise
[ "Note", "that", "we", "re", "returning", "a", "Promise", "object", "here", "and", "bypassing", "the", "helper", "functionality", "that", "normally", "sets", "the", "results", "struct", "from", "the", "returned", "object", ".", "Instead", "we", "set", "_context", ".", "results", "directly", "inside", "of", "another", "promise" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/examples/calculator_server.py#L73-L81
train
capnproto/pycapnp
buildutils/detect.py
detect_version
def detect_version(basedir, compiler=None, **compiler_attrs): """Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compiled and run compiler : str The distutils compiler key (e.g. 'unix', 'msvc', or 'mingw32') **compiler_attrs : dict Any extra compiler attributes, which will be set via ``setattr(cc)``. Returns ------- A dict of properties for zmq compilation, with the following two keys: vers : tuple The ZMQ version as a tuple of ints, e.g. (2,2,0) settings : dict The compiler options used to compile the test function, e.g. `include_dirs`, `library_dirs`, `libs`, etc. """ if compiler is None: compiler = get_default_compiler() cfile = pjoin(basedir, 'vers.cpp') shutil.copy(pjoin(os.path.dirname(__file__), 'vers.cpp'), cfile) # check if we need to link against Realtime Extensions library if sys.platform.startswith('linux'): cc = ccompiler.new_compiler(compiler=compiler) cc.output_dir = basedir if not cc.has_function('timer_create'): if 'libraries' not in compiler_attrs: compiler_attrs['libraries'] = [] compiler_attrs['libraries'].append('rt') cc = get_compiler(compiler=compiler, **compiler_attrs) efile = test_compilation(cfile, compiler=cc) patch_lib_paths(efile, cc.library_dirs) rc, so, se = get_output_error([efile]) if rc: msg = "Error running version detection script:\n%s\n%s" % (so,se) logging.error(msg) raise IOError(msg) handlers = {'vers': lambda val: tuple(int(v) for v in val.split('.'))} props = {} for line in (x for x in so.split('\n') if x): key, val = line.split(':') props[key] = handlers[key](val) return props
python
def detect_version(basedir, compiler=None, **compiler_attrs): """Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compiled and run compiler : str The distutils compiler key (e.g. 'unix', 'msvc', or 'mingw32') **compiler_attrs : dict Any extra compiler attributes, which will be set via ``setattr(cc)``. Returns ------- A dict of properties for zmq compilation, with the following two keys: vers : tuple The ZMQ version as a tuple of ints, e.g. (2,2,0) settings : dict The compiler options used to compile the test function, e.g. `include_dirs`, `library_dirs`, `libs`, etc. """ if compiler is None: compiler = get_default_compiler() cfile = pjoin(basedir, 'vers.cpp') shutil.copy(pjoin(os.path.dirname(__file__), 'vers.cpp'), cfile) # check if we need to link against Realtime Extensions library if sys.platform.startswith('linux'): cc = ccompiler.new_compiler(compiler=compiler) cc.output_dir = basedir if not cc.has_function('timer_create'): if 'libraries' not in compiler_attrs: compiler_attrs['libraries'] = [] compiler_attrs['libraries'].append('rt') cc = get_compiler(compiler=compiler, **compiler_attrs) efile = test_compilation(cfile, compiler=cc) patch_lib_paths(efile, cc.library_dirs) rc, so, se = get_output_error([efile]) if rc: msg = "Error running version detection script:\n%s\n%s" % (so,se) logging.error(msg) raise IOError(msg) handlers = {'vers': lambda val: tuple(int(v) for v in val.split('.'))} props = {} for line in (x for x in so.split('\n') if x): key, val = line.split(':') props[key] = handlers[key](val) return props
[ "def", "detect_version", "(", "basedir", ",", "compiler", "=", "None", ",", "*", "*", "compiler_attrs", ")", ":", "if", "compiler", "is", "None", ":", "compiler", "=", "get_default_compiler", "(", ")", "cfile", "=", "pjoin", "(", "basedir", ",", "'vers.cpp'", ")", "shutil", ".", "copy", "(", "pjoin", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'vers.cpp'", ")", ",", "cfile", ")", "# check if we need to link against Realtime Extensions library", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "cc", "=", "ccompiler", ".", "new_compiler", "(", "compiler", "=", "compiler", ")", "cc", ".", "output_dir", "=", "basedir", "if", "not", "cc", ".", "has_function", "(", "'timer_create'", ")", ":", "if", "'libraries'", "not", "in", "compiler_attrs", ":", "compiler_attrs", "[", "'libraries'", "]", "=", "[", "]", "compiler_attrs", "[", "'libraries'", "]", ".", "append", "(", "'rt'", ")", "cc", "=", "get_compiler", "(", "compiler", "=", "compiler", ",", "*", "*", "compiler_attrs", ")", "efile", "=", "test_compilation", "(", "cfile", ",", "compiler", "=", "cc", ")", "patch_lib_paths", "(", "efile", ",", "cc", ".", "library_dirs", ")", "rc", ",", "so", ",", "se", "=", "get_output_error", "(", "[", "efile", "]", ")", "if", "rc", ":", "msg", "=", "\"Error running version detection script:\\n%s\\n%s\"", "%", "(", "so", ",", "se", ")", "logging", ".", "error", "(", "msg", ")", "raise", "IOError", "(", "msg", ")", "handlers", "=", "{", "'vers'", ":", "lambda", "val", ":", "tuple", "(", "int", "(", "v", ")", "for", "v", "in", "val", ".", "split", "(", "'.'", ")", ")", "}", "props", "=", "{", "}", "for", "line", "in", "(", "x", "for", "x", "in", "so", ".", "split", "(", "'\\n'", ")", "if", "x", ")", ":", "key", ",", "val", "=", "line", ".", "split", "(", "':'", ")", "props", "[", "key", "]", "=", "handlers", "[", "key", "]", "(", "val", ")", "return", "props" ]
Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compiled and run compiler : str The distutils compiler key (e.g. 'unix', 'msvc', or 'mingw32') **compiler_attrs : dict Any extra compiler attributes, which will be set via ``setattr(cc)``. Returns ------- A dict of properties for zmq compilation, with the following two keys: vers : tuple The ZMQ version as a tuple of ints, e.g. (2,2,0) settings : dict The compiler options used to compile the test function, e.g. `include_dirs`, `library_dirs`, `libs`, etc.
[ "Compile", "link", "&", "execute", "a", "test", "program", "in", "empty", "directory", "basedir", "." ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/detect.py#L87-L144
train
capnproto/pycapnp
buildutils/constants.py
generate_file
def generate_file(fname, ns_func, dest_dir="."): """generate a constants file from its template""" with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f: tpl = f.read() out = tpl.format(**ns_func()) dest = pjoin(dest_dir, fname) info("generating %s from template" % dest) with open(dest, 'w') as f: f.write(out)
python
def generate_file(fname, ns_func, dest_dir="."): """generate a constants file from its template""" with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f: tpl = f.read() out = tpl.format(**ns_func()) dest = pjoin(dest_dir, fname) info("generating %s from template" % dest) with open(dest, 'w') as f: f.write(out)
[ "def", "generate_file", "(", "fname", ",", "ns_func", ",", "dest_dir", "=", "\".\"", ")", ":", "with", "open", "(", "pjoin", "(", "root", ",", "'buildutils'", ",", "'templates'", ",", "'%s'", "%", "fname", ")", ",", "'r'", ")", "as", "f", ":", "tpl", "=", "f", ".", "read", "(", ")", "out", "=", "tpl", ".", "format", "(", "*", "*", "ns_func", "(", ")", ")", "dest", "=", "pjoin", "(", "dest_dir", ",", "fname", ")", "info", "(", "\"generating %s from template\"", "%", "dest", ")", "with", "open", "(", "dest", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "out", ")" ]
generate a constants file from its template
[ "generate", "a", "constants", "file", "from", "its", "template" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/constants.py#L66-L74
train
capnproto/pycapnp
buildutils/constants.py
render_constants
def render_constants(): """render generated constant files from templates""" generate_file("constant_enums.pxi", cython_enums, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("constants.pxi", constants_pyx, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("zmq_constants.h", ifndefs, pjoin(root, 'zmq', 'utils'))
python
def render_constants(): """render generated constant files from templates""" generate_file("constant_enums.pxi", cython_enums, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("constants.pxi", constants_pyx, pjoin(root, 'zmq', 'backend', 'cython')) generate_file("zmq_constants.h", ifndefs, pjoin(root, 'zmq', 'utils'))
[ "def", "render_constants", "(", ")", ":", "generate_file", "(", "\"constant_enums.pxi\"", ",", "cython_enums", ",", "pjoin", "(", "root", ",", "'zmq'", ",", "'backend'", ",", "'cython'", ")", ")", "generate_file", "(", "\"constants.pxi\"", ",", "constants_pyx", ",", "pjoin", "(", "root", ",", "'zmq'", ",", "'backend'", ",", "'cython'", ")", ")", "generate_file", "(", "\"zmq_constants.h\"", ",", "ifndefs", ",", "pjoin", "(", "root", ",", "'zmq'", ",", "'utils'", ")", ")" ]
render generated constant files from templates
[ "render", "generated", "constant", "files", "from", "templates" ]
cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5
https://github.com/capnproto/pycapnp/blob/cb3f190b955bdb1bfb6e0ac0b2f9306a5c79f7b5/buildutils/constants.py#L76-L80
train
byroot/pysrt
pysrt/srttime.py
SubRipTime.from_time
def from_time(cls, source): """ datetime.time -> SubRipTime corresponding to time object """ return cls(hours=source.hour, minutes=source.minute, seconds=source.second, milliseconds=source.microsecond // 1000)
python
def from_time(cls, source): """ datetime.time -> SubRipTime corresponding to time object """ return cls(hours=source.hour, minutes=source.minute, seconds=source.second, milliseconds=source.microsecond // 1000)
[ "def", "from_time", "(", "cls", ",", "source", ")", ":", "return", "cls", "(", "hours", "=", "source", ".", "hour", ",", "minutes", "=", "source", ".", "minute", ",", "seconds", "=", "source", ".", "second", ",", "milliseconds", "=", "source", ".", "microsecond", "//", "1000", ")" ]
datetime.time -> SubRipTime corresponding to time object
[ "datetime", ".", "time", "-", ">", "SubRipTime", "corresponding", "to", "time", "object" ]
e23ca39de37d54e988f4726c311aee4d4770c2ca
https://github.com/byroot/pysrt/blob/e23ca39de37d54e988f4726c311aee4d4770c2ca/pysrt/srttime.py#L165-L170
train
byroot/pysrt
pysrt/srttime.py
SubRipTime.to_time
def to_time(self): """ Convert SubRipTime instance into a pure datetime.time object """ return time(self.hours, self.minutes, self.seconds, self.milliseconds * 1000)
python
def to_time(self): """ Convert SubRipTime instance into a pure datetime.time object """ return time(self.hours, self.minutes, self.seconds, self.milliseconds * 1000)
[ "def", "to_time", "(", "self", ")", ":", "return", "time", "(", "self", ".", "hours", ",", "self", ".", "minutes", ",", "self", ".", "seconds", ",", "self", ".", "milliseconds", "*", "1000", ")" ]
Convert SubRipTime instance into a pure datetime.time object
[ "Convert", "SubRipTime", "instance", "into", "a", "pure", "datetime", ".", "time", "object" ]
e23ca39de37d54e988f4726c311aee4d4770c2ca
https://github.com/byroot/pysrt/blob/e23ca39de37d54e988f4726c311aee4d4770c2ca/pysrt/srttime.py#L172-L177
train
torchbox/wagtail-import-export
wagtailimportexport/exporting.py
export_pages
def export_pages(root_page, export_unpublished=False): """ Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures that there are no orphan pages when the subtree is created in the destination site. If export_unpublished=True the root_page and all its descendants are included. """ pages = Page.objects.descendant_of(root_page, inclusive=True).order_by('path').specific() if not export_unpublished: pages = pages.filter(live=True) page_data = [] exported_paths = set() for (i, page) in enumerate(pages): parent_path = page.path[:-(Page.steplen)] # skip over pages whose parents haven't already been exported # (which means that export_unpublished is false and the parent was unpublished) if i == 0 or (parent_path in exported_paths): page_data.append({ 'content': json.loads(page.to_json()), 'model': page.content_type.model, 'app_label': page.content_type.app_label, }) exported_paths.add(page.path) return { 'pages': page_data }
python
def export_pages(root_page, export_unpublished=False): """ Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures that there are no orphan pages when the subtree is created in the destination site. If export_unpublished=True the root_page and all its descendants are included. """ pages = Page.objects.descendant_of(root_page, inclusive=True).order_by('path').specific() if not export_unpublished: pages = pages.filter(live=True) page_data = [] exported_paths = set() for (i, page) in enumerate(pages): parent_path = page.path[:-(Page.steplen)] # skip over pages whose parents haven't already been exported # (which means that export_unpublished is false and the parent was unpublished) if i == 0 or (parent_path in exported_paths): page_data.append({ 'content': json.loads(page.to_json()), 'model': page.content_type.model, 'app_label': page.content_type.app_label, }) exported_paths.add(page.path) return { 'pages': page_data }
[ "def", "export_pages", "(", "root_page", ",", "export_unpublished", "=", "False", ")", ":", "pages", "=", "Page", ".", "objects", ".", "descendant_of", "(", "root_page", ",", "inclusive", "=", "True", ")", ".", "order_by", "(", "'path'", ")", ".", "specific", "(", ")", "if", "not", "export_unpublished", ":", "pages", "=", "pages", ".", "filter", "(", "live", "=", "True", ")", "page_data", "=", "[", "]", "exported_paths", "=", "set", "(", ")", "for", "(", "i", ",", "page", ")", "in", "enumerate", "(", "pages", ")", ":", "parent_path", "=", "page", ".", "path", "[", ":", "-", "(", "Page", ".", "steplen", ")", "]", "# skip over pages whose parents haven't already been exported", "# (which means that export_unpublished is false and the parent was unpublished)", "if", "i", "==", "0", "or", "(", "parent_path", "in", "exported_paths", ")", ":", "page_data", ".", "append", "(", "{", "'content'", ":", "json", ".", "loads", "(", "page", ".", "to_json", "(", ")", ")", ",", "'model'", ":", "page", ".", "content_type", ".", "model", ",", "'app_label'", ":", "page", ".", "content_type", ".", "app_label", ",", "}", ")", "exported_paths", ".", "add", "(", "page", ".", "path", ")", "return", "{", "'pages'", ":", "page_data", "}" ]
Create a JSON defintion of part of a site's page tree starting from root_page and descending into its descendants By default only published pages are exported. If a page is unpublished it and all its descendants are pruned even if some of those descendants are themselves published. This ensures that there are no orphan pages when the subtree is created in the destination site. If export_unpublished=True the root_page and all its descendants are included.
[ "Create", "a", "JSON", "defintion", "of", "part", "of", "a", "site", "s", "page", "tree", "starting", "from", "root_page", "and", "descending", "into", "its", "descendants" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/exporting.py#L6-L40
train
torchbox/wagtail-import-export
wagtailimportexport/views.py
import_from_api
def import_from_api(request): """ Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromAPIForm(request.POST) if form.is_valid(): # remove trailing slash from base url base_url = re.sub(r'\/$', '', form.cleaned_data['source_site_base_url']) import_url = ( base_url + reverse('wagtailimportexport:export', args=[form.cleaned_data['source_page_id']]) ) r = requests.get(import_url) import_data = r.json() parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromAPIForm() return render(request, 'wagtailimportexport/import_from_api.html', { 'form': form, })
python
def import_from_api(request): """ Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromAPIForm(request.POST) if form.is_valid(): # remove trailing slash from base url base_url = re.sub(r'\/$', '', form.cleaned_data['source_site_base_url']) import_url = ( base_url + reverse('wagtailimportexport:export', args=[form.cleaned_data['source_page_id']]) ) r = requests.get(import_url) import_data = r.json() parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromAPIForm() return render(request, 'wagtailimportexport/import_from_api.html', { 'form': form, })
[ "def", "import_from_api", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "ImportFromAPIForm", "(", "request", ".", "POST", ")", "if", "form", ".", "is_valid", "(", ")", ":", "# remove trailing slash from base url", "base_url", "=", "re", ".", "sub", "(", "r'\\/$'", ",", "''", ",", "form", ".", "cleaned_data", "[", "'source_site_base_url'", "]", ")", "import_url", "=", "(", "base_url", "+", "reverse", "(", "'wagtailimportexport:export'", ",", "args", "=", "[", "form", ".", "cleaned_data", "[", "'source_page_id'", "]", "]", ")", ")", "r", "=", "requests", ".", "get", "(", "import_url", ")", "import_data", "=", "r", ".", "json", "(", ")", "parent_page", "=", "form", ".", "cleaned_data", "[", "'parent_page'", "]", "try", ":", "page_count", "=", "import_pages", "(", "import_data", ",", "parent_page", ")", "except", "LookupError", "as", "e", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "\"Import failed: %(reason)s\"", ")", "%", "{", "'reason'", ":", "e", "}", ")", "else", ":", "messages", ".", "success", "(", "request", ",", "ungettext", "(", "\"%(count)s page imported.\"", ",", "\"%(count)s pages imported.\"", ",", "page_count", ")", "%", "{", "'count'", ":", "page_count", "}", ")", "return", "redirect", "(", "'wagtailadmin_explore'", ",", "parent_page", ".", "pk", ")", "else", ":", "form", "=", "ImportFromAPIForm", "(", ")", "return", "render", "(", "request", ",", "'wagtailimportexport/import_from_api.html'", ",", "{", "'form'", ":", "form", ",", "}", ")" ]
Import a part of a source site's page tree via a direct API request from this Wagtail Admin to the source site The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to.
[ "Import", "a", "part", "of", "a", "source", "site", "s", "page", "tree", "via", "a", "direct", "API", "request", "from", "this", "Wagtail", "Admin", "to", "the", "source", "site" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L21-L60
train
torchbox/wagtail-import-export
wagtailimportexport/views.py
import_from_file
def import_from_file(request): """ Import a part of a source site's page tree via an import of a JSON file exported to a user's filesystem from the source site's Wagtail Admin The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromFileForm(request.POST, request.FILES) if form.is_valid(): import_data = json.loads(form.cleaned_data['file'].read().decode('utf-8-sig')) parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromFileForm() return render(request, 'wagtailimportexport/import_from_file.html', { 'form': form, })
python
def import_from_file(request): """ Import a part of a source site's page tree via an import of a JSON file exported to a user's filesystem from the source site's Wagtail Admin The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to. """ if request.method == 'POST': form = ImportFromFileForm(request.POST, request.FILES) if form.is_valid(): import_data = json.loads(form.cleaned_data['file'].read().decode('utf-8-sig')) parent_page = form.cleaned_data['parent_page'] try: page_count = import_pages(import_data, parent_page) except LookupError as e: messages.error(request, _( "Import failed: %(reason)s") % {'reason': e} ) else: messages.success(request, ungettext( "%(count)s page imported.", "%(count)s pages imported.", page_count) % {'count': page_count} ) return redirect('wagtailadmin_explore', parent_page.pk) else: form = ImportFromFileForm() return render(request, 'wagtailimportexport/import_from_file.html', { 'form': form, })
[ "def", "import_from_file", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "ImportFromFileForm", "(", "request", ".", "POST", ",", "request", ".", "FILES", ")", "if", "form", ".", "is_valid", "(", ")", ":", "import_data", "=", "json", ".", "loads", "(", "form", ".", "cleaned_data", "[", "'file'", "]", ".", "read", "(", ")", ".", "decode", "(", "'utf-8-sig'", ")", ")", "parent_page", "=", "form", ".", "cleaned_data", "[", "'parent_page'", "]", "try", ":", "page_count", "=", "import_pages", "(", "import_data", ",", "parent_page", ")", "except", "LookupError", "as", "e", ":", "messages", ".", "error", "(", "request", ",", "_", "(", "\"Import failed: %(reason)s\"", ")", "%", "{", "'reason'", ":", "e", "}", ")", "else", ":", "messages", ".", "success", "(", "request", ",", "ungettext", "(", "\"%(count)s page imported.\"", ",", "\"%(count)s pages imported.\"", ",", "page_count", ")", "%", "{", "'count'", ":", "page_count", "}", ")", "return", "redirect", "(", "'wagtailadmin_explore'", ",", "parent_page", ".", "pk", ")", "else", ":", "form", "=", "ImportFromFileForm", "(", ")", "return", "render", "(", "request", ",", "'wagtailimportexport/import_from_file.html'", ",", "{", "'form'", ":", "form", ",", "}", ")" ]
Import a part of a source site's page tree via an import of a JSON file exported to a user's filesystem from the source site's Wagtail Admin The source site's base url and the source page id of the point in the tree to import defined what to import and the destination parent page defines where to import it to.
[ "Import", "a", "part", "of", "a", "source", "site", "s", "page", "tree", "via", "an", "import", "of", "a", "JSON", "file", "exported", "to", "a", "user", "s", "filesystem", "from", "the", "source", "site", "s", "Wagtail", "Admin" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L63-L96
train
torchbox/wagtail-import-export
wagtailimportexport/views.py
export_to_file
def export_to_file(request): """ Export a part of this source site's page tree to a JSON file on this user's filesystem for subsequent import in a destination site's Wagtail Admin """ if request.method == 'POST': form = ExportForm(request.POST) if form.is_valid(): payload = export_pages(form.cleaned_data['root_page'], export_unpublished=True) response = JsonResponse(payload) response['Content-Disposition'] = 'attachment; filename="export.json"' return response else: form = ExportForm() return render(request, 'wagtailimportexport/export_to_file.html', { 'form': form, })
python
def export_to_file(request): """ Export a part of this source site's page tree to a JSON file on this user's filesystem for subsequent import in a destination site's Wagtail Admin """ if request.method == 'POST': form = ExportForm(request.POST) if form.is_valid(): payload = export_pages(form.cleaned_data['root_page'], export_unpublished=True) response = JsonResponse(payload) response['Content-Disposition'] = 'attachment; filename="export.json"' return response else: form = ExportForm() return render(request, 'wagtailimportexport/export_to_file.html', { 'form': form, })
[ "def", "export_to_file", "(", "request", ")", ":", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "ExportForm", "(", "request", ".", "POST", ")", "if", "form", ".", "is_valid", "(", ")", ":", "payload", "=", "export_pages", "(", "form", ".", "cleaned_data", "[", "'root_page'", "]", ",", "export_unpublished", "=", "True", ")", "response", "=", "JsonResponse", "(", "payload", ")", "response", "[", "'Content-Disposition'", "]", "=", "'attachment; filename=\"export.json\"'", "return", "response", "else", ":", "form", "=", "ExportForm", "(", ")", "return", "render", "(", "request", ",", "'wagtailimportexport/export_to_file.html'", ",", "{", "'form'", ":", "form", ",", "}", ")" ]
Export a part of this source site's page tree to a JSON file on this user's filesystem for subsequent import in a destination site's Wagtail Admin
[ "Export", "a", "part", "of", "this", "source", "site", "s", "page", "tree", "to", "a", "JSON", "file", "on", "this", "user", "s", "filesystem", "for", "subsequent", "import", "in", "a", "destination", "site", "s", "Wagtail", "Admin" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L99-L117
train
torchbox/wagtail-import-export
wagtailimportexport/views.py
export
def export(request, page_id, export_unpublished=False): """ API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view. """ try: if export_unpublished: root_page = Page.objects.get(id=page_id) else: root_page = Page.objects.get(id=page_id, live=True) except Page.DoesNotExist: return JsonResponse({'error': _('page not found')}) payload = export_pages(root_page, export_unpublished=export_unpublished) return JsonResponse(payload)
python
def export(request, page_id, export_unpublished=False): """ API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view. """ try: if export_unpublished: root_page = Page.objects.get(id=page_id) else: root_page = Page.objects.get(id=page_id, live=True) except Page.DoesNotExist: return JsonResponse({'error': _('page not found')}) payload = export_pages(root_page, export_unpublished=export_unpublished) return JsonResponse(payload)
[ "def", "export", "(", "request", ",", "page_id", ",", "export_unpublished", "=", "False", ")", ":", "try", ":", "if", "export_unpublished", ":", "root_page", "=", "Page", ".", "objects", ".", "get", "(", "id", "=", "page_id", ")", "else", ":", "root_page", "=", "Page", ".", "objects", ".", "get", "(", "id", "=", "page_id", ",", "live", "=", "True", ")", "except", "Page", ".", "DoesNotExist", ":", "return", "JsonResponse", "(", "{", "'error'", ":", "_", "(", "'page not found'", ")", "}", ")", "payload", "=", "export_pages", "(", "root_page", ",", "export_unpublished", "=", "export_unpublished", ")", "return", "JsonResponse", "(", "payload", ")" ]
API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view.
[ "API", "endpoint", "of", "this", "source", "site", "to", "export", "a", "part", "of", "the", "page", "tree", "rooted", "at", "page_id" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/views.py#L120-L137
train
torchbox/wagtail-import-export
wagtailimportexport/importing.py
import_pages
def import_pages(import_data, parent_page): """ Take a JSON export of part of a source site's page tree and create those pages under the parent page """ pages_by_original_path = {} pages_by_original_id = {} # First create the base Page records; these contain no foreign keys, so this allows us to # build a complete mapping from old IDs to new IDs before we go on to importing the # specific page models, which may require us to rewrite page IDs within foreign keys / rich # text / streamfields. page_content_type = ContentType.objects.get_for_model(Page) for (i, page_record) in enumerate(import_data['pages']): # build a base Page instance from the exported content (so that we pick up its title and other # core attributes) page = Page.from_serializable_data(page_record['content']) original_path = page.path original_id = page.id # clear id and treebeard-related fields so that they get reassigned when we save via add_child page.id = None page.path = None page.depth = None page.numchild = 0 page.url_path = None page.content_type = page_content_type if i == 0: parent_page.add_child(instance=page) else: # Child pages are created in the same sibling path order as the # source tree because the export is ordered by path parent_path = original_path[:-(Page.steplen)] pages_by_original_path[parent_path].add_child(instance=page) pages_by_original_path[original_path] = page pages_by_original_id[original_id] = page for (i, page_record) in enumerate(import_data['pages']): # Get the page model of the source page by app_label and model name # The content type ID of the source page is not in general the same # between the source and destination sites but the page model needs # to exist on both. # Raises LookupError exception if there is no matching model model = apps.get_model(page_record['app_label'], page_record['model']) specific_page = model.from_serializable_data(page_record['content'], check_fks=False, strict_fks=False) base_page = pages_by_original_id[specific_page.id] specific_page.page_ptr = base_page specific_page.__dict__.update(base_page.__dict__) specific_page.content_type = ContentType.objects.get_for_model(model) update_page_references(specific_page, pages_by_original_id) specific_page.save() return len(import_data['pages'])
python
def import_pages(import_data, parent_page): """ Take a JSON export of part of a source site's page tree and create those pages under the parent page """ pages_by_original_path = {} pages_by_original_id = {} # First create the base Page records; these contain no foreign keys, so this allows us to # build a complete mapping from old IDs to new IDs before we go on to importing the # specific page models, which may require us to rewrite page IDs within foreign keys / rich # text / streamfields. page_content_type = ContentType.objects.get_for_model(Page) for (i, page_record) in enumerate(import_data['pages']): # build a base Page instance from the exported content (so that we pick up its title and other # core attributes) page = Page.from_serializable_data(page_record['content']) original_path = page.path original_id = page.id # clear id and treebeard-related fields so that they get reassigned when we save via add_child page.id = None page.path = None page.depth = None page.numchild = 0 page.url_path = None page.content_type = page_content_type if i == 0: parent_page.add_child(instance=page) else: # Child pages are created in the same sibling path order as the # source tree because the export is ordered by path parent_path = original_path[:-(Page.steplen)] pages_by_original_path[parent_path].add_child(instance=page) pages_by_original_path[original_path] = page pages_by_original_id[original_id] = page for (i, page_record) in enumerate(import_data['pages']): # Get the page model of the source page by app_label and model name # The content type ID of the source page is not in general the same # between the source and destination sites but the page model needs # to exist on both. # Raises LookupError exception if there is no matching model model = apps.get_model(page_record['app_label'], page_record['model']) specific_page = model.from_serializable_data(page_record['content'], check_fks=False, strict_fks=False) base_page = pages_by_original_id[specific_page.id] specific_page.page_ptr = base_page specific_page.__dict__.update(base_page.__dict__) specific_page.content_type = ContentType.objects.get_for_model(model) update_page_references(specific_page, pages_by_original_id) specific_page.save() return len(import_data['pages'])
[ "def", "import_pages", "(", "import_data", ",", "parent_page", ")", ":", "pages_by_original_path", "=", "{", "}", "pages_by_original_id", "=", "{", "}", "# First create the base Page records; these contain no foreign keys, so this allows us to", "# build a complete mapping from old IDs to new IDs before we go on to importing the", "# specific page models, which may require us to rewrite page IDs within foreign keys / rich", "# text / streamfields.", "page_content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "Page", ")", "for", "(", "i", ",", "page_record", ")", "in", "enumerate", "(", "import_data", "[", "'pages'", "]", ")", ":", "# build a base Page instance from the exported content (so that we pick up its title and other", "# core attributes)", "page", "=", "Page", ".", "from_serializable_data", "(", "page_record", "[", "'content'", "]", ")", "original_path", "=", "page", ".", "path", "original_id", "=", "page", ".", "id", "# clear id and treebeard-related fields so that they get reassigned when we save via add_child", "page", ".", "id", "=", "None", "page", ".", "path", "=", "None", "page", ".", "depth", "=", "None", "page", ".", "numchild", "=", "0", "page", ".", "url_path", "=", "None", "page", ".", "content_type", "=", "page_content_type", "if", "i", "==", "0", ":", "parent_page", ".", "add_child", "(", "instance", "=", "page", ")", "else", ":", "# Child pages are created in the same sibling path order as the", "# source tree because the export is ordered by path", "parent_path", "=", "original_path", "[", ":", "-", "(", "Page", ".", "steplen", ")", "]", "pages_by_original_path", "[", "parent_path", "]", ".", "add_child", "(", "instance", "=", "page", ")", "pages_by_original_path", "[", "original_path", "]", "=", "page", "pages_by_original_id", "[", "original_id", "]", "=", "page", "for", "(", "i", ",", "page_record", ")", "in", "enumerate", "(", "import_data", "[", "'pages'", "]", ")", ":", "# Get the page model of the source page by app_label and model name", "# The content type ID of the source page is not in general the same", "# between the source and destination sites but the page model needs", "# to exist on both.", "# Raises LookupError exception if there is no matching model", "model", "=", "apps", ".", "get_model", "(", "page_record", "[", "'app_label'", "]", ",", "page_record", "[", "'model'", "]", ")", "specific_page", "=", "model", ".", "from_serializable_data", "(", "page_record", "[", "'content'", "]", ",", "check_fks", "=", "False", ",", "strict_fks", "=", "False", ")", "base_page", "=", "pages_by_original_id", "[", "specific_page", ".", "id", "]", "specific_page", ".", "page_ptr", "=", "base_page", "specific_page", ".", "__dict__", ".", "update", "(", "base_page", ".", "__dict__", ")", "specific_page", ".", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "model", ")", "update_page_references", "(", "specific_page", ",", "pages_by_original_id", ")", "specific_page", ".", "save", "(", ")", "return", "len", "(", "import_data", "[", "'pages'", "]", ")" ]
Take a JSON export of part of a source site's page tree and create those pages under the parent page
[ "Take", "a", "JSON", "export", "of", "part", "of", "a", "source", "site", "s", "page", "tree", "and", "create", "those", "pages", "under", "the", "parent", "page" ]
4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e
https://github.com/torchbox/wagtail-import-export/blob/4a4b0b0fde00e8062c52a8bc3e57cb91acfc920e/wagtailimportexport/importing.py#L10-L64
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.remove_all_filters
def remove_all_filters(self): """ Removes all filters """ # attitude: None = no attitude, True = positive, False = negative self.attitude_filter = self.source_filter = None self.question_filter = self.link_filter = False
python
def remove_all_filters(self): """ Removes all filters """ # attitude: None = no attitude, True = positive, False = negative self.attitude_filter = self.source_filter = None self.question_filter = self.link_filter = False
[ "def", "remove_all_filters", "(", "self", ")", ":", "# attitude: None = no attitude, True = positive, False = negative", "self", ".", "attitude_filter", "=", "self", ".", "source_filter", "=", "None", "self", ".", "question_filter", "=", "self", ".", "link_filter", "=", "False" ]
Removes all filters
[ "Removes", "all", "filters" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L71-L76
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_source_filter
def set_source_filter(self, source): """ Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException """ if isinstance(source, str if py3k else basestring) and len(source) >= 2: self.source_filter = source else: raise TwitterSearchException(1009)
python
def set_source_filter(self, source): """ Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException """ if isinstance(source, str if py3k else basestring) and len(source) >= 2: self.source_filter = source else: raise TwitterSearchException(1009)
[ "def", "set_source_filter", "(", "self", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "str", "if", "py3k", "else", "basestring", ")", "and", "len", "(", "source", ")", ">=", "2", ":", "self", ".", "source_filter", "=", "source", "else", ":", "raise", "TwitterSearchException", "(", "1009", ")" ]
Only search for tweets entered via given source :param source: String. Name of the source to search for. An example \ would be ``source=twitterfeed`` for tweets submitted via TwitterFeed :raises: TwitterSearchException
[ "Only", "search", "for", "tweets", "entered", "via", "given", "source" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L78-L89
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.add_keyword
def add_keyword(self, word, or_operator=False): """ Adds a given string or list to the current keyword list :param word: String or list of at least 2 character long keyword(s) :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Is ignored is word is not a list. Thus it is \ possible to search for ``foo OR bar``. Default value is False \ which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if isinstance(word, str if py3k else basestring) and len(word) >= 2: self.searchterms.append(word if " " not in word else '"%s"' % word) elif isinstance(word, (tuple,list)): word = [ (i if " " not in i else '"%s"' % i) for i in word ] self.searchterms += [" OR ".join(word)] if or_operator else word else: raise TwitterSearchException(1000)
python
def add_keyword(self, word, or_operator=False): """ Adds a given string or list to the current keyword list :param word: String or list of at least 2 character long keyword(s) :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Is ignored is word is not a list. Thus it is \ possible to search for ``foo OR bar``. Default value is False \ which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if isinstance(word, str if py3k else basestring) and len(word) >= 2: self.searchterms.append(word if " " not in word else '"%s"' % word) elif isinstance(word, (tuple,list)): word = [ (i if " " not in i else '"%s"' % i) for i in word ] self.searchterms += [" OR ".join(word)] if or_operator else word else: raise TwitterSearchException(1000)
[ "def", "add_keyword", "(", "self", ",", "word", ",", "or_operator", "=", "False", ")", ":", "if", "isinstance", "(", "word", ",", "str", "if", "py3k", "else", "basestring", ")", "and", "len", "(", "word", ")", ">=", "2", ":", "self", ".", "searchterms", ".", "append", "(", "word", "if", "\" \"", "not", "in", "word", "else", "'\"%s\"'", "%", "word", ")", "elif", "isinstance", "(", "word", ",", "(", "tuple", ",", "list", ")", ")", ":", "word", "=", "[", "(", "i", "if", "\" \"", "not", "in", "i", "else", "'\"%s\"'", "%", "i", ")", "for", "i", "in", "word", "]", "self", ".", "searchterms", "+=", "[", "\" OR \"", ".", "join", "(", "word", ")", "]", "if", "or_operator", "else", "word", "else", ":", "raise", "TwitterSearchException", "(", "1000", ")" ]
Adds a given string or list to the current keyword list :param word: String or list of at least 2 character long keyword(s) :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Is ignored is word is not a list. Thus it is \ possible to search for ``foo OR bar``. Default value is False \ which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException
[ "Adds", "a", "given", "string", "or", "list", "to", "the", "current", "keyword", "list" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L132-L149
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_keywords
def set_keywords(self, words, or_operator=False): """ Sets a given list as the new keyword list :param words: A list of at least 2 character long new keywords :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Enables searches for ``foo OR bar``. Default value \ is False which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if not isinstance(words, (tuple,list)): raise TwitterSearchException(1001) words = [ (i if " " not in i else '"%s"' % i) for i in words ] self.searchterms = [" OR ".join(words)] if or_operator else words
python
def set_keywords(self, words, or_operator=False): """ Sets a given list as the new keyword list :param words: A list of at least 2 character long new keywords :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Enables searches for ``foo OR bar``. Default value \ is False which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException """ if not isinstance(words, (tuple,list)): raise TwitterSearchException(1001) words = [ (i if " " not in i else '"%s"' % i) for i in words ] self.searchterms = [" OR ".join(words)] if or_operator else words
[ "def", "set_keywords", "(", "self", ",", "words", ",", "or_operator", "=", "False", ")", ":", "if", "not", "isinstance", "(", "words", ",", "(", "tuple", ",", "list", ")", ")", ":", "raise", "TwitterSearchException", "(", "1001", ")", "words", "=", "[", "(", "i", "if", "\" \"", "not", "in", "i", "else", "'\"%s\"'", "%", "i", ")", "for", "i", "in", "words", "]", "self", ".", "searchterms", "=", "[", "\" OR \"", ".", "join", "(", "words", ")", "]", "if", "or_operator", "else", "words" ]
Sets a given list as the new keyword list :param words: A list of at least 2 character long new keywords :param or_operator: Boolean. Concatenates all elements of parameter \ word with ``OR``. Enables searches for ``foo OR bar``. Default value \ is False which corresponds to a search of ``foo AND bar``. :raises: TwitterSearchException
[ "Sets", "a", "given", "list", "as", "the", "new", "keyword", "list" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L151-L164
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_language
def set_language(self, lang): """ Sets 'lang' parameter used to only fetch tweets within \ a certain language :param lang: A 2-letter language code string (ISO 6391 compatible) :raises: TwitterSearchException """ if lang in self.iso_6391: self.arguments.update({'lang': '%s' % lang}) else: raise TwitterSearchException(1002)
python
def set_language(self, lang): """ Sets 'lang' parameter used to only fetch tweets within \ a certain language :param lang: A 2-letter language code string (ISO 6391 compatible) :raises: TwitterSearchException """ if lang in self.iso_6391: self.arguments.update({'lang': '%s' % lang}) else: raise TwitterSearchException(1002)
[ "def", "set_language", "(", "self", ",", "lang", ")", ":", "if", "lang", "in", "self", ".", "iso_6391", ":", "self", ".", "arguments", ".", "update", "(", "{", "'lang'", ":", "'%s'", "%", "lang", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1002", ")" ]
Sets 'lang' parameter used to only fetch tweets within \ a certain language :param lang: A 2-letter language code string (ISO 6391 compatible) :raises: TwitterSearchException
[ "Sets", "lang", "parameter", "used", "to", "only", "fetch", "tweets", "within", "\\", "a", "certain", "language" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L254-L265
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_callback
def set_callback(self, func): """ Sets 'callback' parameter. If supplied, the response \ will use the JSONP format with a callback of the given name :param func: A string containing the name of the callback function :raises: TwitterSearchException """ if isinstance(func, str if py3k else basestring) and func: self.arguments.update({'callback': '%s' % func}) else: raise TwitterSearchException(1006)
python
def set_callback(self, func): """ Sets 'callback' parameter. If supplied, the response \ will use the JSONP format with a callback of the given name :param func: A string containing the name of the callback function :raises: TwitterSearchException """ if isinstance(func, str if py3k else basestring) and func: self.arguments.update({'callback': '%s' % func}) else: raise TwitterSearchException(1006)
[ "def", "set_callback", "(", "self", ",", "func", ")", ":", "if", "isinstance", "(", "func", ",", "str", "if", "py3k", "else", "basestring", ")", "and", "func", ":", "self", ".", "arguments", ".", "update", "(", "{", "'callback'", ":", "'%s'", "%", "func", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1006", ")" ]
Sets 'callback' parameter. If supplied, the response \ will use the JSONP format with a callback of the given name :param func: A string containing the name of the callback function :raises: TwitterSearchException
[ "Sets", "callback", "parameter", ".", "If", "supplied", "the", "response", "\\", "will", "use", "the", "JSONP", "format", "with", "a", "callback", "of", "the", "given", "name" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L333-L344
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearchOrder.py
TwitterSearchOrder.set_until
def set_until(self, date): """ Sets 'until' parameter used to return \ only tweets generated before the given date :param date: A datetime instance :raises: TwitterSearchException """ if isinstance(date, datetime.date) and date <= datetime.date.today(): self.arguments.update({'until': '%s' % date.strftime('%Y-%m-%d')}) else: raise TwitterSearchException(1007)
python
def set_until(self, date): """ Sets 'until' parameter used to return \ only tweets generated before the given date :param date: A datetime instance :raises: TwitterSearchException """ if isinstance(date, datetime.date) and date <= datetime.date.today(): self.arguments.update({'until': '%s' % date.strftime('%Y-%m-%d')}) else: raise TwitterSearchException(1007)
[ "def", "set_until", "(", "self", ",", "date", ")", ":", "if", "isinstance", "(", "date", ",", "datetime", ".", "date", ")", "and", "date", "<=", "datetime", ".", "date", ".", "today", "(", ")", ":", "self", ".", "arguments", ".", "update", "(", "{", "'until'", ":", "'%s'", "%", "date", ".", "strftime", "(", "'%Y-%m-%d'", ")", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1007", ")" ]
Sets 'until' parameter used to return \ only tweets generated before the given date :param date: A datetime instance :raises: TwitterSearchException
[ "Sets", "until", "parameter", "used", "to", "return", "\\", "only", "tweets", "generated", "before", "the", "given", "date" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearchOrder.py#L346-L357
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearch.py
TwitterSearch.set_proxy
def set_proxy(self, proxy): """ Sets a HTTPS proxy to query the Twitter API :param proxy: A string of containing a HTTPS proxy \ e.g. ``set_proxy("my.proxy.com:8080")``. :raises: TwitterSearchException """ if isinstance(proxy, str if py3k else basestring): self.__proxy = proxy else: raise TwitterSearchException(1009)
python
def set_proxy(self, proxy): """ Sets a HTTPS proxy to query the Twitter API :param proxy: A string of containing a HTTPS proxy \ e.g. ``set_proxy("my.proxy.com:8080")``. :raises: TwitterSearchException """ if isinstance(proxy, str if py3k else basestring): self.__proxy = proxy else: raise TwitterSearchException(1009)
[ "def", "set_proxy", "(", "self", ",", "proxy", ")", ":", "if", "isinstance", "(", "proxy", ",", "str", "if", "py3k", "else", "basestring", ")", ":", "self", ".", "__proxy", "=", "proxy", "else", ":", "raise", "TwitterSearchException", "(", "1009", ")" ]
Sets a HTTPS proxy to query the Twitter API :param proxy: A string of containing a HTTPS proxy \ e.g. ``set_proxy("my.proxy.com:8080")``. :raises: TwitterSearchException
[ "Sets", "a", "HTTPS", "proxy", "to", "query", "the", "Twitter", "API" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearch.py#L129-L140
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearch.py
TwitterSearch.get_minimal_id
def get_minimal_id(self): """ Returns the minimal tweet ID of the current response :returns: minimal tweet identification number :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return min( self.__response['content']['statuses'] if self.__order_is_search else self.__response['content'], key=lambda i: i['id'] )['id'] - 1
python
def get_minimal_id(self): """ Returns the minimal tweet ID of the current response :returns: minimal tweet identification number :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return min( self.__response['content']['statuses'] if self.__order_is_search else self.__response['content'], key=lambda i: i['id'] )['id'] - 1
[ "def", "get_minimal_id", "(", "self", ")", ":", "if", "not", "self", ".", "__response", ":", "raise", "TwitterSearchException", "(", "1013", ")", "return", "min", "(", "self", ".", "__response", "[", "'content'", "]", "[", "'statuses'", "]", "if", "self", ".", "__order_is_search", "else", "self", ".", "__response", "[", "'content'", "]", ",", "key", "=", "lambda", "i", ":", "i", "[", "'id'", "]", ")", "[", "'id'", "]", "-", "1" ]
Returns the minimal tweet ID of the current response :returns: minimal tweet identification number :raises: TwitterSearchException
[ "Returns", "the", "minimal", "tweet", "ID", "of", "the", "current", "response" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearch.py#L207-L221
train
ckoepp/TwitterSearch
TwitterSearch/TwitterSearch.py
TwitterSearch.get_amount_of_tweets
def get_amount_of_tweets(self): """ Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return (len(self.__response['content']['statuses']) if self.__order_is_search else len(self.__response['content']))
python
def get_amount_of_tweets(self): """ Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException """ if not self.__response: raise TwitterSearchException(1013) return (len(self.__response['content']['statuses']) if self.__order_is_search else len(self.__response['content']))
[ "def", "get_amount_of_tweets", "(", "self", ")", ":", "if", "not", "self", ".", "__response", ":", "raise", "TwitterSearchException", "(", "1013", ")", "return", "(", "len", "(", "self", ".", "__response", "[", "'content'", "]", "[", "'statuses'", "]", ")", "if", "self", ".", "__order_is_search", "else", "len", "(", "self", ".", "__response", "[", "'content'", "]", ")", ")" ]
Returns current amount of tweets available within this instance :returns: The amount of tweets currently available :raises: TwitterSearchException
[ "Returns", "current", "amount", "of", "tweets", "available", "within", "this", "instance" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterSearch.py#L367-L379
train
ckoepp/TwitterSearch
TwitterSearch/TwitterOrder.py
TwitterOrder.set_count
def set_count(self, cnt): """ Sets 'count' parameter used to define the number of \ tweets to return per page. Maximum and default value is 100 :param cnt: Integer containing the number of tweets per \ page within a range of 1 to 100 :raises: TwitterSearchException """ if isinstance(cnt, int) and cnt > 0 and cnt <= 100: self.arguments.update({'count': '%s' % cnt}) else: raise TwitterSearchException(1004)
python
def set_count(self, cnt): """ Sets 'count' parameter used to define the number of \ tweets to return per page. Maximum and default value is 100 :param cnt: Integer containing the number of tweets per \ page within a range of 1 to 100 :raises: TwitterSearchException """ if isinstance(cnt, int) and cnt > 0 and cnt <= 100: self.arguments.update({'count': '%s' % cnt}) else: raise TwitterSearchException(1004)
[ "def", "set_count", "(", "self", ",", "cnt", ")", ":", "if", "isinstance", "(", "cnt", ",", "int", ")", "and", "cnt", ">", "0", "and", "cnt", "<=", "100", ":", "self", ".", "arguments", ".", "update", "(", "{", "'count'", ":", "'%s'", "%", "cnt", "}", ")", "else", ":", "raise", "TwitterSearchException", "(", "1004", ")" ]
Sets 'count' parameter used to define the number of \ tweets to return per page. Maximum and default value is 100 :param cnt: Integer containing the number of tweets per \ page within a range of 1 to 100 :raises: TwitterSearchException
[ "Sets", "count", "parameter", "used", "to", "define", "the", "number", "of", "\\", "tweets", "to", "return", "per", "page", ".", "Maximum", "and", "default", "value", "is", "100" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterOrder.py#L77-L89
train
ckoepp/TwitterSearch
TwitterSearch/TwitterOrder.py
TwitterOrder.set_include_entities
def set_include_entities(self, include): """ Sets 'include entities' parameter to either \ include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException """ if not isinstance(include, bool): raise TwitterSearchException(1008) self.arguments.update( {'include_entities': 'true' if include else 'false'} )
python
def set_include_entities(self, include): """ Sets 'include entities' parameter to either \ include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException """ if not isinstance(include, bool): raise TwitterSearchException(1008) self.arguments.update( {'include_entities': 'true' if include else 'false'} )
[ "def", "set_include_entities", "(", "self", ",", "include", ")", ":", "if", "not", "isinstance", "(", "include", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'include_entities'", ":", "'true'", "if", "include", "else", "'false'", "}", ")" ]
Sets 'include entities' parameter to either \ include or exclude the entities node within the results :param include: Boolean to trigger the 'include entities' parameter :raises: TwitterSearchException
[ "Sets", "include", "entities", "parameter", "to", "either", "\\", "include", "or", "exclude", "the", "entities", "node", "within", "the", "results" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterOrder.py#L91-L103
train
ckoepp/TwitterSearch
TwitterSearch/TwitterUserOrder.py
TwitterUserOrder.set_trim_user
def set_trim_user(self, trim): """ Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(trim, bool): raise TwitterSearchException(1008) self.arguments.update({'trim_user': 'true' if trim else 'false'})
python
def set_trim_user(self, trim): """ Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(trim, bool): raise TwitterSearchException(1008) self.arguments.update({'trim_user': 'true' if trim else 'false'})
[ "def", "set_trim_user", "(", "self", ",", "trim", ")", ":", "if", "not", "isinstance", "(", "trim", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'trim_user'", ":", "'true'", "if", "trim", "else", "'false'", "}", ")" ]
Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException
[ "Sets", "trim_user", "parameter", ".", "When", "set", "to", "True", "\\", "each", "tweet", "returned", "in", "a", "timeline", "will", "include", "a", "\\", "user", "object", "including", "only", "the", "status", "authors", "numerical", "ID" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L55-L66
train
ckoepp/TwitterSearch
TwitterSearch/TwitterUserOrder.py
TwitterUserOrder.set_include_rts
def set_include_rts(self, rts): """ Sets 'include_rts' parameter. When set to False, \ the timeline will strip any native retweets from the returned timeline :param rts: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(rts, bool): raise TwitterSearchException(1008) self.arguments.update({'include_rts': 'true' if rts else 'false'})
python
def set_include_rts(self, rts): """ Sets 'include_rts' parameter. When set to False, \ the timeline will strip any native retweets from the returned timeline :param rts: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(rts, bool): raise TwitterSearchException(1008) self.arguments.update({'include_rts': 'true' if rts else 'false'})
[ "def", "set_include_rts", "(", "self", ",", "rts", ")", ":", "if", "not", "isinstance", "(", "rts", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'include_rts'", ":", "'true'", "if", "rts", "else", "'false'", "}", ")" ]
Sets 'include_rts' parameter. When set to False, \ the timeline will strip any native retweets from the returned timeline :param rts: Boolean triggering the usage of the parameter :raises: TwitterSearchException
[ "Sets", "include_rts", "parameter", ".", "When", "set", "to", "False", "\\", "the", "timeline", "will", "strip", "any", "native", "retweets", "from", "the", "returned", "timeline" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L68-L78
train
ckoepp/TwitterSearch
TwitterSearch/TwitterUserOrder.py
TwitterUserOrder.set_exclude_replies
def set_exclude_replies(self, exclude): """ Sets 'exclude_replies' parameter used to \ prevent replies from appearing in the returned timeline :param exclude: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(exclude, bool): raise TwitterSearchException(1008) self.arguments.update({'exclude_replies': 'true' if exclude else 'false'})
python
def set_exclude_replies(self, exclude): """ Sets 'exclude_replies' parameter used to \ prevent replies from appearing in the returned timeline :param exclude: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(exclude, bool): raise TwitterSearchException(1008) self.arguments.update({'exclude_replies': 'true' if exclude else 'false'})
[ "def", "set_exclude_replies", "(", "self", ",", "exclude", ")", ":", "if", "not", "isinstance", "(", "exclude", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'exclude_replies'", ":", "'true'", "if", "exclude", "else", "'false'", "}", ")" ]
Sets 'exclude_replies' parameter used to \ prevent replies from appearing in the returned timeline :param exclude: Boolean triggering the usage of the parameter :raises: TwitterSearchException
[ "Sets", "exclude_replies", "parameter", "used", "to", "\\", "prevent", "replies", "from", "appearing", "in", "the", "returned", "timeline" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L80-L92
train
ckoepp/TwitterSearch
TwitterSearch/TwitterUserOrder.py
TwitterUserOrder.set_contributor_details
def set_contributor_details(self, contdetails): """ Sets 'contributor_details' parameter used to enhance the \ contributors element of the status response to include \ the screen_name of the contributor. By default only \ the user_id of the contributor is included :param contdetails: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(contdetails, bool): raise TwitterSearchException(1008) self.arguments.update({'contributor_details': 'true' if contdetails else 'false'})
python
def set_contributor_details(self, contdetails): """ Sets 'contributor_details' parameter used to enhance the \ contributors element of the status response to include \ the screen_name of the contributor. By default only \ the user_id of the contributor is included :param contdetails: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(contdetails, bool): raise TwitterSearchException(1008) self.arguments.update({'contributor_details': 'true' if contdetails else 'false'})
[ "def", "set_contributor_details", "(", "self", ",", "contdetails", ")", ":", "if", "not", "isinstance", "(", "contdetails", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'contributor_details'", ":", "'true'", "if", "contdetails", "else", "'false'", "}", ")" ]
Sets 'contributor_details' parameter used to enhance the \ contributors element of the status response to include \ the screen_name of the contributor. By default only \ the user_id of the contributor is included :param contdetails: Boolean triggering the usage of the parameter :raises: TwitterSearchException
[ "Sets", "contributor_details", "parameter", "used", "to", "enhance", "the", "\\", "contributors", "element", "of", "the", "status", "response", "to", "include", "\\", "the", "screen_name", "of", "the", "contributor", ".", "By", "default", "only", "\\", "the", "user_id", "of", "the", "contributor", "is", "included" ]
627b9f519d49faf6b83859717f9082b3b2622aaf
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L94-L108
train
tkaemming/django-subdomains
subdomains/templatetags/subdomainurls.py
url
def url(context, view, subdomain=UNSET, *args, **kwargs): """ Resolves a URL in a template, using subdomain-based URL resolution. If no subdomain is provided and a ``request`` is in the template context when rendering, the URL will be resolved relative to the current request's subdomain. If no ``request`` is provided, the URL will be resolved relative to current domain with the ``settings.ROOT_URLCONF``. Usage:: {% load subdomainurls %} {% url 'view-name' subdomain='subdomain' %} .. note:: This tag uses the variable URL syntax introduced in Django 1.3 as ``{% load url from future %}`` and was made the standard in Django 1.5. If you are upgrading a legacy application from one of the previous template tag formats, make sure to quote your constant string URL names to avoid :exc:`~django.core.urlresolver.NoReverseMatch` errors during template rendering. """ if subdomain is UNSET: request = context.get('request') if request is not None: subdomain = getattr(request, 'subdomain', None) else: subdomain = None elif subdomain is '': subdomain = None return reverse(view, subdomain=subdomain, args=args, kwargs=kwargs)
python
def url(context, view, subdomain=UNSET, *args, **kwargs): """ Resolves a URL in a template, using subdomain-based URL resolution. If no subdomain is provided and a ``request`` is in the template context when rendering, the URL will be resolved relative to the current request's subdomain. If no ``request`` is provided, the URL will be resolved relative to current domain with the ``settings.ROOT_URLCONF``. Usage:: {% load subdomainurls %} {% url 'view-name' subdomain='subdomain' %} .. note:: This tag uses the variable URL syntax introduced in Django 1.3 as ``{% load url from future %}`` and was made the standard in Django 1.5. If you are upgrading a legacy application from one of the previous template tag formats, make sure to quote your constant string URL names to avoid :exc:`~django.core.urlresolver.NoReverseMatch` errors during template rendering. """ if subdomain is UNSET: request = context.get('request') if request is not None: subdomain = getattr(request, 'subdomain', None) else: subdomain = None elif subdomain is '': subdomain = None return reverse(view, subdomain=subdomain, args=args, kwargs=kwargs)
[ "def", "url", "(", "context", ",", "view", ",", "subdomain", "=", "UNSET", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "subdomain", "is", "UNSET", ":", "request", "=", "context", ".", "get", "(", "'request'", ")", "if", "request", "is", "not", "None", ":", "subdomain", "=", "getattr", "(", "request", ",", "'subdomain'", ",", "None", ")", "else", ":", "subdomain", "=", "None", "elif", "subdomain", "is", "''", ":", "subdomain", "=", "None", "return", "reverse", "(", "view", ",", "subdomain", "=", "subdomain", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")" ]
Resolves a URL in a template, using subdomain-based URL resolution. If no subdomain is provided and a ``request`` is in the template context when rendering, the URL will be resolved relative to the current request's subdomain. If no ``request`` is provided, the URL will be resolved relative to current domain with the ``settings.ROOT_URLCONF``. Usage:: {% load subdomainurls %} {% url 'view-name' subdomain='subdomain' %} .. note:: This tag uses the variable URL syntax introduced in Django 1.3 as ``{% load url from future %}`` and was made the standard in Django 1.5. If you are upgrading a legacy application from one of the previous template tag formats, make sure to quote your constant string URL names to avoid :exc:`~django.core.urlresolver.NoReverseMatch` errors during template rendering.
[ "Resolves", "a", "URL", "in", "a", "template", "using", "subdomain", "-", "based", "URL", "resolution", "." ]
be6cc1c556a2007287ef4e647ea1784cf7690a44
https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/templatetags/subdomainurls.py#L12-L43
train
tkaemming/django-subdomains
subdomains/utils.py
urljoin
def urljoin(domain, path=None, scheme=None): """ Joins a domain, path and scheme part together, returning a full URL. :param domain: the domain, e.g. ``example.com`` :param path: the path part of the URL, e.g. ``/example/`` :param scheme: the scheme part of the URL, e.g. ``http``, defaulting to the value of ``settings.DEFAULT_URL_SCHEME`` :returns: a full URL """ if scheme is None: scheme = getattr(settings, 'DEFAULT_URL_SCHEME', 'http') return urlunparse((scheme, domain, path or '', None, None, None))
python
def urljoin(domain, path=None, scheme=None): """ Joins a domain, path and scheme part together, returning a full URL. :param domain: the domain, e.g. ``example.com`` :param path: the path part of the URL, e.g. ``/example/`` :param scheme: the scheme part of the URL, e.g. ``http``, defaulting to the value of ``settings.DEFAULT_URL_SCHEME`` :returns: a full URL """ if scheme is None: scheme = getattr(settings, 'DEFAULT_URL_SCHEME', 'http') return urlunparse((scheme, domain, path or '', None, None, None))
[ "def", "urljoin", "(", "domain", ",", "path", "=", "None", ",", "scheme", "=", "None", ")", ":", "if", "scheme", "is", "None", ":", "scheme", "=", "getattr", "(", "settings", ",", "'DEFAULT_URL_SCHEME'", ",", "'http'", ")", "return", "urlunparse", "(", "(", "scheme", ",", "domain", ",", "path", "or", "''", ",", "None", ",", "None", ",", "None", ")", ")" ]
Joins a domain, path and scheme part together, returning a full URL. :param domain: the domain, e.g. ``example.com`` :param path: the path part of the URL, e.g. ``/example/`` :param scheme: the scheme part of the URL, e.g. ``http``, defaulting to the value of ``settings.DEFAULT_URL_SCHEME`` :returns: a full URL
[ "Joins", "a", "domain", "path", "and", "scheme", "part", "together", "returning", "a", "full", "URL", "." ]
be6cc1c556a2007287ef4e647ea1784cf7690a44
https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/utils.py#L25-L38
train
tkaemming/django-subdomains
subdomains/middleware.py
SubdomainMiddleware.process_request
def process_request(self, request): """ Adds a ``subdomain`` attribute to the ``request`` parameter. """ domain, host = map(lower, (self.get_domain_for_request(request), request.get_host())) pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re.escape(domain) matches = re.match(pattern, host) if matches: request.subdomain = matches.group('subdomain') else: request.subdomain = None logger.warning('The host %s does not belong to the domain %s, ' 'unable to identify the subdomain for this request', request.get_host(), domain)
python
def process_request(self, request): """ Adds a ``subdomain`` attribute to the ``request`` parameter. """ domain, host = map(lower, (self.get_domain_for_request(request), request.get_host())) pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re.escape(domain) matches = re.match(pattern, host) if matches: request.subdomain = matches.group('subdomain') else: request.subdomain = None logger.warning('The host %s does not belong to the domain %s, ' 'unable to identify the subdomain for this request', request.get_host(), domain)
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "domain", ",", "host", "=", "map", "(", "lower", ",", "(", "self", ".", "get_domain_for_request", "(", "request", ")", ",", "request", ".", "get_host", "(", ")", ")", ")", "pattern", "=", "r'^(?:(?P<subdomain>.*?)\\.)?%s(?::.*)?$'", "%", "re", ".", "escape", "(", "domain", ")", "matches", "=", "re", ".", "match", "(", "pattern", ",", "host", ")", "if", "matches", ":", "request", ".", "subdomain", "=", "matches", ".", "group", "(", "'subdomain'", ")", "else", ":", "request", ".", "subdomain", "=", "None", "logger", ".", "warning", "(", "'The host %s does not belong to the domain %s, '", "'unable to identify the subdomain for this request'", ",", "request", ".", "get_host", "(", ")", ",", "domain", ")" ]
Adds a ``subdomain`` attribute to the ``request`` parameter.
[ "Adds", "a", "subdomain", "attribute", "to", "the", "request", "parameter", "." ]
be6cc1c556a2007287ef4e647ea1784cf7690a44
https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/middleware.py#L28-L44
train
tkaemming/django-subdomains
subdomains/middleware.py
SubdomainURLRoutingMiddleware.process_request
def process_request(self, request): """ Sets the current request's ``urlconf`` attribute to the urlconf associated with the subdomain, if it is listed in ``settings.SUBDOMAIN_URLCONFS``. """ super(SubdomainURLRoutingMiddleware, self).process_request(request) subdomain = getattr(request, 'subdomain', UNSET) if subdomain is not UNSET: urlconf = settings.SUBDOMAIN_URLCONFS.get(subdomain) if urlconf is not None: logger.debug("Using urlconf %s for subdomain: %s", repr(urlconf), repr(subdomain)) request.urlconf = urlconf
python
def process_request(self, request): """ Sets the current request's ``urlconf`` attribute to the urlconf associated with the subdomain, if it is listed in ``settings.SUBDOMAIN_URLCONFS``. """ super(SubdomainURLRoutingMiddleware, self).process_request(request) subdomain = getattr(request, 'subdomain', UNSET) if subdomain is not UNSET: urlconf = settings.SUBDOMAIN_URLCONFS.get(subdomain) if urlconf is not None: logger.debug("Using urlconf %s for subdomain: %s", repr(urlconf), repr(subdomain)) request.urlconf = urlconf
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "super", "(", "SubdomainURLRoutingMiddleware", ",", "self", ")", ".", "process_request", "(", "request", ")", "subdomain", "=", "getattr", "(", "request", ",", "'subdomain'", ",", "UNSET", ")", "if", "subdomain", "is", "not", "UNSET", ":", "urlconf", "=", "settings", ".", "SUBDOMAIN_URLCONFS", ".", "get", "(", "subdomain", ")", "if", "urlconf", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"Using urlconf %s for subdomain: %s\"", ",", "repr", "(", "urlconf", ")", ",", "repr", "(", "subdomain", ")", ")", "request", ".", "urlconf", "=", "urlconf" ]
Sets the current request's ``urlconf`` attribute to the urlconf associated with the subdomain, if it is listed in ``settings.SUBDOMAIN_URLCONFS``.
[ "Sets", "the", "current", "request", "s", "urlconf", "attribute", "to", "the", "urlconf", "associated", "with", "the", "subdomain", "if", "it", "is", "listed", "in", "settings", ".", "SUBDOMAIN_URLCONFS", "." ]
be6cc1c556a2007287ef4e647ea1784cf7690a44
https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/middleware.py#L51-L66
train
tkaemming/django-subdomains
subdomains/middleware.py
SubdomainURLRoutingMiddleware.process_response
def process_response(self, request, response): """ Forces the HTTP ``Vary`` header onto requests to avoid having responses cached across subdomains. """ if getattr(settings, 'FORCE_VARY_ON_HOST', True): patch_vary_headers(response, ('Host',)) return response
python
def process_response(self, request, response): """ Forces the HTTP ``Vary`` header onto requests to avoid having responses cached across subdomains. """ if getattr(settings, 'FORCE_VARY_ON_HOST', True): patch_vary_headers(response, ('Host',)) return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "getattr", "(", "settings", ",", "'FORCE_VARY_ON_HOST'", ",", "True", ")", ":", "patch_vary_headers", "(", "response", ",", "(", "'Host'", ",", ")", ")", "return", "response" ]
Forces the HTTP ``Vary`` header onto requests to avoid having responses cached across subdomains.
[ "Forces", "the", "HTTP", "Vary", "header", "onto", "requests", "to", "avoid", "having", "responses", "cached", "across", "subdomains", "." ]
be6cc1c556a2007287ef4e647ea1784cf7690a44
https://github.com/tkaemming/django-subdomains/blob/be6cc1c556a2007287ef4e647ea1784cf7690a44/subdomains/middleware.py#L68-L76
train
python-constraint/python-constraint
documentation/source/conf.py
process_docstring
def process_docstring(app, what, name, obj, options, lines): """ Process the docstring for a given python object. Note that the list 'lines' is changed in this function. Sphinx uses the altered content of the list. """ result = [re.sub(r'U\{([^}]*)\}', r'\1', re.sub(r'(L|C)\{([^}]*)\}', r':py:obj:`\2`', re.sub(r'@(' + '|'.join(FIELDS) + r')', r':\1', l))) for l in lines] lines[:] = result[:]
python
def process_docstring(app, what, name, obj, options, lines): """ Process the docstring for a given python object. Note that the list 'lines' is changed in this function. Sphinx uses the altered content of the list. """ result = [re.sub(r'U\{([^}]*)\}', r'\1', re.sub(r'(L|C)\{([^}]*)\}', r':py:obj:`\2`', re.sub(r'@(' + '|'.join(FIELDS) + r')', r':\1', l))) for l in lines] lines[:] = result[:]
[ "def", "process_docstring", "(", "app", ",", "what", ",", "name", ",", "obj", ",", "options", ",", "lines", ")", ":", "result", "=", "[", "re", ".", "sub", "(", "r'U\\{([^}]*)\\}'", ",", "r'\\1'", ",", "re", ".", "sub", "(", "r'(L|C)\\{([^}]*)\\}'", ",", "r':py:obj:`\\2`'", ",", "re", ".", "sub", "(", "r'@('", "+", "'|'", ".", "join", "(", "FIELDS", ")", "+", "r')'", ",", "r':\\1'", ",", "l", ")", ")", ")", "for", "l", "in", "lines", "]", "lines", "[", ":", "]", "=", "result", "[", ":", "]" ]
Process the docstring for a given python object. Note that the list 'lines' is changed in this function. Sphinx uses the altered content of the list.
[ "Process", "the", "docstring", "for", "a", "given", "python", "object", ".", "Note", "that", "the", "list", "lines", "is", "changed", "in", "this", "function", ".", "Sphinx", "uses", "the", "altered", "content", "of", "the", "list", "." ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/documentation/source/conf.py#L86-L97
train
python-constraint/python-constraint
constraint/__init__.py
doArc8
def doArc8(arcs, domains, assignments): """ Perform the ARC-8 arc checking algorithm and prune domains @attention: Currently unused. """ check = dict.fromkeys(domains, True) while check: variable, _ = check.popitem() if variable not in arcs or variable in assignments: continue domain = domains[variable] arcsvariable = arcs[variable] for othervariable in arcsvariable: arcconstraints = arcsvariable[othervariable] if othervariable in assignments: otherdomain = [assignments[othervariable]] else: otherdomain = domains[othervariable] if domain: # changed = False for value in domain[:]: assignments[variable] = value if otherdomain: for othervalue in otherdomain: assignments[othervariable] = othervalue for constraint, variables in arcconstraints: if not constraint( variables, domains, assignments, True ): break else: # All constraints passed. Value is safe. break else: # All othervalues failed. Kill value. domain.hideValue(value) # changed = True del assignments[othervariable] del assignments[variable] # if changed: # check.update(dict.fromkeys(arcsvariable)) if not domain: return False return True
python
def doArc8(arcs, domains, assignments): """ Perform the ARC-8 arc checking algorithm and prune domains @attention: Currently unused. """ check = dict.fromkeys(domains, True) while check: variable, _ = check.popitem() if variable not in arcs or variable in assignments: continue domain = domains[variable] arcsvariable = arcs[variable] for othervariable in arcsvariable: arcconstraints = arcsvariable[othervariable] if othervariable in assignments: otherdomain = [assignments[othervariable]] else: otherdomain = domains[othervariable] if domain: # changed = False for value in domain[:]: assignments[variable] = value if otherdomain: for othervalue in otherdomain: assignments[othervariable] = othervalue for constraint, variables in arcconstraints: if not constraint( variables, domains, assignments, True ): break else: # All constraints passed. Value is safe. break else: # All othervalues failed. Kill value. domain.hideValue(value) # changed = True del assignments[othervariable] del assignments[variable] # if changed: # check.update(dict.fromkeys(arcsvariable)) if not domain: return False return True
[ "def", "doArc8", "(", "arcs", ",", "domains", ",", "assignments", ")", ":", "check", "=", "dict", ".", "fromkeys", "(", "domains", ",", "True", ")", "while", "check", ":", "variable", ",", "_", "=", "check", ".", "popitem", "(", ")", "if", "variable", "not", "in", "arcs", "or", "variable", "in", "assignments", ":", "continue", "domain", "=", "domains", "[", "variable", "]", "arcsvariable", "=", "arcs", "[", "variable", "]", "for", "othervariable", "in", "arcsvariable", ":", "arcconstraints", "=", "arcsvariable", "[", "othervariable", "]", "if", "othervariable", "in", "assignments", ":", "otherdomain", "=", "[", "assignments", "[", "othervariable", "]", "]", "else", ":", "otherdomain", "=", "domains", "[", "othervariable", "]", "if", "domain", ":", "# changed = False", "for", "value", "in", "domain", "[", ":", "]", ":", "assignments", "[", "variable", "]", "=", "value", "if", "otherdomain", ":", "for", "othervalue", "in", "otherdomain", ":", "assignments", "[", "othervariable", "]", "=", "othervalue", "for", "constraint", ",", "variables", "in", "arcconstraints", ":", "if", "not", "constraint", "(", "variables", ",", "domains", ",", "assignments", ",", "True", ")", ":", "break", "else", ":", "# All constraints passed. Value is safe.", "break", "else", ":", "# All othervalues failed. Kill value.", "domain", ".", "hideValue", "(", "value", ")", "# changed = True", "del", "assignments", "[", "othervariable", "]", "del", "assignments", "[", "variable", "]", "# if changed:", "# check.update(dict.fromkeys(arcsvariable))", "if", "not", "domain", ":", "return", "False", "return", "True" ]
Perform the ARC-8 arc checking algorithm and prune domains @attention: Currently unused.
[ "Perform", "the", "ARC", "-", "8", "arc", "checking", "algorithm", "and", "prune", "domains" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L322-L366
train
python-constraint/python-constraint
constraint/__init__.py
Problem.addVariables
def addVariables(self, variables, domain): """ Add one or more variables to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> solutions = problem.getSolutions() >>> len(solutions) 9 >>> {'a': 3, 'b': 1} in solutions True @param variables: Any object containing a sequence of objects represeting problem variables @type variables: sequence of hashable objects @param domain: Set of items defining the possible values that the given variables may assume @type domain: list, tuple, or instance of C{Domain} """ for variable in variables: self.addVariable(variable, domain)
python
def addVariables(self, variables, domain): """ Add one or more variables to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> solutions = problem.getSolutions() >>> len(solutions) 9 >>> {'a': 3, 'b': 1} in solutions True @param variables: Any object containing a sequence of objects represeting problem variables @type variables: sequence of hashable objects @param domain: Set of items defining the possible values that the given variables may assume @type domain: list, tuple, or instance of C{Domain} """ for variable in variables: self.addVariable(variable, domain)
[ "def", "addVariables", "(", "self", ",", "variables", ",", "domain", ")", ":", "for", "variable", "in", "variables", ":", "self", ".", "addVariable", "(", "variable", ",", "domain", ")" ]
Add one or more variables to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> solutions = problem.getSolutions() >>> len(solutions) 9 >>> {'a': 3, 'b': 1} in solutions True @param variables: Any object containing a sequence of objects represeting problem variables @type variables: sequence of hashable objects @param domain: Set of items defining the possible values that the given variables may assume @type domain: list, tuple, or instance of C{Domain}
[ "Add", "one", "or", "more", "variables", "to", "the", "problem" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L160-L182
train
python-constraint/python-constraint
constraint/__init__.py
Problem.addConstraint
def addConstraint(self, constraint, variables=None): """ Add a constraint to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"]) >>> solutions = problem.getSolutions() >>> @param constraint: Constraint to be included in the problem @type constraint: instance a L{Constraint} subclass or a function to be wrapped by L{FunctionConstraint} @param variables: Variables affected by the constraint (default to all variables). Depending on the constraint type the order may be important. @type variables: set or sequence of variables """ if not isinstance(constraint, Constraint): if callable(constraint): constraint = FunctionConstraint(constraint) else: msg = "Constraints must be instances of subclasses " "of the Constraint class" raise ValueError(msg) self._constraints.append((constraint, variables))
python
def addConstraint(self, constraint, variables=None): """ Add a constraint to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"]) >>> solutions = problem.getSolutions() >>> @param constraint: Constraint to be included in the problem @type constraint: instance a L{Constraint} subclass or a function to be wrapped by L{FunctionConstraint} @param variables: Variables affected by the constraint (default to all variables). Depending on the constraint type the order may be important. @type variables: set or sequence of variables """ if not isinstance(constraint, Constraint): if callable(constraint): constraint = FunctionConstraint(constraint) else: msg = "Constraints must be instances of subclasses " "of the Constraint class" raise ValueError(msg) self._constraints.append((constraint, variables))
[ "def", "addConstraint", "(", "self", ",", "constraint", ",", "variables", "=", "None", ")", ":", "if", "not", "isinstance", "(", "constraint", ",", "Constraint", ")", ":", "if", "callable", "(", "constraint", ")", ":", "constraint", "=", "FunctionConstraint", "(", "constraint", ")", "else", ":", "msg", "=", "\"Constraints must be instances of subclasses \"", "\"of the Constraint class\"", "raise", "ValueError", "(", "msg", ")", "self", ".", "_constraints", ".", "append", "(", "(", "constraint", ",", "variables", ")", ")" ]
Add a constraint to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"]) >>> solutions = problem.getSolutions() >>> @param constraint: Constraint to be included in the problem @type constraint: instance a L{Constraint} subclass or a function to be wrapped by L{FunctionConstraint} @param variables: Variables affected by the constraint (default to all variables). Depending on the constraint type the order may be important. @type variables: set or sequence of variables
[ "Add", "a", "constraint", "to", "the", "problem" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L184-L210
train
python-constraint/python-constraint
constraint/__init__.py
Problem.getSolution
def getSolution(self): """ Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} @return: Solution for the problem @rtype: dictionary mapping variables to values """ domains, constraints, vconstraints = self._getArgs() if not domains: return None return self._solver.getSolution(domains, constraints, vconstraints)
python
def getSolution(self): """ Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} @return: Solution for the problem @rtype: dictionary mapping variables to values """ domains, constraints, vconstraints = self._getArgs() if not domains: return None return self._solver.getSolution(domains, constraints, vconstraints)
[ "def", "getSolution", "(", "self", ")", ":", "domains", ",", "constraints", ",", "vconstraints", "=", "self", ".", "_getArgs", "(", ")", "if", "not", "domains", ":", "return", "None", "return", "self", ".", "_solver", ".", "getSolution", "(", "domains", ",", "constraints", ",", "vconstraints", ")" ]
Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} @return: Solution for the problem @rtype: dictionary mapping variables to values
[ "Find", "and", "return", "a", "solution", "to", "the", "problem" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L212-L231
train
python-constraint/python-constraint
constraint/__init__.py
Problem.getSolutions
def getSolutions(self): """ Find and return all solutions to the problem Example: >>> problem = Problem() >>> problem.getSolutions() == [] True >>> problem.addVariables(["a"], [42]) >>> problem.getSolutions() [{'a': 42}] @return: All solutions for the problem @rtype: list of dictionaries mapping variables to values """ domains, constraints, vconstraints = self._getArgs() if not domains: return [] return self._solver.getSolutions(domains, constraints, vconstraints)
python
def getSolutions(self): """ Find and return all solutions to the problem Example: >>> problem = Problem() >>> problem.getSolutions() == [] True >>> problem.addVariables(["a"], [42]) >>> problem.getSolutions() [{'a': 42}] @return: All solutions for the problem @rtype: list of dictionaries mapping variables to values """ domains, constraints, vconstraints = self._getArgs() if not domains: return [] return self._solver.getSolutions(domains, constraints, vconstraints)
[ "def", "getSolutions", "(", "self", ")", ":", "domains", ",", "constraints", ",", "vconstraints", "=", "self", ".", "_getArgs", "(", ")", "if", "not", "domains", ":", "return", "[", "]", "return", "self", ".", "_solver", ".", "getSolutions", "(", "domains", ",", "constraints", ",", "vconstraints", ")" ]
Find and return all solutions to the problem Example: >>> problem = Problem() >>> problem.getSolutions() == [] True >>> problem.addVariables(["a"], [42]) >>> problem.getSolutions() [{'a': 42}] @return: All solutions for the problem @rtype: list of dictionaries mapping variables to values
[ "Find", "and", "return", "all", "solutions", "to", "the", "problem" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L233-L252
train
python-constraint/python-constraint
constraint/__init__.py
Problem.getSolutionIter
def getSolutionIter(self): """ Return an iterator to the solutions of the problem Example: >>> problem = Problem() >>> list(problem.getSolutionIter()) == [] True >>> problem.addVariables(["a"], [42]) >>> iter = problem.getSolutionIter() >>> next(iter) {'a': 42} >>> next(iter) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration """ domains, constraints, vconstraints = self._getArgs() if not domains: return iter(()) return self._solver.getSolutionIter(domains, constraints, vconstraints)
python
def getSolutionIter(self): """ Return an iterator to the solutions of the problem Example: >>> problem = Problem() >>> list(problem.getSolutionIter()) == [] True >>> problem.addVariables(["a"], [42]) >>> iter = problem.getSolutionIter() >>> next(iter) {'a': 42} >>> next(iter) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration """ domains, constraints, vconstraints = self._getArgs() if not domains: return iter(()) return self._solver.getSolutionIter(domains, constraints, vconstraints)
[ "def", "getSolutionIter", "(", "self", ")", ":", "domains", ",", "constraints", ",", "vconstraints", "=", "self", ".", "_getArgs", "(", ")", "if", "not", "domains", ":", "return", "iter", "(", "(", ")", ")", "return", "self", ".", "_solver", ".", "getSolutionIter", "(", "domains", ",", "constraints", ",", "vconstraints", ")" ]
Return an iterator to the solutions of the problem Example: >>> problem = Problem() >>> list(problem.getSolutionIter()) == [] True >>> problem.addVariables(["a"], [42]) >>> iter = problem.getSolutionIter() >>> next(iter) {'a': 42} >>> next(iter) Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration
[ "Return", "an", "iterator", "to", "the", "solutions", "of", "the", "problem" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L254-L275
train
python-constraint/python-constraint
constraint/__init__.py
Solver.getSolution
def getSolution(self, domains, constraints, vconstraints): """ Return one solution for the given problem @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting the given variables. @type vconstraints: dict """ msg = "%s is an abstract class" % self.__class__.__name__ raise NotImplementedError(msg)
python
def getSolution(self, domains, constraints, vconstraints): """ Return one solution for the given problem @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting the given variables. @type vconstraints: dict """ msg = "%s is an abstract class" % self.__class__.__name__ raise NotImplementedError(msg)
[ "def", "getSolution", "(", "self", ",", "domains", ",", "constraints", ",", "vconstraints", ")", ":", "msg", "=", "\"%s is an abstract class\"", "%", "self", ".", "__class__", ".", "__name__", "raise", "NotImplementedError", "(", "msg", ")" ]
Return one solution for the given problem @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting the given variables. @type vconstraints: dict
[ "Return", "one", "solution", "for", "the", "given", "problem" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L373-L386
train
python-constraint/python-constraint
constraint/__init__.py
Domain.resetState
def resetState(self): """ Reset to the original domain state, including all possible values """ self.extend(self._hidden) del self._hidden[:] del self._states[:]
python
def resetState(self): """ Reset to the original domain state, including all possible values """ self.extend(self._hidden) del self._hidden[:] del self._states[:]
[ "def", "resetState", "(", "self", ")", ":", "self", ".", "extend", "(", "self", ".", "_hidden", ")", "del", "self", ".", "_hidden", "[", ":", "]", "del", "self", ".", "_states", "[", ":", "]" ]
Reset to the original domain state, including all possible values
[ "Reset", "to", "the", "original", "domain", "state", "including", "all", "possible", "values" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L770-L776
train
python-constraint/python-constraint
constraint/__init__.py
Domain.popState
def popState(self): """ Restore domain state from the top of the stack Variables hidden since the last popped state are then available again. """ diff = self._states.pop() - len(self) if diff: self.extend(self._hidden[-diff:]) del self._hidden[-diff:]
python
def popState(self): """ Restore domain state from the top of the stack Variables hidden since the last popped state are then available again. """ diff = self._states.pop() - len(self) if diff: self.extend(self._hidden[-diff:]) del self._hidden[-diff:]
[ "def", "popState", "(", "self", ")", ":", "diff", "=", "self", ".", "_states", ".", "pop", "(", ")", "-", "len", "(", "self", ")", "if", "diff", ":", "self", ".", "extend", "(", "self", ".", "_hidden", "[", "-", "diff", ":", "]", ")", "del", "self", ".", "_hidden", "[", "-", "diff", ":", "]" ]
Restore domain state from the top of the stack Variables hidden since the last popped state are then available again.
[ "Restore", "domain", "state", "from", "the", "top", "of", "the", "stack" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L787-L797
train
python-constraint/python-constraint
constraint/__init__.py
Domain.hideValue
def hideValue(self, value): """ Hide the given value from the domain After that call the given value won't be seen as a possible value on that domain anymore. The hidden value will be restored when the previous saved state is popped. @param value: Object currently available in the domain """ list.remove(self, value) self._hidden.append(value)
python
def hideValue(self, value): """ Hide the given value from the domain After that call the given value won't be seen as a possible value on that domain anymore. The hidden value will be restored when the previous saved state is popped. @param value: Object currently available in the domain """ list.remove(self, value) self._hidden.append(value)
[ "def", "hideValue", "(", "self", ",", "value", ")", ":", "list", ".", "remove", "(", "self", ",", "value", ")", "self", ".", "_hidden", ".", "append", "(", "value", ")" ]
Hide the given value from the domain After that call the given value won't be seen as a possible value on that domain anymore. The hidden value will be restored when the previous saved state is popped. @param value: Object currently available in the domain
[ "Hide", "the", "given", "value", "from", "the", "domain" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L799-L810
train
python-constraint/python-constraint
constraint/__init__.py
Constraint.preProcess
def preProcess(self, variables, domains, constraints, vconstraints): """ Preprocess variable domains This method is called before starting to look for solutions, and is used to prune domains with specific constraint logic when possible. For instance, any constraints with a single variable may be applied on all possible values and removed, since they may act on individual values even without further knowledge about other assignments. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting the given variables. @type vconstraints: dict """ if len(variables) == 1: variable = variables[0] domain = domains[variable] for value in domain[:]: if not self(variables, domains, {variable: value}): domain.remove(value) constraints.remove((self, variables)) vconstraints[variable].remove((self, variables))
python
def preProcess(self, variables, domains, constraints, vconstraints): """ Preprocess variable domains This method is called before starting to look for solutions, and is used to prune domains with specific constraint logic when possible. For instance, any constraints with a single variable may be applied on all possible values and removed, since they may act on individual values even without further knowledge about other assignments. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting the given variables. @type vconstraints: dict """ if len(variables) == 1: variable = variables[0] domain = domains[variable] for value in domain[:]: if not self(variables, domains, {variable: value}): domain.remove(value) constraints.remove((self, variables)) vconstraints[variable].remove((self, variables))
[ "def", "preProcess", "(", "self", ",", "variables", ",", "domains", ",", "constraints", ",", "vconstraints", ")", ":", "if", "len", "(", "variables", ")", "==", "1", ":", "variable", "=", "variables", "[", "0", "]", "domain", "=", "domains", "[", "variable", "]", "for", "value", "in", "domain", "[", ":", "]", ":", "if", "not", "self", "(", "variables", ",", "domains", ",", "{", "variable", ":", "value", "}", ")", ":", "domain", ".", "remove", "(", "value", ")", "constraints", ".", "remove", "(", "(", "self", ",", "variables", ")", ")", "vconstraints", "[", "variable", "]", ".", "remove", "(", "(", "self", ",", "variables", ")", ")" ]
Preprocess variable domains This method is called before starting to look for solutions, and is used to prune domains with specific constraint logic when possible. For instance, any constraints with a single variable may be applied on all possible values and removed, since they may act on individual values even without further knowledge about other assignments. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param domains: Dictionary mapping variables to their domains @type domains: dict @param constraints: List of pairs of (constraint, variables) @type constraints: list @param vconstraints: Dictionary mapping variables to a list of constraints affecting the given variables. @type vconstraints: dict
[ "Preprocess", "variable", "domains" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L849-L878
train
python-constraint/python-constraint
constraint/__init__.py
Constraint.forwardCheck
def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned): """ Helper method for generic forward checking Currently, this method acts only when there's a single unassigned variable. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param domains: Dictionary mapping variables to their domains @type domains: dict @param assignments: Dictionary mapping assigned variables to their current assumed value @type assignments: dict @return: Boolean value stating if this constraint is currently broken or not @rtype: bool """ unassignedvariable = _unassigned for variable in variables: if variable not in assignments: if unassignedvariable is _unassigned: unassignedvariable = variable else: break else: if unassignedvariable is not _unassigned: # Remove from the unassigned variable domain's all # values which break our variable's constraints. domain = domains[unassignedvariable] if domain: for value in domain[:]: assignments[unassignedvariable] = value if not self(variables, domains, assignments): domain.hideValue(value) del assignments[unassignedvariable] if not domain: return False return True
python
def forwardCheck(self, variables, domains, assignments, _unassigned=Unassigned): """ Helper method for generic forward checking Currently, this method acts only when there's a single unassigned variable. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param domains: Dictionary mapping variables to their domains @type domains: dict @param assignments: Dictionary mapping assigned variables to their current assumed value @type assignments: dict @return: Boolean value stating if this constraint is currently broken or not @rtype: bool """ unassignedvariable = _unassigned for variable in variables: if variable not in assignments: if unassignedvariable is _unassigned: unassignedvariable = variable else: break else: if unassignedvariable is not _unassigned: # Remove from the unassigned variable domain's all # values which break our variable's constraints. domain = domains[unassignedvariable] if domain: for value in domain[:]: assignments[unassignedvariable] = value if not self(variables, domains, assignments): domain.hideValue(value) del assignments[unassignedvariable] if not domain: return False return True
[ "def", "forwardCheck", "(", "self", ",", "variables", ",", "domains", ",", "assignments", ",", "_unassigned", "=", "Unassigned", ")", ":", "unassignedvariable", "=", "_unassigned", "for", "variable", "in", "variables", ":", "if", "variable", "not", "in", "assignments", ":", "if", "unassignedvariable", "is", "_unassigned", ":", "unassignedvariable", "=", "variable", "else", ":", "break", "else", ":", "if", "unassignedvariable", "is", "not", "_unassigned", ":", "# Remove from the unassigned variable domain's all", "# values which break our variable's constraints.", "domain", "=", "domains", "[", "unassignedvariable", "]", "if", "domain", ":", "for", "value", "in", "domain", "[", ":", "]", ":", "assignments", "[", "unassignedvariable", "]", "=", "value", "if", "not", "self", "(", "variables", ",", "domains", ",", "assignments", ")", ":", "domain", ".", "hideValue", "(", "value", ")", "del", "assignments", "[", "unassignedvariable", "]", "if", "not", "domain", ":", "return", "False", "return", "True" ]
Helper method for generic forward checking Currently, this method acts only when there's a single unassigned variable. @param variables: Variables affected by that constraint, in the same order provided by the user @type variables: sequence @param domains: Dictionary mapping variables to their domains @type domains: dict @param assignments: Dictionary mapping assigned variables to their current assumed value @type assignments: dict @return: Boolean value stating if this constraint is currently broken or not @rtype: bool
[ "Helper", "method", "for", "generic", "forward", "checking" ]
e23fe9852cddddf1c3e258e03f2175df24b4c702
https://github.com/python-constraint/python-constraint/blob/e23fe9852cddddf1c3e258e03f2175df24b4c702/constraint/__init__.py#L880-L919
train
kencochrane/django-defender
defender/views.py
block_view
def block_view(request): """ List the blocked IP and Usernames """ blocked_ip_list = get_blocked_ips() blocked_username_list = get_blocked_usernames() context = {'blocked_ip_list': blocked_ip_list, 'blocked_username_list': blocked_username_list} return render(request, 'defender/admin/blocks.html', context)
python
def block_view(request): """ List the blocked IP and Usernames """ blocked_ip_list = get_blocked_ips() blocked_username_list = get_blocked_usernames() context = {'blocked_ip_list': blocked_ip_list, 'blocked_username_list': blocked_username_list} return render(request, 'defender/admin/blocks.html', context)
[ "def", "block_view", "(", "request", ")", ":", "blocked_ip_list", "=", "get_blocked_ips", "(", ")", "blocked_username_list", "=", "get_blocked_usernames", "(", ")", "context", "=", "{", "'blocked_ip_list'", ":", "blocked_ip_list", ",", "'blocked_username_list'", ":", "blocked_username_list", "}", "return", "render", "(", "request", ",", "'defender/admin/blocks.html'", ",", "context", ")" ]
List the blocked IP and Usernames
[ "List", "the", "blocked", "IP", "and", "Usernames" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/views.py#L14-L21
train
kencochrane/django-defender
defender/utils.py
get_ip
def get_ip(request): """ get the ip address from the request """ if config.BEHIND_REVERSE_PROXY: ip_address = request.META.get(config.REVERSE_PROXY_HEADER, '') ip_address = ip_address.split(",", 1)[0].strip() if ip_address == '': ip_address = get_ip_address_from_request(request) else: ip_address = get_ip_address_from_request(request) return ip_address
python
def get_ip(request): """ get the ip address from the request """ if config.BEHIND_REVERSE_PROXY: ip_address = request.META.get(config.REVERSE_PROXY_HEADER, '') ip_address = ip_address.split(",", 1)[0].strip() if ip_address == '': ip_address = get_ip_address_from_request(request) else: ip_address = get_ip_address_from_request(request) return ip_address
[ "def", "get_ip", "(", "request", ")", ":", "if", "config", ".", "BEHIND_REVERSE_PROXY", ":", "ip_address", "=", "request", ".", "META", ".", "get", "(", "config", ".", "REVERSE_PROXY_HEADER", ",", "''", ")", "ip_address", "=", "ip_address", ".", "split", "(", "\",\"", ",", "1", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "ip_address", "==", "''", ":", "ip_address", "=", "get_ip_address_from_request", "(", "request", ")", "else", ":", "ip_address", "=", "get_ip_address_from_request", "(", "request", ")", "return", "ip_address" ]
get the ip address from the request
[ "get", "the", "ip", "address", "from", "the", "request" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L41-L50
train
kencochrane/django-defender
defender/utils.py
get_blocked_ips
def get_blocked_ips(): """ get a list of blocked ips from redis """ if config.DISABLE_IP_LOCKOUT: # There are no blocked IP's since we disabled them. return [] key = get_ip_blocked_cache_key("*") key_list = [redis_key.decode('utf-8') for redis_key in REDIS_SERVER.keys(key)] return strip_keys(key_list)
python
def get_blocked_ips(): """ get a list of blocked ips from redis """ if config.DISABLE_IP_LOCKOUT: # There are no blocked IP's since we disabled them. return [] key = get_ip_blocked_cache_key("*") key_list = [redis_key.decode('utf-8') for redis_key in REDIS_SERVER.keys(key)] return strip_keys(key_list)
[ "def", "get_blocked_ips", "(", ")", ":", "if", "config", ".", "DISABLE_IP_LOCKOUT", ":", "# There are no blocked IP's since we disabled them.", "return", "[", "]", "key", "=", "get_ip_blocked_cache_key", "(", "\"*\"", ")", "key_list", "=", "[", "redis_key", ".", "decode", "(", "'utf-8'", ")", "for", "redis_key", "in", "REDIS_SERVER", ".", "keys", "(", "key", ")", "]", "return", "strip_keys", "(", "key_list", ")" ]
get a list of blocked ips from redis
[ "get", "a", "list", "of", "blocked", "ips", "from", "redis" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L101-L109
train
kencochrane/django-defender
defender/utils.py
get_blocked_usernames
def get_blocked_usernames(): """ get a list of blocked usernames from redis """ if config.DISABLE_USERNAME_LOCKOUT: # There are no blocked usernames since we disabled them. return [] key = get_username_blocked_cache_key("*") key_list = [redis_key.decode('utf-8') for redis_key in REDIS_SERVER.keys(key)] return strip_keys(key_list)
python
def get_blocked_usernames(): """ get a list of blocked usernames from redis """ if config.DISABLE_USERNAME_LOCKOUT: # There are no blocked usernames since we disabled them. return [] key = get_username_blocked_cache_key("*") key_list = [redis_key.decode('utf-8') for redis_key in REDIS_SERVER.keys(key)] return strip_keys(key_list)
[ "def", "get_blocked_usernames", "(", ")", ":", "if", "config", ".", "DISABLE_USERNAME_LOCKOUT", ":", "# There are no blocked usernames since we disabled them.", "return", "[", "]", "key", "=", "get_username_blocked_cache_key", "(", "\"*\"", ")", "key_list", "=", "[", "redis_key", ".", "decode", "(", "'utf-8'", ")", "for", "redis_key", "in", "REDIS_SERVER", ".", "keys", "(", "key", ")", "]", "return", "strip_keys", "(", "key_list", ")" ]
get a list of blocked usernames from redis
[ "get", "a", "list", "of", "blocked", "usernames", "from", "redis" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L112-L120
train
kencochrane/django-defender
defender/utils.py
increment_key
def increment_key(key): """ given a key increment the value """ pipe = REDIS_SERVER.pipeline() pipe.incr(key, 1) if config.COOLOFF_TIME: pipe.expire(key, config.COOLOFF_TIME) new_value = pipe.execute()[0] return new_value
python
def increment_key(key): """ given a key increment the value """ pipe = REDIS_SERVER.pipeline() pipe.incr(key, 1) if config.COOLOFF_TIME: pipe.expire(key, config.COOLOFF_TIME) new_value = pipe.execute()[0] return new_value
[ "def", "increment_key", "(", "key", ")", ":", "pipe", "=", "REDIS_SERVER", ".", "pipeline", "(", ")", "pipe", ".", "incr", "(", "key", ",", "1", ")", "if", "config", ".", "COOLOFF_TIME", ":", "pipe", ".", "expire", "(", "key", ",", "config", ".", "COOLOFF_TIME", ")", "new_value", "=", "pipe", ".", "execute", "(", ")", "[", "0", "]", "return", "new_value" ]
given a key increment the value
[ "given", "a", "key", "increment", "the", "value" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L123-L130
train
kencochrane/django-defender
defender/utils.py
username_from_request
def username_from_request(request): """ unloads username from default POST request """ if config.USERNAME_FORM_FIELD in request.POST: return request.POST[config.USERNAME_FORM_FIELD][:255] return None
python
def username_from_request(request): """ unloads username from default POST request """ if config.USERNAME_FORM_FIELD in request.POST: return request.POST[config.USERNAME_FORM_FIELD][:255] return None
[ "def", "username_from_request", "(", "request", ")", ":", "if", "config", ".", "USERNAME_FORM_FIELD", "in", "request", ".", "POST", ":", "return", "request", ".", "POST", "[", "config", ".", "USERNAME_FORM_FIELD", "]", "[", ":", "255", "]", "return", "None" ]
unloads username from default POST request
[ "unloads", "username", "from", "default", "POST", "request" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L133-L137
train
kencochrane/django-defender
defender/utils.py
get_user_attempts
def get_user_attempts(request, get_username=get_username_from_request, username=None): """ Returns number of access attempts for this ip, username """ ip_address = get_ip(request) username = lower_username(username or get_username(request)) # get by IP ip_count = REDIS_SERVER.get(get_ip_attempt_cache_key(ip_address)) if not ip_count: ip_count = 0 ip_count = int(ip_count) # get by username username_count = REDIS_SERVER.get(get_username_attempt_cache_key(username)) if not username_count: username_count = 0 username_count = int(username_count) # return the larger of the two. return max(ip_count, username_count)
python
def get_user_attempts(request, get_username=get_username_from_request, username=None): """ Returns number of access attempts for this ip, username """ ip_address = get_ip(request) username = lower_username(username or get_username(request)) # get by IP ip_count = REDIS_SERVER.get(get_ip_attempt_cache_key(ip_address)) if not ip_count: ip_count = 0 ip_count = int(ip_count) # get by username username_count = REDIS_SERVER.get(get_username_attempt_cache_key(username)) if not username_count: username_count = 0 username_count = int(username_count) # return the larger of the two. return max(ip_count, username_count)
[ "def", "get_user_attempts", "(", "request", ",", "get_username", "=", "get_username_from_request", ",", "username", "=", "None", ")", ":", "ip_address", "=", "get_ip", "(", "request", ")", "username", "=", "lower_username", "(", "username", "or", "get_username", "(", "request", ")", ")", "# get by IP", "ip_count", "=", "REDIS_SERVER", ".", "get", "(", "get_ip_attempt_cache_key", "(", "ip_address", ")", ")", "if", "not", "ip_count", ":", "ip_count", "=", "0", "ip_count", "=", "int", "(", "ip_count", ")", "# get by username", "username_count", "=", "REDIS_SERVER", ".", "get", "(", "get_username_attempt_cache_key", "(", "username", ")", ")", "if", "not", "username_count", ":", "username_count", "=", "0", "username_count", "=", "int", "(", "username_count", ")", "# return the larger of the two.", "return", "max", "(", "ip_count", ",", "username_count", ")" ]
Returns number of access attempts for this ip, username
[ "Returns", "number", "of", "access", "attempts", "for", "this", "ip", "username" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L145-L165
train
kencochrane/django-defender
defender/utils.py
block_ip
def block_ip(ip_address): """ given the ip, block it """ if not ip_address: # no reason to continue when there is no ip return if config.DISABLE_IP_LOCKOUT: # no need to block, we disabled it. return key = get_ip_blocked_cache_key(ip_address) if config.COOLOFF_TIME: REDIS_SERVER.set(key, 'blocked', config.COOLOFF_TIME) else: REDIS_SERVER.set(key, 'blocked') send_ip_block_signal(ip_address)
python
def block_ip(ip_address): """ given the ip, block it """ if not ip_address: # no reason to continue when there is no ip return if config.DISABLE_IP_LOCKOUT: # no need to block, we disabled it. return key = get_ip_blocked_cache_key(ip_address) if config.COOLOFF_TIME: REDIS_SERVER.set(key, 'blocked', config.COOLOFF_TIME) else: REDIS_SERVER.set(key, 'blocked') send_ip_block_signal(ip_address)
[ "def", "block_ip", "(", "ip_address", ")", ":", "if", "not", "ip_address", ":", "# no reason to continue when there is no ip", "return", "if", "config", ".", "DISABLE_IP_LOCKOUT", ":", "# no need to block, we disabled it.", "return", "key", "=", "get_ip_blocked_cache_key", "(", "ip_address", ")", "if", "config", ".", "COOLOFF_TIME", ":", "REDIS_SERVER", ".", "set", "(", "key", ",", "'blocked'", ",", "config", ".", "COOLOFF_TIME", ")", "else", ":", "REDIS_SERVER", ".", "set", "(", "key", ",", "'blocked'", ")", "send_ip_block_signal", "(", "ip_address", ")" ]
given the ip, block it
[ "given", "the", "ip", "block", "it" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L168-L181
train
kencochrane/django-defender
defender/utils.py
block_username
def block_username(username): """ given the username block it. """ if not username: # no reason to continue when there is no username return if config.DISABLE_USERNAME_LOCKOUT: # no need to block, we disabled it. return key = get_username_blocked_cache_key(username) if config.COOLOFF_TIME: REDIS_SERVER.set(key, 'blocked', config.COOLOFF_TIME) else: REDIS_SERVER.set(key, 'blocked') send_username_block_signal(username)
python
def block_username(username): """ given the username block it. """ if not username: # no reason to continue when there is no username return if config.DISABLE_USERNAME_LOCKOUT: # no need to block, we disabled it. return key = get_username_blocked_cache_key(username) if config.COOLOFF_TIME: REDIS_SERVER.set(key, 'blocked', config.COOLOFF_TIME) else: REDIS_SERVER.set(key, 'blocked') send_username_block_signal(username)
[ "def", "block_username", "(", "username", ")", ":", "if", "not", "username", ":", "# no reason to continue when there is no username", "return", "if", "config", ".", "DISABLE_USERNAME_LOCKOUT", ":", "# no need to block, we disabled it.", "return", "key", "=", "get_username_blocked_cache_key", "(", "username", ")", "if", "config", ".", "COOLOFF_TIME", ":", "REDIS_SERVER", ".", "set", "(", "key", ",", "'blocked'", ",", "config", ".", "COOLOFF_TIME", ")", "else", ":", "REDIS_SERVER", ".", "set", "(", "key", ",", "'blocked'", ")", "send_username_block_signal", "(", "username", ")" ]
given the username block it.
[ "given", "the", "username", "block", "it", "." ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L184-L197
train
kencochrane/django-defender
defender/utils.py
record_failed_attempt
def record_failed_attempt(ip_address, username): """ record the failed login attempt, if over limit return False, if not over limit return True """ # increment the failed count, and get current number ip_block = False if not config.DISABLE_IP_LOCKOUT: # we only want to increment the IP if this is disabled. ip_count = increment_key(get_ip_attempt_cache_key(ip_address)) # if over the limit, add to block if ip_count > config.IP_FAILURE_LIMIT: block_ip(ip_address) ip_block = True user_block = False if username and not config.DISABLE_USERNAME_LOCKOUT: user_count = increment_key(get_username_attempt_cache_key(username)) # if over the limit, add to block if user_count > config.USERNAME_FAILURE_LIMIT: block_username(username) user_block = True # if we have this turned on, then there is no reason to look at ip_block # we will just look at user_block, and short circut the result since # we don't need to continue. if config.DISABLE_IP_LOCKOUT: # if user_block is True, it means it was blocked # we need to return False return not user_block if config.DISABLE_USERNAME_LOCKOUT: # The same as DISABLE_IP_LOCKOUT return not ip_block # we want to make sure both the IP and user is blocked before we # return False # this is mostly used when a lot of your users are using proxies, # and you don't want one user to block everyone on that one IP. if config.LOCKOUT_BY_IP_USERNAME: # both ip_block and user_block need to be True in order # to return a False. return not (ip_block and user_block) # if any blocks return False, no blocks. return True return not (ip_block or user_block)
python
def record_failed_attempt(ip_address, username): """ record the failed login attempt, if over limit return False, if not over limit return True """ # increment the failed count, and get current number ip_block = False if not config.DISABLE_IP_LOCKOUT: # we only want to increment the IP if this is disabled. ip_count = increment_key(get_ip_attempt_cache_key(ip_address)) # if over the limit, add to block if ip_count > config.IP_FAILURE_LIMIT: block_ip(ip_address) ip_block = True user_block = False if username and not config.DISABLE_USERNAME_LOCKOUT: user_count = increment_key(get_username_attempt_cache_key(username)) # if over the limit, add to block if user_count > config.USERNAME_FAILURE_LIMIT: block_username(username) user_block = True # if we have this turned on, then there is no reason to look at ip_block # we will just look at user_block, and short circut the result since # we don't need to continue. if config.DISABLE_IP_LOCKOUT: # if user_block is True, it means it was blocked # we need to return False return not user_block if config.DISABLE_USERNAME_LOCKOUT: # The same as DISABLE_IP_LOCKOUT return not ip_block # we want to make sure both the IP and user is blocked before we # return False # this is mostly used when a lot of your users are using proxies, # and you don't want one user to block everyone on that one IP. if config.LOCKOUT_BY_IP_USERNAME: # both ip_block and user_block need to be True in order # to return a False. return not (ip_block and user_block) # if any blocks return False, no blocks. return True return not (ip_block or user_block)
[ "def", "record_failed_attempt", "(", "ip_address", ",", "username", ")", ":", "# increment the failed count, and get current number", "ip_block", "=", "False", "if", "not", "config", ".", "DISABLE_IP_LOCKOUT", ":", "# we only want to increment the IP if this is disabled.", "ip_count", "=", "increment_key", "(", "get_ip_attempt_cache_key", "(", "ip_address", ")", ")", "# if over the limit, add to block", "if", "ip_count", ">", "config", ".", "IP_FAILURE_LIMIT", ":", "block_ip", "(", "ip_address", ")", "ip_block", "=", "True", "user_block", "=", "False", "if", "username", "and", "not", "config", ".", "DISABLE_USERNAME_LOCKOUT", ":", "user_count", "=", "increment_key", "(", "get_username_attempt_cache_key", "(", "username", ")", ")", "# if over the limit, add to block", "if", "user_count", ">", "config", ".", "USERNAME_FAILURE_LIMIT", ":", "block_username", "(", "username", ")", "user_block", "=", "True", "# if we have this turned on, then there is no reason to look at ip_block", "# we will just look at user_block, and short circut the result since", "# we don't need to continue.", "if", "config", ".", "DISABLE_IP_LOCKOUT", ":", "# if user_block is True, it means it was blocked", "# we need to return False", "return", "not", "user_block", "if", "config", ".", "DISABLE_USERNAME_LOCKOUT", ":", "# The same as DISABLE_IP_LOCKOUT", "return", "not", "ip_block", "# we want to make sure both the IP and user is blocked before we", "# return False", "# this is mostly used when a lot of your users are using proxies,", "# and you don't want one user to block everyone on that one IP.", "if", "config", ".", "LOCKOUT_BY_IP_USERNAME", ":", "# both ip_block and user_block need to be True in order", "# to return a False.", "return", "not", "(", "ip_block", "and", "user_block", ")", "# if any blocks return False, no blocks. return True", "return", "not", "(", "ip_block", "or", "user_block", ")" ]
record the failed login attempt, if over limit return False, if not over limit return True
[ "record", "the", "failed", "login", "attempt", "if", "over", "limit", "return", "False", "if", "not", "over", "limit", "return", "True" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L200-L243
train
kencochrane/django-defender
defender/utils.py
unblock_ip
def unblock_ip(ip_address, pipe=None): """ unblock the given IP """ do_commit = False if not pipe: pipe = REDIS_SERVER.pipeline() do_commit = True if ip_address: pipe.delete(get_ip_attempt_cache_key(ip_address)) pipe.delete(get_ip_blocked_cache_key(ip_address)) if do_commit: pipe.execute()
python
def unblock_ip(ip_address, pipe=None): """ unblock the given IP """ do_commit = False if not pipe: pipe = REDIS_SERVER.pipeline() do_commit = True if ip_address: pipe.delete(get_ip_attempt_cache_key(ip_address)) pipe.delete(get_ip_blocked_cache_key(ip_address)) if do_commit: pipe.execute()
[ "def", "unblock_ip", "(", "ip_address", ",", "pipe", "=", "None", ")", ":", "do_commit", "=", "False", "if", "not", "pipe", ":", "pipe", "=", "REDIS_SERVER", ".", "pipeline", "(", ")", "do_commit", "=", "True", "if", "ip_address", ":", "pipe", ".", "delete", "(", "get_ip_attempt_cache_key", "(", "ip_address", ")", ")", "pipe", ".", "delete", "(", "get_ip_blocked_cache_key", "(", "ip_address", ")", ")", "if", "do_commit", ":", "pipe", ".", "execute", "(", ")" ]
unblock the given IP
[ "unblock", "the", "given", "IP" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L246-L256
train
kencochrane/django-defender
defender/utils.py
unblock_username
def unblock_username(username, pipe=None): """ unblock the given Username """ do_commit = False if not pipe: pipe = REDIS_SERVER.pipeline() do_commit = True if username: pipe.delete(get_username_attempt_cache_key(username)) pipe.delete(get_username_blocked_cache_key(username)) if do_commit: pipe.execute()
python
def unblock_username(username, pipe=None): """ unblock the given Username """ do_commit = False if not pipe: pipe = REDIS_SERVER.pipeline() do_commit = True if username: pipe.delete(get_username_attempt_cache_key(username)) pipe.delete(get_username_blocked_cache_key(username)) if do_commit: pipe.execute()
[ "def", "unblock_username", "(", "username", ",", "pipe", "=", "None", ")", ":", "do_commit", "=", "False", "if", "not", "pipe", ":", "pipe", "=", "REDIS_SERVER", ".", "pipeline", "(", ")", "do_commit", "=", "True", "if", "username", ":", "pipe", ".", "delete", "(", "get_username_attempt_cache_key", "(", "username", ")", ")", "pipe", ".", "delete", "(", "get_username_blocked_cache_key", "(", "username", ")", ")", "if", "do_commit", ":", "pipe", ".", "execute", "(", ")" ]
unblock the given Username
[ "unblock", "the", "given", "Username" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L259-L269
train
kencochrane/django-defender
defender/utils.py
reset_failed_attempts
def reset_failed_attempts(ip_address=None, username=None): """ reset the failed attempts for these ip's and usernames """ pipe = REDIS_SERVER.pipeline() unblock_ip(ip_address, pipe=pipe) unblock_username(username, pipe=pipe) pipe.execute()
python
def reset_failed_attempts(ip_address=None, username=None): """ reset the failed attempts for these ip's and usernames """ pipe = REDIS_SERVER.pipeline() unblock_ip(ip_address, pipe=pipe) unblock_username(username, pipe=pipe) pipe.execute()
[ "def", "reset_failed_attempts", "(", "ip_address", "=", "None", ",", "username", "=", "None", ")", ":", "pipe", "=", "REDIS_SERVER", ".", "pipeline", "(", ")", "unblock_ip", "(", "ip_address", ",", "pipe", "=", "pipe", ")", "unblock_username", "(", "username", ",", "pipe", "=", "pipe", ")", "pipe", ".", "execute", "(", ")" ]
reset the failed attempts for these ip's and usernames
[ "reset", "the", "failed", "attempts", "for", "these", "ip", "s", "and", "usernames" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L272-L280
train
kencochrane/django-defender
defender/utils.py
lockout_response
def lockout_response(request): """ if we are locked out, here is the response """ if config.LOCKOUT_TEMPLATE: context = { 'cooloff_time_seconds': config.COOLOFF_TIME, 'cooloff_time_minutes': config.COOLOFF_TIME / 60, 'failure_limit': config.FAILURE_LIMIT, } return render(request, config.LOCKOUT_TEMPLATE, context) if config.LOCKOUT_URL: return HttpResponseRedirect(config.LOCKOUT_URL) if config.COOLOFF_TIME: return HttpResponse("Account locked: too many login attempts. " "Please try again later.") else: return HttpResponse("Account locked: too many login attempts. " "Contact an admin to unlock your account.")
python
def lockout_response(request): """ if we are locked out, here is the response """ if config.LOCKOUT_TEMPLATE: context = { 'cooloff_time_seconds': config.COOLOFF_TIME, 'cooloff_time_minutes': config.COOLOFF_TIME / 60, 'failure_limit': config.FAILURE_LIMIT, } return render(request, config.LOCKOUT_TEMPLATE, context) if config.LOCKOUT_URL: return HttpResponseRedirect(config.LOCKOUT_URL) if config.COOLOFF_TIME: return HttpResponse("Account locked: too many login attempts. " "Please try again later.") else: return HttpResponse("Account locked: too many login attempts. " "Contact an admin to unlock your account.")
[ "def", "lockout_response", "(", "request", ")", ":", "if", "config", ".", "LOCKOUT_TEMPLATE", ":", "context", "=", "{", "'cooloff_time_seconds'", ":", "config", ".", "COOLOFF_TIME", ",", "'cooloff_time_minutes'", ":", "config", ".", "COOLOFF_TIME", "/", "60", ",", "'failure_limit'", ":", "config", ".", "FAILURE_LIMIT", ",", "}", "return", "render", "(", "request", ",", "config", ".", "LOCKOUT_TEMPLATE", ",", "context", ")", "if", "config", ".", "LOCKOUT_URL", ":", "return", "HttpResponseRedirect", "(", "config", ".", "LOCKOUT_URL", ")", "if", "config", ".", "COOLOFF_TIME", ":", "return", "HttpResponse", "(", "\"Account locked: too many login attempts. \"", "\"Please try again later.\"", ")", "else", ":", "return", "HttpResponse", "(", "\"Account locked: too many login attempts. \"", "\"Contact an admin to unlock your account.\"", ")" ]
if we are locked out, here is the response
[ "if", "we", "are", "locked", "out", "here", "is", "the", "response" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L283-L301
train
kencochrane/django-defender
defender/utils.py
is_user_already_locked
def is_user_already_locked(username): """Is this username already locked?""" if username is None: return False if config.DISABLE_USERNAME_LOCKOUT: return False return REDIS_SERVER.get(get_username_blocked_cache_key(username))
python
def is_user_already_locked(username): """Is this username already locked?""" if username is None: return False if config.DISABLE_USERNAME_LOCKOUT: return False return REDIS_SERVER.get(get_username_blocked_cache_key(username))
[ "def", "is_user_already_locked", "(", "username", ")", ":", "if", "username", "is", "None", ":", "return", "False", "if", "config", ".", "DISABLE_USERNAME_LOCKOUT", ":", "return", "False", "return", "REDIS_SERVER", ".", "get", "(", "get_username_blocked_cache_key", "(", "username", ")", ")" ]
Is this username already locked?
[ "Is", "this", "username", "already", "locked?" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L304-L310
train
kencochrane/django-defender
defender/utils.py
is_source_ip_already_locked
def is_source_ip_already_locked(ip_address): """Is this IP already locked?""" if ip_address is None: return False if config.DISABLE_IP_LOCKOUT: return False return REDIS_SERVER.get(get_ip_blocked_cache_key(ip_address))
python
def is_source_ip_already_locked(ip_address): """Is this IP already locked?""" if ip_address is None: return False if config.DISABLE_IP_LOCKOUT: return False return REDIS_SERVER.get(get_ip_blocked_cache_key(ip_address))
[ "def", "is_source_ip_already_locked", "(", "ip_address", ")", ":", "if", "ip_address", "is", "None", ":", "return", "False", "if", "config", ".", "DISABLE_IP_LOCKOUT", ":", "return", "False", "return", "REDIS_SERVER", ".", "get", "(", "get_ip_blocked_cache_key", "(", "ip_address", ")", ")" ]
Is this IP already locked?
[ "Is", "this", "IP", "already", "locked?" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L313-L319
train
kencochrane/django-defender
defender/utils.py
is_already_locked
def is_already_locked(request, get_username=get_username_from_request, username=None): """Parse the username & IP from the request, and see if it's already locked.""" user_blocked = is_user_already_locked(username or get_username(request)) ip_blocked = is_source_ip_already_locked(get_ip(request)) if config.LOCKOUT_BY_IP_USERNAME: # if both this IP and this username are present the request is blocked return ip_blocked and user_blocked return ip_blocked or user_blocked
python
def is_already_locked(request, get_username=get_username_from_request, username=None): """Parse the username & IP from the request, and see if it's already locked.""" user_blocked = is_user_already_locked(username or get_username(request)) ip_blocked = is_source_ip_already_locked(get_ip(request)) if config.LOCKOUT_BY_IP_USERNAME: # if both this IP and this username are present the request is blocked return ip_blocked and user_blocked return ip_blocked or user_blocked
[ "def", "is_already_locked", "(", "request", ",", "get_username", "=", "get_username_from_request", ",", "username", "=", "None", ")", ":", "user_blocked", "=", "is_user_already_locked", "(", "username", "or", "get_username", "(", "request", ")", ")", "ip_blocked", "=", "is_source_ip_already_locked", "(", "get_ip", "(", "request", ")", ")", "if", "config", ".", "LOCKOUT_BY_IP_USERNAME", ":", "# if both this IP and this username are present the request is blocked", "return", "ip_blocked", "and", "user_blocked", "return", "ip_blocked", "or", "user_blocked" ]
Parse the username & IP from the request, and see if it's already locked.
[ "Parse", "the", "username", "&", "IP", "from", "the", "request", "and", "see", "if", "it", "s", "already", "locked", "." ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L322-L332
train
kencochrane/django-defender
defender/utils.py
check_request
def check_request(request, login_unsuccessful, get_username=get_username_from_request, username=None): """ check the request, and process results""" ip_address = get_ip(request) username = username or get_username(request) if not login_unsuccessful: # user logged in -- forget the failed attempts reset_failed_attempts(ip_address=ip_address, username=username) return True else: # add a failed attempt for this user return record_failed_attempt(ip_address, username)
python
def check_request(request, login_unsuccessful, get_username=get_username_from_request, username=None): """ check the request, and process results""" ip_address = get_ip(request) username = username or get_username(request) if not login_unsuccessful: # user logged in -- forget the failed attempts reset_failed_attempts(ip_address=ip_address, username=username) return True else: # add a failed attempt for this user return record_failed_attempt(ip_address, username)
[ "def", "check_request", "(", "request", ",", "login_unsuccessful", ",", "get_username", "=", "get_username_from_request", ",", "username", "=", "None", ")", ":", "ip_address", "=", "get_ip", "(", "request", ")", "username", "=", "username", "or", "get_username", "(", "request", ")", "if", "not", "login_unsuccessful", ":", "# user logged in -- forget the failed attempts", "reset_failed_attempts", "(", "ip_address", "=", "ip_address", ",", "username", "=", "username", ")", "return", "True", "else", ":", "# add a failed attempt for this user", "return", "record_failed_attempt", "(", "ip_address", ",", "username", ")" ]
check the request, and process results
[ "check", "the", "request", "and", "process", "results" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L335-L348
train
kencochrane/django-defender
defender/utils.py
add_login_attempt_to_db
def add_login_attempt_to_db(request, login_valid, get_username=get_username_from_request, username=None): """ Create a record for the login attempt If using celery call celery task, if not, call the method normally """ if not config.STORE_ACCESS_ATTEMPTS: # If we don't want to store in the database, then don't proceed. return username = username or get_username(request) user_agent = request.META.get('HTTP_USER_AGENT', '<unknown>')[:255] ip_address = get_ip(request) http_accept = request.META.get('HTTP_ACCEPT', '<unknown>') path_info = request.META.get('PATH_INFO', '<unknown>') if config.USE_CELERY: from .tasks import add_login_attempt_task add_login_attempt_task.delay(user_agent, ip_address, username, http_accept, path_info, login_valid) else: store_login_attempt(user_agent, ip_address, username, http_accept, path_info, login_valid)
python
def add_login_attempt_to_db(request, login_valid, get_username=get_username_from_request, username=None): """ Create a record for the login attempt If using celery call celery task, if not, call the method normally """ if not config.STORE_ACCESS_ATTEMPTS: # If we don't want to store in the database, then don't proceed. return username = username or get_username(request) user_agent = request.META.get('HTTP_USER_AGENT', '<unknown>')[:255] ip_address = get_ip(request) http_accept = request.META.get('HTTP_ACCEPT', '<unknown>') path_info = request.META.get('PATH_INFO', '<unknown>') if config.USE_CELERY: from .tasks import add_login_attempt_task add_login_attempt_task.delay(user_agent, ip_address, username, http_accept, path_info, login_valid) else: store_login_attempt(user_agent, ip_address, username, http_accept, path_info, login_valid)
[ "def", "add_login_attempt_to_db", "(", "request", ",", "login_valid", ",", "get_username", "=", "get_username_from_request", ",", "username", "=", "None", ")", ":", "if", "not", "config", ".", "STORE_ACCESS_ATTEMPTS", ":", "# If we don't want to store in the database, then don't proceed.", "return", "username", "=", "username", "or", "get_username", "(", "request", ")", "user_agent", "=", "request", ".", "META", ".", "get", "(", "'HTTP_USER_AGENT'", ",", "'<unknown>'", ")", "[", ":", "255", "]", "ip_address", "=", "get_ip", "(", "request", ")", "http_accept", "=", "request", ".", "META", ".", "get", "(", "'HTTP_ACCEPT'", ",", "'<unknown>'", ")", "path_info", "=", "request", ".", "META", ".", "get", "(", "'PATH_INFO'", ",", "'<unknown>'", ")", "if", "config", ".", "USE_CELERY", ":", "from", ".", "tasks", "import", "add_login_attempt_task", "add_login_attempt_task", ".", "delay", "(", "user_agent", ",", "ip_address", ",", "username", ",", "http_accept", ",", "path_info", ",", "login_valid", ")", "else", ":", "store_login_attempt", "(", "user_agent", ",", "ip_address", ",", "username", ",", "http_accept", ",", "path_info", ",", "login_valid", ")" ]
Create a record for the login attempt If using celery call celery task, if not, call the method normally
[ "Create", "a", "record", "for", "the", "login", "attempt", "If", "using", "celery", "call", "celery", "task", "if", "not", "call", "the", "method", "normally" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L351-L374
train
kencochrane/django-defender
defender/tasks.py
add_login_attempt_task
def add_login_attempt_task(user_agent, ip_address, username, http_accept, path_info, login_valid): """ Create a record for the login attempt """ store_login_attempt(user_agent, ip_address, username, http_accept, path_info, login_valid)
python
def add_login_attempt_task(user_agent, ip_address, username, http_accept, path_info, login_valid): """ Create a record for the login attempt """ store_login_attempt(user_agent, ip_address, username, http_accept, path_info, login_valid)
[ "def", "add_login_attempt_task", "(", "user_agent", ",", "ip_address", ",", "username", ",", "http_accept", ",", "path_info", ",", "login_valid", ")", ":", "store_login_attempt", "(", "user_agent", ",", "ip_address", ",", "username", ",", "http_accept", ",", "path_info", ",", "login_valid", ")" ]
Create a record for the login attempt
[ "Create", "a", "record", "for", "the", "login", "attempt" ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/tasks.py#L10-L14
train
kencochrane/django-defender
defender/data.py
store_login_attempt
def store_login_attempt(user_agent, ip_address, username, http_accept, path_info, login_valid): """ Store the login attempt to the db. """ AccessAttempt.objects.create( user_agent=user_agent, ip_address=ip_address, username=username, http_accept=http_accept, path_info=path_info, login_valid=login_valid, )
python
def store_login_attempt(user_agent, ip_address, username, http_accept, path_info, login_valid): """ Store the login attempt to the db. """ AccessAttempt.objects.create( user_agent=user_agent, ip_address=ip_address, username=username, http_accept=http_accept, path_info=path_info, login_valid=login_valid, )
[ "def", "store_login_attempt", "(", "user_agent", ",", "ip_address", ",", "username", ",", "http_accept", ",", "path_info", ",", "login_valid", ")", ":", "AccessAttempt", ".", "objects", ".", "create", "(", "user_agent", "=", "user_agent", ",", "ip_address", "=", "ip_address", ",", "username", "=", "username", ",", "http_accept", "=", "http_accept", ",", "path_info", "=", "path_info", ",", "login_valid", "=", "login_valid", ",", ")" ]
Store the login attempt to the db.
[ "Store", "the", "login", "attempt", "to", "the", "db", "." ]
e3e547dbb83235e0d564a6d64652c7df00412ff2
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/data.py#L4-L14
train