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 |
|---|---|---|---|---|---|---|---|---|---|---|
twneale/uni | uni/checker.py | SpecChecker.path_eval | def path_eval(self, obj, keypath):
'''Given an object and a mongo-style dotted key path, return the
object value referenced by that key path.
'''
segs = keypath.split('.')
this = obj
for seg in segs:
if isinstance(this, dict):
try:
... | python | def path_eval(self, obj, keypath):
'''Given an object and a mongo-style dotted key path, return the
object value referenced by that key path.
'''
segs = keypath.split('.')
this = obj
for seg in segs:
if isinstance(this, dict):
try:
... | [
"def",
"path_eval",
"(",
"self",
",",
"obj",
",",
"keypath",
")",
":",
"segs",
"=",
"keypath",
".",
"split",
"(",
"'.'",
")",
"this",
"=",
"obj",
"for",
"seg",
"in",
"segs",
":",
"if",
"isinstance",
"(",
"this",
",",
"dict",
")",
":",
"try",
":",... | Given an object and a mongo-style dotted key path, return the
object value referenced by that key path. | [
"Given",
"an",
"object",
"and",
"a",
"mongo",
"-",
"style",
"dotted",
"key",
"path",
"return",
"the",
"object",
"value",
"referenced",
"by",
"that",
"key",
"path",
"."
] | train | https://github.com/twneale/uni/blob/1d2f3ef2cb97f544e878b8a1cde37ca8420af4e5/uni/checker.py#L43-L63 |
twneale/uni | uni/checker.py | SpecChecker.check | def check(self, spec, data):
'''Given a mongo-style spec and some data or python object,
check whether the object complies with the spec. Fails eagerly.
'''
path_eval = self.path_eval
for keypath, specvalue in spec.items():
if keypath.startswith('$'):
... | python | def check(self, spec, data):
'''Given a mongo-style spec and some data or python object,
check whether the object complies with the spec. Fails eagerly.
'''
path_eval = self.path_eval
for keypath, specvalue in spec.items():
if keypath.startswith('$'):
... | [
"def",
"check",
"(",
"self",
",",
"spec",
",",
"data",
")",
":",
"path_eval",
"=",
"self",
".",
"path_eval",
"for",
"keypath",
",",
"specvalue",
"in",
"spec",
".",
"items",
"(",
")",
":",
"if",
"keypath",
".",
"startswith",
"(",
"'$'",
")",
":",
"o... | Given a mongo-style spec and some data or python object,
check whether the object complies with the spec. Fails eagerly. | [
"Given",
"a",
"mongo",
"-",
"style",
"spec",
"and",
"some",
"data",
"or",
"python",
"object",
"check",
"whether",
"the",
"object",
"complies",
"with",
"the",
"spec",
".",
"Fails",
"eagerly",
"."
] | train | https://github.com/twneale/uni/blob/1d2f3ef2cb97f544e878b8a1cde37ca8420af4e5/uni/checker.py#L65-L87 |
twneale/uni | uni/checker.py | SpecChecker.handle_literal | def handle_literal(self, val, checkable):
'''This one's tricky...check for equality,
then for contains.
'''
# I.e., spec: {'x': 1}, data: {'x': 1}
if val == checkable:
yield True
return
# I.e., spec: {'x': 1}, data: {'x': [1, 2, 3]}
else:
... | python | def handle_literal(self, val, checkable):
'''This one's tricky...check for equality,
then for contains.
'''
# I.e., spec: {'x': 1}, data: {'x': 1}
if val == checkable:
yield True
return
# I.e., spec: {'x': 1}, data: {'x': [1, 2, 3]}
else:
... | [
"def",
"handle_literal",
"(",
"self",
",",
"val",
",",
"checkable",
")",
":",
"# I.e., spec: {'x': 1}, data: {'x': 1}",
"if",
"val",
"==",
"checkable",
":",
"yield",
"True",
"return",
"# I.e., spec: {'x': 1}, data: {'x': [1, 2, 3]}",
"else",
":",
"try",
":",
"yield",
... | This one's tricky...check for equality,
then for contains. | [
"This",
"one",
"s",
"tricky",
"...",
"check",
"for",
"equality",
"then",
"for",
"contains",
"."
] | train | https://github.com/twneale/uni/blob/1d2f3ef2cb97f544e878b8a1cde37ca8420af4e5/uni/checker.py#L95-L110 |
twneale/uni | uni/checker.py | SpecChecker.handle_exists | def handle_exists(self, spec, checkable):
'''The implementation of this one is weird. By the time
the {'$exists': True} spec gets to the dispatched
handler, the key presumably exists.
So we just parrot the assertion the spec makes. If it
asserts the key exists, we return True. I... | python | def handle_exists(self, spec, checkable):
'''The implementation of this one is weird. By the time
the {'$exists': True} spec gets to the dispatched
handler, the key presumably exists.
So we just parrot the assertion the spec makes. If it
asserts the key exists, we return True. I... | [
"def",
"handle_exists",
"(",
"self",
",",
"spec",
",",
"checkable",
")",
":",
"if",
"not",
"isinstance",
"(",
"spec",
",",
"bool",
")",
":",
"msg",
"=",
"'The argument of an exists query must be of type bool.'",
"raise",
"InvalidQuery",
"(",
"msg",
")",
"return"... | The implementation of this one is weird. By the time
the {'$exists': True} spec gets to the dispatched
handler, the key presumably exists.
So we just parrot the assertion the spec makes. If it
asserts the key exists, we return True. If it asserts
the key doesn't exist, we return... | [
"The",
"implementation",
"of",
"this",
"one",
"is",
"weird",
".",
"By",
"the",
"time",
"the",
"{",
"$exists",
":",
"True",
"}",
"spec",
"gets",
"to",
"the",
"dispatched",
"handler",
"the",
"key",
"presumably",
"exists",
"."
] | train | https://github.com/twneale/uni/blob/1d2f3ef2cb97f544e878b8a1cde37ca8420af4e5/uni/checker.py#L220-L233 |
anjos/rrbob | rr/preprocessor.py | normalize | def normalize(X, norm):
'''Applies the given norm to the input data set
Parameters:
X (numpy.ndarray): A 3D numpy ndarray in which the rows represent examples
while the columns, features of the data set you want to normalize. Every
depth corresponds to data for a particular class
norm (tuple... | python | def normalize(X, norm):
'''Applies the given norm to the input data set
Parameters:
X (numpy.ndarray): A 3D numpy ndarray in which the rows represent examples
while the columns, features of the data set you want to normalize. Every
depth corresponds to data for a particular class
norm (tuple... | [
"def",
"normalize",
"(",
"X",
",",
"norm",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"(",
"k",
"-",
"norm",
"[",
"0",
"]",
")",
"/",
"norm",
"[",
"1",
"]",
"for",
"k",
"in",
"X",
"]",
")"
] | Applies the given norm to the input data set
Parameters:
X (numpy.ndarray): A 3D numpy ndarray in which the rows represent examples
while the columns, features of the data set you want to normalize. Every
depth corresponds to data for a particular class
norm (tuple): A tuple containing two 1D ... | [
"Applies",
"the",
"given",
"norm",
"to",
"the",
"input",
"data",
"set"
] | train | https://github.com/anjos/rrbob/blob/d32d35bab2aa2698d3caa923fd02afb6d67f3235/rr/preprocessor.py#L37-L58 |
krukas/Trionyx | trionyx/trionyx/search.py | auto_register_search_models | def auto_register_search_models():
"""Auto register all search models"""
for config in models_config.get_all_configs():
if config.disable_search_index:
continue
search.register(
config.model.objects.get_queryset(),
ModelSearchAdapter,
fields=confi... | python | def auto_register_search_models():
"""Auto register all search models"""
for config in models_config.get_all_configs():
if config.disable_search_index:
continue
search.register(
config.model.objects.get_queryset(),
ModelSearchAdapter,
fields=confi... | [
"def",
"auto_register_search_models",
"(",
")",
":",
"for",
"config",
"in",
"models_config",
".",
"get_all_configs",
"(",
")",
":",
"if",
"config",
".",
"disable_search_index",
":",
"continue",
"search",
".",
"register",
"(",
"config",
".",
"model",
".",
"obje... | Auto register all search models | [
"Auto",
"register",
"all",
"search",
"models"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/search.py#L42-L53 |
krukas/Trionyx | trionyx/trionyx/search.py | ModelSearchAdapter.get_title | def get_title(self, obj):
"""Set search entry title for object"""
search_title = self.get_model_config_value(obj, 'search_title')
if not search_title:
return super().get_title(obj)
return search_title.format(**obj.__dict__) | python | def get_title(self, obj):
"""Set search entry title for object"""
search_title = self.get_model_config_value(obj, 'search_title')
if not search_title:
return super().get_title(obj)
return search_title.format(**obj.__dict__) | [
"def",
"get_title",
"(",
"self",
",",
"obj",
")",
":",
"search_title",
"=",
"self",
".",
"get_model_config_value",
"(",
"obj",
",",
"'search_title'",
")",
"if",
"not",
"search_title",
":",
"return",
"super",
"(",
")",
".",
"get_title",
"(",
"obj",
")",
"... | Set search entry title for object | [
"Set",
"search",
"entry",
"title",
"for",
"object"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/search.py#L18-L25 |
krukas/Trionyx | trionyx/trionyx/search.py | ModelSearchAdapter.get_description | def get_description(self, obj):
"""Set search entry description for object"""
search_description = self.get_model_config_value(obj, 'search_description')
if not search_description:
return super().get_description(obj)
return search_description.format(**obj.__dict__) | python | def get_description(self, obj):
"""Set search entry description for object"""
search_description = self.get_model_config_value(obj, 'search_description')
if not search_description:
return super().get_description(obj)
return search_description.format(**obj.__dict__) | [
"def",
"get_description",
"(",
"self",
",",
"obj",
")",
":",
"search_description",
"=",
"self",
".",
"get_model_config_value",
"(",
"obj",
",",
"'search_description'",
")",
"if",
"not",
"search_description",
":",
"return",
"super",
"(",
")",
".",
"get_descriptio... | Set search entry description for object | [
"Set",
"search",
"entry",
"description",
"for",
"object"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/search.py#L27-L34 |
krukas/Trionyx | trionyx/trionyx/search.py | ModelSearchAdapter.get_model_config_value | def get_model_config_value(self, obj, name):
"""Get config value for given model"""
config = models_config.get_config(obj)
return getattr(config, name) | python | def get_model_config_value(self, obj, name):
"""Get config value for given model"""
config = models_config.get_config(obj)
return getattr(config, name) | [
"def",
"get_model_config_value",
"(",
"self",
",",
"obj",
",",
"name",
")",
":",
"config",
"=",
"models_config",
".",
"get_config",
"(",
"obj",
")",
"return",
"getattr",
"(",
"config",
",",
"name",
")"
] | Get config value for given model | [
"Get",
"config",
"value",
"for",
"given",
"model"
] | train | https://github.com/krukas/Trionyx/blob/edac132cc0797190153f2e60bc7e88cb50e80da6/trionyx/trionyx/search.py#L36-L39 |
ereOn/pyslot | pyslot/signal.py | Signal.connect | def connect(self, callback, weak=False):
"""
Connects a new callback to this signal.
:param callback: The callback to connect.
:param weak: If `True`, only holds a weak reference to the specified
callback.
`callback` will be called whenever `emit` gets called on the... | python | def connect(self, callback, weak=False):
"""
Connects a new callback to this signal.
:param callback: The callback to connect.
:param weak: If `True`, only holds a weak reference to the specified
callback.
`callback` will be called whenever `emit` gets called on the... | [
"def",
"connect",
"(",
"self",
",",
"callback",
",",
"weak",
"=",
"False",
")",
":",
"if",
"weak",
":",
"callback",
"=",
"ref",
"(",
"callback",
",",
"self",
".",
"_callbacks",
".",
"remove",
")",
"self",
".",
"_callbacks",
".",
"append",
"(",
"callb... | Connects a new callback to this signal.
:param callback: The callback to connect.
:param weak: If `True`, only holds a weak reference to the specified
callback.
`callback` will be called whenever `emit` gets called on the `Signal`
instance.
If a weak reference is k... | [
"Connects",
"a",
"new",
"callback",
"to",
"this",
"signal",
"."
] | train | https://github.com/ereOn/pyslot/blob/9201ce84449ca811afb65fde6cd46a3cb7029182/pyslot/signal.py#L26-L55 |
ereOn/pyslot | pyslot/signal.py | Signal.disconnect | def disconnect(self, callback):
"""
Disconnects a callback from this signal.
:param callback: The callback to disconnect.
:param weak: A flag that must have the same value than the one
specified during the call to `connect`.
.. warning::
If the callback ... | python | def disconnect(self, callback):
"""
Disconnects a callback from this signal.
:param callback: The callback to disconnect.
:param weak: A flag that must have the same value than the one
specified during the call to `connect`.
.. warning::
If the callback ... | [
"def",
"disconnect",
"(",
"self",
",",
"callback",
")",
":",
"try",
":",
"self",
".",
"_callbacks",
".",
"remove",
"(",
"callback",
")",
"except",
"ValueError",
":",
"self",
".",
"_callbacks",
".",
"remove",
"(",
"ref",
"(",
"callback",
")",
")"
] | Disconnects a callback from this signal.
:param callback: The callback to disconnect.
:param weak: A flag that must have the same value than the one
specified during the call to `connect`.
.. warning::
If the callback is not connected at the time of call, a
... | [
"Disconnects",
"a",
"callback",
"from",
"this",
"signal",
"."
] | train | https://github.com/ereOn/pyslot/blob/9201ce84449ca811afb65fde6cd46a3cb7029182/pyslot/signal.py#L57-L75 |
ereOn/pyslot | pyslot/signal.py | Signal.emit | def emit(self, *args, **kwargs):
"""
Emit the signal.
:param args: The arguments.
:param kwargs: The keyword arguments.
All the connected callbacks will be called synchronously in order of
their registration.
"""
for callback in self.callbacks:
... | python | def emit(self, *args, **kwargs):
"""
Emit the signal.
:param args: The arguments.
:param kwargs: The keyword arguments.
All the connected callbacks will be called synchronously in order of
their registration.
"""
for callback in self.callbacks:
... | [
"def",
"emit",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Emit the signal.
:param args: The arguments.
:param kwargs: The keyword arguments.
All the connected callbacks will be called synchronously in order of
their registration. | [
"Emit",
"the",
"signal",
"."
] | train | https://github.com/ereOn/pyslot/blob/9201ce84449ca811afb65fde6cd46a3cb7029182/pyslot/signal.py#L84-L95 |
Kopachris/seshet | seshet/bot.py | _add_channel_names | def _add_channel_names(client, e):
"""Add a new channel to self.channels and initialize its user list.
Called as event handler for RPL_NAMES events. Do not call directly.
"""
chan = IRCstr(e.channel)
names = set([IRCstr(n) for n in e.name_list])
client.channels[chan] = ... | python | def _add_channel_names(client, e):
"""Add a new channel to self.channels and initialize its user list.
Called as event handler for RPL_NAMES events. Do not call directly.
"""
chan = IRCstr(e.channel)
names = set([IRCstr(n) for n in e.name_list])
client.channels[chan] = ... | [
"def",
"_add_channel_names",
"(",
"client",
",",
"e",
")",
":",
"chan",
"=",
"IRCstr",
"(",
"e",
".",
"channel",
")",
"names",
"=",
"set",
"(",
"[",
"IRCstr",
"(",
"n",
")",
"for",
"n",
"in",
"e",
".",
"name_list",
"]",
")",
"client",
".",
"chann... | Add a new channel to self.channels and initialize its user list.
Called as event handler for RPL_NAMES events. Do not call directly. | [
"Add",
"a",
"new",
"channel",
"to",
"self",
".",
"channels",
"and",
"initialize",
"its",
"user",
"list",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L517-L525 |
Kopachris/seshet | seshet/bot.py | SeshetUser.join | def join(self, channel):
"""Add this user to the channel's user list and add the channel to this
user's list of joined channels.
"""
if channel not in self.channels:
channel.users.add(self.nick)
self.channels.append(channel) | python | def join(self, channel):
"""Add this user to the channel's user list and add the channel to this
user's list of joined channels.
"""
if channel not in self.channels:
channel.users.add(self.nick)
self.channels.append(channel) | [
"def",
"join",
"(",
"self",
",",
"channel",
")",
":",
"if",
"channel",
"not",
"in",
"self",
".",
"channels",
":",
"channel",
".",
"users",
".",
"add",
"(",
"self",
".",
"nick",
")",
"self",
".",
"channels",
".",
"append",
"(",
"channel",
")"
] | Add this user to the channel's user list and add the channel to this
user's list of joined channels. | [
"Add",
"this",
"user",
"to",
"the",
"channel",
"s",
"user",
"list",
"and",
"add",
"the",
"channel",
"to",
"this",
"user",
"s",
"list",
"of",
"joined",
"channels",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L23-L30 |
Kopachris/seshet | seshet/bot.py | SeshetUser.part | def part(self, channel):
"""Remove this user from the channel's user list and remove the channel
from this user's list of joined channels.
"""
if channel in self.channels:
channel.users.remove(self.nick)
self.channels.remove(channel) | python | def part(self, channel):
"""Remove this user from the channel's user list and remove the channel
from this user's list of joined channels.
"""
if channel in self.channels:
channel.users.remove(self.nick)
self.channels.remove(channel) | [
"def",
"part",
"(",
"self",
",",
"channel",
")",
":",
"if",
"channel",
"in",
"self",
".",
"channels",
":",
"channel",
".",
"users",
".",
"remove",
"(",
"self",
".",
"nick",
")",
"self",
".",
"channels",
".",
"remove",
"(",
"channel",
")"
] | Remove this user from the channel's user list and remove the channel
from this user's list of joined channels. | [
"Remove",
"this",
"user",
"from",
"the",
"channel",
"s",
"user",
"list",
"and",
"remove",
"the",
"channel",
"from",
"this",
"user",
"s",
"list",
"of",
"joined",
"channels",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L32-L39 |
Kopachris/seshet | seshet/bot.py | SeshetUser.quit | def quit(self):
"""Remove this user from all channels and reinitialize the user's list
of joined channels.
"""
for c in self.channels:
c.users.remove(self.nick)
self.channels = [] | python | def quit(self):
"""Remove this user from all channels and reinitialize the user's list
of joined channels.
"""
for c in self.channels:
c.users.remove(self.nick)
self.channels = [] | [
"def",
"quit",
"(",
"self",
")",
":",
"for",
"c",
"in",
"self",
".",
"channels",
":",
"c",
".",
"users",
".",
"remove",
"(",
"self",
".",
"nick",
")",
"self",
".",
"channels",
"=",
"[",
"]"
] | Remove this user from all channels and reinitialize the user's list
of joined channels. | [
"Remove",
"this",
"user",
"from",
"all",
"channels",
"and",
"reinitialize",
"the",
"user",
"s",
"list",
"of",
"joined",
"channels",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L41-L48 |
Kopachris/seshet | seshet/bot.py | SeshetUser.change_nick | def change_nick(self, nick):
"""Update this user's nick in all joined channels."""
old_nick = self.nick
self.nick = IRCstr(nick)
for c in self.channels:
c.users.remove(old_nick)
c.users.add(self.nick) | python | def change_nick(self, nick):
"""Update this user's nick in all joined channels."""
old_nick = self.nick
self.nick = IRCstr(nick)
for c in self.channels:
c.users.remove(old_nick)
c.users.add(self.nick) | [
"def",
"change_nick",
"(",
"self",
",",
"nick",
")",
":",
"old_nick",
"=",
"self",
".",
"nick",
"self",
".",
"nick",
"=",
"IRCstr",
"(",
"nick",
")",
"for",
"c",
"in",
"self",
".",
"channels",
":",
"c",
".",
"users",
".",
"remove",
"(",
"old_nick",... | Update this user's nick in all joined channels. | [
"Update",
"this",
"user",
"s",
"nick",
"in",
"all",
"joined",
"channels",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L50-L58 |
Kopachris/seshet | seshet/bot.py | SeshetChannel.log_message | def log_message(self, user, message):
"""Log a channel message.
This log acts as a sort of cache so that recent activity can be searched
by the bot and command modules without querying the database.
"""
if isinstance(user, SeshetUser):
user = user.ni... | python | def log_message(self, user, message):
"""Log a channel message.
This log acts as a sort of cache so that recent activity can be searched
by the bot and command modules without querying the database.
"""
if isinstance(user, SeshetUser):
user = user.ni... | [
"def",
"log_message",
"(",
"self",
",",
"user",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"user",
",",
"SeshetUser",
")",
":",
"user",
"=",
"user",
".",
"nick",
"elif",
"not",
"isinstance",
"(",
"user",
",",
"IRCstr",
")",
":",
"user",
"=",
... | Log a channel message.
This log acts as a sort of cache so that recent activity can be searched
by the bot and command modules without querying the database. | [
"Log",
"a",
"channel",
"message",
".",
"This",
"log",
"acts",
"as",
"a",
"sort",
"of",
"cache",
"so",
"that",
"recent",
"activity",
"can",
"be",
"searched",
"by",
"the",
"bot",
"and",
"command",
"modules",
"without",
"querying",
"the",
"database",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L77-L94 |
Kopachris/seshet | seshet/bot.py | SeshetBot.log | def log(self, etype, source, msg='', target='', hostmask='', params=''):
"""Log an event in the database.
Required:
`etype` - event type. One of 'PRIVMSG', 'QUIT', 'PART', 'ACTION',
'NICK', 'JOIN', 'MODE', 'KICK', 'CTCP', or 'ERROR'. Enforced
by data... | python | def log(self, etype, source, msg='', target='', hostmask='', params=''):
"""Log an event in the database.
Required:
`etype` - event type. One of 'PRIVMSG', 'QUIT', 'PART', 'ACTION',
'NICK', 'JOIN', 'MODE', 'KICK', 'CTCP', or 'ERROR'. Enforced
by data... | [
"def",
"log",
"(",
"self",
",",
"etype",
",",
"source",
",",
"msg",
"=",
"''",
",",
"target",
"=",
"''",
",",
"hostmask",
"=",
"''",
",",
"params",
"=",
"''",
")",
":",
"self",
".",
"db",
".",
"event_log",
".",
"insert",
"(",
"event_type",
"=",
... | Log an event in the database.
Required:
`etype` - event type. One of 'PRIVMSG', 'QUIT', 'PART', 'ACTION',
'NICK', 'JOIN', 'MODE', 'KICK', 'CTCP', or 'ERROR'. Enforced
by database model.
`source` - source of the event. Usually a user. For NICK eve... | [
"Log",
"an",
"event",
"in",
"the",
"database",
".",
"Required",
":",
"etype",
"-",
"event",
"type",
".",
"One",
"of",
"PRIVMSG",
"QUIT",
"PART",
"ACTION",
"NICK",
"JOIN",
"MODE",
"KICK",
"CTCP",
"or",
"ERROR",
".",
"Enforced",
"by",
"database",
"model",
... | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L163-L194 |
Kopachris/seshet | seshet/bot.py | SeshetBot.get_unique_users | def get_unique_users(self, chan):
"""Get the set of users that are unique to the given channel (i.e. not
present in any other channel the bot is in).
"""
chan = IRCstr(chan)
these_users = self.channels[chan].users
other_users = set()
for c in sel... | python | def get_unique_users(self, chan):
"""Get the set of users that are unique to the given channel (i.e. not
present in any other channel the bot is in).
"""
chan = IRCstr(chan)
these_users = self.channels[chan].users
other_users = set()
for c in sel... | [
"def",
"get_unique_users",
"(",
"self",
",",
"chan",
")",
":",
"chan",
"=",
"IRCstr",
"(",
"chan",
")",
"these_users",
"=",
"self",
".",
"channels",
"[",
"chan",
"]",
".",
"users",
"other_users",
"=",
"set",
"(",
")",
"for",
"c",
"in",
"self",
".",
... | Get the set of users that are unique to the given channel (i.e. not
present in any other channel the bot is in). | [
"Get",
"the",
"set",
"of",
"users",
"that",
"are",
"unique",
"to",
"the",
"given",
"channel",
"(",
"i",
".",
"e",
".",
"not",
"present",
"in",
"any",
"other",
"channel",
"the",
"bot",
"is",
"in",
")",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L279-L292 |
Kopachris/seshet | seshet/bot.py | SeshetBot.connect | def connect(self, *args, **kwargs):
"""Extend `client.SimpleClient.connect()` with defaults"""
defaults = {}
for i, k in enumerate(('host', 'port', 'channel', 'use_ssl', 'password')):
if i < len(args):
defaults[k] = args[i]
elif k in kwargs:
... | python | def connect(self, *args, **kwargs):
"""Extend `client.SimpleClient.connect()` with defaults"""
defaults = {}
for i, k in enumerate(('host', 'port', 'channel', 'use_ssl', 'password')):
if i < len(args):
defaults[k] = args[i]
elif k in kwargs:
... | [
"def",
"connect",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"(",
"'host'",
",",
"'port'",
",",
"'channel'",
",",
"'use_ssl'",
",",
"'password'",
")",
... | Extend `client.SimpleClient.connect()` with defaults | [
"Extend",
"client",
".",
"SimpleClient",
".",
"connect",
"()",
"with",
"defaults"
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L430-L454 |
Kopachris/seshet | seshet/bot.py | SeshetBot._log_to_file | def _log_to_file(self, etype, source, msg='', target='', hostmask='', params=''):
"""Override `log()` if bot is not initialized with a database
connection. Do not call this method directly.
"""
today = datetime.utcnow()
# TODO: Use self.locale['timezone'] for changing time
... | python | def _log_to_file(self, etype, source, msg='', target='', hostmask='', params=''):
"""Override `log()` if bot is not initialized with a database
connection. Do not call this method directly.
"""
today = datetime.utcnow()
# TODO: Use self.locale['timezone'] for changing time
... | [
"def",
"_log_to_file",
"(",
"self",
",",
"etype",
",",
"source",
",",
"msg",
"=",
"''",
",",
"target",
"=",
"''",
",",
"hostmask",
"=",
"''",
",",
"params",
"=",
"''",
")",
":",
"today",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"# TODO: Use self.loc... | Override `log()` if bot is not initialized with a database
connection. Do not call this method directly. | [
"Override",
"log",
"()",
"if",
"bot",
"is",
"not",
"initialized",
"with",
"a",
"database",
"connection",
".",
"Do",
"not",
"call",
"this",
"method",
"directly",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L460-L482 |
Kopachris/seshet | seshet/bot.py | SeshetBot._loop | def _loop(self, map):
"""The main loop. Poll sockets for I/O and run any other functions
that need to be run every loop.
"""
try:
from asyncore import poll
except ImportError:
raise Exception("Couldn't find poll function. Cannot start bot.")
w... | python | def _loop(self, map):
"""The main loop. Poll sockets for I/O and run any other functions
that need to be run every loop.
"""
try:
from asyncore import poll
except ImportError:
raise Exception("Couldn't find poll function. Cannot start bot.")
w... | [
"def",
"_loop",
"(",
"self",
",",
"map",
")",
":",
"try",
":",
"from",
"asyncore",
"import",
"poll",
"except",
"ImportError",
":",
"raise",
"Exception",
"(",
"\"Couldn't find poll function. Cannot start bot.\"",
")",
"while",
"map",
":",
"self",
".",
"before_pol... | The main loop. Poll sockets for I/O and run any other functions
that need to be run every loop. | [
"The",
"main",
"loop",
".",
"Poll",
"sockets",
"for",
"I",
"/",
"O",
"and",
"run",
"any",
"other",
"functions",
"that",
"need",
"to",
"be",
"run",
"every",
"loop",
"."
] | train | https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L502-L514 |
clearclaw/logtool | logtool/log_fault_impl.py | log_fault | def log_fault (exc, message = "", level = logging.CRITICAL,
traceback = False):
"""Print the usual traceback information, followed by a listing of all
the local variables in each frame.
"""
tb = sys.exc_info ()[2]
stack = _get_stack (tb)
LOG.log (level,
"FAULT: %s%s(%s): %s", ("%s ... | python | def log_fault (exc, message = "", level = logging.CRITICAL,
traceback = False):
"""Print the usual traceback information, followed by a listing of all
the local variables in each frame.
"""
tb = sys.exc_info ()[2]
stack = _get_stack (tb)
LOG.log (level,
"FAULT: %s%s(%s): %s", ("%s ... | [
"def",
"log_fault",
"(",
"exc",
",",
"message",
"=",
"\"\"",
",",
"level",
"=",
"logging",
".",
"CRITICAL",
",",
"traceback",
"=",
"False",
")",
":",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"stack",
"=",
"_get_stack",
"(",
"tb",... | Print the usual traceback information, followed by a listing of all
the local variables in each frame. | [
"Print",
"the",
"usual",
"traceback",
"information",
"followed",
"by",
"a",
"listing",
"of",
"all",
"the",
"local",
"variables",
"in",
"each",
"frame",
"."
] | train | https://github.com/clearclaw/logtool/blob/e34c9a580538a9a14fec9b4bbab8b8df92ad36e7/logtool/log_fault_impl.py#L38-L52 |
clearclaw/logtool | logtool/log_fault_impl.py | log_fault_exc_str | def log_fault_exc_str (exc, # pylint: disable=W0613
message = "", level = logging.CRITICAL,
traceback = False):
"""Make a StringIO of the usual traceback information, followed by a
listing of all the local variables in each frame.
"""
return log_fault_info_str (sys.... | python | def log_fault_exc_str (exc, # pylint: disable=W0613
message = "", level = logging.CRITICAL,
traceback = False):
"""Make a StringIO of the usual traceback information, followed by a
listing of all the local variables in each frame.
"""
return log_fault_info_str (sys.... | [
"def",
"log_fault_exc_str",
"(",
"exc",
",",
"# pylint: disable=W0613",
"message",
"=",
"\"\"",
",",
"level",
"=",
"logging",
".",
"CRITICAL",
",",
"traceback",
"=",
"False",
")",
":",
"return",
"log_fault_info_str",
"(",
"sys",
".",
"exc_info",
"(",
")",
",... | Make a StringIO of the usual traceback information, followed by a
listing of all the local variables in each frame. | [
"Make",
"a",
"StringIO",
"of",
"the",
"usual",
"traceback",
"information",
"followed",
"by",
"a",
"listing",
"of",
"all",
"the",
"local",
"variables",
"in",
"each",
"frame",
"."
] | train | https://github.com/clearclaw/logtool/blob/e34c9a580538a9a14fec9b4bbab8b8df92ad36e7/logtool/log_fault_impl.py#L74-L81 |
clearclaw/logtool | logtool/log_fault_impl.py | log_fault_info_str | def log_fault_info_str (exc_info, message = "", level = logging.CRITICAL,
traceback = False):
"""Make a StringIO of the usual traceback information, followed by a
listing of all the local variables in each frame.
"""
tb = sys.exc_info ()[2]
stack = _get_stack (tb)
rc = StringIO ()
... | python | def log_fault_info_str (exc_info, message = "", level = logging.CRITICAL,
traceback = False):
"""Make a StringIO of the usual traceback information, followed by a
listing of all the local variables in each frame.
"""
tb = sys.exc_info ()[2]
stack = _get_stack (tb)
rc = StringIO ()
... | [
"def",
"log_fault_info_str",
"(",
"exc_info",
",",
"message",
"=",
"\"\"",
",",
"level",
"=",
"logging",
".",
"CRITICAL",
",",
"traceback",
"=",
"False",
")",
":",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"stack",
"=",
"_get_stack",
... | Make a StringIO of the usual traceback information, followed by a
listing of all the local variables in each frame. | [
"Make",
"a",
"StringIO",
"of",
"the",
"usual",
"traceback",
"information",
"followed",
"by",
"a",
"listing",
"of",
"all",
"the",
"local",
"variables",
"in",
"each",
"frame",
"."
] | train | https://github.com/clearclaw/logtool/blob/e34c9a580538a9a14fec9b4bbab8b8df92ad36e7/logtool/log_fault_impl.py#L84-L101 |
luismasuelli/python-cantrips | cantrips/patterns/snapshot.py | can_take | def can_take(attrs_to_freeze=(), defaults=None, source_attr='source', instance_property_name='snapshot', inner_class_name='Snapshot'):
"""
Decorator to make a class allow their instances to generate
snapshot of themselves.
Decorates the class by allowing it to have:
* A custom class to serve each... | python | def can_take(attrs_to_freeze=(), defaults=None, source_attr='source', instance_property_name='snapshot', inner_class_name='Snapshot'):
"""
Decorator to make a class allow their instances to generate
snapshot of themselves.
Decorates the class by allowing it to have:
* A custom class to serve each... | [
"def",
"can_take",
"(",
"attrs_to_freeze",
"=",
"(",
")",
",",
"defaults",
"=",
"None",
",",
"source_attr",
"=",
"'source'",
",",
"instance_property_name",
"=",
"'snapshot'",
",",
"inner_class_name",
"=",
"'Snapshot'",
")",
":",
"def",
"wrapper",
"(",
"klass",... | Decorator to make a class allow their instances to generate
snapshot of themselves.
Decorates the class by allowing it to have:
* A custom class to serve each snapshot. Such class
will have a subset of attributes to serve from the object,
and a special designed attribute ('source', by def... | [
"Decorator",
"to",
"make",
"a",
"class",
"allow",
"their",
"instances",
"to",
"generate",
"snapshot",
"of",
"themselves",
"."
] | train | https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/patterns/snapshot.py#L4-L39 |
Archived-Object/ligament | ligament/buildcontext.py | Context.register_dependency | def register_dependency(self, data_src, data_sink):
""" registers a dependency of data_src -> data_sink
by placing appropriate entries in provides_for and depends_on
"""
pdebug("registering dependency %s -> %s" % (data_src, data_sink))
if (data_src not in self._gettask(data... | python | def register_dependency(self, data_src, data_sink):
""" registers a dependency of data_src -> data_sink
by placing appropriate entries in provides_for and depends_on
"""
pdebug("registering dependency %s -> %s" % (data_src, data_sink))
if (data_src not in self._gettask(data... | [
"def",
"register_dependency",
"(",
"self",
",",
"data_src",
",",
"data_sink",
")",
":",
"pdebug",
"(",
"\"registering dependency %s -> %s\"",
"%",
"(",
"data_src",
",",
"data_sink",
")",
")",
"if",
"(",
"data_src",
"not",
"in",
"self",
".",
"_gettask",
"(",
... | registers a dependency of data_src -> data_sink
by placing appropriate entries in provides_for and depends_on | [
"registers",
"a",
"dependency",
"of",
"data_src",
"-",
">",
"data_sink",
"by",
"placing",
"appropriate",
"entries",
"in",
"provides_for",
"and",
"depends_on"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L55-L66 |
Archived-Object/ligament | ligament/buildcontext.py | Context.build_task | def build_task(self, name):
""" Builds a task by name, resolving any dependencies on the way """
try:
self._gettask(name).value = (
self._gettask(name).task.resolve_and_build())
except TaskExecutionException as e:
perror(e.header, indent="+0")
... | python | def build_task(self, name):
""" Builds a task by name, resolving any dependencies on the way """
try:
self._gettask(name).value = (
self._gettask(name).task.resolve_and_build())
except TaskExecutionException as e:
perror(e.header, indent="+0")
... | [
"def",
"build_task",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"_gettask",
"(",
"name",
")",
".",
"value",
"=",
"(",
"self",
".",
"_gettask",
"(",
"name",
")",
".",
"task",
".",
"resolve_and_build",
"(",
")",
")",
"except",
"Task... | Builds a task by name, resolving any dependencies on the way | [
"Builds",
"a",
"task",
"by",
"name",
"resolving",
"any",
"dependencies",
"on",
"the",
"way"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L68-L84 |
Archived-Object/ligament | ligament/buildcontext.py | Context.is_build_needed | def is_build_needed(self, data_sink, data_src):
""" returns true if data_src needs to be rebuilt, given that data_sink
has had a rebuild requested.
"""
return (self._gettask(data_src).last_build_time == 0 or
self._gettask(data_src).last_build_time <
se... | python | def is_build_needed(self, data_sink, data_src):
""" returns true if data_src needs to be rebuilt, given that data_sink
has had a rebuild requested.
"""
return (self._gettask(data_src).last_build_time == 0 or
self._gettask(data_src).last_build_time <
se... | [
"def",
"is_build_needed",
"(",
"self",
",",
"data_sink",
",",
"data_src",
")",
":",
"return",
"(",
"self",
".",
"_gettask",
"(",
"data_src",
")",
".",
"last_build_time",
"==",
"0",
"or",
"self",
".",
"_gettask",
"(",
"data_src",
")",
".",
"last_build_time"... | returns true if data_src needs to be rebuilt, given that data_sink
has had a rebuild requested. | [
"returns",
"true",
"if",
"data_src",
"needs",
"to",
"be",
"rebuilt",
"given",
"that",
"data_sink",
"has",
"had",
"a",
"rebuild",
"requested",
"."
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L86-L92 |
Archived-Object/ligament | ligament/buildcontext.py | Context.verify_valid_dependencies | def verify_valid_dependencies(self):
""" Checks if the assigned dependencies are valid
valid dependency graphs are:
- noncyclic (i.e. no `A -> B -> ... -> A`)
- Contain no undefined dependencies
(dependencies referencing undefined tasks)
"""
un... | python | def verify_valid_dependencies(self):
""" Checks if the assigned dependencies are valid
valid dependency graphs are:
- noncyclic (i.e. no `A -> B -> ... -> A`)
- Contain no undefined dependencies
(dependencies referencing undefined tasks)
"""
un... | [
"def",
"verify_valid_dependencies",
"(",
"self",
")",
":",
"unobserved_dependencies",
"=",
"set",
"(",
"self",
".",
"tasks",
".",
"keys",
"(",
")",
")",
"target_queue",
"=",
"[",
"]",
"while",
"len",
"(",
"unobserved_dependencies",
")",
">",
"0",
":",
"tar... | Checks if the assigned dependencies are valid
valid dependency graphs are:
- noncyclic (i.e. no `A -> B -> ... -> A`)
- Contain no undefined dependencies
(dependencies referencing undefined tasks) | [
"Checks",
"if",
"the",
"assigned",
"dependencies",
"are",
"valid",
"valid",
"dependency",
"graphs",
"are",
":"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L94-L110 |
Archived-Object/ligament | ligament/buildcontext.py | Context.deep_dependendants | def deep_dependendants(self, target):
""" Recursively finds the dependents of a given build target.
Assumes the dependency graph is noncyclic
"""
direct_dependents = self._gettask(target).provides_for
return (direct_dependents +
reduce(
la... | python | def deep_dependendants(self, target):
""" Recursively finds the dependents of a given build target.
Assumes the dependency graph is noncyclic
"""
direct_dependents = self._gettask(target).provides_for
return (direct_dependents +
reduce(
la... | [
"def",
"deep_dependendants",
"(",
"self",
",",
"target",
")",
":",
"direct_dependents",
"=",
"self",
".",
"_gettask",
"(",
"target",
")",
".",
"provides_for",
"return",
"(",
"direct_dependents",
"+",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"a",
"+",
... | Recursively finds the dependents of a given build target.
Assumes the dependency graph is noncyclic | [
"Recursively",
"finds",
"the",
"dependents",
"of",
"a",
"given",
"build",
"target",
".",
"Assumes",
"the",
"dependency",
"graph",
"is",
"noncyclic"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L114-L124 |
Archived-Object/ligament | ligament/buildcontext.py | Context.resolve_dependency_graph | def resolve_dependency_graph(self, target):
""" resolves the build order for interdependent build targets
Assumes no cyclic dependencies
"""
targets = self.deep_dependendants(target)
# print "deep dependants:", targets
return sorted(targets,
cmp... | python | def resolve_dependency_graph(self, target):
""" resolves the build order for interdependent build targets
Assumes no cyclic dependencies
"""
targets = self.deep_dependendants(target)
# print "deep dependants:", targets
return sorted(targets,
cmp... | [
"def",
"resolve_dependency_graph",
"(",
"self",
",",
"target",
")",
":",
"targets",
"=",
"self",
".",
"deep_dependendants",
"(",
"target",
")",
"# print \"deep dependants:\", targets",
"return",
"sorted",
"(",
"targets",
",",
"cmp",
"=",
"lambda",
"a",
",",
"b",... | resolves the build order for interdependent build targets
Assumes no cyclic dependencies | [
"resolves",
"the",
"build",
"order",
"for",
"interdependent",
"build",
"targets"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L126-L137 |
Archived-Object/ligament | ligament/buildcontext.py | DeferredDependency.resolve | def resolve(self):
"""Builds all targets of this dependency and returns the result
of self.function on the resulting values
"""
values = {}
for target_name in self.target_names:
if self.context.is_build_needed(self.parent, target_name):
self.context... | python | def resolve(self):
"""Builds all targets of this dependency and returns the result
of self.function on the resulting values
"""
values = {}
for target_name in self.target_names:
if self.context.is_build_needed(self.parent, target_name):
self.context... | [
"def",
"resolve",
"(",
"self",
")",
":",
"values",
"=",
"{",
"}",
"for",
"target_name",
"in",
"self",
".",
"target_names",
":",
"if",
"self",
".",
"context",
".",
"is_build_needed",
"(",
"self",
".",
"parent",
",",
"target_name",
")",
":",
"self",
".",... | Builds all targets of this dependency and returns the result
of self.function on the resulting values | [
"Builds",
"all",
"targets",
"of",
"this",
"dependency",
"and",
"returns",
"the",
"result",
"of",
"self",
".",
"function",
"on",
"the",
"resulting",
"values"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L188-L204 |
shreyaspotnis/rampage | rampage/widgets/KeyFrameWidgets.py | QKeyFrameList.updateAllKeys | def updateAllKeys(self):
"""Update times for all keys in the layout."""
for kf, key in zip(self.kf_list, self.sorted_key_list()):
kf.update(key, self.dct[key]) | python | def updateAllKeys(self):
"""Update times for all keys in the layout."""
for kf, key in zip(self.kf_list, self.sorted_key_list()):
kf.update(key, self.dct[key]) | [
"def",
"updateAllKeys",
"(",
"self",
")",
":",
"for",
"kf",
",",
"key",
"in",
"zip",
"(",
"self",
".",
"kf_list",
",",
"self",
".",
"sorted_key_list",
"(",
")",
")",
":",
"kf",
".",
"update",
"(",
"key",
",",
"self",
".",
"dct",
"[",
"key",
"]",
... | Update times for all keys in the layout. | [
"Update",
"times",
"for",
"all",
"keys",
"in",
"the",
"layout",
"."
] | train | https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/widgets/KeyFrameWidgets.py#L472-L475 |
macbre/phantomas-python | phantomas/utils.py | format_args | def format_args(options):
""" Convert hash/key options into arguments list """
args = list()
for key, value in options.items():
# convert foo_bar key into --foo-bar option
key = key.replace('_', '-')
if value is True:
# key: True
# --key
args.app... | python | def format_args(options):
""" Convert hash/key options into arguments list """
args = list()
for key, value in options.items():
# convert foo_bar key into --foo-bar option
key = key.replace('_', '-')
if value is True:
# key: True
# --key
args.app... | [
"def",
"format_args",
"(",
"options",
")",
":",
"args",
"=",
"list",
"(",
")",
"for",
"key",
",",
"value",
"in",
"options",
".",
"items",
"(",
")",
":",
"# convert foo_bar key into --foo-bar option",
"key",
"=",
"key",
".",
"replace",
"(",
"'_'",
",",
"'... | Convert hash/key options into arguments list | [
"Convert",
"hash",
"/",
"key",
"options",
"into",
"arguments",
"list"
] | train | https://github.com/macbre/phantomas-python/blob/63b1b1bd3fc97feb460beb6ae509bfb5cccf04f5/phantomas/utils.py#L11-L34 |
unfoldingWord-dev/tx-shared-tools | general_tools/print_utils.py | print_with_header | def print_with_header(header, message, color, indent=0):
"""
Use one of the functions below for printing, not this one.
"""
print()
padding = ' ' * indent
print(padding + color + BOLD + header + ENDC + color + message + ENDC) | python | def print_with_header(header, message, color, indent=0):
"""
Use one of the functions below for printing, not this one.
"""
print()
padding = ' ' * indent
print(padding + color + BOLD + header + ENDC + color + message + ENDC) | [
"def",
"print_with_header",
"(",
"header",
",",
"message",
",",
"color",
",",
"indent",
"=",
"0",
")",
":",
"print",
"(",
")",
"padding",
"=",
"' '",
"*",
"indent",
"print",
"(",
"padding",
"+",
"color",
"+",
"BOLD",
"+",
"header",
"+",
"ENDC",
"+",
... | Use one of the functions below for printing, not this one. | [
"Use",
"one",
"of",
"the",
"functions",
"below",
"for",
"printing",
"not",
"this",
"one",
"."
] | train | https://github.com/unfoldingWord-dev/tx-shared-tools/blob/6ff5cd024e1ab54c53dd1bc788bbc78e2358772e/general_tools/print_utils.py#L22-L28 |
macbre/phantomas-python | phantomas/client.py | Phantomas.run | def run(self):
""" Perform phantomas run """
self._logger.info("running for <{url}>".format(url=self._url))
args = format_args(self._options)
self._logger.debug("command: `{cmd}` / args: {args}".
format(cmd=self._cmd, args=args))
# run the process
... | python | def run(self):
""" Perform phantomas run """
self._logger.info("running for <{url}>".format(url=self._url))
args = format_args(self._options)
self._logger.debug("command: `{cmd}` / args: {args}".
format(cmd=self._cmd, args=args))
# run the process
... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"\"running for <{url}>\"",
".",
"format",
"(",
"url",
"=",
"self",
".",
"_url",
")",
")",
"args",
"=",
"format_args",
"(",
"self",
".",
"_options",
")",
"self",
".",
"_log... | Perform phantomas run | [
"Perform",
"phantomas",
"run"
] | train | https://github.com/macbre/phantomas-python/blob/63b1b1bd3fc97feb460beb6ae509bfb5cccf04f5/phantomas/client.py#L44-L96 |
EnTeQuAk/django-babel-underscore | src/django_babel_underscore/__init__.py | extract | def extract(fileobj, keywords, comment_tags, options):
"""Extracts translation messages from underscore template files.
This method does also extract django templates. If a template does not
contain any django translation tags we always fallback to underscore extraction.
This is a plugin to Babel, wri... | python | def extract(fileobj, keywords, comment_tags, options):
"""Extracts translation messages from underscore template files.
This method does also extract django templates. If a template does not
contain any django translation tags we always fallback to underscore extraction.
This is a plugin to Babel, wri... | [
"def",
"extract",
"(",
"fileobj",
",",
"keywords",
",",
"comment_tags",
",",
"options",
")",
":",
"encoding",
"=",
"options",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
"original_position",
"=",
"fileobj",
".",
"tell",
"(",
")",
"text",
"=",
"fi... | Extracts translation messages from underscore template files.
This method does also extract django templates. If a template does not
contain any django translation tags we always fallback to underscore extraction.
This is a plugin to Babel, written according to
http://babel.pocoo.org/docs/messages/#wr... | [
"Extracts",
"translation",
"messages",
"from",
"underscore",
"template",
"files",
"."
] | train | https://github.com/EnTeQuAk/django-babel-underscore/blob/cba715691850c956a1ab97c9f2457c6a4016d877/src/django_babel_underscore/__init__.py#L16-L90 |
boatd/python-boatd | boatdclient/point.py | Point.from_radians | def from_radians(cls, lat_radians, long_radians):
'''
Return a new instance of Point from a pair of coordinates in radians.
'''
return cls(math.degrees(lat_radians), math.degrees(long_radians)) | python | def from_radians(cls, lat_radians, long_radians):
'''
Return a new instance of Point from a pair of coordinates in radians.
'''
return cls(math.degrees(lat_radians), math.degrees(long_radians)) | [
"def",
"from_radians",
"(",
"cls",
",",
"lat_radians",
",",
"long_radians",
")",
":",
"return",
"cls",
"(",
"math",
".",
"degrees",
"(",
"lat_radians",
")",
",",
"math",
".",
"degrees",
"(",
"long_radians",
")",
")"
] | Return a new instance of Point from a pair of coordinates in radians. | [
"Return",
"a",
"new",
"instance",
"of",
"Point",
"from",
"a",
"pair",
"of",
"coordinates",
"in",
"radians",
"."
] | train | https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/point.py#L17-L21 |
boatd/python-boatd | boatdclient/point.py | Point.distance_to | def distance_to(self, point):
'''
Return the distance between this point and another point in meters.
:param point: Point to measure distance to
:type point: Point
:returns: The distance to the other point
:rtype: float
'''
angle = math.acos(
... | python | def distance_to(self, point):
'''
Return the distance between this point and another point in meters.
:param point: Point to measure distance to
:type point: Point
:returns: The distance to the other point
:rtype: float
'''
angle = math.acos(
... | [
"def",
"distance_to",
"(",
"self",
",",
"point",
")",
":",
"angle",
"=",
"math",
".",
"acos",
"(",
"sin",
"(",
"self",
".",
"lat_radians",
")",
"*",
"sin",
"(",
"point",
".",
"lat_radians",
")",
"+",
"cos",
"(",
"self",
".",
"lat_radians",
")",
"*"... | Return the distance between this point and another point in meters.
:param point: Point to measure distance to
:type point: Point
:returns: The distance to the other point
:rtype: float | [
"Return",
"the",
"distance",
"between",
"this",
"point",
"and",
"another",
"point",
"in",
"meters",
"."
] | train | https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/point.py#L63-L78 |
boatd/python-boatd | boatdclient/point.py | Point.bearing_to | def bearing_to(self, point):
'''
Return the bearing to another point.
:param point: Point to measure bearing to
:type point: Point
:returns: The bearing to the other point
:rtype: Bearing
'''
delta_long = point.long_radians - self.long_radians
y ... | python | def bearing_to(self, point):
'''
Return the bearing to another point.
:param point: Point to measure bearing to
:type point: Point
:returns: The bearing to the other point
:rtype: Bearing
'''
delta_long = point.long_radians - self.long_radians
y ... | [
"def",
"bearing_to",
"(",
"self",
",",
"point",
")",
":",
"delta_long",
"=",
"point",
".",
"long_radians",
"-",
"self",
".",
"long_radians",
"y",
"=",
"sin",
"(",
"delta_long",
")",
"*",
"cos",
"(",
"point",
".",
"lat_radians",
")",
"x",
"=",
"(",
"c... | Return the bearing to another point.
:param point: Point to measure bearing to
:type point: Point
:returns: The bearing to the other point
:rtype: Bearing | [
"Return",
"the",
"bearing",
"to",
"another",
"point",
"."
] | train | https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/point.py#L80-L97 |
boatd/python-boatd | boatdclient/point.py | Point.cross_track_distance | def cross_track_distance(self, start_point, end_point):
'''
Return the cross track distance from this point to the line between two
points::
* end_point
/
/
/ * this point
/
... | python | def cross_track_distance(self, start_point, end_point):
'''
Return the cross track distance from this point to the line between two
points::
* end_point
/
/
/ * this point
/
... | [
"def",
"cross_track_distance",
"(",
"self",
",",
"start_point",
",",
"end_point",
")",
":",
"dist",
"=",
"start_point",
".",
"distance_to",
"(",
"self",
")",
"bearing_to_end",
"=",
"start_point",
".",
"bearing_to",
"(",
"end_point",
")",
".",
"radians",
"beari... | Return the cross track distance from this point to the line between two
points::
* end_point
/
/
/ * this point
/
/
*
start_point
:param st... | [
"Return",
"the",
"cross",
"track",
"distance",
"from",
"this",
"point",
"to",
"the",
"line",
"between",
"two",
"points",
"::"
] | train | https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/point.py#L99-L130 |
boatd/python-boatd | boatdclient/point.py | Point.relative_point | def relative_point(self, bearing_to_point, distance):
'''
Return a waypoint at a location described relative to the current point
:param bearing_to_point: Relative bearing from the current waypoint
:type bearing_to_point: Bearing
:param distance: Distance from the current waypoi... | python | def relative_point(self, bearing_to_point, distance):
'''
Return a waypoint at a location described relative to the current point
:param bearing_to_point: Relative bearing from the current waypoint
:type bearing_to_point: Bearing
:param distance: Distance from the current waypoi... | [
"def",
"relative_point",
"(",
"self",
",",
"bearing_to_point",
",",
"distance",
")",
":",
"bearing",
"=",
"math",
".",
"radians",
"(",
"360",
"-",
"bearing_to_point",
")",
"rad_distance",
"=",
"(",
"distance",
"/",
"EARTH_RADIUS",
")",
"lat1",
"=",
"(",
"s... | Return a waypoint at a location described relative to the current point
:param bearing_to_point: Relative bearing from the current waypoint
:type bearing_to_point: Bearing
:param distance: Distance from the current waypoint
:type distance: float
:return: The point described by t... | [
"Return",
"a",
"waypoint",
"at",
"a",
"location",
"described",
"relative",
"to",
"the",
"current",
"point"
] | train | https://github.com/boatd/python-boatd/blob/404ff0d0c389f6ed84ddbfea1c41db6569ad2ed4/boatdclient/point.py#L132-L150 |
rehandalal/buchner | buchner/project-template/PROJECTMODULE/main.py | create_app | def create_app(settings):
"""Create a new Flask application"""
app = Flask(__name__)
# Import settings from file
for name in dir(settings):
value = getattr(settings, name)
if not (name.startswith('_') or isinstance(value, ModuleType)
or isinstance(value, FunctionType)):
... | python | def create_app(settings):
"""Create a new Flask application"""
app = Flask(__name__)
# Import settings from file
for name in dir(settings):
value = getattr(settings, name)
if not (name.startswith('_') or isinstance(value, ModuleType)
or isinstance(value, FunctionType)):
... | [
"def",
"create_app",
"(",
"settings",
")",
":",
"app",
"=",
"Flask",
"(",
"__name__",
")",
"# Import settings from file",
"for",
"name",
"in",
"dir",
"(",
"settings",
")",
":",
"value",
"=",
"getattr",
"(",
"settings",
",",
"name",
")",
"if",
"not",
"(",... | Create a new Flask application | [
"Create",
"a",
"new",
"Flask",
"application"
] | train | https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/project-template/PROJECTMODULE/main.py#L10-L49 |
vinu76jsr/pipsort | lib/pipsort/cli.py | _cmdline | def _cmdline(argv=None):
""" Parse command line arguments.
"""
parser = ArgumentParser()
parser.add_argument("-c", "--config", action="append",
help="config file [etc/config.yml]")
parser.add_argument("-v", "--version", action="version",
version="pipsort {:s}".format(__versi... | python | def _cmdline(argv=None):
""" Parse command line arguments.
"""
parser = ArgumentParser()
parser.add_argument("-c", "--config", action="append",
help="config file [etc/config.yml]")
parser.add_argument("-v", "--version", action="version",
version="pipsort {:s}".format(__versi... | [
"def",
"_cmdline",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"-c\"",
",",
"\"--config\"",
",",
"action",
"=",
"\"append\"",
",",
"help",
"=",
"\"config file [etc/config.yml]\"",
")",
... | Parse command line arguments. | [
"Parse",
"command",
"line",
"arguments",
"."
] | train | https://github.com/vinu76jsr/pipsort/blob/71ead1269de85ee0255741390bf1da85d81b7d16/lib/pipsort/cli.py#L21-L38 |
vinu76jsr/pipsort | lib/pipsort/cli.py | main | def main(argv=None):
""" Execute the application CLI.
Arguments are taken from sys.argv by default.
"""
args = _cmdline(argv)
config.load(args.config)
results = get_package_list(args.search_term)
results = sorted(results, key=lambda a: sort_function(a[1]), reverse=True)
results_normali... | python | def main(argv=None):
""" Execute the application CLI.
Arguments are taken from sys.argv by default.
"""
args = _cmdline(argv)
config.load(args.config)
results = get_package_list(args.search_term)
results = sorted(results, key=lambda a: sort_function(a[1]), reverse=True)
results_normali... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"args",
"=",
"_cmdline",
"(",
"argv",
")",
"config",
".",
"load",
"(",
"args",
".",
"config",
")",
"results",
"=",
"get_package_list",
"(",
"args",
".",
"search_term",
")",
"results",
"=",
"sorted",
... | Execute the application CLI.
Arguments are taken from sys.argv by default. | [
"Execute",
"the",
"application",
"CLI",
"."
] | train | https://github.com/vinu76jsr/pipsort/blob/71ead1269de85ee0255741390bf1da85d81b7d16/lib/pipsort/cli.py#L60-L78 |
Perfectial/django-view-acl | view_acl/utils.py | generate_permissions | def generate_permissions(urlpatterns, permissions={}):
"""Generate names for permissions."""
for pattern in urlpatterns:
if isinstance(pattern, urlresolvers.RegexURLPattern):
perm = generate_perm_name(pattern.callback)
if is_allowed_view(perm) and perm not in permissions:
... | python | def generate_permissions(urlpatterns, permissions={}):
"""Generate names for permissions."""
for pattern in urlpatterns:
if isinstance(pattern, urlresolvers.RegexURLPattern):
perm = generate_perm_name(pattern.callback)
if is_allowed_view(perm) and perm not in permissions:
... | [
"def",
"generate_permissions",
"(",
"urlpatterns",
",",
"permissions",
"=",
"{",
"}",
")",
":",
"for",
"pattern",
"in",
"urlpatterns",
":",
"if",
"isinstance",
"(",
"pattern",
",",
"urlresolvers",
".",
"RegexURLPattern",
")",
":",
"perm",
"=",
"generate_perm_n... | Generate names for permissions. | [
"Generate",
"names",
"for",
"permissions",
"."
] | train | https://github.com/Perfectial/django-view-acl/blob/71f514f65761895bc64d5ca735997c5455c254fa/view_acl/utils.py#L16-L25 |
Perfectial/django-view-acl | view_acl/utils.py | is_allowed_view | def is_allowed_view(perm):
"""Check if permission is in acl list."""
# Check if permission is in excluded list
for view in ACL_EXCLUDED_VIEWS:
module, separator, view_name = view.partition('*')
if view and perm.startswith(module):
return False
# Check if permission is in ac... | python | def is_allowed_view(perm):
"""Check if permission is in acl list."""
# Check if permission is in excluded list
for view in ACL_EXCLUDED_VIEWS:
module, separator, view_name = view.partition('*')
if view and perm.startswith(module):
return False
# Check if permission is in ac... | [
"def",
"is_allowed_view",
"(",
"perm",
")",
":",
"# Check if permission is in excluded list",
"for",
"view",
"in",
"ACL_EXCLUDED_VIEWS",
":",
"module",
",",
"separator",
",",
"view_name",
"=",
"view",
".",
"partition",
"(",
"'*'",
")",
"if",
"view",
"and",
"perm... | Check if permission is in acl list. | [
"Check",
"if",
"permission",
"is",
"in",
"acl",
"list",
"."
] | train | https://github.com/Perfectial/django-view-acl/blob/71f514f65761895bc64d5ca735997c5455c254fa/view_acl/utils.py#L34-L54 |
Perfectial/django-view-acl | view_acl/utils.py | refresh_permissions | def refresh_permissions(permissions):
"""Refresh permission:
Remove deprecated permissions,
Add generated permissions."""
available_permissions = [x.codename for x in
Permission.objects.filter(
codename__startswith=ACL_CODE_PREFIX)]
... | python | def refresh_permissions(permissions):
"""Refresh permission:
Remove deprecated permissions,
Add generated permissions."""
available_permissions = [x.codename for x in
Permission.objects.filter(
codename__startswith=ACL_CODE_PREFIX)]
... | [
"def",
"refresh_permissions",
"(",
"permissions",
")",
":",
"available_permissions",
"=",
"[",
"x",
".",
"codename",
"for",
"x",
"in",
"Permission",
".",
"objects",
".",
"filter",
"(",
"codename__startswith",
"=",
"ACL_CODE_PREFIX",
")",
"]",
"active_permissions",... | Refresh permission:
Remove deprecated permissions,
Add generated permissions. | [
"Refresh",
"permission",
":",
"Remove",
"deprecated",
"permissions",
"Add",
"generated",
"permissions",
"."
] | train | https://github.com/Perfectial/django-view-acl/blob/71f514f65761895bc64d5ca735997c5455c254fa/view_acl/utils.py#L57-L78 |
openp2pdesign/makerlabs | makerlabs/utils.py | get_location | def get_location(query, format, api_key):
"""Get geographic data of a lab in a coherent way for all labs."""
# Play nice with the API...
sleep(1)
geolocator = OpenCage(api_key=api_key, timeout=10)
# Variables for storing the data
data = {"city": None,
"address_1": None,
... | python | def get_location(query, format, api_key):
"""Get geographic data of a lab in a coherent way for all labs."""
# Play nice with the API...
sleep(1)
geolocator = OpenCage(api_key=api_key, timeout=10)
# Variables for storing the data
data = {"city": None,
"address_1": None,
... | [
"def",
"get_location",
"(",
"query",
",",
"format",
",",
"api_key",
")",
":",
"# Play nice with the API...",
"sleep",
"(",
"1",
")",
"geolocator",
"=",
"OpenCage",
"(",
"api_key",
"=",
"api_key",
",",
"timeout",
"=",
"10",
")",
"# Variables for storing the data"... | Get geographic data of a lab in a coherent way for all labs. | [
"Get",
"geographic",
"data",
"of",
"a",
"lab",
"in",
"a",
"coherent",
"way",
"for",
"all",
"labs",
"."
] | train | https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/utils.py#L18-L110 |
vilmibm/done | sql_interp/sql_interp.py | SQLInterp.interp | def interp(self, *args):
"""
This method takes a list of SQL snippets and returns a SQL statement and
a list of bind variables to be passed to the DB API's execute method.
"""
sql = ""
bind = ()
def _append_sql(sql, part):
"Handle whitespace when appe... | python | def interp(self, *args):
"""
This method takes a list of SQL snippets and returns a SQL statement and
a list of bind variables to be passed to the DB API's execute method.
"""
sql = ""
bind = ()
def _append_sql(sql, part):
"Handle whitespace when appe... | [
"def",
"interp",
"(",
"self",
",",
"*",
"args",
")",
":",
"sql",
"=",
"\"\"",
"bind",
"=",
"(",
")",
"def",
"_append_sql",
"(",
"sql",
",",
"part",
")",
":",
"\"Handle whitespace when appending properly.\"",
"if",
"len",
"(",
"sql",
")",
"==",
"0",
":"... | This method takes a list of SQL snippets and returns a SQL statement and
a list of bind variables to be passed to the DB API's execute method. | [
"This",
"method",
"takes",
"a",
"list",
"of",
"SQL",
"snippets",
"and",
"returns",
"a",
"SQL",
"statement",
"and",
"a",
"list",
"of",
"bind",
"variables",
"to",
"be",
"passed",
"to",
"the",
"DB",
"API",
"s",
"execute",
"method",
"."
] | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/sql_interp/sql_interp.py#L16-L50 |
vilmibm/done | sql_interp/sql_interp.py | SQLInterp.esc | def esc(self, val):
"""
Returns the given object in the appropriate wrapper class from esc_types.py.
In most cases, you will not need to call this directly. However, if you are
passing a string to the interp method that should be used as an SQL bind value
and not raw SQL, you m... | python | def esc(self, val):
"""
Returns the given object in the appropriate wrapper class from esc_types.py.
In most cases, you will not need to call this directly. However, if you are
passing a string to the interp method that should be used as an SQL bind value
and not raw SQL, you m... | [
"def",
"esc",
"(",
"self",
",",
"val",
")",
":",
"if",
"type",
"(",
"val",
")",
"in",
"self",
".",
"type_map",
":",
"return",
"self",
".",
"type_map",
"[",
"type",
"(",
"val",
")",
"]",
"(",
"val",
")",
"else",
":",
"return",
"Esc",
"(",
"val",... | Returns the given object in the appropriate wrapper class from esc_types.py.
In most cases, you will not need to call this directly. However, if you are
passing a string to the interp method that should be used as an SQL bind value
and not raw SQL, you must pass it to this method to avoid a SQ... | [
"Returns",
"the",
"given",
"object",
"in",
"the",
"appropriate",
"wrapper",
"class",
"from",
"esc_types",
".",
"py",
"."
] | train | https://github.com/vilmibm/done/blob/7e5b60d2900ceddefa49de352a19b794199b51a8/sql_interp/sql_interp.py#L52-L77 |
AndresMWeber/Nomenclate | nomenclate/core/tokens.py | TokenAttrList.purge_tokens | def purge_tokens(self, input_token_attrs=None):
""" Removes all specified token_attrs that exist in instance.token_attrs
:param token_attrs: list(str), list of string values of tokens to remove. If None, removes all
"""
if input_token_attrs is None:
remove_attrs = s... | python | def purge_tokens(self, input_token_attrs=None):
""" Removes all specified token_attrs that exist in instance.token_attrs
:param token_attrs: list(str), list of string values of tokens to remove. If None, removes all
"""
if input_token_attrs is None:
remove_attrs = s... | [
"def",
"purge_tokens",
"(",
"self",
",",
"input_token_attrs",
"=",
"None",
")",
":",
"if",
"input_token_attrs",
"is",
"None",
":",
"remove_attrs",
"=",
"self",
".",
"token_attrs",
"else",
":",
"remove_attrs",
"=",
"[",
"token_attr",
"for",
"token_attr",
"in",
... | Removes all specified token_attrs that exist in instance.token_attrs
:param token_attrs: list(str), list of string values of tokens to remove. If None, removes all | [
"Removes",
"all",
"specified",
"token_attrs",
"that",
"exist",
"in",
"instance",
".",
"token_attrs",
":",
"param",
"token_attrs",
":",
"list",
"(",
"str",
")",
"list",
"of",
"string",
"values",
"of",
"tokens",
"to",
"remove",
".",
"If",
"None",
"removes",
... | train | https://github.com/AndresMWeber/Nomenclate/blob/e6d6fc28beac042bad588e56fbe77531d2de6b6f/nomenclate/core/tokens.py#L133-L143 |
arcus-io/puppetdb-python | puppetdb/utils.py | api_request | def api_request(api_base_url='http://localhost:8080/', path='', method='get',
data=None, params={}, verify=True, cert=list()):
"""
Wrapper function for requests
:param api_base_url: Base URL for requests
:param path: Path to request
:param method: HTTP method
:param data: Data for post (ign... | python | def api_request(api_base_url='http://localhost:8080/', path='', method='get',
data=None, params={}, verify=True, cert=list()):
"""
Wrapper function for requests
:param api_base_url: Base URL for requests
:param path: Path to request
:param method: HTTP method
:param data: Data for post (ign... | [
"def",
"api_request",
"(",
"api_base_url",
"=",
"'http://localhost:8080/'",
",",
"path",
"=",
"''",
",",
"method",
"=",
"'get'",
",",
"data",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"list",
"(",
")",
"... | Wrapper function for requests
:param api_base_url: Base URL for requests
:param path: Path to request
:param method: HTTP method
:param data: Data for post (ignored for GETs)
:param params: Dict of key, value query params
:param verify: True/False/CA_File_Name to perform SSL Verification of CA ... | [
"Wrapper",
"function",
"for",
"requests"
] | train | https://github.com/arcus-io/puppetdb-python/blob/d772eb80a1dfb1154a1f421c7ecdc1ac951b5ea2/puppetdb/utils.py#L29-L59 |
shi-cong/PYSTUDY | PYSTUDY/net/tornadolib.py | Application.add_view | def add_view(self, view_name, handler):
"""
增加handler
:param view_name: 路由
:param handler: 处理类
:return:
"""
# 如果不是BaseHandler的子类则不加入
if is_subclass(handler, BaseHandler):
self.views.append((view_name, handler)) | python | def add_view(self, view_name, handler):
"""
增加handler
:param view_name: 路由
:param handler: 处理类
:return:
"""
# 如果不是BaseHandler的子类则不加入
if is_subclass(handler, BaseHandler):
self.views.append((view_name, handler)) | [
"def",
"add_view",
"(",
"self",
",",
"view_name",
",",
"handler",
")",
":",
"# 如果不是BaseHandler的子类则不加入",
"if",
"is_subclass",
"(",
"handler",
",",
"BaseHandler",
")",
":",
"self",
".",
"views",
".",
"append",
"(",
"(",
"view_name",
",",
"handler",
")",
")"
... | 增加handler
:param view_name: 路由
:param handler: 处理类
:return: | [
"增加handler",
":",
"param",
"view_name",
":",
"路由",
":",
"param",
"handler",
":",
"处理类",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/net/tornadolib.py#L76-L85 |
shi-cong/PYSTUDY | PYSTUDY/net/tornadolib.py | Application.start | def start(self, port):
"""
启动服务器
:param port: 端口号
:return:
"""
self.application = tornado.web.Application(self.views,
template_path=self.templatePath,
static_path=self.staticPath)
self.application.listen(port)
self.ioloop.... | python | def start(self, port):
"""
启动服务器
:param port: 端口号
:return:
"""
self.application = tornado.web.Application(self.views,
template_path=self.templatePath,
static_path=self.staticPath)
self.application.listen(port)
self.ioloop.... | [
"def",
"start",
"(",
"self",
",",
"port",
")",
":",
"self",
".",
"application",
"=",
"tornado",
".",
"web",
".",
"Application",
"(",
"self",
".",
"views",
",",
"template_path",
"=",
"self",
".",
"templatePath",
",",
"static_path",
"=",
"self",
".",
"st... | 启动服务器
:param port: 端口号
:return: | [
"启动服务器",
":",
"param",
"port",
":",
"端口号",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/net/tornadolib.py#L103-L113 |
fr33jc/bang | bang/cmd_bang.py | set_ssh_creds | def set_ssh_creds(config, args):
"""
Set ssh credentials into config.
Note that these values might also be set in ~/.bangrc. If they are
specified both in ~/.bangrc and as command-line arguments to ``bang``, then
the command-line arguments win.
"""
creds = config.get(A.DEPLOYER_CREDS, {})... | python | def set_ssh_creds(config, args):
"""
Set ssh credentials into config.
Note that these values might also be set in ~/.bangrc. If they are
specified both in ~/.bangrc and as command-line arguments to ``bang``, then
the command-line arguments win.
"""
creds = config.get(A.DEPLOYER_CREDS, {})... | [
"def",
"set_ssh_creds",
"(",
"config",
",",
"args",
")",
":",
"creds",
"=",
"config",
".",
"get",
"(",
"A",
".",
"DEPLOYER_CREDS",
",",
"{",
"}",
")",
"creds",
"[",
"A",
".",
"creds",
".",
"SSH_USER",
"]",
"=",
"args",
".",
"user",
"if",
"args",
... | Set ssh credentials into config.
Note that these values might also be set in ~/.bangrc. If they are
specified both in ~/.bangrc and as command-line arguments to ``bang``, then
the command-line arguments win. | [
"Set",
"ssh",
"credentials",
"into",
"config",
"."
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/cmd_bang.py#L39-L55 |
fr33jc/bang | bang/cmd_bang.py | run_bang | def run_bang(alt_args=None):
"""
Runs bang with optional list of strings as command line options.
If ``alt_args`` is not specified, defaults to parsing ``sys.argv`` for
command line options.
"""
parser = get_parser()
args = parser.parse_args(alt_args)
source = args.config_specs or get_... | python | def run_bang(alt_args=None):
"""
Runs bang with optional list of strings as command line options.
If ``alt_args`` is not specified, defaults to parsing ``sys.argv`` for
command line options.
"""
parser = get_parser()
args = parser.parse_args(alt_args)
source = args.config_specs or get_... | [
"def",
"run_bang",
"(",
"alt_args",
"=",
"None",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"alt_args",
")",
"source",
"=",
"args",
".",
"config_specs",
"or",
"get_env_configs",
"(",
")",
"if",
"not",
... | Runs bang with optional list of strings as command line options.
If ``alt_args`` is not specified, defaults to parsing ``sys.argv`` for
command line options. | [
"Runs",
"bang",
"with",
"optional",
"list",
"of",
"strings",
"as",
"command",
"line",
"options",
"."
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/cmd_bang.py#L209-L258 |
listen-lavender/webcrawl | webcrawl/daemon.py | Daemon._daemonize | def _daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
... | python | def _daemonize(self):
"""
do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
"""
try:
pid = os.fork()
if pid > 0:
... | [
"def",
"_daemonize",
"(",
"self",
")",
":",
"try",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
">",
"0",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"OSError",
",",
"e",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"fo... | do the UNIX double-fork magic, see Stevens' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 | [
"do",
"the",
"UNIX",
"double",
"-",
"fork",
"magic",
"see",
"Stevens",
"Advanced",
"Programming",
"in",
"the",
"UNIX",
"Environment",
"for",
"details",
"(",
"ISBN",
"0201563177",
")",
"http",
":",
"//",
"www",
".",
"erlenstar",
".",
"demon",
".",
"co",
"... | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/daemon.py#L35-L76 |
listen-lavender/webcrawl | webcrawl/daemon.py | Daemon.stop | def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile ... | python | def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile ... | [
"def",
"stop",
"(",
"self",
")",
":",
"# Get the pid from the pidfile",
"try",
":",
"pf",
"=",
"file",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"pid",
"=",
"int",
"(",
"pf",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"pf",
".",
"clo... | Stop the daemon | [
"Stop",
"the",
"daemon"
] | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/daemon.py#L117-L155 |
listen-lavender/webcrawl | webcrawl/daemon.py | Daemon.monitor | def monitor(self, timeout):
"""
Monitor the process, check whether it runs out of time.
"""
def check(self, timeout):
time.sleep(timeout)
self.stop()
wather = threading.Thread(target=check)
wather.setDaemon(True)
wather.start() | python | def monitor(self, timeout):
"""
Monitor the process, check whether it runs out of time.
"""
def check(self, timeout):
time.sleep(timeout)
self.stop()
wather = threading.Thread(target=check)
wather.setDaemon(True)
wather.start() | [
"def",
"monitor",
"(",
"self",
",",
"timeout",
")",
":",
"def",
"check",
"(",
"self",
",",
"timeout",
")",
":",
"time",
".",
"sleep",
"(",
"timeout",
")",
"self",
".",
"stop",
"(",
")",
"wather",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",... | Monitor the process, check whether it runs out of time. | [
"Monitor",
"the",
"process",
"check",
"whether",
"it",
"runs",
"out",
"of",
"time",
"."
] | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/daemon.py#L164-L174 |
listen-lavender/webcrawl | webcrawl/daemon.py | DaemonWithoutRun.start | def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
os.kill(pid, 0)
except IOError:
pid = No... | python | def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
try:
pf = file(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
os.kill(pid, 0)
except IOError:
pid = No... | [
"def",
"start",
"(",
"self",
")",
":",
"# Check for a pidfile to see if the daemon already runs",
"try",
":",
"pf",
"=",
"file",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"pid",
"=",
"int",
"(",
"pf",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
... | Start the daemon | [
"Start",
"the",
"daemon"
] | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/daemon.py#L206-L227 |
DecBayComp/RWA-python | rwa/hdf5.py | hdf5_storable | def hdf5_storable(type_or_storable, *args, **kwargs):
'''Registers a `Storable` instance in the global service.'''
if not isinstance(type_or_storable, Storable):
type_or_storable = default_storable(type_or_storable)
hdf5_service.registerStorable(type_or_storable, *args, **kwargs) | python | def hdf5_storable(type_or_storable, *args, **kwargs):
'''Registers a `Storable` instance in the global service.'''
if not isinstance(type_or_storable, Storable):
type_or_storable = default_storable(type_or_storable)
hdf5_service.registerStorable(type_or_storable, *args, **kwargs) | [
"def",
"hdf5_storable",
"(",
"type_or_storable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"type_or_storable",
",",
"Storable",
")",
":",
"type_or_storable",
"=",
"default_storable",
"(",
"type_or_storable",
")",
"hdf... | Registers a `Storable` instance in the global service. | [
"Registers",
"a",
"Storable",
"instance",
"in",
"the",
"global",
"service",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/hdf5.py#L266-L270 |
DecBayComp/RWA-python | rwa/hdf5.py | hdf5_not_storable | def hdf5_not_storable(_type, *args, **kwargs):
'''Tags a type as not serializable.'''
hdf5_service.registerStorable(not_storable(_type), *args, **kwargs) | python | def hdf5_not_storable(_type, *args, **kwargs):
'''Tags a type as not serializable.'''
hdf5_service.registerStorable(not_storable(_type), *args, **kwargs) | [
"def",
"hdf5_not_storable",
"(",
"_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"hdf5_service",
".",
"registerStorable",
"(",
"not_storable",
"(",
"_type",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Tags a type as not serializable. | [
"Tags",
"a",
"type",
"as",
"not",
"serializable",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/hdf5.py#L272-L274 |
Archived-Object/ligament | ligament_precompiler_template/__init__.py | Precompiler.compile_and_process | def compile_and_process(self, in_path):
"""compile a file, save it to the ouput file if the inline flag true"""
out_path = self.path_mapping[in_path]
if not self.embed:
pdebug("[%s::%s] %s -> %s" % (
self.compiler_name,
self.name,
os.p... | python | def compile_and_process(self, in_path):
"""compile a file, save it to the ouput file if the inline flag true"""
out_path = self.path_mapping[in_path]
if not self.embed:
pdebug("[%s::%s] %s -> %s" % (
self.compiler_name,
self.name,
os.p... | [
"def",
"compile_and_process",
"(",
"self",
",",
"in_path",
")",
":",
"out_path",
"=",
"self",
".",
"path_mapping",
"[",
"in_path",
"]",
"if",
"not",
"self",
".",
"embed",
":",
"pdebug",
"(",
"\"[%s::%s] %s -> %s\"",
"%",
"(",
"self",
".",
"compiler_name",
... | compile a file, save it to the ouput file if the inline flag true | [
"compile",
"a",
"file",
"save",
"it",
"to",
"the",
"ouput",
"file",
"if",
"the",
"inline",
"flag",
"true"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament_precompiler_template/__init__.py#L87-L114 |
Archived-Object/ligament | ligament_precompiler_template/__init__.py | Precompiler.collect_output | def collect_output(self):
""" helper function to gather the results of `compile_and_process` on
all target files
"""
if self.embed:
if self.concat:
concat_scripts = [self.compiled_scripts[path]
for path in self.build_order... | python | def collect_output(self):
""" helper function to gather the results of `compile_and_process` on
all target files
"""
if self.embed:
if self.concat:
concat_scripts = [self.compiled_scripts[path]
for path in self.build_order... | [
"def",
"collect_output",
"(",
"self",
")",
":",
"if",
"self",
".",
"embed",
":",
"if",
"self",
".",
"concat",
":",
"concat_scripts",
"=",
"[",
"self",
".",
"compiled_scripts",
"[",
"path",
"]",
"for",
"path",
"in",
"self",
".",
"build_order",
"]",
"ret... | helper function to gather the results of `compile_and_process` on
all target files | [
"helper",
"function",
"to",
"gather",
"the",
"results",
"of",
"compile_and_process",
"on",
"all",
"target",
"files"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament_precompiler_template/__init__.py#L116-L139 |
Archived-Object/ligament | ligament_precompiler_template/__init__.py | Precompiler.build | def build(self):
"""build the scripts and return a string"""
if not self.embed:
mkdir_recursive(self.output_directory)
# get list of script files in build order
self.build_order = remove_dups(
reduce(lambda a, b: a + glob.glob(b),
self.build_t... | python | def build(self):
"""build the scripts and return a string"""
if not self.embed:
mkdir_recursive(self.output_directory)
# get list of script files in build order
self.build_order = remove_dups(
reduce(lambda a, b: a + glob.glob(b),
self.build_t... | [
"def",
"build",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"embed",
":",
"mkdir_recursive",
"(",
"self",
".",
"output_directory",
")",
"# get list of script files in build order",
"self",
".",
"build_order",
"=",
"remove_dups",
"(",
"reduce",
"(",
"lambda"... | build the scripts and return a string | [
"build",
"the",
"scripts",
"and",
"return",
"a",
"string"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament_precompiler_template/__init__.py#L141-L181 |
Archived-Object/ligament | ligament_precompiler_template/__init__.py | Precompiler.update_build | def update_build(self, updated_files):
""" updates a build based on updated files
TODO implement this pls
"""
for f in updated_files:
self.compiled_scripts[f] = self.compile_and_process(f)
return self.collect_output() | python | def update_build(self, updated_files):
""" updates a build based on updated files
TODO implement this pls
"""
for f in updated_files:
self.compiled_scripts[f] = self.compile_and_process(f)
return self.collect_output() | [
"def",
"update_build",
"(",
"self",
",",
"updated_files",
")",
":",
"for",
"f",
"in",
"updated_files",
":",
"self",
".",
"compiled_scripts",
"[",
"f",
"]",
"=",
"self",
".",
"compile_and_process",
"(",
"f",
")",
"return",
"self",
".",
"collect_output",
"("... | updates a build based on updated files
TODO implement this pls | [
"updates",
"a",
"build",
"based",
"on",
"updated",
"files",
"TODO",
"implement",
"this",
"pls"
] | train | https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament_precompiler_template/__init__.py#L183-L190 |
hobson/pug-invest | pug/invest/gof.py | log_loss | def log_loss(actual, predicted):
"""Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of probabilities for each
... | python | def log_loss(actual, predicted):
"""Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of probabilities for each
... | [
"def",
"log_loss",
"(",
"actual",
",",
"predicted",
")",
":",
"predicted",
",",
"actual",
"=",
"np",
".",
"array",
"(",
"predicted",
")",
",",
"np",
".",
"array",
"(",
"actual",
")",
"small_value",
"=",
"1e-15",
"predicted",
"[",
"predicted",
"<",
"sma... | Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of probabilities for each
category (columns) and each record (ro... | [
"Log",
"of",
"the",
"loss",
"(",
"error",
")",
"summed",
"over",
"all",
"entries"
] | train | https://github.com/hobson/pug-invest/blob/836911258a0e920083a88c91beae88eefdebb20c/pug/invest/gof.py#L21-L45 |
bernoulli-metrics/bernoulli-python | bernoulli/client_api.py | get_experiments | def get_experiments(experiment_ids=None, user_id=None, client_id=None, bucket_if_necessary=True, user_data=None):
"""
Retrieve the experiments the user is a part of
@param experiment_ids : Either a single or list of experiment ids to retreive
@param user_id : An identifier for the user
@param client... | python | def get_experiments(experiment_ids=None, user_id=None, client_id=None, bucket_if_necessary=True, user_data=None):
"""
Retrieve the experiments the user is a part of
@param experiment_ids : Either a single or list of experiment ids to retreive
@param user_id : An identifier for the user
@param client... | [
"def",
"get_experiments",
"(",
"experiment_ids",
"=",
"None",
",",
"user_id",
"=",
"None",
",",
"client_id",
"=",
"None",
",",
"bucket_if_necessary",
"=",
"True",
",",
"user_data",
"=",
"None",
")",
":",
"if",
"not",
"client_id",
":",
"client_id",
"=",
"os... | Retrieve the experiments the user is a part of
@param experiment_ids : Either a single or list of experiment ids to retreive
@param user_id : An identifier for the user
@param client_id : Bernoulli Client ID - will default to BERNOULLI_CLIENT_ID ENV variable
@param bucket_if_necessary : Choose a variant... | [
"Retrieve",
"the",
"experiments",
"the",
"user",
"is",
"a",
"part",
"of"
] | train | https://github.com/bernoulli-metrics/bernoulli-python/blob/572bd165ac354eb4b95ac3abdfe74b67f4fd703b/bernoulli/client_api.py#L6-L44 |
bernoulli-metrics/bernoulli-python | bernoulli/client_api.py | record_goal_attained | def record_goal_attained(experiment_id, user_id, client_id = None):
"""
Record that a variant was successful for a user
@param experiment_id : A single experiment id
@param user_id : An identifier for the user
@param client_id : Bernoulli Client ID
"""
if not client_id:
client_id = ... | python | def record_goal_attained(experiment_id, user_id, client_id = None):
"""
Record that a variant was successful for a user
@param experiment_id : A single experiment id
@param user_id : An identifier for the user
@param client_id : Bernoulli Client ID
"""
if not client_id:
client_id = ... | [
"def",
"record_goal_attained",
"(",
"experiment_id",
",",
"user_id",
",",
"client_id",
"=",
"None",
")",
":",
"if",
"not",
"client_id",
":",
"client_id",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'BERNOULLI_CLIENT_ID'",
")",
"if",
"not",
"client_id",
":",... | Record that a variant was successful for a user
@param experiment_id : A single experiment id
@param user_id : An identifier for the user
@param client_id : Bernoulli Client ID | [
"Record",
"that",
"a",
"variant",
"was",
"successful",
"for",
"a",
"user"
] | train | https://github.com/bernoulli-metrics/bernoulli-python/blob/572bd165ac354eb4b95ac3abdfe74b67f4fd703b/bernoulli/client_api.py#L46-L73 |
Fuyukai/ConfigMaster | configmaster/YAMLConfigFile.py | yaml_dump_hook | def yaml_dump_hook(cfg, text: bool=False):
"""
Dumps all the data into a YAML file.
"""
data = cfg.config.dump()
if not text:
yaml.dump(data, cfg.fd, Dumper=cfg.dumper, default_flow_style=False)
else:
return yaml.dump(data, Dumper=cfg.dumper, default_flow_style=False) | python | def yaml_dump_hook(cfg, text: bool=False):
"""
Dumps all the data into a YAML file.
"""
data = cfg.config.dump()
if not text:
yaml.dump(data, cfg.fd, Dumper=cfg.dumper, default_flow_style=False)
else:
return yaml.dump(data, Dumper=cfg.dumper, default_flow_style=False) | [
"def",
"yaml_dump_hook",
"(",
"cfg",
",",
"text",
":",
"bool",
"=",
"False",
")",
":",
"data",
"=",
"cfg",
".",
"config",
".",
"dump",
"(",
")",
"if",
"not",
"text",
":",
"yaml",
".",
"dump",
"(",
"data",
",",
"cfg",
".",
"fd",
",",
"Dumper",
"... | Dumps all the data into a YAML file. | [
"Dumps",
"all",
"the",
"data",
"into",
"a",
"YAML",
"file",
"."
] | train | https://github.com/Fuyukai/ConfigMaster/blob/8018aa415da55c84edaa8a49664f674758a14edd/configmaster/YAMLConfigFile.py#L94-L103 |
Baguage/django-auth-pubtkt | django_auth_pubtkt/middleware.py | DjangoAuthPubtkt.add_user_to_group | def add_user_to_group(self, user, group_name):
""" Add user to a group
"""
group, _ = Group.objects.get_or_create(name = group_name)
group.user_set.add(user) | python | def add_user_to_group(self, user, group_name):
""" Add user to a group
"""
group, _ = Group.objects.get_or_create(name = group_name)
group.user_set.add(user) | [
"def",
"add_user_to_group",
"(",
"self",
",",
"user",
",",
"group_name",
")",
":",
"group",
",",
"_",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"group_name",
")",
"group",
".",
"user_set",
".",
"add",
"(",
"user",
")"
] | Add user to a group | [
"Add",
"user",
"to",
"a",
"group"
] | train | https://github.com/Baguage/django-auth-pubtkt/blob/d3f4284212ffbfdc3588929a31e36a4cc7f39786/django_auth_pubtkt/middleware.py#L41-L45 |
wtsi-hgi/gitlab-build-variables | gitlabbuildvariables/executables/gitlab_get_variables.py | _parse_args | def _parse_args(args: List[str]) -> ProjectRunConfig:
"""
Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments
"""
parser = argparse.ArgumentParser(prog="gitlab-get-variables", description="Tool for ... | python | def _parse_args(args: List[str]) -> ProjectRunConfig:
"""
Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments
"""
parser = argparse.ArgumentParser(prog="gitlab-get-variables", description="Tool for ... | [
"def",
"_parse_args",
"(",
"args",
":",
"List",
"[",
"str",
"]",
")",
"->",
"ProjectRunConfig",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"\"gitlab-get-variables\"",
",",
"description",
"=",
"\"Tool for getting a GitLab project's \"",
... | Parses the given CLI arguments to get a run configuration.
:param args: CLI arguments
:return: run configuration derived from the given CLI arguments | [
"Parses",
"the",
"given",
"CLI",
"arguments",
"to",
"get",
"a",
"run",
"configuration",
".",
":",
"param",
"args",
":",
"CLI",
"arguments",
":",
"return",
":",
"run",
"configuration",
"derived",
"from",
"the",
"given",
"CLI",
"arguments"
] | train | https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_get_variables.py#L11-L21 |
wtsi-hgi/gitlab-build-variables | gitlabbuildvariables/executables/gitlab_get_variables.py | main | def main():
"""
Main method.
"""
run_config = _parse_args(sys.argv[1:])
gitlab_config = GitLabConfig(run_config.url, run_config.token)
manager = ProjectVariablesManager(gitlab_config, run_config.project)
output = json.dumps(manager.get(), sort_keys=True, indent=4, separators=(",", ": "))
... | python | def main():
"""
Main method.
"""
run_config = _parse_args(sys.argv[1:])
gitlab_config = GitLabConfig(run_config.url, run_config.token)
manager = ProjectVariablesManager(gitlab_config, run_config.project)
output = json.dumps(manager.get(), sort_keys=True, indent=4, separators=(",", ": "))
... | [
"def",
"main",
"(",
")",
":",
"run_config",
"=",
"_parse_args",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"gitlab_config",
"=",
"GitLabConfig",
"(",
"run_config",
".",
"url",
",",
"run_config",
".",
"token",
")",
"manager",
"=",
"ProjectVariables... | Main method. | [
"Main",
"method",
"."
] | train | https://github.com/wtsi-hgi/gitlab-build-variables/blob/ed1afe50bc41fa20ffb29cacba5ff6dbc2446808/gitlabbuildvariables/executables/gitlab_get_variables.py#L24-L32 |
Exanis/django-rest-generators | django_rest_generators/steps/authentication.py | given_i_am_logged_in | def given_i_am_logged_in(context, username):
"""
:type username: str
:type context: behave.runner.Context
"""
user = get_user_model().objects.get(username=username)
context.apiClient.force_authenticate(user=user) | python | def given_i_am_logged_in(context, username):
"""
:type username: str
:type context: behave.runner.Context
"""
user = get_user_model().objects.get(username=username)
context.apiClient.force_authenticate(user=user) | [
"def",
"given_i_am_logged_in",
"(",
"context",
",",
"username",
")",
":",
"user",
"=",
"get_user_model",
"(",
")",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"context",
".",
"apiClient",
".",
"force_authenticate",
"(",
"user",
"=",
... | :type username: str
:type context: behave.runner.Context | [
":",
"type",
"username",
":",
"str",
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/authentication.py#L11-L17 |
Exanis/django-rest-generators | django_rest_generators/steps/authentication.py | basic_set_of_users_exists_in_the_database | def basic_set_of_users_exists_in_the_database(context):
"""
:type context: behave.runner.Context
"""
user_model = get_user_model()
user_model.objects.create(
username='administrator',
is_staff=True
)
user_model.objects.create(
username='allowed_user'
)
... | python | def basic_set_of_users_exists_in_the_database(context):
"""
:type context: behave.runner.Context
"""
user_model = get_user_model()
user_model.objects.create(
username='administrator',
is_staff=True
)
user_model.objects.create(
username='allowed_user'
)
... | [
"def",
"basic_set_of_users_exists_in_the_database",
"(",
"context",
")",
":",
"user_model",
"=",
"get_user_model",
"(",
")",
"user_model",
".",
"objects",
".",
"create",
"(",
"username",
"=",
"'administrator'",
",",
"is_staff",
"=",
"True",
")",
"user_model",
".",... | :type context: behave.runner.Context | [
":",
"type",
"context",
":",
"behave",
".",
"runner",
".",
"Context"
] | train | https://github.com/Exanis/django-rest-generators/blob/fb14ccbba8cb029dc056d852bc13d9216dc924e4/django_rest_generators/steps/authentication.py#L29-L43 |
bretth/djset | djset/commands.py | _create_djset | def _create_djset(args, cls):
""" Return a DjSecret object """
name = args.get('--name')
settings = args.get('--settings')
if name:
return cls(name=name)
elif settings:
return cls(name=settings)
else:
return cls() | python | def _create_djset(args, cls):
""" Return a DjSecret object """
name = args.get('--name')
settings = args.get('--settings')
if name:
return cls(name=name)
elif settings:
return cls(name=settings)
else:
return cls() | [
"def",
"_create_djset",
"(",
"args",
",",
"cls",
")",
":",
"name",
"=",
"args",
".",
"get",
"(",
"'--name'",
")",
"settings",
"=",
"args",
".",
"get",
"(",
"'--settings'",
")",
"if",
"name",
":",
"return",
"cls",
"(",
"name",
"=",
"name",
")",
"eli... | Return a DjSecret object | [
"Return",
"a",
"DjSecret",
"object"
] | train | https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/commands.py#L16-L25 |
bretth/djset | djset/commands.py | _parse_args | def _parse_args(args, cls):
""" Parse a docopt dictionary of arguments """
d = _create_djset(args, cls)
key_value_pair = args.get('<key>=<value>')
key = args.get('<key>')
func = None
if args.get('add') and key_value_pair:
fargs = tuple(args.get('<key>=<value>').split('='))
... | python | def _parse_args(args, cls):
""" Parse a docopt dictionary of arguments """
d = _create_djset(args, cls)
key_value_pair = args.get('<key>=<value>')
key = args.get('<key>')
func = None
if args.get('add') and key_value_pair:
fargs = tuple(args.get('<key>=<value>').split('='))
... | [
"def",
"_parse_args",
"(",
"args",
",",
"cls",
")",
":",
"d",
"=",
"_create_djset",
"(",
"args",
",",
"cls",
")",
"key_value_pair",
"=",
"args",
".",
"get",
"(",
"'<key>=<value>'",
")",
"key",
"=",
"args",
".",
"get",
"(",
"'<key>'",
")",
"func",
"="... | Parse a docopt dictionary of arguments | [
"Parse",
"a",
"docopt",
"dictionary",
"of",
"arguments"
] | train | https://github.com/bretth/djset/blob/e04cbcadc311f6edec50a718415d0004aa304034/djset/commands.py#L28-L47 |
ddorn/pyconfiglib | configlib/core.py | prompt_update_all | def prompt_update_all(config: 'Config'):
"""Prompt each field of the configuration to the user."""
click.echo()
click.echo('Welcome !')
click.echo('Press enter to keep the defaults or enter a new value to update the configuration.')
click.echo('Press Ctrl+C at any time to quit and save')
click.... | python | def prompt_update_all(config: 'Config'):
"""Prompt each field of the configuration to the user."""
click.echo()
click.echo('Welcome !')
click.echo('Press enter to keep the defaults or enter a new value to update the configuration.')
click.echo('Press Ctrl+C at any time to quit and save')
click.... | [
"def",
"prompt_update_all",
"(",
"config",
":",
"'Config'",
")",
":",
"click",
".",
"echo",
"(",
")",
"click",
".",
"echo",
"(",
"'Welcome !'",
")",
"click",
".",
"echo",
"(",
"'Press enter to keep the defaults or enter a new value to update the configuration.'",
")",... | Prompt each field of the configuration to the user. | [
"Prompt",
"each",
"field",
"of",
"the",
"configuration",
"to",
"the",
"user",
"."
] | train | https://github.com/ddorn/pyconfiglib/blob/3ad01d0bb9344e18719d82a5928b4d8e5fe726ac/configlib/core.py#L85-L128 |
ddorn/pyconfiglib | configlib/core.py | update_config | def update_config(configclass: type(Config)):
"""Command line function to update and the a config."""
# we build the real click command inside the function, because it needs to be done
# dynamically, depending on the config.
# we ignore the type errors, keeping the the defaults if needed
# everyth... | python | def update_config(configclass: type(Config)):
"""Command line function to update and the a config."""
# we build the real click command inside the function, because it needs to be done
# dynamically, depending on the config.
# we ignore the type errors, keeping the the defaults if needed
# everyth... | [
"def",
"update_config",
"(",
"configclass",
":",
"type",
"(",
"Config",
")",
")",
":",
"# we build the real click command inside the function, because it needs to be done",
"# dynamically, depending on the config.",
"# we ignore the type errors, keeping the the defaults if needed",
"# ev... | Command line function to update and the a config. | [
"Command",
"line",
"function",
"to",
"update",
"and",
"the",
"a",
"config",
"."
] | train | https://github.com/ddorn/pyconfiglib/blob/3ad01d0bb9344e18719d82a5928b4d8e5fe726ac/configlib/core.py#L495-L603 |
Deisss/python-sockjsroom | examples/chat/server.py | configureLogger | def configureLogger(logFolder, logFile):
''' Start the logger instance and configure it '''
# Set debug level
logLevel = 'DEBUG'
logger = logging.getLogger()
logger.setLevel(logLevel)
# Format
formatter = logging.Formatter('%(asctime)s - %(levelname)s | %(name)s -> %(message)s', '%Y-%m-%d %... | python | def configureLogger(logFolder, logFile):
''' Start the logger instance and configure it '''
# Set debug level
logLevel = 'DEBUG'
logger = logging.getLogger()
logger.setLevel(logLevel)
# Format
formatter = logging.Formatter('%(asctime)s - %(levelname)s | %(name)s -> %(message)s', '%Y-%m-%d %... | [
"def",
"configureLogger",
"(",
"logFolder",
",",
"logFile",
")",
":",
"# Set debug level",
"logLevel",
"=",
"'DEBUG'",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"logger",
".",
"setLevel",
"(",
"logLevel",
")",
"# Format",
"formatter",
"=",
"logging... | Start the logger instance and configure it | [
"Start",
"the",
"logger",
"instance",
"and",
"configure",
"it"
] | train | https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/examples/chat/server.py#L111-L153 |
Deisss/python-sockjsroom | examples/chat/server.py | printWelcomeMessage | def printWelcomeMessage(msg, place=10):
''' Print any welcome message '''
logging.debug('*' * 30)
welcome = ' ' * place
welcome+= msg
logging.debug(welcome)
logging.debug('*' * 30 + '\n') | python | def printWelcomeMessage(msg, place=10):
''' Print any welcome message '''
logging.debug('*' * 30)
welcome = ' ' * place
welcome+= msg
logging.debug(welcome)
logging.debug('*' * 30 + '\n') | [
"def",
"printWelcomeMessage",
"(",
"msg",
",",
"place",
"=",
"10",
")",
":",
"logging",
".",
"debug",
"(",
"'*'",
"*",
"30",
")",
"welcome",
"=",
"' '",
"*",
"place",
"welcome",
"+=",
"msg",
"logging",
".",
"debug",
"(",
"welcome",
")",
"logging",
".... | Print any welcome message | [
"Print",
"any",
"welcome",
"message"
] | train | https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/examples/chat/server.py#L155-L162 |
Deisss/python-sockjsroom | examples/chat/server.py | ChatSocketHandler.on_chat | def on_chat(self, data):
''' Transfert a message to everybody '''
# XXX: we cannot use on_message as it's 'official' one already used
# by sockjsroom to create multiple on_* elements (like on_chat),
# so we use on_chat instead of on_message
# data => message
if self.room... | python | def on_chat(self, data):
''' Transfert a message to everybody '''
# XXX: we cannot use on_message as it's 'official' one already used
# by sockjsroom to create multiple on_* elements (like on_chat),
# so we use on_chat instead of on_message
# data => message
if self.room... | [
"def",
"on_chat",
"(",
"self",
",",
"data",
")",
":",
"# XXX: we cannot use on_message as it's 'official' one already used",
"# by sockjsroom to create multiple on_* elements (like on_chat),",
"# so we use on_chat instead of on_message",
"# data => message",
"if",
"self",
".",
"roomId"... | Transfert a message to everybody | [
"Transfert",
"a",
"message",
"to",
"everybody"
] | train | https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/examples/chat/server.py#L61-L73 |
Deisss/python-sockjsroom | examples/chat/server.py | ChatSocketHandler.on_leave | def on_leave(self):
''' Quit chat room '''
# Only if user has time to call self.initialize
# (sometimes it's not the case)
if self.roomId != '-1':
# Debug
logging.debug('chat: leave room (roomId: %s)' % self.roomId)
# Say to other users the current us... | python | def on_leave(self):
''' Quit chat room '''
# Only if user has time to call self.initialize
# (sometimes it's not the case)
if self.roomId != '-1':
# Debug
logging.debug('chat: leave room (roomId: %s)' % self.roomId)
# Say to other users the current us... | [
"def",
"on_leave",
"(",
"self",
")",
":",
"# Only if user has time to call self.initialize",
"# (sometimes it's not the case)",
"if",
"self",
".",
"roomId",
"!=",
"'-1'",
":",
"# Debug",
"logging",
".",
"debug",
"(",
"'chat: leave room (roomId: %s)'",
"%",
"self",
".",
... | Quit chat room | [
"Quit",
"chat",
"room"
] | train | https://github.com/Deisss/python-sockjsroom/blob/7c20187571d39e7fede848dc98f954235ca77241/examples/chat/server.py#L76-L93 |
klmitch/tendril | tendril/udp.py | UDPTendril.send_frame | def send_frame(self, frame):
"""
Sends a frame to the other end of the connection.
"""
# Get the socket
sock = self.manager.sock
if not sock:
raise ValueError("UDPTendrilManager not running")
# Send the packet
try:
sock.sendto(se... | python | def send_frame(self, frame):
"""
Sends a frame to the other end of the connection.
"""
# Get the socket
sock = self.manager.sock
if not sock:
raise ValueError("UDPTendrilManager not running")
# Send the packet
try:
sock.sendto(se... | [
"def",
"send_frame",
"(",
"self",
",",
"frame",
")",
":",
"# Get the socket",
"sock",
"=",
"self",
".",
"manager",
".",
"sock",
"if",
"not",
"sock",
":",
"raise",
"ValueError",
"(",
"\"UDPTendrilManager not running\"",
")",
"# Send the packet",
"try",
":",
"so... | Sends a frame to the other end of the connection. | [
"Sends",
"a",
"frame",
"to",
"the",
"other",
"end",
"of",
"the",
"connection",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/udp.py#L35-L51 |
klmitch/tendril | tendril/udp.py | UDPTendrilManager.start | def start(self, acceptor=None, wrapper=None):
"""
Starts the TendrilManager.
:param acceptor: If given, specifies a callable that will be
called with each newly received Tendril;
that callable is responsible for initial
... | python | def start(self, acceptor=None, wrapper=None):
"""
Starts the TendrilManager.
:param acceptor: If given, specifies a callable that will be
called with each newly received Tendril;
that callable is responsible for initial
... | [
"def",
"start",
"(",
"self",
",",
"acceptor",
"=",
"None",
",",
"wrapper",
"=",
"None",
")",
":",
"super",
"(",
"UDPTendrilManager",
",",
"self",
")",
".",
"start",
"(",
"acceptor",
",",
"wrapper",
")",
"# Reset the socket and socket event",
"self",
".",
"... | Starts the TendrilManager.
:param acceptor: If given, specifies a callable that will be
called with each newly received Tendril;
that callable is responsible for initial
acceptance of the connection and for setting
... | [
"Starts",
"the",
"TendrilManager",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/udp.py#L101-L127 |
klmitch/tendril | tendril/udp.py | UDPTendrilManager.stop | def stop(self, *args):
"""
Stops the TendrilManager. Requires cooperation from the
listener implementation, which must watch the ``running``
attribute and ensure that it stops accepting connections
should that attribute become False. Note that some tendril
managers will... | python | def stop(self, *args):
"""
Stops the TendrilManager. Requires cooperation from the
listener implementation, which must watch the ``running``
attribute and ensure that it stops accepting connections
should that attribute become False. Note that some tendril
managers will... | [
"def",
"stop",
"(",
"self",
",",
"*",
"args",
")",
":",
"super",
"(",
"UDPTendrilManager",
",",
"self",
")",
".",
"stop",
"(",
"*",
"args",
")",
"# Reset the socket and socket event",
"self",
".",
"_sock",
"=",
"None",
"self",
".",
"_sock_event",
".",
"c... | Stops the TendrilManager. Requires cooperation from the
listener implementation, which must watch the ``running``
attribute and ensure that it stops accepting connections
should that attribute become False. Note that some tendril
managers will not exit from the listening thread until a... | [
"Stops",
"the",
"TendrilManager",
".",
"Requires",
"cooperation",
"from",
"the",
"listener",
"implementation",
"which",
"must",
"watch",
"the",
"running",
"attribute",
"and",
"ensure",
"that",
"it",
"stops",
"accepting",
"connections",
"should",
"that",
"attribute",... | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/udp.py#L129-L143 |
klmitch/tendril | tendril/udp.py | UDPTendrilManager.shutdown | def shutdown(self):
"""
Unconditionally shuts the TendrilManager down, killing all
threads and closing all tendrils.
"""
super(UDPTendrilManager, self).shutdown()
# Reset the socket and socket event
self._sock = None
self._sock_event.clear() | python | def shutdown(self):
"""
Unconditionally shuts the TendrilManager down, killing all
threads and closing all tendrils.
"""
super(UDPTendrilManager, self).shutdown()
# Reset the socket and socket event
self._sock = None
self._sock_event.clear() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"super",
"(",
"UDPTendrilManager",
",",
"self",
")",
".",
"shutdown",
"(",
")",
"# Reset the socket and socket event",
"self",
".",
"_sock",
"=",
"None",
"self",
".",
"_sock_event",
".",
"clear",
"(",
")"
] | Unconditionally shuts the TendrilManager down, killing all
threads and closing all tendrils. | [
"Unconditionally",
"shuts",
"the",
"TendrilManager",
"down",
"killing",
"all",
"threads",
"and",
"closing",
"all",
"tendrils",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/udp.py#L145-L155 |
klmitch/tendril | tendril/udp.py | UDPTendrilManager.connect | def connect(self, target, acceptor):
"""
Initiate a connection from the tendril manager's endpoint.
Once the connection is completed, a UDPTendril object will be
created and passed to the given acceptor.
:param target: The target of the connection attempt.
:param accepto... | python | def connect(self, target, acceptor):
"""
Initiate a connection from the tendril manager's endpoint.
Once the connection is completed, a UDPTendril object will be
created and passed to the given acceptor.
:param target: The target of the connection attempt.
:param accepto... | [
"def",
"connect",
"(",
"self",
",",
"target",
",",
"acceptor",
")",
":",
"# Call some common sanity-checks",
"super",
"(",
"UDPTendrilManager",
",",
"self",
")",
".",
"connect",
"(",
"target",
",",
"acceptor",
",",
"None",
")",
"# Construct the Tendril",
"tend",... | Initiate a connection from the tendril manager's endpoint.
Once the connection is completed, a UDPTendril object will be
created and passed to the given acceptor.
:param target: The target of the connection attempt.
:param acceptor: A callable which will initialize the state of
... | [
"Initiate",
"a",
"connection",
"from",
"the",
"tendril",
"manager",
"s",
"endpoint",
".",
"Once",
"the",
"connection",
"is",
"completed",
"a",
"UDPTendril",
"object",
"will",
"be",
"created",
"and",
"passed",
"to",
"the",
"given",
"acceptor",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/udp.py#L157-L185 |
klmitch/tendril | tendril/udp.py | UDPTendrilManager.listener | def listener(self, acceptor, wrapper):
"""
Listens for new connections to the manager's endpoint. Once a
new connection is received, a UDPTendril object is generated
for it and it is passed to the acceptor, which must initialize
the state of the connection. If no acceptor is gi... | python | def listener(self, acceptor, wrapper):
"""
Listens for new connections to the manager's endpoint. Once a
new connection is received, a UDPTendril object is generated
for it and it is passed to the acceptor, which must initialize
the state of the connection. If no acceptor is gi... | [
"def",
"listener",
"(",
"self",
",",
"acceptor",
",",
"wrapper",
")",
":",
"# OK, set up the socket",
"sock",
"=",
"socket",
".",
"socket",
"(",
"self",
".",
"addr_family",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"with",
"utils",
".",
"SocketCloser",
"(",
"... | Listens for new connections to the manager's endpoint. Once a
new connection is received, a UDPTendril object is generated
for it and it is passed to the acceptor, which must initialize
the state of the connection. If no acceptor is given, no new
connections can be initialized.
... | [
"Listens",
"for",
"new",
"connections",
"to",
"the",
"manager",
"s",
"endpoint",
".",
"Once",
"a",
"new",
"connection",
"is",
"received",
"a",
"UDPTendril",
"object",
"is",
"generated",
"for",
"it",
"and",
"it",
"is",
"passed",
"to",
"the",
"acceptor",
"wh... | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/udp.py#L187-L260 |
fr33jc/bang | bang/providers/hpcloud/load_balancer.py | HPLoadBalancer.find_lb_by_name | def find_lb_by_name(self, name):
"""
Look up a LBaaS instance by name (rather than id)
:attr string name: The LBaaS name assigned at creation time
:rtype :class:`dict`
"""
log.debug("Finding load balancers matching name '%s'" % name)
matching = filter(lambda l:... | python | def find_lb_by_name(self, name):
"""
Look up a LBaaS instance by name (rather than id)
:attr string name: The LBaaS name assigned at creation time
:rtype :class:`dict`
"""
log.debug("Finding load balancers matching name '%s'" % name)
matching = filter(lambda l:... | [
"def",
"find_lb_by_name",
"(",
"self",
",",
"name",
")",
":",
"log",
".",
"debug",
"(",
"\"Finding load balancers matching name '%s'\"",
"%",
"name",
")",
"matching",
"=",
"filter",
"(",
"lambda",
"l",
":",
"l",
"[",
"'name'",
"]",
"==",
"name",
",",
"self... | Look up a LBaaS instance by name (rather than id)
:attr string name: The LBaaS name assigned at creation time
:rtype :class:`dict` | [
"Look",
"up",
"a",
"LBaaS",
"instance",
"by",
"name",
"(",
"rather",
"than",
"id",
")"
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/load_balancer.py#L60-L75 |
fr33jc/bang | bang/providers/hpcloud/load_balancer.py | HPLoadBalancer.create_lb | def create_lb(self, name, protocol='HTTP', port=80, algorithm=None,
virtual_ips=[], nodes=[], node_port=None):
"""
Create a new LBaaS instance. A name is required. If no nodes
are required, the instance ``status`` (after it's built) will be
``ERROR`` until nodes are added. Th... | python | def create_lb(self, name, protocol='HTTP', port=80, algorithm=None,
virtual_ips=[], nodes=[], node_port=None):
"""
Create a new LBaaS instance. A name is required. If no nodes
are required, the instance ``status`` (after it's built) will be
``ERROR`` until nodes are added. Th... | [
"def",
"create_lb",
"(",
"self",
",",
"name",
",",
"protocol",
"=",
"'HTTP'",
",",
"port",
"=",
"80",
",",
"algorithm",
"=",
"None",
",",
"virtual_ips",
"=",
"[",
"]",
",",
"nodes",
"=",
"[",
"]",
",",
"node_port",
"=",
"None",
")",
":",
"log",
"... | Create a new LBaaS instance. A name is required. If no nodes
are required, the instance ``status`` (after it's built) will be
``ERROR`` until nodes are added. The return dict contains the id
and ``virtualIps`` (the external IP).
:param string name: The LBaaS name - should be unique
... | [
"Create",
"a",
"new",
"LBaaS",
"instance",
".",
"A",
"name",
"is",
"required",
".",
"If",
"no",
"nodes",
"are",
"required",
"the",
"instance",
"status",
"(",
"after",
"it",
"s",
"built",
")",
"will",
"be",
"ERROR",
"until",
"nodes",
"are",
"added",
"."... | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/load_balancer.py#L77-L115 |
fr33jc/bang | bang/providers/hpcloud/load_balancer.py | HPLoadBalancer.add_lb_nodes | def add_lb_nodes(self, lb_id, nodes):
"""
Adds nodes to an existing LBaaS instance
:param string lb_id: Balancer id
:param list nodes: Nodes to add. {address, port, [condition]}
:rtype :class:`list`
"""
log.info("Adding load balancer nodes %s" % nodes)
... | python | def add_lb_nodes(self, lb_id, nodes):
"""
Adds nodes to an existing LBaaS instance
:param string lb_id: Balancer id
:param list nodes: Nodes to add. {address, port, [condition]}
:rtype :class:`list`
"""
log.info("Adding load balancer nodes %s" % nodes)
... | [
"def",
"add_lb_nodes",
"(",
"self",
",",
"lb_id",
",",
"nodes",
")",
":",
"log",
".",
"info",
"(",
"\"Adding load balancer nodes %s\"",
"%",
"nodes",
")",
"resp",
",",
"body",
"=",
"self",
".",
"_request",
"(",
"'post'",
",",
"'/loadbalancers/%s/nodes'",
"%"... | Adds nodes to an existing LBaaS instance
:param string lb_id: Balancer id
:param list nodes: Nodes to add. {address, port, [condition]}
:rtype :class:`list` | [
"Adds",
"nodes",
"to",
"an",
"existing",
"LBaaS",
"instance"
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/load_balancer.py#L126-L141 |
fr33jc/bang | bang/providers/hpcloud/load_balancer.py | HPLoadBalancer.match_lb_nodes | def match_lb_nodes(self, lb_id, existing_nodes, host_addresses, host_port):
"""
Add and remove nodes to match the host addresses
and port given, based on existing_nodes. HPCS doesn't
allow a load balancer with no backends, so we'll add
first, delete after.
:param string ... | python | def match_lb_nodes(self, lb_id, existing_nodes, host_addresses, host_port):
"""
Add and remove nodes to match the host addresses
and port given, based on existing_nodes. HPCS doesn't
allow a load balancer with no backends, so we'll add
first, delete after.
:param string ... | [
"def",
"match_lb_nodes",
"(",
"self",
",",
"lb_id",
",",
"existing_nodes",
",",
"host_addresses",
",",
"host_port",
")",
":",
"delete_filter",
"=",
"lambda",
"n",
":",
"n",
"[",
"'address'",
"]",
"not",
"in",
"host_addresses",
"or",
"str",
"(",
"n",
"[",
... | Add and remove nodes to match the host addresses
and port given, based on existing_nodes. HPCS doesn't
allow a load balancer with no backends, so we'll add
first, delete after.
:param string lb_id: Load balancer id
:param :class:`list` of :class:`dict` existing_nodes: Existing ... | [
"Add",
"and",
"remove",
"nodes",
"to",
"match",
"the",
"host",
"addresses",
"and",
"port",
"given",
"based",
"on",
"existing_nodes",
".",
"HPCS",
"doesn",
"t",
"allow",
"a",
"load",
"balancer",
"with",
"no",
"backends",
"so",
"we",
"ll",
"add",
"first",
... | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/load_balancer.py#L143-L183 |
fr33jc/bang | bang/providers/hpcloud/load_balancer.py | HPLoadBalancer.remove_lb_nodes | def remove_lb_nodes(self, lb_id, node_ids):
"""
Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids
"""
log.info("Removing load balancer nodes %s" % node_ids)
for node_id in node_ids:
self._request('dele... | python | def remove_lb_nodes(self, lb_id, node_ids):
"""
Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids
"""
log.info("Removing load balancer nodes %s" % node_ids)
for node_id in node_ids:
self._request('dele... | [
"def",
"remove_lb_nodes",
"(",
"self",
",",
"lb_id",
",",
"node_ids",
")",
":",
"log",
".",
"info",
"(",
"\"Removing load balancer nodes %s\"",
"%",
"node_ids",
")",
"for",
"node_id",
"in",
"node_ids",
":",
"self",
".",
"_request",
"(",
"'delete'",
",",
"'/l... | Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids | [
"Remove",
"one",
"or",
"more",
"nodes"
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/load_balancer.py#L185-L195 |
fr33jc/bang | bang/providers/hpcloud/load_balancer.py | HPLoadBalancer.update_lb_node_condition | def update_lb_node_condition(self, lb_id, node_id, condition):
"""
Update node condition - specifically to disable/enable
:param string lb_id: Balancer id
:param string node_id: Node id
:param string condition: ENABLED/DISABLED
"""
self._request(
... | python | def update_lb_node_condition(self, lb_id, node_id, condition):
"""
Update node condition - specifically to disable/enable
:param string lb_id: Balancer id
:param string node_id: Node id
:param string condition: ENABLED/DISABLED
"""
self._request(
... | [
"def",
"update_lb_node_condition",
"(",
"self",
",",
"lb_id",
",",
"node_id",
",",
"condition",
")",
":",
"self",
".",
"_request",
"(",
"'put'",
",",
"'/loadbalancers/%s/nodes/%s'",
"%",
"(",
"lb_id",
",",
"node_id",
")",
",",
"data",
"=",
"{",
"'condition'"... | Update node condition - specifically to disable/enable
:param string lb_id: Balancer id
:param string node_id: Node id
:param string condition: ENABLED/DISABLED | [
"Update",
"node",
"condition",
"-",
"specifically",
"to",
"disable",
"/",
"enable"
] | train | https://github.com/fr33jc/bang/blob/8f000713f88d2a9a8c1193b63ca10a6578560c16/bang/providers/hpcloud/load_balancer.py#L197-L210 |
estilen/simplebrowser | simplebrowser/browser.py | SimpleBrowser.soup | def soup(self, *args, **kwargs):
"""Parse the currently loaded website.
Optionally, SoupStrainer can be used to only parse relevant
parts of the page. This can be particularly useful if the website is
complex or perfomance is a factor.
<https://www.crummy.com/software/BeautifulS... | python | def soup(self, *args, **kwargs):
"""Parse the currently loaded website.
Optionally, SoupStrainer can be used to only parse relevant
parts of the page. This can be particularly useful if the website is
complex or perfomance is a factor.
<https://www.crummy.com/software/BeautifulS... | [
"def",
"soup",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_url",
"is",
"None",
":",
"raise",
"NoWebsiteLoadedError",
"(",
"'website parsing requires a loaded website'",
")",
"content_type",
"=",
"self",
".",
"_respo... | Parse the currently loaded website.
Optionally, SoupStrainer can be used to only parse relevant
parts of the page. This can be particularly useful if the website is
complex or perfomance is a factor.
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#soupstrainer>
Args:
... | [
"Parse",
"the",
"currently",
"loaded",
"website",
"."
] | train | https://github.com/estilen/simplebrowser/blob/76c1c0d770f8a209a7a32fa65ed46f9d6e60f91b/simplebrowser/browser.py#L49-L76 |
estilen/simplebrowser | simplebrowser/browser.py | SimpleBrowser.get | def get(self, url, **kwargs):
"""Send a GET request to the specified URL.
Method directly wraps around `Session.get` and updates browser
attributes.
<http://docs.python-requests.org/en/master/api/#requests.get>
Args:
url: URL for the new `Request` object.
... | python | def get(self, url, **kwargs):
"""Send a GET request to the specified URL.
Method directly wraps around `Session.get` and updates browser
attributes.
<http://docs.python-requests.org/en/master/api/#requests.get>
Args:
url: URL for the new `Request` object.
... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_url",
"=",
"response",
".",
"url",
"self",
".",
"_response",
... | Send a GET request to the specified URL.
Method directly wraps around `Session.get` and updates browser
attributes.
<http://docs.python-requests.org/en/master/api/#requests.get>
Args:
url: URL for the new `Request` object.
**kwargs: Optional arguments that `Requ... | [
"Send",
"a",
"GET",
"request",
"to",
"the",
"specified",
"URL",
"."
] | train | https://github.com/estilen/simplebrowser/blob/76c1c0d770f8a209a7a32fa65ed46f9d6e60f91b/simplebrowser/browser.py#L78-L95 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.