repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
Celeo/Pycord | pycord/__init__.py | Pycord.connect_to_websocket | def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the we... | python | def connect_to_websocket(self):
"""Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the we... | [
"def",
"connect_to_websocket",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Making websocket connection'",
")",
"try",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_ws'",
")",
":",
"self",
".",
"_ws",
".",
"close",
"(",
")",
"except",
... | Call this method to make the connection to the Discord websocket
This method is not blocking, so you'll probably want to call it after
initializating your Pycord object, and then move on with your code. When
you want to block on just maintaining the websocket connection, then call
``kee... | [
"Call",
"this",
"method",
"to",
"make",
"the",
"connection",
"to",
"the",
"Discord",
"websocket"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L374-L399 |
Celeo/Pycord | pycord/__init__.py | Pycord.disconnect_from_websocket | def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self... | python | def disconnect_from_websocket(self):
"""Disconnects from the websocket
Args:
None
"""
self.logger.warning('Disconnecting from websocket')
self.logger.info('Stopping keep alive thread')
self._ws_keep_alive.stop()
self._ws_keep_alive.join()
self... | [
"def",
"disconnect_from_websocket",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Disconnecting from websocket'",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'Stopping keep alive thread'",
")",
"self",
".",
"_ws_keep_alive",
".",
"stop",
... | Disconnects from the websocket
Args:
None | [
"Disconnects",
"from",
"the",
"websocket"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L424-L440 |
Celeo/Pycord | pycord/__init__.py | Pycord.set_status | def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
... | python | def set_status(self, name: str = None):
"""Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
... | [
"def",
"set_status",
"(",
"self",
",",
"name",
":",
"str",
"=",
"None",
")",
":",
"game",
"=",
"None",
"if",
"name",
":",
"game",
"=",
"{",
"'name'",
":",
"name",
"}",
"payload",
"=",
"{",
"'op'",
":",
"WebSocketEvent",
".",
"STATUS_UPDATE",
".",
"... | Updates the bot's status
This is used to get the game that the bot is "playing" or to clear it.
If you want to set a game, pass a name; if you want to clear it, either
call this method without the optional ``name`` parameter or explicitly
pass ``None``.
Args:
name: ... | [
"Updates",
"the",
"bot",
"s",
"status"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L442-L469 |
Celeo/Pycord | pycord/__init__.py | Pycord.get_guild_info | def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
... | python | def get_guild_info(self, id: str) -> Dict[str, Any]:
"""Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
... | [
"def",
"get_guild_info",
"(",
"self",
",",
"id",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"self",
".",
"_query",
"(",
"f'guilds/{id}'",
",",
"'GET'",
")"
] | Get a guild's information by its id
Args:
id: snowflake id of the guild
Returns:
Dictionary data for the guild API object
Example:
{
"id": "41771983423143937",
"name": "Discord Developers",
... | [
"Get",
"a",
"guild",
"s",
"information",
"by",
"its",
"id"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L549-L577 |
Celeo/Pycord | pycord/__init__.py | Pycord.get_channels_in | def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels... | python | def get_channels_in(self, guild_id: str) -> List[Dict[str, Any]]:
"""Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels... | [
"def",
"get_channels_in",
"(",
"self",
",",
"guild_id",
":",
"str",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"self",
".",
"_query",
"(",
"f'guilds/{guild_id}/channels'",
",",
"'GET'",
")"
] | Get a list of channels in the guild
Args:
guild_id: id of the guild to fetch channels from
Returns:
List of dictionary objects of channels in the guild. Note the different
types of channels: text, voice, DM, group DM.
https://discordapp.com/developers/d... | [
"Get",
"a",
"list",
"of",
"channels",
"in",
"the",
"guild"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L579-L628 |
Celeo/Pycord | pycord/__init__.py | Pycord.get_channel_info | def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
... | python | def get_channel_info(self, id: str) -> Dict[str, Any]:
"""Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
... | [
"def",
"get_channel_info",
"(",
"self",
",",
"id",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"self",
".",
"_query",
"(",
"f'channels/{id}'",
",",
"'GET'",
")"
] | Get a chanel's information by its id
Args:
id: snowflake id of the chanel
Returns:
Dictionary data for the chanel API object
Example:
{
"id": "41771983423143937",
"guild_id": "41771983423143937",
... | [
"Get",
"a",
"chanel",
"s",
"information",
"by",
"its",
"id"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L630-L651 |
Celeo/Pycord | pycord/__init__.py | Pycord.get_guild_members | def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
... | python | def get_guild_members(self, guild_id: int) -> List[Dict[str, Any]]:
"""Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
... | [
"def",
"get_guild_members",
"(",
"self",
",",
"guild_id",
":",
"int",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"self",
".",
"_query",
"(",
"f'guilds/{guild_id}/members'",
",",
"'GET'",
")"
] | Get a list of members in the guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of users in the guild.
Example:
[
{
"id": "41771983423143937",
"name... | [
"Get",
"a",
"list",
"of",
"members",
"in",
"the",
"guild"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L653-L700 |
Celeo/Pycord | pycord/__init__.py | Pycord.get_guild_member_by_id | def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
E... | python | def get_guild_member_by_id(self, guild_id: int, member_id: int) -> Dict[str, Any]:
"""Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
E... | [
"def",
"get_guild_member_by_id",
"(",
"self",
",",
"guild_id",
":",
"int",
",",
"member_id",
":",
"int",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"self",
".",
"_query",
"(",
"f'guilds/{guild_id}/members/{member_id}'",
",",
"'GET'",
")"
... | Get a guild member by their id
Args:
guild_id: snowflake id of the guild
member_id: snowflake id of the member
Returns:
Dictionary data for the guild member.
Example:
{
"id": "41771983423143937",
"... | [
"Get",
"a",
"guild",
"member",
"by",
"their",
"id"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L702-L735 |
Celeo/Pycord | pycord/__init__.py | Pycord.get_all_guild_roles | def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
... | python | def get_all_guild_roles(self, guild_id: int) -> List[Dict[str, Any]]:
"""Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
... | [
"def",
"get_all_guild_roles",
"(",
"self",
",",
"guild_id",
":",
"int",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"self",
".",
"_query",
"(",
"f'guilds/{guild_id}/roles'",
",",
"'GET'",
")"
] | Gets all the roles for the specified guild
Args:
guild_id: snowflake id of the guild
Returns:
List of dictionary objects of roles in the guild.
Example:
[
{
"id": "41771983423143936",
... | [
"Gets",
"all",
"the",
"roles",
"for",
"the",
"specified",
"guild"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L737-L780 |
Celeo/Pycord | pycord/__init__.py | Pycord.set_member_roles | def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
... | python | def set_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
... | [
"def",
"set_member_roles",
"(",
"self",
",",
"guild_id",
":",
"int",
",",
"member_id",
":",
"int",
",",
"roles",
":",
"List",
"[",
"int",
"]",
")",
":",
"self",
".",
"_query",
"(",
"f'guilds/{guild_id}/members/{member_id}'",
",",
"'PATCH'",
",",
"{",
"'rol... | Set the member's roles
This method takes a list of **role ids** that you want the user to have. This
method will **overwrite** all of the user's current roles with the roles in
the passed list of roles.
When calling this method, be sure that the list of roles that you're setting
... | [
"Set",
"the",
"member",
"s",
"roles"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L782-L799 |
Celeo/Pycord | pycord/__init__.py | Pycord.add_member_roles | def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to t... | python | def add_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to t... | [
"def",
"add_member_roles",
"(",
"self",
",",
"guild_id",
":",
"int",
",",
"member_id",
":",
"int",
",",
"roles",
":",
"List",
"[",
"int",
"]",
")",
":",
"current_roles",
"=",
"[",
"role",
"for",
"role",
"in",
"self",
".",
"get_guild_member_by_id",
"(",
... | Add roles to a member
This method takes a list of **role ids** that you want to give to the user,
on top of whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. The
user's resulting list of roles will not contai... | [
"Add",
"roles",
"to",
"a",
"member"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L801-L821 |
Celeo/Pycord | pycord/__init__.py | Pycord.remove_member_roles | def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles,... | python | def remove_member_roles(self, guild_id: int, member_id: int, roles: List[int]):
"""Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles,... | [
"def",
"remove_member_roles",
"(",
"self",
",",
"guild_id",
":",
"int",
",",
"member_id",
":",
"int",
",",
"roles",
":",
"List",
"[",
"int",
"]",
")",
":",
"current_roles",
"=",
"[",
"role",
"for",
"role",
"in",
"self",
".",
"get_guild_member_by_id",
"("... | Add roles to a member
This method takes a list of **role ids** that you want to strip from the user,
subtracting from whatever roles they may already have. This method will fetch
the user's current roles, and add to that list the roles passed in. This method
will only remove roles from ... | [
"Add",
"roles",
"to",
"a",
"member"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L823-L843 |
Celeo/Pycord | pycord/__init__.py | Pycord.send_message | def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: you... | python | def send_message(self, id: str, message: str) -> Dict[str, Any]:
"""Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: you... | [
"def",
"send_message",
"(",
"self",
",",
"id",
":",
"str",
",",
"message",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"ValueError",
"(",
"'Websocket not connected'",
")",
"retur... | Send a message to a channel
For formatting options, see the documentation:
https://discordapp.com/developers/docs/resources/channel#create-message
Args:
id: channel snowflake id
message: your message (string)
Returns:
Dictionary object of the ne... | [
"Send",
"a",
"message",
"to",
"a",
"channel"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L845-L860 |
Celeo/Pycord | pycord/__init__.py | Pycord.command | def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, ... | python | def command(self, name: str) -> Callable:
"""Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, ... | [
"def",
"command",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Callable",
":",
"def",
"inner",
"(",
"f",
":",
"Callable",
")",
":",
"self",
".",
"_commands",
".",
"append",
"(",
"(",
"name",
",",
"f",
")",
")",
"return",
"inner"
] | Decorator to wrap methods to register them as commands
The argument to this method is the command that you want to trigger your
callback. If you want users to send "!hello bob" and your method "command_hello"
to get called when someone does, then your setup will look like:
@pycord.... | [
"Decorator",
"to",
"wrap",
"methods",
"to",
"register",
"them",
"as",
"commands"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L865-L915 |
Celeo/Pycord | pycord/__init__.py | Pycord.register_command | def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or out... | python | def register_command(self, name: str, f: Callable):
"""Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or out... | [
"def",
"register_command",
"(",
"self",
",",
"name",
":",
"str",
",",
"f",
":",
"Callable",
")",
":",
"self",
".",
"_commands",
".",
"append",
"(",
"(",
"name",
",",
"f",
")",
")"
] | Registers an existing callable object as a command callback
This method can be used instead of the ``@command`` decorator. Both
do the same thing, but this method is useful for registering callbacks
for methods defined before or outside the scope of your bot object,
allowing you to defi... | [
"Registers",
"an",
"existing",
"callable",
"object",
"as",
"a",
"command",
"callback"
] | train | https://github.com/Celeo/Pycord/blob/15c38e39b508c89c35f7f6d7009fe8e9f161a94e/pycord/__init__.py#L917-L942 |
GMadorell/abris | abris_transform/parsing/csv_parsing.py | prepare_csv_to_dataframe | def prepare_csv_to_dataframe(data_file, config, use_target=True):
"""
Parses the given data file following the data model of the given configuration.
@return: pandas DataFrame
"""
names, dtypes = [], []
model = config.get_data_model()
for feature in model:
assert feature.get_name() n... | python | def prepare_csv_to_dataframe(data_file, config, use_target=True):
"""
Parses the given data file following the data model of the given configuration.
@return: pandas DataFrame
"""
names, dtypes = [], []
model = config.get_data_model()
for feature in model:
assert feature.get_name() n... | [
"def",
"prepare_csv_to_dataframe",
"(",
"data_file",
",",
"config",
",",
"use_target",
"=",
"True",
")",
":",
"names",
",",
"dtypes",
"=",
"[",
"]",
",",
"[",
"]",
"model",
"=",
"config",
".",
"get_data_model",
"(",
")",
"for",
"feature",
"in",
"model",
... | Parses the given data file following the data model of the given configuration.
@return: pandas DataFrame | [
"Parses",
"the",
"given",
"data",
"file",
"following",
"the",
"data",
"model",
"of",
"the",
"given",
"configuration",
"."
] | train | https://github.com/GMadorell/abris/blob/0d8ab7ec506835a45fae6935d129f5d7e6937bb2/abris_transform/parsing/csv_parsing.py#L4-L20 |
bitlabstudio/django-tagging-translated | tagging_translated/migrations/0002_create_translations_for_existing_tags.py | Migration.forwards | def forwards(self, orm):
"Write your forwards methods here."
for tag in orm['tagging.Tag'].objects.all():
if tag.tagtitle_set.all().count() == 0:
orm['tagging_translated.TagTitle'].objects.create(
trans_name=tag.name, tag=tag, language='en') | python | def forwards(self, orm):
"Write your forwards methods here."
for tag in orm['tagging.Tag'].objects.all():
if tag.tagtitle_set.all().count() == 0:
orm['tagging_translated.TagTitle'].objects.create(
trans_name=tag.name, tag=tag, language='en') | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"for",
"tag",
"in",
"orm",
"[",
"'tagging.Tag'",
"]",
".",
"objects",
".",
"all",
"(",
")",
":",
"if",
"tag",
".",
"tagtitle_set",
".",
"all",
"(",
")",
".",
"count",
"(",
")",
"==",
"0",
":... | Write your forwards methods here. | [
"Write",
"your",
"forwards",
"methods",
"here",
"."
] | train | https://github.com/bitlabstudio/django-tagging-translated/blob/8766d88077959efb07a97a116538e53b800b6019/tagging_translated/migrations/0002_create_translations_for_existing_tags.py#L10-L15 |
sunlightlabs/django-locksmith | locksmith/hub/models.py | resolve_model | def resolve_model(model, fields):
"""
model: Model class
fields: List of 2-tuples of the form (field, value) in order of descending priority
"""
for (f, v) in fields:
if v is not None:
try:
kwargs = {f: v}
obj = model.objects.get(**kwargs)
... | python | def resolve_model(model, fields):
"""
model: Model class
fields: List of 2-tuples of the form (field, value) in order of descending priority
"""
for (f, v) in fields:
if v is not None:
try:
kwargs = {f: v}
obj = model.objects.get(**kwargs)
... | [
"def",
"resolve_model",
"(",
"model",
",",
"fields",
")",
":",
"for",
"(",
"f",
",",
"v",
")",
"in",
"fields",
":",
"if",
"v",
"is",
"not",
"None",
":",
"try",
":",
"kwargs",
"=",
"{",
"f",
":",
"v",
"}",
"obj",
"=",
"model",
".",
"objects",
... | model: Model class
fields: List of 2-tuples of the form (field, value) in order of descending priority | [
"model",
":",
"Model",
"class",
"fields",
":",
"List",
"of",
"2",
"-",
"tuples",
"of",
"the",
"form",
"(",
"field",
"value",
")",
"in",
"order",
"of",
"descending",
"priority"
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/models.py#L16-L31 |
sunlightlabs/django-locksmith | locksmith/hub/models.py | kps_callback | def kps_callback(sender, instance, created, raw, **kwargs):
''' create KeyPublicationStatus object for Keys/Apis '''
if created and not raw:
if sender == Api:
for key in Key.objects.all():
KeyPublicationStatus.objects.create(key=key, api=instance)
elif isinstance(inst... | python | def kps_callback(sender, instance, created, raw, **kwargs):
''' create KeyPublicationStatus object for Keys/Apis '''
if created and not raw:
if sender == Api:
for key in Key.objects.all():
KeyPublicationStatus.objects.create(key=key, api=instance)
elif isinstance(inst... | [
"def",
"kps_callback",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"raw",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
"and",
"not",
"raw",
":",
"if",
"sender",
"==",
"Api",
":",
"for",
"key",
"in",
"Key",
".",
"objects",
".",
"all"... | create KeyPublicationStatus object for Keys/Apis | [
"create",
"KeyPublicationStatus",
"object",
"for",
"Keys",
"/",
"Apis"
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/models.py#L122-L130 |
sunlightlabs/django-locksmith | locksmith/hub/models.py | Key.mark_for_update | def mark_for_update(self):
'''
Note that a change has been made so all Statuses need update
'''
self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE)
push_key.delay(self) | python | def mark_for_update(self):
'''
Note that a change has been made so all Statuses need update
'''
self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE)
push_key.delay(self) | [
"def",
"mark_for_update",
"(",
"self",
")",
":",
"self",
".",
"pub_statuses",
".",
"exclude",
"(",
"status",
"=",
"UNPUBLISHED",
")",
".",
"update",
"(",
"status",
"=",
"NEEDS_UPDATE",
")",
"push_key",
".",
"delay",
"(",
"self",
")"
] | Note that a change has been made so all Statuses need update | [
"Note",
"that",
"a",
"change",
"has",
"been",
"made",
"so",
"all",
"Statuses",
"need",
"update"
] | train | https://github.com/sunlightlabs/django-locksmith/blob/eef5b7c25404560aaad50b6e622594f89239b74b/locksmith/hub/models.py#L82-L87 |
drongo-framework/drongo | drongo/response.py | Response.set_cookie | def set_cookie(self, key, value, domain=None, path='/', secure=False,
httponly=True):
"""Set a cookie.
Args:
key (:obj:`str`): Cookie name
value (:obj:`str`): Cookie value
domain (:obj:`str`): Cookie domain
path (:obj:`str`): Cookie val... | python | def set_cookie(self, key, value, domain=None, path='/', secure=False,
httponly=True):
"""Set a cookie.
Args:
key (:obj:`str`): Cookie name
value (:obj:`str`): Cookie value
domain (:obj:`str`): Cookie domain
path (:obj:`str`): Cookie val... | [
"def",
"set_cookie",
"(",
"self",
",",
"key",
",",
"value",
",",
"domain",
"=",
"None",
",",
"path",
"=",
"'/'",
",",
"secure",
"=",
"False",
",",
"httponly",
"=",
"True",
")",
":",
"self",
".",
"_cookies",
"[",
"key",
"]",
"=",
"value",
"if",
"d... | Set a cookie.
Args:
key (:obj:`str`): Cookie name
value (:obj:`str`): Cookie value
domain (:obj:`str`): Cookie domain
path (:obj:`str`): Cookie value
secure (:obj:`bool`): True if secure, False otherwise
httponly (:obj:`bool`): True if it'... | [
"Set",
"a",
"cookie",
"."
] | train | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/response.py#L51-L72 |
drongo-framework/drongo | drongo/response.py | Response.set_content | def set_content(self, content, content_length=None):
"""Set content for the response.
Args:
content (:obj:`str` or :obj:`iterable`): Response content. Can be
either unicode or raw bytes. When returning large content,
an iterable (or a generator) can be used t... | python | def set_content(self, content, content_length=None):
"""Set content for the response.
Args:
content (:obj:`str` or :obj:`iterable`): Response content. Can be
either unicode or raw bytes. When returning large content,
an iterable (or a generator) can be used t... | [
"def",
"set_content",
"(",
"self",
",",
"content",
",",
"content_length",
"=",
"None",
")",
":",
"if",
"content_length",
"is",
"not",
"None",
":",
"self",
".",
"_content_length",
"=",
"content_length",
"self",
".",
"_content",
"=",
"content"
] | Set content for the response.
Args:
content (:obj:`str` or :obj:`iterable`): Response content. Can be
either unicode or raw bytes. When returning large content,
an iterable (or a generator) can be used to avoid loading
entire content into the memory.
... | [
"Set",
"content",
"for",
"the",
"response",
"."
] | train | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/response.py#L74-L88 |
drongo-framework/drongo | drongo/response.py | Response.bake | def bake(self, start_response):
"""Bakes the response and returns the content.
Args:
start_response (:obj:`callable`): Callback method that accepts
status code and a list of tuples (pairs) containing headers'
key and value respectively.
"""
if... | python | def bake(self, start_response):
"""Bakes the response and returns the content.
Args:
start_response (:obj:`callable`): Callback method that accepts
status code and a list of tuples (pairs) containing headers'
key and value respectively.
"""
if... | [
"def",
"bake",
"(",
"self",
",",
"start_response",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_content",
",",
"six",
".",
"text_type",
")",
":",
"self",
".",
"_content",
"=",
"self",
".",
"_content",
".",
"encode",
"(",
"'utf8'",
")",
"if",
"se... | Bakes the response and returns the content.
Args:
start_response (:obj:`callable`): Callback method that accepts
status code and a list of tuples (pairs) containing headers'
key and value respectively. | [
"Bakes",
"the",
"response",
"and",
"returns",
"the",
"content",
"."
] | train | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/response.py#L90-L117 |
drongo-framework/drongo | drongo/response.py | Response.set_redirect | def set_redirect(self, url, status=HttpStatusCodes.HTTP_303):
"""Helper method to set a redirect response.
Args:
url (:obj:`str`): URL to redirect to
status (:obj:`str`, optional): Status code of the response
"""
self.set_status(status)
self.set_content('... | python | def set_redirect(self, url, status=HttpStatusCodes.HTTP_303):
"""Helper method to set a redirect response.
Args:
url (:obj:`str`): URL to redirect to
status (:obj:`str`, optional): Status code of the response
"""
self.set_status(status)
self.set_content('... | [
"def",
"set_redirect",
"(",
"self",
",",
"url",
",",
"status",
"=",
"HttpStatusCodes",
".",
"HTTP_303",
")",
":",
"self",
".",
"set_status",
"(",
"status",
")",
"self",
".",
"set_content",
"(",
"''",
")",
"self",
".",
"set_header",
"(",
"HttpResponseHeader... | Helper method to set a redirect response.
Args:
url (:obj:`str`): URL to redirect to
status (:obj:`str`, optional): Status code of the response | [
"Helper",
"method",
"to",
"set",
"a",
"redirect",
"response",
"."
] | train | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/response.py#L120-L129 |
drongo-framework/drongo | drongo/response.py | Response.set_json | def set_json(self, obj, status=HttpStatusCodes.HTTP_200):
"""Helper method to set a JSON response.
Args:
obj (:obj:`object`): JSON serializable object
status (:obj:`str`, optional): Status code of the response
"""
obj = json.dumps(obj, sort_keys=True, default=lam... | python | def set_json(self, obj, status=HttpStatusCodes.HTTP_200):
"""Helper method to set a JSON response.
Args:
obj (:obj:`object`): JSON serializable object
status (:obj:`str`, optional): Status code of the response
"""
obj = json.dumps(obj, sort_keys=True, default=lam... | [
"def",
"set_json",
"(",
"self",
",",
"obj",
",",
"status",
"=",
"HttpStatusCodes",
".",
"HTTP_200",
")",
":",
"obj",
"=",
"json",
".",
"dumps",
"(",
"obj",
",",
"sort_keys",
"=",
"True",
",",
"default",
"=",
"lambda",
"x",
":",
"str",
"(",
"x",
")"... | Helper method to set a JSON response.
Args:
obj (:obj:`object`): JSON serializable object
status (:obj:`str`, optional): Status code of the response | [
"Helper",
"method",
"to",
"set",
"a",
"JSON",
"response",
"."
] | train | https://github.com/drongo-framework/drongo/blob/487edb370ae329f370bcf3b433ed3f28ba4c1d8c/drongo/response.py#L131-L141 |
Huong-nt/flask-rak | flask_rak/core.py | copy_func | def copy_func(f, name=None):
"""Based on https://stackoverflow.com/a/30714299 (Aaron Hall)"""
'''
return a function with same code, globals, defaults, closure, and
name (or provide a new name)
'''
fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
... | python | def copy_func(f, name=None):
"""Based on https://stackoverflow.com/a/30714299 (Aaron Hall)"""
'''
return a function with same code, globals, defaults, closure, and
name (or provide a new name)
'''
fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
... | [
"def",
"copy_func",
"(",
"f",
",",
"name",
"=",
"None",
")",
":",
"'''\n return a function with same code, globals, defaults, closure, and \n name (or provide a new name)\n '''",
"fn",
"=",
"types",
".",
"FunctionType",
"(",
"f",
".",
"__code__",
",",
"f",
".",
... | Based on https://stackoverflow.com/a/30714299 (Aaron Hall) | [
"Based",
"on",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"30714299",
"(",
"Aaron",
"Hall",
")"
] | train | https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/core.py#L16-L26 |
Huong-nt/flask-rak | flask_rak/core.py | find_rak | def find_rak():
"""
Find our instance of Rak, navigating Local's and possible blueprints.
"""
if hasattr(current_app, 'rak'):
return getattr(current_app, 'rak')
else:
if hasattr(current_app, 'blueprints'):
blueprints = getattr(current_app, 'blueprints')
for bl... | python | def find_rak():
"""
Find our instance of Rak, navigating Local's and possible blueprints.
"""
if hasattr(current_app, 'rak'):
return getattr(current_app, 'rak')
else:
if hasattr(current_app, 'blueprints'):
blueprints = getattr(current_app, 'blueprints')
for bl... | [
"def",
"find_rak",
"(",
")",
":",
"if",
"hasattr",
"(",
"current_app",
",",
"'rak'",
")",
":",
"return",
"getattr",
"(",
"current_app",
",",
"'rak'",
")",
"else",
":",
"if",
"hasattr",
"(",
"current_app",
",",
"'blueprints'",
")",
":",
"blueprints",
"=",... | Find our instance of Rak, navigating Local's and possible blueprints. | [
"Find",
"our",
"instance",
"of",
"Rak",
"navigating",
"Local",
"s",
"and",
"possible",
"blueprints",
"."
] | train | https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/core.py#L29-L40 |
Huong-nt/flask-rak | flask_rak/core.py | RAK.init_app | def init_app(self, app):
"""Initializes Ask app by setting configuration variables and maps RAK route to a flask view.
The RAK instance is given the following configuration variables by calling on Flask's configuration:
"""
if self._route is None:
raise TypeError(
... | python | def init_app(self, app):
"""Initializes Ask app by setting configuration variables and maps RAK route to a flask view.
The RAK instance is given the following configuration variables by calling on Flask's configuration:
"""
if self._route is None:
raise TypeError(
... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"self",
".",
"_route",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"route is a required argument when app is not None\"",
")",
"app",
".",
"rak",
"=",
"self",
"app",
".",
"add_url_rule",
"(",
"s... | Initializes Ask app by setting configuration variables and maps RAK route to a flask view.
The RAK instance is given the following configuration variables by calling on Flask's configuration: | [
"Initializes",
"Ask",
"app",
"by",
"setting",
"configuration",
"variables",
"and",
"maps",
"RAK",
"route",
"to",
"a",
"flask",
"view",
".",
"The",
"RAK",
"instance",
"is",
"given",
"the",
"following",
"configuration",
"variables",
"by",
"calling",
"on",
"Flask... | train | https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/core.py#L88-L98 |
Huong-nt/flask-rak | flask_rak/core.py | RAK.init_blueprint | def init_blueprint(self, blueprint):
"""Initialize a Flask Blueprint, similar to init_app, but without the access
to the application config.
Keyword Arguments:
blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None})
"""
if self._route i... | python | def init_blueprint(self, blueprint):
"""Initialize a Flask Blueprint, similar to init_app, but without the access
to the application config.
Keyword Arguments:
blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None})
"""
if self._route i... | [
"def",
"init_blueprint",
"(",
"self",
",",
"blueprint",
")",
":",
"if",
"self",
".",
"_route",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"route cannot be set when using blueprints!\"",
")",
"blueprint",
".",
"rak",
"=",
"self",
"blueprint",
".",
"... | Initialize a Flask Blueprint, similar to init_app, but without the access
to the application config.
Keyword Arguments:
blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None}) | [
"Initialize",
"a",
"Flask",
"Blueprint",
"similar",
"to",
"init_app",
"but",
"without",
"the",
"access",
"to",
"the",
"application",
"config",
".",
"Keyword",
"Arguments",
":",
"blueprint",
"{",
"Flask",
"Blueprint",
"}",
"--",
"Flask",
"Blueprint",
"instance",
... | train | https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/core.py#L100-L110 |
Huong-nt/flask-rak | flask_rak/core.py | RAK.intent | def intent(self, intent_name):
"""Decorator routes an Rogo IntentRequest.
Functions decorated as an intent are registered as the view function for the Intent's URL,
and provide the backend responses to give your Skill its functionality.
@ask.intent('WeatherIntent')
def weather(ci... | python | def intent(self, intent_name):
"""Decorator routes an Rogo IntentRequest.
Functions decorated as an intent are registered as the view function for the Intent's URL,
and provide the backend responses to give your Skill its functionality.
@ask.intent('WeatherIntent')
def weather(ci... | [
"def",
"intent",
"(",
"self",
",",
"intent_name",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"self",
".",
"_intent_view_funcs",
"[",
"intent_name",
"]",
"=",
"f",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*"... | Decorator routes an Rogo IntentRequest.
Functions decorated as an intent are registered as the view function for the Intent's URL,
and provide the backend responses to give your Skill its functionality.
@ask.intent('WeatherIntent')
def weather(city):
return statement('I predi... | [
"Decorator",
"routes",
"an",
"Rogo",
"IntentRequest",
".",
"Functions",
"decorated",
"as",
"an",
"intent",
"are",
"registered",
"as",
"the",
"view",
"function",
"for",
"the",
"Intent",
"s",
"URL",
"and",
"provide",
"the",
"backend",
"responses",
"to",
"give",
... | train | https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/core.py#L155-L172 |
Huong-nt/flask-rak | flask_rak/core.py | RAK._map_intent_to_view_func | def _map_intent_to_view_func(self, intent):
"""Provides appropiate parameters to the intent functions."""
if intent.label in self._intent_view_funcs:
view_func = self._intent_view_funcs[intent.label]
elif self._default_intent_view_func is not None:
view_func = self._defau... | python | def _map_intent_to_view_func(self, intent):
"""Provides appropiate parameters to the intent functions."""
if intent.label in self._intent_view_funcs:
view_func = self._intent_view_funcs[intent.label]
elif self._default_intent_view_func is not None:
view_func = self._defau... | [
"def",
"_map_intent_to_view_func",
"(",
"self",
",",
"intent",
")",
":",
"if",
"intent",
".",
"label",
"in",
"self",
".",
"_intent_view_funcs",
":",
"view_func",
"=",
"self",
".",
"_intent_view_funcs",
"[",
"intent",
".",
"label",
"]",
"elif",
"self",
".",
... | Provides appropiate parameters to the intent functions. | [
"Provides",
"appropiate",
"parameters",
"to",
"the",
"intent",
"functions",
"."
] | train | https://github.com/Huong-nt/flask-rak/blob/ffe16b0fc3d49e83c1d220c445ce14632219f69d/flask_rak/core.py#L217-L231 |
andreycizov/python-xrpc | xrpc/popen.py | popen | def popen(fn, *args, **kwargs) -> subprocess.Popen:
"""
Please ensure you're not killing the process before it had started properly
:param fn:
:param args:
:param kwargs:
:return:
"""
args = popen_encode(fn, *args, **kwargs)
logging.getLogger(__name__).debug('Start %s', args)
... | python | def popen(fn, *args, **kwargs) -> subprocess.Popen:
"""
Please ensure you're not killing the process before it had started properly
:param fn:
:param args:
:param kwargs:
:return:
"""
args = popen_encode(fn, *args, **kwargs)
logging.getLogger(__name__).debug('Start %s', args)
... | [
"def",
"popen",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"subprocess",
".",
"Popen",
":",
"args",
"=",
"popen_encode",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"logging",
".",
"getLogger",
"(",
"__name__",
... | Please ensure you're not killing the process before it had started properly
:param fn:
:param args:
:param kwargs:
:return: | [
"Please",
"ensure",
"you",
"re",
"not",
"killing",
"the",
"process",
"before",
"it",
"had",
"started",
"properly",
":",
"param",
"fn",
":",
":",
"param",
"args",
":",
":",
"param",
"kwargs",
":",
":",
"return",
":"
] | train | https://github.com/andreycizov/python-xrpc/blob/4f916383cda7de3272962f3ba07a64f7ec451098/xrpc/popen.py#L88-L102 |
emin63/eyap | eyap/core/comments.py | SingleComment.make_anchor_id | def make_anchor_id(self):
"""Return string to use as URL anchor for this comment.
"""
result = re.sub(
'[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp)
return result | python | def make_anchor_id(self):
"""Return string to use as URL anchor for this comment.
"""
result = re.sub(
'[^a-zA-Z0-9_]', '_', self.user + '_' + self.timestamp)
return result | [
"def",
"make_anchor_id",
"(",
"self",
")",
":",
"result",
"=",
"re",
".",
"sub",
"(",
"'[^a-zA-Z0-9_]'",
",",
"'_'",
",",
"self",
".",
"user",
"+",
"'_'",
"+",
"self",
".",
"timestamp",
")",
"return",
"result"
] | Return string to use as URL anchor for this comment. | [
"Return",
"string",
"to",
"use",
"as",
"URL",
"anchor",
"for",
"this",
"comment",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L60-L65 |
emin63/eyap | eyap/core/comments.py | SingleComment.make_url | def make_url(self, my_request, anchor_id=None):
"""Make URL to this comment.
:arg my_request: The request object where this comment is seen from.
:arg anchor_id=None: Optional anchor id. If None, we use
self.make_anchor_id()
~-~-~-~-~-~-~-~-~-~-~-~-... | python | def make_url(self, my_request, anchor_id=None):
"""Make URL to this comment.
:arg my_request: The request object where this comment is seen from.
:arg anchor_id=None: Optional anchor id. If None, we use
self.make_anchor_id()
~-~-~-~-~-~-~-~-~-~-~-~-... | [
"def",
"make_url",
"(",
"self",
",",
"my_request",
",",
"anchor_id",
"=",
"None",
")",
":",
"if",
"anchor_id",
"is",
"None",
":",
"anchor_id",
"=",
"self",
".",
"make_anchor_id",
"(",
")",
"result",
"=",
"'{}?{}#{}'",
".",
"format",
"(",
"my_request",
".... | Make URL to this comment.
:arg my_request: The request object where this comment is seen from.
:arg anchor_id=None: Optional anchor id. If None, we use
self.make_anchor_id()
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
:returns: Str... | [
"Make",
"URL",
"to",
"this",
"comment",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L67-L90 |
emin63/eyap | eyap/core/comments.py | SingleComment.to_dict | def to_dict(self):
"""Return description of self in dict format.
This is useful for serializing to something like json later.
"""
jdict = {
'user': self.user,
'summary': self.summary,
'body': self.body,
'markup': self.markup,
'... | python | def to_dict(self):
"""Return description of self in dict format.
This is useful for serializing to something like json later.
"""
jdict = {
'user': self.user,
'summary': self.summary,
'body': self.body,
'markup': self.markup,
'... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"jdict",
"=",
"{",
"'user'",
":",
"self",
".",
"user",
",",
"'summary'",
":",
"self",
".",
"summary",
",",
"'body'",
":",
"self",
".",
"body",
",",
"'markup'",
":",
"self",
".",
"markup",
",",
"'url'",
":",
... | Return description of self in dict format.
This is useful for serializing to something like json later. | [
"Return",
"description",
"of",
"self",
"in",
"dict",
"format",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L92-L105 |
emin63/eyap | eyap/core/comments.py | SingleComment.set_display_mode | def set_display_mode(self, mytz, fmt):
"""Set the display mode for self.
:arg mytz: A pytz.timezone object.
:arg fmt: A format string for strftime.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Modifies self.display_timestamp to first p... | python | def set_display_mode(self, mytz, fmt):
"""Set the display mode for self.
:arg mytz: A pytz.timezone object.
:arg fmt: A format string for strftime.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Modifies self.display_timestamp to first p... | [
"def",
"set_display_mode",
"(",
"self",
",",
"mytz",
",",
"fmt",
")",
":",
"my_stamp",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"self",
".",
"timestamp",
")",
"tz_stamp",
"=",
"my_stamp",
".",
"astimezone",
"(",
"mytz",
")",
"if",
"my_stamp",
... | Set the display mode for self.
:arg mytz: A pytz.timezone object.
:arg fmt: A format string for strftime.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Modifies self.display_timestamp to first parse
self.timestamp and th... | [
"Set",
"the",
"display",
"mode",
"for",
"self",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L107-L124 |
emin63/eyap | eyap/core/comments.py | CommentSection.set_display_mode | def set_display_mode(self, mytz, fmt="%Y-%m-%d %H:%M:%S %Z%z"):
"""Call set_display_mode on items in self.comments with given args.
:arg mytz: A pytz.timezone object.
:arg fmt="%Y-%m-%d%H:%M:%S%Z%z": Optional format string.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-... | python | def set_display_mode(self, mytz, fmt="%Y-%m-%d %H:%M:%S %Z%z"):
"""Call set_display_mode on items in self.comments with given args.
:arg mytz: A pytz.timezone object.
:arg fmt="%Y-%m-%d%H:%M:%S%Z%z": Optional format string.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-... | [
"def",
"set_display_mode",
"(",
"self",
",",
"mytz",
",",
"fmt",
"=",
"\"%Y-%m-%d %H:%M:%S %Z%z\"",
")",
":",
"for",
"item",
"in",
"self",
".",
"comments",
":",
"item",
".",
"set_display_mode",
"(",
"mytz",
",",
"fmt",
")"
] | Call set_display_mode on items in self.comments with given args.
:arg mytz: A pytz.timezone object.
:arg fmt="%Y-%m-%d%H:%M:%S%Z%z": Optional format string.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Call set_display_mode(mytz, fmt) for everything i... | [
"Call",
"set_display_mode",
"on",
"items",
"in",
"self",
".",
"comments",
"with",
"given",
"args",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L156-L170 |
emin63/eyap | eyap/core/comments.py | CommentThread.get_comment_section | def get_comment_section(self, force_reload=False, reverse=False):
"""Get CommentSection instance representing all comments for thread.
:arg force_reload=False: Whether to force reloading comments
directly or allow using what is cached
... | python | def get_comment_section(self, force_reload=False, reverse=False):
"""Get CommentSection instance representing all comments for thread.
:arg force_reload=False: Whether to force reloading comments
directly or allow using what is cached
... | [
"def",
"get_comment_section",
"(",
"self",
",",
"force_reload",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"self",
".",
"content",
"is",
"not",
"None",
"and",
"not",
"force_reload",
":",
"return",
"self",
".",
"content",
"if",
"self",
".... | Get CommentSection instance representing all comments for thread.
:arg force_reload=False: Whether to force reloading comments
directly or allow using what is cached
in self.content if possible.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-... | [
"Get",
"CommentSection",
"instance",
"representing",
"all",
"comments",
"for",
"thread",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L318-L340 |
emin63/eyap | eyap/core/comments.py | CommentThread.validate_attachment_location | def validate_attachment_location(self, location):
"""Validate a proposed attachment location.
:arg location: String representing location to put attachment.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Raises an exception if attachment location is bad.
... | python | def validate_attachment_location(self, location):
"""Validate a proposed attachment location.
:arg location: String representing location to put attachment.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Raises an exception if attachment location is bad.
... | [
"def",
"validate_attachment_location",
"(",
"self",
",",
"location",
")",
":",
"if",
"not",
"re",
".",
"compile",
"(",
"self",
".",
"valid_attachment_loc_re",
")",
".",
"match",
"(",
"location",
")",
":",
"raise",
"ValueError",
"(",
"'Bad chars in attachment loc... | Validate a proposed attachment location.
:arg location: String representing location to put attachment.
~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-
PURPOSE: Raises an exception if attachment location is bad.
By default, this just forces reasonable character... | [
"Validate",
"a",
"proposed",
"attachment",
"location",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L342-L357 |
emin63/eyap | eyap/core/comments.py | FileCommentThread.lookup_thread_id | def lookup_thread_id(self):
"Lookup the thread id as path to comment file."
path = os.path.join(self.realm, self.topic + '.csv')
return path | python | def lookup_thread_id(self):
"Lookup the thread id as path to comment file."
path = os.path.join(self.realm, self.topic + '.csv')
return path | [
"def",
"lookup_thread_id",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"realm",
",",
"self",
".",
"topic",
"+",
"'.csv'",
")",
"return",
"path"
] | Lookup the thread id as path to comment file. | [
"Lookup",
"the",
"thread",
"id",
"as",
"path",
"to",
"comment",
"file",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L398-L402 |
emin63/eyap | eyap/core/comments.py | FileCommentThread.lookup_comments | def lookup_comments(self, reverse=False):
"Implement as required by parent to lookup comments in file system."
comments = []
if self.thread_id is None:
self.thread_id = self.lookup_thread_id()
path = self.thread_id
with open(self.thread_id, 'r', newline='') as fdesc:... | python | def lookup_comments(self, reverse=False):
"Implement as required by parent to lookup comments in file system."
comments = []
if self.thread_id is None:
self.thread_id = self.lookup_thread_id()
path = self.thread_id
with open(self.thread_id, 'r', newline='') as fdesc:... | [
"def",
"lookup_comments",
"(",
"self",
",",
"reverse",
"=",
"False",
")",
":",
"comments",
"=",
"[",
"]",
"if",
"self",
".",
"thread_id",
"is",
"None",
":",
"self",
".",
"thread_id",
"=",
"self",
".",
"lookup_thread_id",
"(",
")",
"path",
"=",
"self",
... | Implement as required by parent to lookup comments in file system. | [
"Implement",
"as",
"required",
"by",
"parent",
"to",
"lookup",
"comments",
"in",
"file",
"system",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L404-L425 |
emin63/eyap | eyap/core/comments.py | FileCommentThread.create_thread | def create_thread(self, body):
"""Implement create_thread as required by parent.
This basically just calls add_comment with allow_create=True
and then builds a response object to indicate everything is fine.
"""
self.add_comment(body, allow_create=True)
the_response = Re... | python | def create_thread(self, body):
"""Implement create_thread as required by parent.
This basically just calls add_comment with allow_create=True
and then builds a response object to indicate everything is fine.
"""
self.add_comment(body, allow_create=True)
the_response = Re... | [
"def",
"create_thread",
"(",
"self",
",",
"body",
")",
":",
"self",
".",
"add_comment",
"(",
"body",
",",
"allow_create",
"=",
"True",
")",
"the_response",
"=",
"Response",
"(",
")",
"the_response",
".",
"code",
"=",
"\"OK\"",
"the_response",
".",
"status_... | Implement create_thread as required by parent.
This basically just calls add_comment with allow_create=True
and then builds a response object to indicate everything is fine. | [
"Implement",
"create_thread",
"as",
"required",
"by",
"parent",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L427-L436 |
emin63/eyap | eyap/core/comments.py | FileCommentThread.add_comment | def add_comment(self, body, allow_create=False, allow_hashes=False,
summary=None):
"Implement as required by parent to store comment in CSV file."
if allow_hashes:
raise ValueError('allow_hashes not implemented for %s yet' % (
self.__class__.__name__))
... | python | def add_comment(self, body, allow_create=False, allow_hashes=False,
summary=None):
"Implement as required by parent to store comment in CSV file."
if allow_hashes:
raise ValueError('allow_hashes not implemented for %s yet' % (
self.__class__.__name__))
... | [
"def",
"add_comment",
"(",
"self",
",",
"body",
",",
"allow_create",
"=",
"False",
",",
"allow_hashes",
"=",
"False",
",",
"summary",
"=",
"None",
")",
":",
"if",
"allow_hashes",
":",
"raise",
"ValueError",
"(",
"'allow_hashes not implemented for %s yet'",
"%",
... | Implement as required by parent to store comment in CSV file. | [
"Implement",
"as",
"required",
"by",
"parent",
"to",
"store",
"comment",
"in",
"CSV",
"file",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L438-L456 |
wushuyi/wsy_captcha | wsy_captcha/bezier.py | pascal_row | def pascal_row(n):
""" Returns n-th row of Pascal's triangle
"""
result = [1]
x, numerator = 1, n
for denominator in range(1, n // 2 + 1):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if n & 1 == 0:
result.extend(reversed(result[:-1]))
... | python | def pascal_row(n):
""" Returns n-th row of Pascal's triangle
"""
result = [1]
x, numerator = 1, n
for denominator in range(1, n // 2 + 1):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if n & 1 == 0:
result.extend(reversed(result[:-1]))
... | [
"def",
"pascal_row",
"(",
"n",
")",
":",
"result",
"=",
"[",
"1",
"]",
"x",
",",
"numerator",
"=",
"1",
",",
"n",
"for",
"denominator",
"in",
"range",
"(",
"1",
",",
"n",
"//",
"2",
"+",
"1",
")",
":",
"x",
"*=",
"numerator",
"x",
"/=",
"deno... | Returns n-th row of Pascal's triangle | [
"Returns",
"n",
"-",
"th",
"row",
"of",
"Pascal",
"s",
"triangle"
] | train | https://github.com/wushuyi/wsy_captcha/blob/eeb8fd8b8d37c3550903a83339109e064da45d89/wsy_captcha/bezier.py#L11-L25 |
wushuyi/wsy_captcha | wsy_captcha/bezier.py | make_bezier | def make_bezier(n):
""" Bezier curves:
http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization
"""
try:
return beziers[n]
except KeyError:
combinations = pascal_row(n - 1)
result = []
for t in tsequence:
tpowers = (t ** i for i in range(n))
... | python | def make_bezier(n):
""" Bezier curves:
http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization
"""
try:
return beziers[n]
except KeyError:
combinations = pascal_row(n - 1)
result = []
for t in tsequence:
tpowers = (t ** i for i in range(n))
... | [
"def",
"make_bezier",
"(",
"n",
")",
":",
"try",
":",
"return",
"beziers",
"[",
"n",
"]",
"except",
"KeyError",
":",
"combinations",
"=",
"pascal_row",
"(",
"n",
"-",
"1",
")",
"result",
"=",
"[",
"]",
"for",
"t",
"in",
"tsequence",
":",
"tpowers",
... | Bezier curves:
http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization | [
"Bezier",
"curves",
":",
"http",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"B%C3%A9zier_curve#Generalization"
] | train | https://github.com/wushuyi/wsy_captcha/blob/eeb8fd8b8d37c3550903a83339109e064da45d89/wsy_captcha/bezier.py#L28-L44 |
edelbluth/blackred | src/blackred/blackred.py | create_salt | def create_salt(length: int=128) -> bytes:
"""
Create a new salt
:param int length: How many bytes should the salt be long?
:return: The salt
:rtype: bytes
"""
return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(length)) | python | def create_salt(length: int=128) -> bytes:
"""
Create a new salt
:param int length: How many bytes should the salt be long?
:return: The salt
:rtype: bytes
"""
return b''.join(bytes([SystemRandom().randint(0, 255)]) for _ in range(length)) | [
"def",
"create_salt",
"(",
"length",
":",
"int",
"=",
"128",
")",
"->",
"bytes",
":",
"return",
"b''",
".",
"join",
"(",
"bytes",
"(",
"[",
"SystemRandom",
"(",
")",
".",
"randint",
"(",
"0",
",",
"255",
")",
"]",
")",
"for",
"_",
"in",
"range",
... | Create a new salt
:param int length: How many bytes should the salt be long?
:return: The salt
:rtype: bytes | [
"Create",
"a",
"new",
"salt"
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L28-L36 |
edelbluth/blackred | src/blackred/blackred.py | BlackRed.__get_connection | def __get_connection(self) -> redis.Redis:
"""
Get a Redis connection
:return: Redis connection instance
:rtype: redis.Redis
"""
if self.__redis_use_socket:
r = redis.from_url(
'unix://{:s}?db={:d}'.format(
self.__redis_ho... | python | def __get_connection(self) -> redis.Redis:
"""
Get a Redis connection
:return: Redis connection instance
:rtype: redis.Redis
"""
if self.__redis_use_socket:
r = redis.from_url(
'unix://{:s}?db={:d}'.format(
self.__redis_ho... | [
"def",
"__get_connection",
"(",
"self",
")",
"->",
"redis",
".",
"Redis",
":",
"if",
"self",
".",
"__redis_use_socket",
":",
"r",
"=",
"redis",
".",
"from_url",
"(",
"'unix://{:s}?db={:d}'",
".",
"format",
"(",
"self",
".",
"__redis_host",
",",
"self",
"."... | Get a Redis connection
:return: Redis connection instance
:rtype: redis.Redis | [
"Get",
"a",
"Redis",
"connection"
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L208-L234 |
edelbluth/blackred | src/blackred/blackred.py | BlackRed._encode_item | def _encode_item(self, item: str) -> str:
"""
If anonymization is on, an item gets salted and hashed here.
:param str item:
:return: Hashed item, if anonymization is on; the unmodified item otherwise
:rtype: str
"""
assert item is not None
if not self.__r... | python | def _encode_item(self, item: str) -> str:
"""
If anonymization is on, an item gets salted and hashed here.
:param str item:
:return: Hashed item, if anonymization is on; the unmodified item otherwise
:rtype: str
"""
assert item is not None
if not self.__r... | [
"def",
"_encode_item",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"str",
":",
"assert",
"item",
"is",
"not",
"None",
"if",
"not",
"self",
".",
"__redis_conf",
"[",
"'anonymization'",
"]",
":",
"return",
"item",
"connection",
"=",
"self",
".",
"__... | If anonymization is on, an item gets salted and hashed here.
:param str item:
:return: Hashed item, if anonymization is on; the unmodified item otherwise
:rtype: str | [
"If",
"anonymization",
"is",
"on",
"an",
"item",
"gets",
"salted",
"and",
"hashed",
"here",
"."
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L245-L262 |
edelbluth/blackred | src/blackred/blackred.py | BlackRed.__get_ttl | def __get_ttl(self, item: str) -> int:
"""
Get the amount of time a specific item will remain in the database.
:param str item: The item to get the TTL for
:return: Time in seconds. Returns None for a non-existing element.
:rtype: int
"""
connection = self.__get_... | python | def __get_ttl(self, item: str) -> int:
"""
Get the amount of time a specific item will remain in the database.
:param str item: The item to get the TTL for
:return: Time in seconds. Returns None for a non-existing element.
:rtype: int
"""
connection = self.__get_... | [
"def",
"__get_ttl",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"int",
":",
"connection",
"=",
"self",
".",
"__get_connection",
"(",
")",
"ttl",
"=",
"connection",
".",
"ttl",
"(",
"item",
")",
"BlackRed",
".",
"__release_connection",
"(",
"connecti... | Get the amount of time a specific item will remain in the database.
:param str item: The item to get the TTL for
:return: Time in seconds. Returns None for a non-existing element.
:rtype: int | [
"Get",
"the",
"amount",
"of",
"time",
"a",
"specific",
"item",
"will",
"remain",
"in",
"the",
"database",
"."
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L264-L275 |
edelbluth/blackred | src/blackred/blackred.py | BlackRed.get_watchlist_ttl | def get_watchlist_ttl(self, item: str) -> int:
"""
Get the amount of time a specific item will remain on the watchlist.
:param str item: The item to get the TTL for on the watchlist
:return: Time in seconds. Returns None for a non-existing element
:rtype: int
"""
... | python | def get_watchlist_ttl(self, item: str) -> int:
"""
Get the amount of time a specific item will remain on the watchlist.
:param str item: The item to get the TTL for on the watchlist
:return: Time in seconds. Returns None for a non-existing element
:rtype: int
"""
... | [
"def",
"get_watchlist_ttl",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"int",
":",
"assert",
"item",
"is",
"not",
"None",
"item",
"=",
"self",
".",
"_encode_item",
"(",
"item",
")",
"return",
"self",
".",
"__get_ttl",
"(",
"self",
".",
"__redis_c... | Get the amount of time a specific item will remain on the watchlist.
:param str item: The item to get the TTL for on the watchlist
:return: Time in seconds. Returns None for a non-existing element
:rtype: int | [
"Get",
"the",
"amount",
"of",
"time",
"a",
"specific",
"item",
"will",
"remain",
"on",
"the",
"watchlist",
"."
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L289-L299 |
edelbluth/blackred | src/blackred/blackred.py | BlackRed.is_not_blocked | def is_not_blocked(self, item: str) -> bool:
"""
Check if an item is _not_ already on the blacklist
:param str item: The item to check
:return: True, when the item is _not_ on the blacklist
:rtype: bool
"""
assert item is not None
item = self._encode_item... | python | def is_not_blocked(self, item: str) -> bool:
"""
Check if an item is _not_ already on the blacklist
:param str item: The item to check
:return: True, when the item is _not_ on the blacklist
:rtype: bool
"""
assert item is not None
item = self._encode_item... | [
"def",
"is_not_blocked",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"bool",
":",
"assert",
"item",
"is",
"not",
"None",
"item",
"=",
"self",
".",
"_encode_item",
"(",
"item",
")",
"connection",
"=",
"self",
".",
"__get_connection",
"(",
")",
"key... | Check if an item is _not_ already on the blacklist
:param str item: The item to check
:return: True, when the item is _not_ on the blacklist
:rtype: bool | [
"Check",
"if",
"an",
"item",
"is",
"_not_",
"already",
"on",
"the",
"blacklist"
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L301-L320 |
edelbluth/blackred | src/blackred/blackred.py | BlackRed.log_fail | def log_fail(self, item: str) -> None:
"""
Log a failed action for an item. If the fail count for this item reaches the threshold, the item is moved to the
blacklist.
:param str item: The item to log
"""
assert item is not None
item = self._encode_item(item)
... | python | def log_fail(self, item: str) -> None:
"""
Log a failed action for an item. If the fail count for this item reaches the threshold, the item is moved to the
blacklist.
:param str item: The item to log
"""
assert item is not None
item = self._encode_item(item)
... | [
"def",
"log_fail",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"None",
":",
"assert",
"item",
"is",
"not",
"None",
"item",
"=",
"self",
".",
"_encode_item",
"(",
"item",
")",
"if",
"self",
".",
"is_blocked",
"(",
"item",
")",
":",
"return",
"c... | Log a failed action for an item. If the fail count for this item reaches the threshold, the item is moved to the
blacklist.
:param str item: The item to log | [
"Log",
"a",
"failed",
"action",
"for",
"an",
"item",
".",
"If",
"the",
"fail",
"count",
"for",
"this",
"item",
"reaches",
"the",
"threshold",
"the",
"item",
"is",
"moved",
"to",
"the",
"blacklist",
"."
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L332-L358 |
edelbluth/blackred | src/blackred/blackred.py | BlackRed.unblock | def unblock(self, item: str) -> None:
"""
Unblock an item and/or reset it's fail count
:param str item: The item to unblock
"""
assert item is not None
item = self._encode_item(item)
watchlist_key = self.__redis_conf['watchlist_template'].format(item)
bla... | python | def unblock(self, item: str) -> None:
"""
Unblock an item and/or reset it's fail count
:param str item: The item to unblock
"""
assert item is not None
item = self._encode_item(item)
watchlist_key = self.__redis_conf['watchlist_template'].format(item)
bla... | [
"def",
"unblock",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"None",
":",
"assert",
"item",
"is",
"not",
"None",
"item",
"=",
"self",
".",
"_encode_item",
"(",
"item",
")",
"watchlist_key",
"=",
"self",
".",
"__redis_conf",
"[",
"'watchlist_templat... | Unblock an item and/or reset it's fail count
:param str item: The item to unblock | [
"Unblock",
"an",
"item",
"and",
"/",
"or",
"reset",
"it",
"s",
"fail",
"count"
] | train | https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L360-L373 |
the01/python-paps | examples/measure/client.py | cmd_line | def cmd_line(line, ctrl):
clients = ctrl.modules
""" :type: list[WrapperClient] """
if line == "update start":
for client in clients:
client.updating_start()
elif line == "update stop":
for client in clients:
client.updating_stop()
return line | python | def cmd_line(line, ctrl):
clients = ctrl.modules
""" :type: list[WrapperClient] """
if line == "update start":
for client in clients:
client.updating_start()
elif line == "update stop":
for client in clients:
client.updating_stop()
return line | [
"def",
"cmd_line",
"(",
"line",
",",
"ctrl",
")",
":",
"clients",
"=",
"ctrl",
".",
"modules",
"if",
"line",
"==",
"\"update start\"",
":",
"for",
"client",
"in",
"clients",
":",
"client",
".",
"updating_start",
"(",
")",
"elif",
"line",
"==",
"\"update ... | :type: list[WrapperClient] | [
":",
"type",
":",
"list",
"[",
"WrapperClient",
"]"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/measure/client.py#L116-L125 |
kblin/aio-standalone | aiostandalone/app.py | StandaloneApplication.start_task | def start_task(self, func):
"""Start up a task"""
task = self.loop.create_task(func(self))
self._started_tasks.append(task)
def done_callback(done_task):
self._started_tasks.remove(done_task)
task.add_done_callback(done_callback)
return task | python | def start_task(self, func):
"""Start up a task"""
task = self.loop.create_task(func(self))
self._started_tasks.append(task)
def done_callback(done_task):
self._started_tasks.remove(done_task)
task.add_done_callback(done_callback)
return task | [
"def",
"start_task",
"(",
"self",
",",
"func",
")",
":",
"task",
"=",
"self",
".",
"loop",
".",
"create_task",
"(",
"func",
"(",
"self",
")",
")",
"self",
".",
"_started_tasks",
".",
"append",
"(",
"task",
")",
"def",
"done_callback",
"(",
"done_task",... | Start up a task | [
"Start",
"up",
"a",
"task"
] | train | https://github.com/kblin/aio-standalone/blob/21f7212ee23e7c2dff679fbf3e9c8d9acf77b568/aiostandalone/app.py#L77-L86 |
kblin/aio-standalone | aiostandalone/app.py | StandaloneApplication.run | def run(self, loop=None):
"""Actually run the application
:param loop: Custom event loop or None for default
"""
if loop is None:
loop = asyncio.get_event_loop()
self.loop = loop
loop.run_until_complete(self.startup())
for func in self.tasks:
... | python | def run(self, loop=None):
"""Actually run the application
:param loop: Custom event loop or None for default
"""
if loop is None:
loop = asyncio.get_event_loop()
self.loop = loop
loop.run_until_complete(self.startup())
for func in self.tasks:
... | [
"def",
"run",
"(",
"self",
",",
"loop",
"=",
"None",
")",
":",
"if",
"loop",
"is",
"None",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"self",
".",
"loop",
"=",
"loop",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"startup",... | Actually run the application
:param loop: Custom event loop or None for default | [
"Actually",
"run",
"the",
"application"
] | train | https://github.com/kblin/aio-standalone/blob/21f7212ee23e7c2dff679fbf3e9c8d9acf77b568/aiostandalone/app.py#L88-L123 |
jonathansick/paperweight | paperweight/gitio.py | read_git_blob | def read_git_blob(commit_ref, path, repo_dir='.'):
"""Get text from a git blob.
Parameters
----------
commit_ref : str
Any SHA or git tag that can resolve into a commit in the
git repository.
path : str
Path to the document in the git repository, relative to the root
... | python | def read_git_blob(commit_ref, path, repo_dir='.'):
"""Get text from a git blob.
Parameters
----------
commit_ref : str
Any SHA or git tag that can resolve into a commit in the
git repository.
path : str
Path to the document in the git repository, relative to the root
... | [
"def",
"read_git_blob",
"(",
"commit_ref",
",",
"path",
",",
"repo_dir",
"=",
"'.'",
")",
":",
"repo",
"=",
"git",
".",
"Repo",
"(",
"repo_dir",
")",
"tree",
"=",
"repo",
".",
"tree",
"(",
"commit_ref",
")",
"dirname",
",",
"fname",
"=",
"os",
".",
... | Get text from a git blob.
Parameters
----------
commit_ref : str
Any SHA or git tag that can resolve into a commit in the
git repository.
path : str
Path to the document in the git repository, relative to the root
of the repository.
repo_dir : str
Path from c... | [
"Get",
"text",
"from",
"a",
"git",
"blob",
"."
] | train | https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/gitio.py#L14-L42 |
jonathansick/paperweight | paperweight/gitio.py | _read_blob_in_tree | def _read_blob_in_tree(tree, components):
"""Recursively open trees to ultimately read a blob"""
if len(components) == 1:
# Tree is direct parent of blob
return _read_blob(tree, components[0])
else:
# Still trees to open
dirname = components.pop(0)
for t in tree.trave... | python | def _read_blob_in_tree(tree, components):
"""Recursively open trees to ultimately read a blob"""
if len(components) == 1:
# Tree is direct parent of blob
return _read_blob(tree, components[0])
else:
# Still trees to open
dirname = components.pop(0)
for t in tree.trave... | [
"def",
"_read_blob_in_tree",
"(",
"tree",
",",
"components",
")",
":",
"if",
"len",
"(",
"components",
")",
"==",
"1",
":",
"# Tree is direct parent of blob",
"return",
"_read_blob",
"(",
"tree",
",",
"components",
"[",
"0",
"]",
")",
"else",
":",
"# Still t... | Recursively open trees to ultimately read a blob | [
"Recursively",
"open",
"trees",
"to",
"ultimately",
"read",
"a",
"blob"
] | train | https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/gitio.py#L45-L55 |
jonathansick/paperweight | paperweight/gitio.py | absolute_git_root_dir | def absolute_git_root_dir(fpath=""):
"""Absolute path to the git root directory containing a given file or
directory.
"""
if len(fpath) == 0:
dirname_str = os.getcwd()
else:
dirname_str = os.path.dirname(fpath)
dirname_str = os.path.abspath(dirname_str)
dirnames = dirname_str... | python | def absolute_git_root_dir(fpath=""):
"""Absolute path to the git root directory containing a given file or
directory.
"""
if len(fpath) == 0:
dirname_str = os.getcwd()
else:
dirname_str = os.path.dirname(fpath)
dirname_str = os.path.abspath(dirname_str)
dirnames = dirname_str... | [
"def",
"absolute_git_root_dir",
"(",
"fpath",
"=",
"\"\"",
")",
":",
"if",
"len",
"(",
"fpath",
")",
"==",
"0",
":",
"dirname_str",
"=",
"os",
".",
"getcwd",
"(",
")",
"else",
":",
"dirname_str",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fpath",
... | Absolute path to the git root directory containing a given file or
directory. | [
"Absolute",
"path",
"to",
"the",
"git",
"root",
"directory",
"containing",
"a",
"given",
"file",
"or",
"directory",
"."
] | train | https://github.com/jonathansick/paperweight/blob/803535b939a56d375967cefecd5fdca81323041e/paperweight/gitio.py#L67-L84 |
DallasMorningNews/django-datafreezer | datafreezer/forms.py | DatasetUploadForm.clean | def clean(self):
"""Verifies that beginning date is before ending date."""
cleaned_data = super(DatasetUploadForm, self).clean()
date_begin = self.cleaned_data.get('date_begin')
date_end = self.cleaned_data.get('date_end')
if date_end < date_begin:
msg = u'End date sh... | python | def clean(self):
"""Verifies that beginning date is before ending date."""
cleaned_data = super(DatasetUploadForm, self).clean()
date_begin = self.cleaned_data.get('date_begin')
date_end = self.cleaned_data.get('date_end')
if date_end < date_begin:
msg = u'End date sh... | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"DatasetUploadForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"date_begin",
"=",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"'date_begin'",
")",
"date_end",
"=",
"self",
".",
... | Verifies that beginning date is before ending date. | [
"Verifies",
"that",
"beginning",
"date",
"is",
"before",
"ending",
"date",
"."
] | train | https://github.com/DallasMorningNews/django-datafreezer/blob/982dcf2015c80a280f1a093e32977cb71d4ea7aa/datafreezer/forms.py#L131-L140 |
Bystroushaak/kwargs_obj | src/kwargs_obj/kwargs_obj.py | KwargsObj._kwargs_to_attributes | def _kwargs_to_attributes(self, kwargs):
"""
Put keys from `kwargs` to `self`, if the keys are already there.
"""
for key, val in kwargs.iteritems():
if key not in self.__dict__:
raise ValueError(
"Can't set %s parameter - it is not defined... | python | def _kwargs_to_attributes(self, kwargs):
"""
Put keys from `kwargs` to `self`, if the keys are already there.
"""
for key, val in kwargs.iteritems():
if key not in self.__dict__:
raise ValueError(
"Can't set %s parameter - it is not defined... | [
"def",
"_kwargs_to_attributes",
"(",
"self",
",",
"kwargs",
")",
":",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"Can't set %s parameter -... | Put keys from `kwargs` to `self`, if the keys are already there. | [
"Put",
"keys",
"from",
"kwargs",
"to",
"self",
"if",
"the",
"keys",
"are",
"already",
"there",
"."
] | train | https://github.com/Bystroushaak/kwargs_obj/blob/67b571706f1dcbdacf465a34cd6a42b58cbd6449/src/kwargs_obj/kwargs_obj.py#L27-L37 |
baverman/supplement | supplement/remote.py | Environment.assist | def assist(self, project_path, source, position, filename):
"""Return completion match and list of completion proposals
:param project_path: absolute project path
:param source: unicode or byte string code source
:param position: character or byte cursor position
:param filename... | python | def assist(self, project_path, source, position, filename):
"""Return completion match and list of completion proposals
:param project_path: absolute project path
:param source: unicode or byte string code source
:param position: character or byte cursor position
:param filename... | [
"def",
"assist",
"(",
"self",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")",
":",
"return",
"self",
".",
"_call",
"(",
"'assist'",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")"
] | Return completion match and list of completion proposals
:param project_path: absolute project path
:param source: unicode or byte string code source
:param position: character or byte cursor position
:param filename: absolute path of file with source code
:returns: tuple (compl... | [
"Return",
"completion",
"match",
"and",
"list",
"of",
"completion",
"proposals"
] | train | https://github.com/baverman/supplement/blob/955002fe5a5749c9f0d89002f0006ec4fcd35bc9/supplement/remote.py#L114-L123 |
baverman/supplement | supplement/remote.py | Environment.get_location | def get_location(self, project_path, source, position, filename):
"""Return line number and file path where name under cursor is defined
If line is None location wasn't finded. If file path is None, defenition is located in
the same source.
:param project_path: absolute project path
... | python | def get_location(self, project_path, source, position, filename):
"""Return line number and file path where name under cursor is defined
If line is None location wasn't finded. If file path is None, defenition is located in
the same source.
:param project_path: absolute project path
... | [
"def",
"get_location",
"(",
"self",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")",
":",
"return",
"self",
".",
"_call",
"(",
"'get_location'",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")"
] | Return line number and file path where name under cursor is defined
If line is None location wasn't finded. If file path is None, defenition is located in
the same source.
:param project_path: absolute project path
:param source: unicode or byte string code source
:param positi... | [
"Return",
"line",
"number",
"and",
"file",
"path",
"where",
"name",
"under",
"cursor",
"is",
"defined"
] | train | https://github.com/baverman/supplement/blob/955002fe5a5749c9f0d89002f0006ec4fcd35bc9/supplement/remote.py#L125-L137 |
baverman/supplement | supplement/remote.py | Environment.get_docstring | def get_docstring(self, project_path, source, position, filename):
"""Return signature and docstring for current cursor call context
Some examples of call context::
func(|
func(arg|
func(arg,|
func(arg, func2(| # call context is func2
Signature ... | python | def get_docstring(self, project_path, source, position, filename):
"""Return signature and docstring for current cursor call context
Some examples of call context::
func(|
func(arg|
func(arg,|
func(arg, func2(| # call context is func2
Signature ... | [
"def",
"get_docstring",
"(",
"self",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")",
":",
"return",
"self",
".",
"_call",
"(",
"'get_docstring'",
",",
"project_path",
",",
"source",
",",
"position",
",",
"filename",
")"
] | Return signature and docstring for current cursor call context
Some examples of call context::
func(|
func(arg|
func(arg,|
func(arg, func2(| # call context is func2
Signature and docstring can be None
:param project_path: absolute project path
... | [
"Return",
"signature",
"and",
"docstring",
"for",
"current",
"cursor",
"call",
"context"
] | train | https://github.com/baverman/supplement/blob/955002fe5a5749c9f0d89002f0006ec4fcd35bc9/supplement/remote.py#L139-L158 |
baverman/supplement | supplement/remote.py | Environment.get_scope | def get_scope(self, project_path, source, lineno, filename, continous=True):
"""
Return scope name at cursor position
For example::
class Foo:
def foo(self):
pass
|
def bar(self):
pass
... | python | def get_scope(self, project_path, source, lineno, filename, continous=True):
"""
Return scope name at cursor position
For example::
class Foo:
def foo(self):
pass
|
def bar(self):
pass
... | [
"def",
"get_scope",
"(",
"self",
",",
"project_path",
",",
"source",
",",
"lineno",
",",
"filename",
",",
"continous",
"=",
"True",
")",
":",
"return",
"self",
".",
"_call",
"(",
"'get_scope'",
",",
"project_path",
",",
"source",
",",
"lineno",
",",
"fil... | Return scope name at cursor position
For example::
class Foo:
def foo(self):
pass
|
def bar(self):
pass
get_scope return Foo.foo if continuous is True and Foo otherwise.
:param project_pat... | [
"Return",
"scope",
"name",
"at",
"cursor",
"position"
] | train | https://github.com/baverman/supplement/blob/955002fe5a5749c9f0d89002f0006ec4fcd35bc9/supplement/remote.py#L168-L189 |
baverman/supplement | supplement/remote.py | Environment.close | def close(self):
"""Shutdown server"""
try:
self.conn
except AttributeError:
pass
else:
self.conn.send_bytes(dumps(('close', (), {}), 2))
self.conn.close()
del self.conn | python | def close(self):
"""Shutdown server"""
try:
self.conn
except AttributeError:
pass
else:
self.conn.send_bytes(dumps(('close', (), {}), 2))
self.conn.close()
del self.conn | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"conn",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"self",
".",
"conn",
".",
"send_bytes",
"(",
"dumps",
"(",
"(",
"'close'",
",",
"(",
")",
",",
"{",
"}",
")",
",",
"2",
... | Shutdown server | [
"Shutdown",
"server"
] | train | https://github.com/baverman/supplement/blob/955002fe5a5749c9f0d89002f0006ec4fcd35bc9/supplement/remote.py#L194-L204 |
Bystroushaak/remove_hairs | src/remove_hairs/__init__.py | remove_hairs | def remove_hairs(inp, hairs=HAIRS):
"""
Remove "special" characters from beginning and the end of the `inp`. For
example ``,a-sd,-/`` -> ``a-sd``.
Args:
inp (str): Input string.
hairs (str): List of characters which should be removed. See
:attr:`HAIRS` for details.
... | python | def remove_hairs(inp, hairs=HAIRS):
"""
Remove "special" characters from beginning and the end of the `inp`. For
example ``,a-sd,-/`` -> ``a-sd``.
Args:
inp (str): Input string.
hairs (str): List of characters which should be removed. See
:attr:`HAIRS` for details.
... | [
"def",
"remove_hairs",
"(",
"inp",
",",
"hairs",
"=",
"HAIRS",
")",
":",
"while",
"inp",
"and",
"inp",
"[",
"-",
"1",
"]",
"in",
"hairs",
":",
"inp",
"=",
"inp",
"[",
":",
"-",
"1",
"]",
"while",
"inp",
"and",
"inp",
"[",
"0",
"]",
"in",
"hai... | Remove "special" characters from beginning and the end of the `inp`. For
example ``,a-sd,-/`` -> ``a-sd``.
Args:
inp (str): Input string.
hairs (str): List of characters which should be removed. See
:attr:`HAIRS` for details.
Returns:
str: Cleaned string. | [
"Remove",
"special",
"characters",
"from",
"beginning",
"and",
"the",
"end",
"of",
"the",
"inp",
".",
"For",
"example",
"a",
"-",
"sd",
"-",
"/",
"-",
">",
"a",
"-",
"sd",
"."
] | train | https://github.com/Bystroushaak/remove_hairs/blob/457ca60a957d22da8347388cc2f6970220f1ca61/src/remove_hairs/__init__.py#L15-L34 |
Bystroushaak/remove_hairs | src/remove_hairs/__init__.py | remove_hairs_decorator | def remove_hairs_decorator(fn=None, hairs=HAIRS):
"""
Parametrized decorator wrapping the :func:`remove_hairs` function.
Args:
hairs (str, default HAIRS): List of characters which should be removed.
See :attr:`HAIRS` for details.
"""
def decorator_wrapper... | python | def remove_hairs_decorator(fn=None, hairs=HAIRS):
"""
Parametrized decorator wrapping the :func:`remove_hairs` function.
Args:
hairs (str, default HAIRS): List of characters which should be removed.
See :attr:`HAIRS` for details.
"""
def decorator_wrapper... | [
"def",
"remove_hairs_decorator",
"(",
"fn",
"=",
"None",
",",
"hairs",
"=",
"HAIRS",
")",
":",
"def",
"decorator_wrapper",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Parametrized decorator wrapping the :func:`remove_hairs` function.
Args:
hairs (str, default HAIRS): List of characters which should be removed.
See :attr:`HAIRS` for details. | [
"Parametrized",
"decorator",
"wrapping",
"the",
":",
"func",
":",
"remove_hairs",
"function",
"."
] | train | https://github.com/Bystroushaak/remove_hairs/blob/457ca60a957d22da8347388cc2f6970220f1ca61/src/remove_hairs/__init__.py#L37-L57 |
andreycizov/python-xrpc | xrpc/runtime.py | _masquerade | def _masquerade(origin: str, orig: ServiceDefn, new: ServiceDefn, **map: str) -> str:
"""build an origin URL such that the orig has all of the mappings to new defined by map"""
origin: ParseResult = urlparse(origin)
prev_maps = {}
if origin.query:
prev_maps = {k: v for k, v in parse_qsl(origi... | python | def _masquerade(origin: str, orig: ServiceDefn, new: ServiceDefn, **map: str) -> str:
"""build an origin URL such that the orig has all of the mappings to new defined by map"""
origin: ParseResult = urlparse(origin)
prev_maps = {}
if origin.query:
prev_maps = {k: v for k, v in parse_qsl(origi... | [
"def",
"_masquerade",
"(",
"origin",
":",
"str",
",",
"orig",
":",
"ServiceDefn",
",",
"new",
":",
"ServiceDefn",
",",
"*",
"*",
"map",
":",
"str",
")",
"->",
"str",
":",
"origin",
":",
"ParseResult",
"=",
"urlparse",
"(",
"origin",
")",
"prev_maps",
... | build an origin URL such that the orig has all of the mappings to new defined by map | [
"build",
"an",
"origin",
"URL",
"such",
"that",
"the",
"orig",
"has",
"all",
"of",
"the",
"mappings",
"to",
"new",
"defined",
"by",
"map"
] | train | https://github.com/andreycizov/python-xrpc/blob/4f916383cda7de3272962f3ba07a64f7ec451098/xrpc/runtime.py#L134-L164 |
andreycizov/python-xrpc | xrpc/runtime.py | masquerade | def masquerade(origin: str, orig: Type[TA], new: Type[TB], **map: str) -> str:
"""Make ``orig`` appear as new"""
return _masquerade(origin, cache_get(orig), cache_get(new), **map) | python | def masquerade(origin: str, orig: Type[TA], new: Type[TB], **map: str) -> str:
"""Make ``orig`` appear as new"""
return _masquerade(origin, cache_get(orig), cache_get(new), **map) | [
"def",
"masquerade",
"(",
"origin",
":",
"str",
",",
"orig",
":",
"Type",
"[",
"TA",
"]",
",",
"new",
":",
"Type",
"[",
"TB",
"]",
",",
"*",
"*",
"map",
":",
"str",
")",
"->",
"str",
":",
"return",
"_masquerade",
"(",
"origin",
",",
"cache_get",
... | Make ``orig`` appear as new | [
"Make",
"orig",
"appear",
"as",
"new"
] | train | https://github.com/andreycizov/python-xrpc/blob/4f916383cda7de3272962f3ba07a64f7ec451098/xrpc/runtime.py#L167-L170 |
codenerix/django-codenerix-extensions | codenerix_extensions/validators.py | spanishNIFNIECIFhelper | def spanishNIFNIECIFhelper(cid):
'''
Given a spanish NIF, CIF or NIE, it returns:
1 for a valid NIF
2 for a valid CIF
3 for a valid NIE
-1 for an invalid NIF (it looks like NIF but it doesn't validate the CRC)
-2 for an invalid CIF (it looks like CIF but it doesn't validate the CRC)
-3 ... | python | def spanishNIFNIECIFhelper(cid):
'''
Given a spanish NIF, CIF or NIE, it returns:
1 for a valid NIF
2 for a valid CIF
3 for a valid NIE
-1 for an invalid NIF (it looks like NIF but it doesn't validate the CRC)
-2 for an invalid CIF (it looks like CIF but it doesn't validate the CRC)
-3 ... | [
"def",
"spanishNIFNIECIFhelper",
"(",
"cid",
")",
":",
"# Set upper case",
"cid",
"=",
"cid",
".",
"upper",
"(",
")",
"# Already too long?",
"if",
"len",
"(",
"cid",
")",
">",
"9",
":",
"# Incorrect CID",
"return",
"-",
"4",
"# Check the format",
"compiled",
... | Given a spanish NIF, CIF or NIE, it returns:
1 for a valid NIF
2 for a valid CIF
3 for a valid NIE
-1 for an invalid NIF (it looks like NIF but it doesn't validate the CRC)
-2 for an invalid CIF (it looks like CIF but it doesn't validate the CRC)
-3 for an invalid NIE (it looks like NIE but id ... | [
"Given",
"a",
"spanish",
"NIF",
"CIF",
"or",
"NIE",
"it",
"returns",
":"
] | train | https://github.com/codenerix/django-codenerix-extensions/blob/e9c1d6f99f3e05833ab103bed2689ec34d64e591/codenerix_extensions/validators.py#L7-L115 |
SOBotics/pyRedunda | pyRedunda/Redunda.py | Redunda.sendStatusPing | def sendStatusPing(self):
"""
Sends a status ping to Redunda with the instance key specified while constructing the object.
"""
data = parse.urlencode({"key": self.key, "version": self.version}).encode()
req = request.Request("https://redunda.sobotics.org/status.json", data)
... | python | def sendStatusPing(self):
"""
Sends a status ping to Redunda with the instance key specified while constructing the object.
"""
data = parse.urlencode({"key": self.key, "version": self.version}).encode()
req = request.Request("https://redunda.sobotics.org/status.json", data)
... | [
"def",
"sendStatusPing",
"(",
"self",
")",
":",
"data",
"=",
"parse",
".",
"urlencode",
"(",
"{",
"\"key\"",
":",
"self",
".",
"key",
",",
"\"version\"",
":",
"self",
".",
"version",
"}",
")",
".",
"encode",
"(",
")",
"req",
"=",
"request",
".",
"R... | Sends a status ping to Redunda with the instance key specified while constructing the object. | [
"Sends",
"a",
"status",
"ping",
"to",
"Redunda",
"with",
"the",
"instance",
"key",
"specified",
"while",
"constructing",
"the",
"object",
"."
] | train | https://github.com/SOBotics/pyRedunda/blob/4bd190dc908861c5fac4c9b60cf79eeb0e5c76ab/pyRedunda/Redunda.py#L36-L49 |
SOBotics/pyRedunda | pyRedunda/Redunda.py | Redunda.uploadFile | def uploadFile(self, filename, ispickle=False, athome=False):
"""
Uploads a single file to Redunda.
:param str filename: The name of the file to upload
:param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False.
:returns: returns nothing
... | python | def uploadFile(self, filename, ispickle=False, athome=False):
"""
Uploads a single file to Redunda.
:param str filename: The name of the file to upload
:param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False.
:returns: returns nothing
... | [
"def",
"uploadFile",
"(",
"self",
",",
"filename",
",",
"ispickle",
"=",
"False",
",",
"athome",
"=",
"False",
")",
":",
"print",
"(",
"\"Uploading file {} to Redunda.\"",
".",
"format",
"(",
"filename",
")",
")",
"_",
",",
"tail",
"=",
"os",
".",
"path"... | Uploads a single file to Redunda.
:param str filename: The name of the file to upload
:param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False.
:returns: returns nothing | [
"Uploads",
"a",
"single",
"file",
"to",
"Redunda",
"."
] | train | https://github.com/SOBotics/pyRedunda/blob/4bd190dc908861c5fac4c9b60cf79eeb0e5c76ab/pyRedunda/Redunda.py#L51-L96 |
SOBotics/pyRedunda | pyRedunda/Redunda.py | Redunda.downloadFile | def downloadFile(self, filename, ispickle=False, athome=False):
"""
Downloads a single file from Redunda.
:param str filename: The name of the file you want to download
:param bool ispickle: Optional variable which tells if the file to be downloaded is a pickle; default is False.
... | python | def downloadFile(self, filename, ispickle=False, athome=False):
"""
Downloads a single file from Redunda.
:param str filename: The name of the file you want to download
:param bool ispickle: Optional variable which tells if the file to be downloaded is a pickle; default is False.
... | [
"def",
"downloadFile",
"(",
"self",
",",
"filename",
",",
"ispickle",
"=",
"False",
",",
"athome",
"=",
"False",
")",
":",
"print",
"(",
"\"Downloading file {} from Redunda.\"",
".",
"format",
"(",
"filename",
")",
")",
"_",
",",
"tail",
"=",
"os",
".",
... | Downloads a single file from Redunda.
:param str filename: The name of the file you want to download
:param bool ispickle: Optional variable which tells if the file to be downloaded is a pickle; default is False.
:returns: returns nothing | [
"Downloads",
"a",
"single",
"file",
"from",
"Redunda",
"."
] | train | https://github.com/SOBotics/pyRedunda/blob/4bd190dc908861c5fac4c9b60cf79eeb0e5c76ab/pyRedunda/Redunda.py#L98-L139 |
SOBotics/pyRedunda | pyRedunda/Redunda.py | Redunda.uploadFiles | def uploadFiles(self):
"""
Uploads all the files in 'filesToSync'
"""
for each_file in self.filesToSync:
self.uploadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) | python | def uploadFiles(self):
"""
Uploads all the files in 'filesToSync'
"""
for each_file in self.filesToSync:
self.uploadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) | [
"def",
"uploadFiles",
"(",
"self",
")",
":",
"for",
"each_file",
"in",
"self",
".",
"filesToSync",
":",
"self",
".",
"uploadFile",
"(",
"each_file",
"[",
"\"name\"",
"]",
",",
"each_file",
"[",
"\"ispickle\"",
"]",
",",
"each_file",
"[",
"\"at_home\"",
"]"... | Uploads all the files in 'filesToSync' | [
"Uploads",
"all",
"the",
"files",
"in",
"filesToSync"
] | train | https://github.com/SOBotics/pyRedunda/blob/4bd190dc908861c5fac4c9b60cf79eeb0e5c76ab/pyRedunda/Redunda.py#L141-L146 |
SOBotics/pyRedunda | pyRedunda/Redunda.py | Redunda.downloadFiles | def downloadFiles(self):
"""
Downloads all the files in 'filesToSync'
"""
for each_file in self.filesToSync:
self.downloadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) | python | def downloadFiles(self):
"""
Downloads all the files in 'filesToSync'
"""
for each_file in self.filesToSync:
self.downloadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) | [
"def",
"downloadFiles",
"(",
"self",
")",
":",
"for",
"each_file",
"in",
"self",
".",
"filesToSync",
":",
"self",
".",
"downloadFile",
"(",
"each_file",
"[",
"\"name\"",
"]",
",",
"each_file",
"[",
"\"ispickle\"",
"]",
",",
"each_file",
"[",
"\"at_home\"",
... | Downloads all the files in 'filesToSync' | [
"Downloads",
"all",
"the",
"files",
"in",
"filesToSync"
] | train | https://github.com/SOBotics/pyRedunda/blob/4bd190dc908861c5fac4c9b60cf79eeb0e5c76ab/pyRedunda/Redunda.py#L148-L153 |
SOBotics/pyRedunda | pyRedunda/Redunda.py | Redunda.getEvents | def getEvents(self):
"""
Gets all events from Redunda and returns them.
:returns: Returns a dictionary of the events which were fetched.
"""
url = "https://redunda.sobotics.org/events.json"
data = parse.urlencode({"key": self.key}).encode()
req = request.Reques... | python | def getEvents(self):
"""
Gets all events from Redunda and returns them.
:returns: Returns a dictionary of the events which were fetched.
"""
url = "https://redunda.sobotics.org/events.json"
data = parse.urlencode({"key": self.key}).encode()
req = request.Reques... | [
"def",
"getEvents",
"(",
"self",
")",
":",
"url",
"=",
"\"https://redunda.sobotics.org/events.json\"",
"data",
"=",
"parse",
".",
"urlencode",
"(",
"{",
"\"key\"",
":",
"self",
".",
"key",
"}",
")",
".",
"encode",
"(",
")",
"req",
"=",
"request",
".",
"R... | Gets all events from Redunda and returns them.
:returns: Returns a dictionary of the events which were fetched. | [
"Gets",
"all",
"events",
"from",
"Redunda",
"and",
"returns",
"them",
"."
] | train | https://github.com/SOBotics/pyRedunda/blob/4bd190dc908861c5fac4c9b60cf79eeb0e5c76ab/pyRedunda/Redunda.py#L155-L169 |
davisd50/sparc.db | sparc/db/splunk/search.py | saved_searches_factory_helper | def saved_searches_factory_helper(splunk_connection_info):
"""Return a valid splunklib.client.SavedSearches object
kwargs:
- see splunklib.client.connect()
"""
if not ISplunkConnectionInfo.providedBy(splunk_connection_info):
DoesNotImplement('argument did not provide expected interf... | python | def saved_searches_factory_helper(splunk_connection_info):
"""Return a valid splunklib.client.SavedSearches object
kwargs:
- see splunklib.client.connect()
"""
if not ISplunkConnectionInfo.providedBy(splunk_connection_info):
DoesNotImplement('argument did not provide expected interf... | [
"def",
"saved_searches_factory_helper",
"(",
"splunk_connection_info",
")",
":",
"if",
"not",
"ISplunkConnectionInfo",
".",
"providedBy",
"(",
"splunk_connection_info",
")",
":",
"DoesNotImplement",
"(",
"'argument did not provide expected interface'",
")",
"service",
"=",
... | Return a valid splunklib.client.SavedSearches object
kwargs:
- see splunklib.client.connect() | [
"Return",
"a",
"valid",
"splunklib",
".",
"client",
".",
"SavedSearches",
"object",
"kwargs",
":",
"-",
"see",
"splunklib",
".",
"client",
".",
"connect",
"()"
] | train | https://github.com/davisd50/sparc.db/blob/12dfcb51f7bdc4fbe9c8ec3b5af65059c1f66392/sparc/db/splunk/search.py#L25-L37 |
asphalt-framework/asphalt-memcached | asphalt/memcached/component.py | MemcachedComponent.configure_client | def configure_client(cls, host: str = 'localhost', port: int = 11211, **client_args):
"""
Configure a Memcached client.
:param host: host name or ip address to connect to
:param port: port number to connect to
:param client_args: extra keyword arguments passed to :class:`aiomcac... | python | def configure_client(cls, host: str = 'localhost', port: int = 11211, **client_args):
"""
Configure a Memcached client.
:param host: host name or ip address to connect to
:param port: port number to connect to
:param client_args: extra keyword arguments passed to :class:`aiomcac... | [
"def",
"configure_client",
"(",
"cls",
",",
"host",
":",
"str",
"=",
"'localhost'",
",",
"port",
":",
"int",
"=",
"11211",
",",
"*",
"*",
"client_args",
")",
":",
"assert",
"check_argument_types",
"(",
")",
"client",
"=",
"Client",
"(",
"host",
",",
"p... | Configure a Memcached client.
:param host: host name or ip address to connect to
:param port: port number to connect to
:param client_args: extra keyword arguments passed to :class:`aiomcache.Client` | [
"Configure",
"a",
"Memcached",
"client",
"."
] | train | https://github.com/asphalt-framework/asphalt-memcached/blob/48739fbc1f492c2ccfbe9ed0d8c8d8eda740bc0b/asphalt/memcached/component.py#L44-L55 |
ThreshingFloor/libtf | libtf/logparsers/tf_auth_log.py | TFAuthLog._extract_features | def _extract_features(self):
"""
Extracts and sets the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
# If it's ssh, we can handle it
if parsed_line.get('program') == 'sshd':
result = self._parse... | python | def _extract_features(self):
"""
Extracts and sets the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
# If it's ssh, we can handle it
if parsed_line.get('program') == 'sshd':
result = self._parse... | [
"def",
"_extract_features",
"(",
"self",
")",
":",
"for",
"parsed_line",
"in",
"self",
".",
"parsed_lines",
":",
"# If it's ssh, we can handle it",
"if",
"parsed_line",
".",
"get",
"(",
"'program'",
")",
"==",
"'sshd'",
":",
"result",
"=",
"self",
".",
"_parse... | Extracts and sets the feature data from the log file necessary for a reduction | [
"Extracts",
"and",
"sets",
"the",
"feature",
"data",
"from",
"the",
"log",
"file",
"necessary",
"for",
"a",
"reduction"
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_auth_log.py#L64-L85 |
ThreshingFloor/libtf | libtf/logparsers/tf_auth_log.py | TFAuthLog._extract_line_features | def _extract_line_features(self):
"""
Parse raw log lines and convert it to a dictionary with extracted features.
"""
for line in self.line_iterator:
m = COMPILED_AUTH_LOG_REGEX.match(line)
data = {
'raw': line
}
if m:
... | python | def _extract_line_features(self):
"""
Parse raw log lines and convert it to a dictionary with extracted features.
"""
for line in self.line_iterator:
m = COMPILED_AUTH_LOG_REGEX.match(line)
data = {
'raw': line
}
if m:
... | [
"def",
"_extract_line_features",
"(",
"self",
")",
":",
"for",
"line",
"in",
"self",
".",
"line_iterator",
":",
"m",
"=",
"COMPILED_AUTH_LOG_REGEX",
".",
"match",
"(",
"line",
")",
"data",
"=",
"{",
"'raw'",
":",
"line",
"}",
"if",
"m",
":",
"data",
".... | Parse raw log lines and convert it to a dictionary with extracted features. | [
"Parse",
"raw",
"log",
"lines",
"and",
"convert",
"it",
"to",
"a",
"dictionary",
"with",
"extracted",
"features",
"."
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_auth_log.py#L87-L107 |
ThreshingFloor/libtf | libtf/logparsers/tf_auth_log.py | TFAuthLog._analyze | def _analyze(self):
"""
Decide which lines should be filtered out
"""
pids = []
for ip in self.filter['ips']:
if ip in self.ips_to_pids:
for pid in self.ips_to_pids[ip]:
pids.append(pid)
for line in self.parsed_lines:
... | python | def _analyze(self):
"""
Decide which lines should be filtered out
"""
pids = []
for ip in self.filter['ips']:
if ip in self.ips_to_pids:
for pid in self.ips_to_pids[ip]:
pids.append(pid)
for line in self.parsed_lines:
... | [
"def",
"_analyze",
"(",
"self",
")",
":",
"pids",
"=",
"[",
"]",
"for",
"ip",
"in",
"self",
".",
"filter",
"[",
"'ips'",
"]",
":",
"if",
"ip",
"in",
"self",
".",
"ips_to_pids",
":",
"for",
"pid",
"in",
"self",
".",
"ips_to_pids",
"[",
"ip",
"]",
... | Decide which lines should be filtered out | [
"Decide",
"which",
"lines",
"should",
"be",
"filtered",
"out"
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_auth_log.py#L109-L124 |
ThreshingFloor/libtf | libtf/logparsers/tf_auth_log.py | TFAuthLog._to_epoch | def _to_epoch(self, ts):
"""
Adds a year to the syslog timestamp because syslog doesn't use years
:param ts: The timestamp to add a year to
:return: Date/time string that includes a year
"""
year = self.year
tmpts = "%s %s" % (ts, str(self.year))
new_tim... | python | def _to_epoch(self, ts):
"""
Adds a year to the syslog timestamp because syslog doesn't use years
:param ts: The timestamp to add a year to
:return: Date/time string that includes a year
"""
year = self.year
tmpts = "%s %s" % (ts, str(self.year))
new_tim... | [
"def",
"_to_epoch",
"(",
"self",
",",
"ts",
")",
":",
"year",
"=",
"self",
".",
"year",
"tmpts",
"=",
"\"%s %s\"",
"%",
"(",
"ts",
",",
"str",
"(",
"self",
".",
"year",
")",
")",
"new_time",
"=",
"int",
"(",
"calendar",
".",
"timegm",
"(",
"time"... | Adds a year to the syslog timestamp because syslog doesn't use years
:param ts: The timestamp to add a year to
:return: Date/time string that includes a year | [
"Adds",
"a",
"year",
"to",
"the",
"syslog",
"timestamp",
"because",
"syslog",
"doesn",
"t",
"use",
"years"
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_auth_log.py#L126-L144 |
ThreshingFloor/libtf | libtf/logparsers/tf_auth_log.py | TFAuthLog._parse_auth_message | def _parse_auth_message(self, auth_message):
"""
Parse a message to see if we have ip addresses or users that we care about
:param auth_message: The auth message to parse
:return: Result
"""
result = {}
has_matched = False
for regex in REGEXES_INVALID_U... | python | def _parse_auth_message(self, auth_message):
"""
Parse a message to see if we have ip addresses or users that we care about
:param auth_message: The auth message to parse
:return: Result
"""
result = {}
has_matched = False
for regex in REGEXES_INVALID_U... | [
"def",
"_parse_auth_message",
"(",
"self",
",",
"auth_message",
")",
":",
"result",
"=",
"{",
"}",
"has_matched",
"=",
"False",
"for",
"regex",
"in",
"REGEXES_INVALID_USER",
":",
"# Check for the invalid user/ip messages",
"m",
"=",
"re",
".",
"search",
"(",
"re... | Parse a message to see if we have ip addresses or users that we care about
:param auth_message: The auth message to parse
:return: Result | [
"Parse",
"a",
"message",
"to",
"see",
"if",
"we",
"have",
"ip",
"addresses",
"or",
"users",
"that",
"we",
"care",
"about"
] | train | https://github.com/ThreshingFloor/libtf/blob/f1a8710f750639c9b9e2a468ece0d2923bf8c3df/libtf/logparsers/tf_auth_log.py#L146-L189 |
guyingbo/iofree | iofree/__init__.py | read_until | def read_until(data: bytes, *, return_tail: bool = True, from_=None) -> bytes:
"""
read until some bytes appear
"""
return (yield (Traps._read_until, data, return_tail, from_)) | python | def read_until(data: bytes, *, return_tail: bool = True, from_=None) -> bytes:
"""
read until some bytes appear
"""
return (yield (Traps._read_until, data, return_tail, from_)) | [
"def",
"read_until",
"(",
"data",
":",
"bytes",
",",
"*",
",",
"return_tail",
":",
"bool",
"=",
"True",
",",
"from_",
"=",
"None",
")",
"->",
"bytes",
":",
"return",
"(",
"yield",
"(",
"Traps",
".",
"_read_until",
",",
"data",
",",
"return_tail",
","... | read until some bytes appear | [
"read",
"until",
"some",
"bytes",
"appear"
] | train | https://github.com/guyingbo/iofree/blob/9a14250c276f88c784d164f60fb22fbc1e7a3243/iofree/__init__.py#L214-L218 |
guyingbo/iofree | iofree/__init__.py | read_int | def read_int(nbytes: int, *, byteorder: str = "big", from_=None) -> int:
"""
read some bytes as integer
"""
return (yield (Traps._read_int, nbytes, byteorder, from_)) | python | def read_int(nbytes: int, *, byteorder: str = "big", from_=None) -> int:
"""
read some bytes as integer
"""
return (yield (Traps._read_int, nbytes, byteorder, from_)) | [
"def",
"read_int",
"(",
"nbytes",
":",
"int",
",",
"*",
",",
"byteorder",
":",
"str",
"=",
"\"big\"",
",",
"from_",
"=",
"None",
")",
"->",
"int",
":",
"return",
"(",
"yield",
"(",
"Traps",
".",
"_read_int",
",",
"nbytes",
",",
"byteorder",
",",
"f... | read some bytes as integer | [
"read",
"some",
"bytes",
"as",
"integer"
] | train | https://github.com/guyingbo/iofree/blob/9a14250c276f88c784d164f60fb22fbc1e7a3243/iofree/__init__.py#L228-L232 |
guyingbo/iofree | iofree/__init__.py | Parser.send | def send(self, data: bytes = b""):
"""
send data for parsing
"""
self.input.extend(data)
self._process() | python | def send(self, data: bytes = b""):
"""
send data for parsing
"""
self.input.extend(data)
self._process() | [
"def",
"send",
"(",
"self",
",",
"data",
":",
"bytes",
"=",
"b\"\"",
")",
":",
"self",
".",
"input",
".",
"extend",
"(",
"data",
")",
"self",
".",
"_process",
"(",
")"
] | send data for parsing | [
"send",
"data",
"for",
"parsing"
] | train | https://github.com/guyingbo/iofree/blob/9a14250c276f88c784d164f60fb22fbc1e7a3243/iofree/__init__.py#L44-L49 |
guyingbo/iofree | iofree/__init__.py | Parser.read | def read(self, nbytes: int = 0) -> bytes:
"""
read *at most* ``nbytes``
"""
if nbytes == 0 or len(self.output) <= nbytes:
data = bytes(self.output)
del self.output[:]
return data
data = bytes(self.output[:nbytes])
del self.output[:nbyte... | python | def read(self, nbytes: int = 0) -> bytes:
"""
read *at most* ``nbytes``
"""
if nbytes == 0 or len(self.output) <= nbytes:
data = bytes(self.output)
del self.output[:]
return data
data = bytes(self.output[:nbytes])
del self.output[:nbyte... | [
"def",
"read",
"(",
"self",
",",
"nbytes",
":",
"int",
"=",
"0",
")",
"->",
"bytes",
":",
"if",
"nbytes",
"==",
"0",
"or",
"len",
"(",
"self",
".",
"output",
")",
"<=",
"nbytes",
":",
"data",
"=",
"bytes",
"(",
"self",
".",
"output",
")",
"del"... | read *at most* ``nbytes`` | [
"read",
"*",
"at",
"most",
"*",
"nbytes"
] | train | https://github.com/guyingbo/iofree/blob/9a14250c276f88c784d164f60fb22fbc1e7a3243/iofree/__init__.py#L51-L61 |
guyingbo/iofree | iofree/__init__.py | Parser.get_result | def get_result(self):
"""
raises *NoResult* exception if no result has been set
"""
self._process()
if not self.has_result:
raise NoResult
return self.res_queue.popleft() | python | def get_result(self):
"""
raises *NoResult* exception if no result has been set
"""
self._process()
if not self.has_result:
raise NoResult
return self.res_queue.popleft() | [
"def",
"get_result",
"(",
"self",
")",
":",
"self",
".",
"_process",
"(",
")",
"if",
"not",
"self",
".",
"has_result",
":",
"raise",
"NoResult",
"return",
"self",
".",
"res_queue",
".",
"popleft",
"(",
")"
] | raises *NoResult* exception if no result has been set | [
"raises",
"*",
"NoResult",
"*",
"exception",
"if",
"no",
"result",
"has",
"been",
"set"
] | train | https://github.com/guyingbo/iofree/blob/9a14250c276f88c784d164f60fb22fbc1e7a3243/iofree/__init__.py#L67-L74 |
ryanjdillon/pylleo | pylleo/utils_bokeh.py | create_bokeh_server | def create_bokeh_server(io_loop, files, argvs, host, port):
'''Start bokeh server with applications paths'''
from bokeh.server.server import Server
from bokeh.command.util import build_single_handler_applications
# Turn file paths into bokeh apps
apps = build_single_handler_applications(files, argv... | python | def create_bokeh_server(io_loop, files, argvs, host, port):
'''Start bokeh server with applications paths'''
from bokeh.server.server import Server
from bokeh.command.util import build_single_handler_applications
# Turn file paths into bokeh apps
apps = build_single_handler_applications(files, argv... | [
"def",
"create_bokeh_server",
"(",
"io_loop",
",",
"files",
",",
"argvs",
",",
"host",
",",
"port",
")",
":",
"from",
"bokeh",
".",
"server",
".",
"server",
"import",
"Server",
"from",
"bokeh",
".",
"command",
".",
"util",
"import",
"build_single_handler_app... | Start bokeh server with applications paths | [
"Start",
"bokeh",
"server",
"with",
"applications",
"paths"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils_bokeh.py#L2-L26 |
FlorianLudwig/rueckenwind | rw/routing.py | _generate_request_handler_proxy | def _generate_request_handler_proxy(handler_class, handler_args, name):
"""When a tornado.web.RequestHandler gets mounted we create a launcher function"""
@scope.inject
def request_handler_wrapper(app, handler, **kwargs):
handler = handler_class(app, handler.request, **handler_args)
handler... | python | def _generate_request_handler_proxy(handler_class, handler_args, name):
"""When a tornado.web.RequestHandler gets mounted we create a launcher function"""
@scope.inject
def request_handler_wrapper(app, handler, **kwargs):
handler = handler_class(app, handler.request, **handler_args)
handler... | [
"def",
"_generate_request_handler_proxy",
"(",
"handler_class",
",",
"handler_args",
",",
"name",
")",
":",
"@",
"scope",
".",
"inject",
"def",
"request_handler_wrapper",
"(",
"app",
",",
"handler",
",",
"*",
"*",
"kwargs",
")",
":",
"handler",
"=",
"handler_c... | When a tornado.web.RequestHandler gets mounted we create a launcher function | [
"When",
"a",
"tornado",
".",
"web",
".",
"RequestHandler",
"gets",
"mounted",
"we",
"create",
"a",
"launcher",
"function"
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/routing.py#L178-L189 |
FlorianLudwig/rueckenwind | rw/routing.py | RoutingTable.setup | def setup(self):
"""setup routing table"""
# get all routes from submodules
for prefix, routes in self.sub_rt:
routes.prefix = self.prefix + prefix
routes.setup()
fn_name_prefixes = {}
for fn_key, fn in routes.fn_namespace.items():
... | python | def setup(self):
"""setup routing table"""
# get all routes from submodules
for prefix, routes in self.sub_rt:
routes.prefix = self.prefix + prefix
routes.setup()
fn_name_prefixes = {}
for fn_key, fn in routes.fn_namespace.items():
... | [
"def",
"setup",
"(",
"self",
")",
":",
"# get all routes from submodules",
"for",
"prefix",
",",
"routes",
"in",
"self",
".",
"sub_rt",
":",
"routes",
".",
"prefix",
"=",
"self",
".",
"prefix",
"+",
"prefix",
"routes",
".",
"setup",
"(",
")",
"fn_name_pref... | setup routing table | [
"setup",
"routing",
"table"
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/routing.py#L202-L229 |
TkTech/pytextql | setup.py | get_version | def get_version():
"""
Loads the current module version from version.py and returns
it.
:returns: module version identifier.
:rtype: str
"""
local_results = {}
version_file_path = os.path.join('pytextql', 'version.py')
# This is compatible with py3k which removed execfile.
with... | python | def get_version():
"""
Loads the current module version from version.py and returns
it.
:returns: module version identifier.
:rtype: str
"""
local_results = {}
version_file_path = os.path.join('pytextql', 'version.py')
# This is compatible with py3k which removed execfile.
with... | [
"def",
"get_version",
"(",
")",
":",
"local_results",
"=",
"{",
"}",
"version_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'pytextql'",
",",
"'version.py'",
")",
"# This is compatible with py3k which removed execfile.",
"with",
"open",
"(",
"version_file_p... | Loads the current module version from version.py and returns
it.
:returns: module version identifier.
:rtype: str | [
"Loads",
"the",
"current",
"module",
"version",
"from",
"version",
".",
"py",
"and",
"returns",
"it",
"."
] | train | https://github.com/TkTech/pytextql/blob/e054a7a4df7262deaca49bdbf748c00acf011b51/setup.py#L7-L25 |
webadmin87/midnight | midnight_main/templatetags/midnight_main.py | show_menu | def show_menu(context, slug, level=2, **kwargs):
"""
Тег для подключения меню
Пример использования::
{% show_menu 'menu_slug' 2 class='menu-class' %}
:param context: контекст шаблона
:param slug: символьный код родительского пункта меню
:param level: максимальный уровень вложенности
... | python | def show_menu(context, slug, level=2, **kwargs):
"""
Тег для подключения меню
Пример использования::
{% show_menu 'menu_slug' 2 class='menu-class' %}
:param context: контекст шаблона
:param slug: символьный код родительского пункта меню
:param level: максимальный уровень вложенности
... | [
"def",
"show_menu",
"(",
"context",
",",
"slug",
",",
"level",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"menu",
"=",
"Menu",
".",
"objects",
".",
"published",
"(",
")",
".",
"get",
"(",
"slug",
"=",
"slug",
")",
"menus",
"=",
"m... | Тег для подключения меню
Пример использования::
{% show_menu 'menu_slug' 2 class='menu-class' %}
:param context: контекст шаблона
:param slug: символьный код родительского пункта меню
:param level: максимальный уровень вложенности
:param kwargs: html атрибуты оборачивающего тега
:retu... | [
"Тег",
"для",
"подключения",
"меню"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L12-L33 |
webadmin87/midnight | midnight_main/templatetags/midnight_main.py | show_gallery | def show_gallery(slug, size="100x100", crop="center", **kwargs):
"""
Тег отображения фотогалереи
Пример использования::
{% show_gallery "gallery-slug" "150x110" "center" class='gallery-class' %}
:param slug: символьный код фотогалереи
:param size: размер
:param crop: параметры кропа
... | python | def show_gallery(slug, size="100x100", crop="center", **kwargs):
"""
Тег отображения фотогалереи
Пример использования::
{% show_gallery "gallery-slug" "150x110" "center" class='gallery-class' %}
:param slug: символьный код фотогалереи
:param size: размер
:param crop: параметры кропа
... | [
"def",
"show_gallery",
"(",
"slug",
",",
"size",
"=",
"\"100x100\"",
",",
"crop",
"=",
"\"center\"",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"album",
"=",
"PhotoAlbum",
".",
"objects",
".",
"published",
"(",
")",
".",
"get",
"(",
"slug",
"=",
... | Тег отображения фотогалереи
Пример использования::
{% show_gallery "gallery-slug" "150x110" "center" class='gallery-class' %}
:param slug: символьный код фотогалереи
:param size: размер
:param crop: параметры кропа
:param kwargs: html атрибуты оборачивающего тега
:return: | [
"Тег",
"отображения",
"фотогалереи"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L38-L58 |
webadmin87/midnight | midnight_main/templatetags/midnight_main.py | show_area | def show_area(slug):
"""
Подключение включаемой области
Пример использования::
{% show_area "area_slug" %}
:param slug: символьный код области
:return:
"""
try:
area = IncludeArea.objects.published().get(slug=slug)
return area.text
except IncludeArea.DoesNotExi... | python | def show_area(slug):
"""
Подключение включаемой области
Пример использования::
{% show_area "area_slug" %}
:param slug: символьный код области
:return:
"""
try:
area = IncludeArea.objects.published().get(slug=slug)
return area.text
except IncludeArea.DoesNotExi... | [
"def",
"show_area",
"(",
"slug",
")",
":",
"try",
":",
"area",
"=",
"IncludeArea",
".",
"objects",
".",
"published",
"(",
")",
".",
"get",
"(",
"slug",
"=",
"slug",
")",
"return",
"area",
".",
"text",
"except",
"IncludeArea",
".",
"DoesNotExist",
":",
... | Подключение включаемой области
Пример использования::
{% show_area "area_slug" %}
:param slug: символьный код области
:return: | [
"Подключение",
"включаемой",
"области"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L64-L79 |
webadmin87/midnight | midnight_main/templatetags/midnight_main.py | ajax_form | def ajax_form(cls_name, view_name, modal=False, tag_id=None):
"""
Подключение Ajax формы
Пример использования (обратная связь)::
{% ajax_form 'midnight_main.forms.Feedback' 'midnight_main:page_feedback' tag_id='feedback_form' modal=True %}
:param cls_name: имя класса формы
:param view_nam... | python | def ajax_form(cls_name, view_name, modal=False, tag_id=None):
"""
Подключение Ajax формы
Пример использования (обратная связь)::
{% ajax_form 'midnight_main.forms.Feedback' 'midnight_main:page_feedback' tag_id='feedback_form' modal=True %}
:param cls_name: имя класса формы
:param view_nam... | [
"def",
"ajax_form",
"(",
"cls_name",
",",
"view_name",
",",
"modal",
"=",
"False",
",",
"tag_id",
"=",
"None",
")",
":",
"if",
"tag_id",
"is",
"None",
":",
"tag_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"[",
":",
"6",
"]",
".",
"lower... | Подключение Ajax формы
Пример использования (обратная связь)::
{% ajax_form 'midnight_main.forms.Feedback' 'midnight_main:page_feedback' tag_id='feedback_form' modal=True %}
:param cls_name: имя класса формы
:param view_name: имя представления для обработки формы
:param modal: форма предназна... | [
"Подключение",
"Ajax",
"формы"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L82-L100 |
webadmin87/midnight | midnight_main/templatetags/midnight_main.py | comments_block | def comments_block(context, comments, form, obj, url, **kwargs):
"""
Тег для отображения блока комментариев
Пример использования (комментарии к текстовой странице)::
{% comments comments comments_form page "midnight_main:page_comments" %}
:param context: контекст
:param comments: список к... | python | def comments_block(context, comments, form, obj, url, **kwargs):
"""
Тег для отображения блока комментариев
Пример использования (комментарии к текстовой странице)::
{% comments comments comments_form page "midnight_main:page_comments" %}
:param context: контекст
:param comments: список к... | [
"def",
"comments_block",
"(",
"context",
",",
"comments",
",",
"form",
",",
"obj",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
"if",
"'class'",
"in",
"data",
":",
"data",
"[",
"'class'",
"]",
"+=",
"' comments-block'",
"else",... | Тег для отображения блока комментариев
Пример использования (комментарии к текстовой странице)::
{% comments comments comments_form page "midnight_main:page_comments" %}
:param context: контекст
:param comments: список комментариев
:param form: форма добавления комментария
:param obj: объ... | [
"Тег",
"для",
"отображения",
"блока",
"комментариев"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L140-L167 |
webadmin87/midnight | midnight_main/templatetags/midnight_main.py | search_simple_form | def search_simple_form(context, **kwargs):
"""
Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return:
"""
data = kwargs
if 'action' in data:
del data['action']
if 'method' in data:
... | python | def search_simple_form(context, **kwargs):
"""
Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return:
"""
data = kwargs
if 'action' in data:
del data['action']
if 'method' in data:
... | [
"def",
"search_simple_form",
"(",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
"if",
"'action'",
"in",
"data",
":",
"del",
"data",
"[",
"'action'",
"]",
"if",
"'method'",
"in",
"data",
":",
"del",
"data",
"[",
"'method'",
"]",
... | Форма поиска
Пример использования::
{% search_simple_form %}
:param context: контекст
:param kwargs: html атрибуты формы
:return: | [
"Форма",
"поиска"
] | train | https://github.com/webadmin87/midnight/blob/b60b3b257b4d633550b82a692f3ea3756c62a0a9/midnight_main/templatetags/midnight_main.py#L172-L193 |
thomasbiddle/Kippt-for-Python | kippt/clips.py | Clip.update | def update(self, **args):
""" Updates a Clip.
Parameters:
- args Dictionary of other fields
Accepted fields can be found here:
https://github.com/kippt/api-documentation/blob/master/objects/clip.md
"""
# JSONify our data.
data = json.dumps(args)
... | python | def update(self, **args):
""" Updates a Clip.
Parameters:
- args Dictionary of other fields
Accepted fields can be found here:
https://github.com/kippt/api-documentation/blob/master/objects/clip.md
"""
# JSONify our data.
data = json.dumps(args)
... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"# JSONify our data.",
"data",
"=",
"json",
".",
"dumps",
"(",
"args",
")",
"r",
"=",
"requests",
".",
"put",
"(",
"\"https://kippt.com/api/clips/%s\"",
"%",
"(",
"self",
".",
"id",
")",
",... | Updates a Clip.
Parameters:
- args Dictionary of other fields
Accepted fields can be found here:
https://github.com/kippt/api-documentation/blob/master/objects/clip.md | [
"Updates",
"a",
"Clip",
"."
] | train | https://github.com/thomasbiddle/Kippt-for-Python/blob/dddd0ff84d70ccf2d84e50e3cff7aad89f9c1267/kippt/clips.py#L150-L165 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.