repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
mattlong/hermes | hermes/server.py | run_server | def run_server(chatrooms, use_default_logging=True):
"""Sets up and serves specified chatrooms. Main entrypoint to Hermes.
:param chatrooms: Dictionary of chatrooms to serve.
:param use_default_logging: (optional) Boolean. Set to True if Hermes should setup its default logging configuration.
"""
if... | python | def run_server(chatrooms, use_default_logging=True):
"""Sets up and serves specified chatrooms. Main entrypoint to Hermes.
:param chatrooms: Dictionary of chatrooms to serve.
:param use_default_logging: (optional) Boolean. Set to True if Hermes should setup its default logging configuration.
"""
if... | [
"def",
"run_server",
"(",
"chatrooms",
",",
"use_default_logging",
"=",
"True",
")",
":",
"if",
"use_default_logging",
":",
"configure_logging",
"(",
")",
"logger",
".",
"info",
"(",
"'Starting Hermes chatroom server...'",
")",
"bots",
"=",
"[",
"]",
"for",
"nam... | Sets up and serves specified chatrooms. Main entrypoint to Hermes.
:param chatrooms: Dictionary of chatrooms to serve.
:param use_default_logging: (optional) Boolean. Set to True if Hermes should setup its default logging configuration. | [
"Sets",
"up",
"and",
"serves",
"specified",
"chatrooms",
".",
"Main",
"entrypoint",
"to",
"Hermes",
"."
] | 63a5afcafe90ca99aeb44edeee9ed6f90baae431 | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/server.py#L23-L67 | train |
mattlong/hermes | hermes/server.py | _get_sockets | def _get_sockets(bots):
"""Connects and gathers sockets for all chatrooms"""
sockets = {}
#sockets[sys.stdin] = 'stdio'
for bot in bots:
bot.connect()
sockets[bot.client.Connection._sock] = bot
return sockets | python | def _get_sockets(bots):
"""Connects and gathers sockets for all chatrooms"""
sockets = {}
#sockets[sys.stdin] = 'stdio'
for bot in bots:
bot.connect()
sockets[bot.client.Connection._sock] = bot
return sockets | [
"def",
"_get_sockets",
"(",
"bots",
")",
":",
"sockets",
"=",
"{",
"}",
"for",
"bot",
"in",
"bots",
":",
"bot",
".",
"connect",
"(",
")",
"sockets",
"[",
"bot",
".",
"client",
".",
"Connection",
".",
"_sock",
"]",
"=",
"bot",
"return",
"sockets"
] | Connects and gathers sockets for all chatrooms | [
"Connects",
"and",
"gathers",
"sockets",
"for",
"all",
"chatrooms"
] | 63a5afcafe90ca99aeb44edeee9ed6f90baae431 | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/server.py#L69-L76 | train |
mattlong/hermes | hermes/server.py | _listen | def _listen(sockets):
"""Main server loop. Listens for incoming events and dispatches them to appropriate chatroom"""
while True:
(i , o, e) = select.select(sockets.keys(),[],[],1)
for socket in i:
if isinstance(sockets[socket], Chatroom):
data_len = sockets[socket].c... | python | def _listen(sockets):
"""Main server loop. Listens for incoming events and dispatches them to appropriate chatroom"""
while True:
(i , o, e) = select.select(sockets.keys(),[],[],1)
for socket in i:
if isinstance(sockets[socket], Chatroom):
data_len = sockets[socket].c... | [
"def",
"_listen",
"(",
"sockets",
")",
":",
"while",
"True",
":",
"(",
"i",
",",
"o",
",",
"e",
")",
"=",
"select",
".",
"select",
"(",
"sockets",
".",
"keys",
"(",
")",
",",
"[",
"]",
",",
"[",
"]",
",",
"1",
")",
"for",
"socket",
"in",
"i... | Main server loop. Listens for incoming events and dispatches them to appropriate chatroom | [
"Main",
"server",
"loop",
".",
"Listens",
"for",
"incoming",
"events",
"and",
"dispatches",
"them",
"to",
"appropriate",
"chatroom"
] | 63a5afcafe90ca99aeb44edeee9ed6f90baae431 | https://github.com/mattlong/hermes/blob/63a5afcafe90ca99aeb44edeee9ed6f90baae431/hermes/server.py#L78-L91 | train |
transifex/transifex-python-library | txlib/http/http_requests.py | HttpRequest._send | def _send(self, method, path, data, filename):
"""Send data to a remote server, either with a POST or a PUT request.
Args:
`method`: The method (POST or PUT) to use.
`path`: The path to the resource.
`data`: The data to send.
`filename`: The filename of t... | python | def _send(self, method, path, data, filename):
"""Send data to a remote server, either with a POST or a PUT request.
Args:
`method`: The method (POST or PUT) to use.
`path`: The path to the resource.
`data`: The data to send.
`filename`: The filename of t... | [
"def",
"_send",
"(",
"self",
",",
"method",
",",
"path",
",",
"data",
",",
"filename",
")",
":",
"if",
"filename",
"is",
"None",
":",
"return",
"self",
".",
"_send_json",
"(",
"method",
",",
"path",
",",
"data",
")",
"else",
":",
"return",
"self",
... | Send data to a remote server, either with a POST or a PUT request.
Args:
`method`: The method (POST or PUT) to use.
`path`: The path to the resource.
`data`: The data to send.
`filename`: The filename of the file to send (if any).
Returns:
The... | [
"Send",
"data",
"to",
"a",
"remote",
"server",
"either",
"with",
"a",
"POST",
"or",
"a",
"PUT",
"request",
"."
] | 9fea86b718973de35ccca6d54bd1f445c9632406 | https://github.com/transifex/transifex-python-library/blob/9fea86b718973de35ccca6d54bd1f445c9632406/txlib/http/http_requests.py#L123-L139 | train |
BernardFW/bernard | src/bernard/platforms/management.py | get_platform_settings | def get_platform_settings():
"""
Returns the content of `settings.PLATFORMS` with a twist.
The platforms settings was created to stay compatible with the old way of
declaring the FB configuration, in order not to break production bots. This
function will convert the legacy configuration into the ne... | python | def get_platform_settings():
"""
Returns the content of `settings.PLATFORMS` with a twist.
The platforms settings was created to stay compatible with the old way of
declaring the FB configuration, in order not to break production bots. This
function will convert the legacy configuration into the ne... | [
"def",
"get_platform_settings",
"(",
")",
":",
"s",
"=",
"settings",
".",
"PLATFORMS",
"if",
"hasattr",
"(",
"settings",
",",
"'FACEBOOK'",
")",
"and",
"settings",
".",
"FACEBOOK",
":",
"s",
".",
"append",
"(",
"{",
"'class'",
":",
"'bernard.platforms.facebo... | Returns the content of `settings.PLATFORMS` with a twist.
The platforms settings was created to stay compatible with the old way of
declaring the FB configuration, in order not to break production bots. This
function will convert the legacy configuration into the new configuration
if required. As a res... | [
"Returns",
"the",
"content",
"of",
"settings",
".",
"PLATFORMS",
"with",
"a",
"twist",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L39-L58 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager.run_checks | async def run_checks(self):
"""
Run checks on itself and on the FSM
"""
async for check in self.fsm.health_check():
yield check
async for check in self.self_check():
yield check
for check in MiddlewareManager.health_check():
yield ch... | python | async def run_checks(self):
"""
Run checks on itself and on the FSM
"""
async for check in self.fsm.health_check():
yield check
async for check in self.self_check():
yield check
for check in MiddlewareManager.health_check():
yield ch... | [
"async",
"def",
"run_checks",
"(",
"self",
")",
":",
"async",
"for",
"check",
"in",
"self",
".",
"fsm",
".",
"health_check",
"(",
")",
":",
"yield",
"check",
"async",
"for",
"check",
"in",
"self",
".",
"self_check",
"(",
")",
":",
"yield",
"check",
"... | Run checks on itself and on the FSM | [
"Run",
"checks",
"on",
"itself",
"and",
"on",
"the",
"FSM"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L109-L121 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager.self_check | async def self_check(self):
"""
Checks that the platforms configuration is all right.
"""
platforms = set()
for platform in get_platform_settings():
try:
name = platform['class']
cls: Type[Platform] = import_class(name)
ex... | python | async def self_check(self):
"""
Checks that the platforms configuration is all right.
"""
platforms = set()
for platform in get_platform_settings():
try:
name = platform['class']
cls: Type[Platform] = import_class(name)
ex... | [
"async",
"def",
"self_check",
"(",
"self",
")",
":",
"platforms",
"=",
"set",
"(",
")",
"for",
"platform",
"in",
"get_platform_settings",
"(",
")",
":",
"try",
":",
"name",
"=",
"platform",
"[",
"'class'",
"]",
"cls",
":",
"Type",
"[",
"Platform",
"]",... | Checks that the platforms configuration is all right. | [
"Checks",
"that",
"the",
"platforms",
"configuration",
"is",
"all",
"right",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L123-L154 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager._index_classes | def _index_classes(self) -> Dict[Text, Type[Platform]]:
"""
Build a name index for all platform classes
"""
out = {}
for p in get_platform_settings():
cls: Type[Platform] = import_class(p['class'])
if 'name' in p:
out[p['name']] = cls
... | python | def _index_classes(self) -> Dict[Text, Type[Platform]]:
"""
Build a name index for all platform classes
"""
out = {}
for p in get_platform_settings():
cls: Type[Platform] = import_class(p['class'])
if 'name' in p:
out[p['name']] = cls
... | [
"def",
"_index_classes",
"(",
"self",
")",
"->",
"Dict",
"[",
"Text",
",",
"Type",
"[",
"Platform",
"]",
"]",
":",
"out",
"=",
"{",
"}",
"for",
"p",
"in",
"get_platform_settings",
"(",
")",
":",
"cls",
":",
"Type",
"[",
"Platform",
"]",
"=",
"impor... | Build a name index for all platform classes | [
"Build",
"a",
"name",
"index",
"for",
"all",
"platform",
"classes"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L156-L171 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager.build_platform | async def build_platform(self, cls: Type[Platform], custom_id):
"""
Build the Facebook platform. Nothing fancy.
"""
from bernard.server.http import router
p = cls()
if custom_id:
p._id = custom_id
await p.async_init()
p.on_message(self.fsm.... | python | async def build_platform(self, cls: Type[Platform], custom_id):
"""
Build the Facebook platform. Nothing fancy.
"""
from bernard.server.http import router
p = cls()
if custom_id:
p._id = custom_id
await p.async_init()
p.on_message(self.fsm.... | [
"async",
"def",
"build_platform",
"(",
"self",
",",
"cls",
":",
"Type",
"[",
"Platform",
"]",
",",
"custom_id",
")",
":",
"from",
"bernard",
".",
"server",
".",
"http",
"import",
"router",
"p",
"=",
"cls",
"(",
")",
"if",
"custom_id",
":",
"p",
".",
... | Build the Facebook platform. Nothing fancy. | [
"Build",
"the",
"Facebook",
"platform",
".",
"Nothing",
"fancy",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L173-L188 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager.get_class | def get_class(self, platform) -> Type[Platform]:
"""
For a given platform name, gets the matching class
"""
if platform in self._classes:
return self._classes[platform]
raise PlatformDoesNotExist('Platform "{}" is not in configuration'
... | python | def get_class(self, platform) -> Type[Platform]:
"""
For a given platform name, gets the matching class
"""
if platform in self._classes:
return self._classes[platform]
raise PlatformDoesNotExist('Platform "{}" is not in configuration'
... | [
"def",
"get_class",
"(",
"self",
",",
"platform",
")",
"->",
"Type",
"[",
"Platform",
"]",
":",
"if",
"platform",
"in",
"self",
".",
"_classes",
":",
"return",
"self",
".",
"_classes",
"[",
"platform",
"]",
"raise",
"PlatformDoesNotExist",
"(",
"'Platform ... | For a given platform name, gets the matching class | [
"For",
"a",
"given",
"platform",
"name",
"gets",
"the",
"matching",
"class"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L190-L199 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager.get_platform | async def get_platform(self, name: Text):
"""
Get a valid instance of the specified platform. Do not cache this
object, it might change with configuration changes.
"""
if not self._is_init:
await self.init()
if name not in self.platforms:
self.pl... | python | async def get_platform(self, name: Text):
"""
Get a valid instance of the specified platform. Do not cache this
object, it might change with configuration changes.
"""
if not self._is_init:
await self.init()
if name not in self.platforms:
self.pl... | [
"async",
"def",
"get_platform",
"(",
"self",
",",
"name",
":",
"Text",
")",
":",
"if",
"not",
"self",
".",
"_is_init",
":",
"await",
"self",
".",
"init",
"(",
")",
"if",
"name",
"not",
"in",
"self",
".",
"platforms",
":",
"self",
".",
"platforms",
... | Get a valid instance of the specified platform. Do not cache this
object, it might change with configuration changes. | [
"Get",
"a",
"valid",
"instance",
"of",
"the",
"specified",
"platform",
".",
"Do",
"not",
"cache",
"this",
"object",
"it",
"might",
"change",
"with",
"configuration",
"changes",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L201-L214 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager.get_all_platforms | async def get_all_platforms(self) -> AsyncIterator[Platform]:
"""
Returns all platform instances
"""
for name in self._classes.keys():
yield await self.get_platform(name) | python | async def get_all_platforms(self) -> AsyncIterator[Platform]:
"""
Returns all platform instances
"""
for name in self._classes.keys():
yield await self.get_platform(name) | [
"async",
"def",
"get_all_platforms",
"(",
"self",
")",
"->",
"AsyncIterator",
"[",
"Platform",
"]",
":",
"for",
"name",
"in",
"self",
".",
"_classes",
".",
"keys",
"(",
")",
":",
"yield",
"await",
"self",
".",
"get_platform",
"(",
"name",
")"
] | Returns all platform instances | [
"Returns",
"all",
"platform",
"instances"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L216-L222 | train |
BernardFW/bernard | src/bernard/platforms/management.py | PlatformManager.message_from_token | async def message_from_token(self, token: Text, payload: Any) \
-> Tuple[Optional[BaseMessage], Optional[Platform]]:
"""
Given an authentication token, find the right platform that can
recognize this token and create a message for this platform.
The payload will be inserted ... | python | async def message_from_token(self, token: Text, payload: Any) \
-> Tuple[Optional[BaseMessage], Optional[Platform]]:
"""
Given an authentication token, find the right platform that can
recognize this token and create a message for this platform.
The payload will be inserted ... | [
"async",
"def",
"message_from_token",
"(",
"self",
",",
"token",
":",
"Text",
",",
"payload",
":",
"Any",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"BaseMessage",
"]",
",",
"Optional",
"[",
"Platform",
"]",
"]",
":",
"async",
"for",
"platform",
"in",
"... | Given an authentication token, find the right platform that can
recognize this token and create a message for this platform.
The payload will be inserted into a Postback layer. | [
"Given",
"an",
"authentication",
"token",
"find",
"the",
"right",
"platform",
"that",
"can",
"recognize",
"this",
"token",
"and",
"create",
"a",
"message",
"for",
"this",
"platform",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/platforms/management.py#L224-L239 | train |
openvax/varlens | varlens/reads_util.py | add_args | def add_args(parser, positional=False):
"""
Extends a commandline argument parser with arguments for specifying
read sources.
"""
group = parser.add_argument_group("read loading")
group.add_argument("reads" if positional else "--reads",
nargs="+", default=[],
help="Paths to bam f... | python | def add_args(parser, positional=False):
"""
Extends a commandline argument parser with arguments for specifying
read sources.
"""
group = parser.add_argument_group("read loading")
group.add_argument("reads" if positional else "--reads",
nargs="+", default=[],
help="Paths to bam f... | [
"def",
"add_args",
"(",
"parser",
",",
"positional",
"=",
"False",
")",
":",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"read loading\"",
")",
"group",
".",
"add_argument",
"(",
"\"reads\"",
"if",
"positional",
"else",
"\"--reads\"",
",",
"nargs... | Extends a commandline argument parser with arguments for specifying
read sources. | [
"Extends",
"a",
"commandline",
"argument",
"parser",
"with",
"arguments",
"for",
"specifying",
"read",
"sources",
"."
] | 715d3ede5893757b2fcba4117515621bca7b1e5d | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/reads_util.py#L104-L141 | train |
openvax/varlens | varlens/reads_util.py | load_from_args | def load_from_args(args):
"""
Given parsed commandline arguments, returns a list of ReadSource objects
"""
if not args.reads:
return None
if args.read_source_name:
read_source_names = util.expand(
args.read_source_name,
'read_source_name',
'read s... | python | def load_from_args(args):
"""
Given parsed commandline arguments, returns a list of ReadSource objects
"""
if not args.reads:
return None
if args.read_source_name:
read_source_names = util.expand(
args.read_source_name,
'read_source_name',
'read s... | [
"def",
"load_from_args",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"reads",
":",
"return",
"None",
"if",
"args",
".",
"read_source_name",
":",
"read_source_names",
"=",
"util",
".",
"expand",
"(",
"args",
".",
"read_source_name",
",",
"'read_source_na... | Given parsed commandline arguments, returns a list of ReadSource objects | [
"Given",
"parsed",
"commandline",
"arguments",
"returns",
"a",
"list",
"of",
"ReadSource",
"objects"
] | 715d3ede5893757b2fcba4117515621bca7b1e5d | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/reads_util.py#L143-L169 | train |
klmitch/turnstile | turnstile/compactor.py | get_int | def get_int(config, key, default):
"""
A helper to retrieve an integer value from a given dictionary
containing string values. If the requested value is not present
in the dictionary, or if it cannot be converted to an integer, a
default value will be returned instead.
:param config: The dicti... | python | def get_int(config, key, default):
"""
A helper to retrieve an integer value from a given dictionary
containing string values. If the requested value is not present
in the dictionary, or if it cannot be converted to an integer, a
default value will be returned instead.
:param config: The dicti... | [
"def",
"get_int",
"(",
"config",
",",
"key",
",",
"default",
")",
":",
"try",
":",
"return",
"int",
"(",
"config",
"[",
"key",
"]",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"return",
"default"
] | A helper to retrieve an integer value from a given dictionary
containing string values. If the requested value is not present
in the dictionary, or if it cannot be converted to an integer, a
default value will be returned instead.
:param config: The dictionary containing the desired value.
:param ... | [
"A",
"helper",
"to",
"retrieve",
"an",
"integer",
"value",
"from",
"a",
"given",
"dictionary",
"containing",
"string",
"values",
".",
"If",
"the",
"requested",
"value",
"is",
"not",
"present",
"in",
"the",
"dictionary",
"or",
"if",
"it",
"cannot",
"be",
"c... | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L64-L83 | train |
klmitch/turnstile | turnstile/compactor.py | compact_bucket | def compact_bucket(db, buck_key, limit):
"""
Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A database handle for... | python | def compact_bucket(db, buck_key, limit):
"""
Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A database handle for... | [
"def",
"compact_bucket",
"(",
"db",
",",
"buck_key",
",",
"limit",
")",
":",
"records",
"=",
"db",
".",
"lrange",
"(",
"str",
"(",
"buck_key",
")",
",",
"0",
",",
"-",
"1",
")",
"loader",
"=",
"limits",
".",
"BucketLoader",
"(",
"limit",
".",
"buck... | Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A database handle for the Redis database.
:param buck_key: A turnstile... | [
"Perform",
"the",
"compaction",
"operation",
".",
"This",
"reads",
"in",
"the",
"bucket",
"information",
"from",
"the",
"database",
"builds",
"a",
"compacted",
"bucket",
"record",
"inserts",
"that",
"record",
"in",
"the",
"appropriate",
"place",
"in",
"the",
"... | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L379-L415 | train |
klmitch/turnstile | turnstile/compactor.py | compactor | def compactor(conf):
"""
The compactor daemon. This fuction watches the sorted set
containing bucket keys that need to be compacted, performing the
necessary compaction.
:param conf: A turnstile.config.Config instance containing the
configuration for the compactor daemon. Note th... | python | def compactor(conf):
"""
The compactor daemon. This fuction watches the sorted set
containing bucket keys that need to be compacted, performing the
necessary compaction.
:param conf: A turnstile.config.Config instance containing the
configuration for the compactor daemon. Note th... | [
"def",
"compactor",
"(",
"conf",
")",
":",
"db",
"=",
"conf",
".",
"get_database",
"(",
"'compactor'",
")",
"limit_map",
"=",
"LimitContainer",
"(",
"conf",
",",
"db",
")",
"config",
"=",
"conf",
"[",
"'compactor'",
"]",
"if",
"get_int",
"(",
"config",
... | The compactor daemon. This fuction watches the sorted set
containing bucket keys that need to be compacted, performing the
necessary compaction.
:param conf: A turnstile.config.Config instance containing the
configuration for the compactor daemon. Note that a
ControlDaem... | [
"The",
"compactor",
"daemon",
".",
"This",
"fuction",
"watches",
"the",
"sorted",
"set",
"containing",
"bucket",
"keys",
"that",
"need",
"to",
"be",
"compacted",
"performing",
"the",
"necessary",
"compaction",
"."
] | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L418-L485 | train |
klmitch/turnstile | turnstile/compactor.py | GetBucketKey.factory | def factory(cls, config, db):
"""
Given a configuration and database, select and return an
appropriate instance of a subclass of GetBucketKey. This will
ensure that both client and server support are available for
the Lua script feature of Redis, and if not, a lock will be
... | python | def factory(cls, config, db):
"""
Given a configuration and database, select and return an
appropriate instance of a subclass of GetBucketKey. This will
ensure that both client and server support are available for
the Lua script feature of Redis, and if not, a lock will be
... | [
"def",
"factory",
"(",
"cls",
",",
"config",
",",
"db",
")",
":",
"if",
"not",
"hasattr",
"(",
"db",
",",
"'register_script'",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Redis client does not support register_script()\"",
")",
"return",
"GetBucketKeyByLock",
"(",
... | Given a configuration and database, select and return an
appropriate instance of a subclass of GetBucketKey. This will
ensure that both client and server support are available for
the Lua script feature of Redis, and if not, a lock will be
used.
:param config: A dictionary of c... | [
"Given",
"a",
"configuration",
"and",
"database",
"select",
"and",
"return",
"an",
"appropriate",
"instance",
"of",
"a",
"subclass",
"of",
"GetBucketKey",
".",
"This",
"will",
"ensure",
"that",
"both",
"client",
"and",
"server",
"support",
"are",
"available",
... | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L99-L128 | train |
klmitch/turnstile | turnstile/compactor.py | GetBucketKeyByLock.get | def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a configured lock to ensure that the bucket
key is popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
... | python | def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a configured lock to ensure that the bucket
key is popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
... | [
"def",
"get",
"(",
"self",
",",
"now",
")",
":",
"with",
"self",
".",
"lock",
":",
"items",
"=",
"self",
".",
"db",
".",
"zrangebyscore",
"(",
"self",
".",
"key",
",",
"0",
",",
"now",
"-",
"self",
".",
"min_age",
",",
"start",
"=",
"0",
",",
... | Get a bucket key to compact. If none are available, returns
None. This uses a configured lock to ensure that the bucket
key is popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
bucket key has been aged sufficientl... | [
"Get",
"a",
"bucket",
"key",
"to",
"compact",
".",
"If",
"none",
"are",
"available",
"returns",
"None",
".",
"This",
"uses",
"a",
"configured",
"lock",
"to",
"ensure",
"that",
"the",
"bucket",
"key",
"is",
"popped",
"off",
"the",
"sorted",
"set",
"in",
... | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L210-L236 | train |
klmitch/turnstile | turnstile/compactor.py | GetBucketKeyByScript.get | def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
b... | python | def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
b... | [
"def",
"get",
"(",
"self",
",",
"now",
")",
":",
"items",
"=",
"self",
".",
"script",
"(",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
",",
"args",
"=",
"[",
"now",
"-",
"self",
".",
"min_age",
"]",
")",
"return",
"items",
"[",
"0",
"]",
"if",... | Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
bucket key has been aged sufficiently to ... | [
"Get",
"a",
"bucket",
"key",
"to",
"compact",
".",
"If",
"none",
"are",
"available",
"returns",
"None",
".",
"This",
"uses",
"a",
"Lua",
"script",
"to",
"ensure",
"that",
"the",
"bucket",
"key",
"is",
"popped",
"off",
"the",
"sorted",
"set",
"in",
"an"... | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/compactor.py#L265-L281 | train |
frostming/marko | marko/inline_parser.py | parse | def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched.
"""
# this is a raw list of ele... | python | def parse(text, elements, fallback):
"""Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched.
"""
# this is a raw list of ele... | [
"def",
"parse",
"(",
"text",
",",
"elements",
",",
"fallback",
")",
":",
"tokens",
"=",
"[",
"]",
"for",
"etype",
"in",
"elements",
":",
"for",
"match",
"in",
"etype",
".",
"find",
"(",
"text",
")",
":",
"tokens",
".",
"append",
"(",
"Token",
"(",
... | Parse given text and produce a list of inline elements.
:param text: the text to be parsed.
:param elements: the element types to be included in parsing
:param fallback: fallback class when no other element type is matched. | [
"Parse",
"given",
"text",
"and",
"produce",
"a",
"list",
"of",
"inline",
"elements",
"."
] | 1cd030b665fa37bad1f8b3a25a89ce1a7c491dde | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L12-L26 | train |
frostming/marko | marko/inline_parser.py | make_elements | def make_elements(tokens, text, start=0, end=None, fallback=None):
"""Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Default... | python | def make_elements(tokens, text, start=0, end=None, fallback=None):
"""Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Default... | [
"def",
"make_elements",
"(",
"tokens",
",",
"text",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
",",
"fallback",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"end",
"=",
"end",
"or",
"len",
"(",
"text",
")",
"prev_end",
"=",
"start",
"for... | Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Defaults to the start of text.
:param end: the offset of where parsing ends. ... | [
"Make",
"elements",
"from",
"a",
"list",
"of",
"parsed",
"tokens",
".",
"It",
"will",
"turn",
"all",
"unmatched",
"holes",
"into",
"fallback",
"elements",
"."
] | 1cd030b665fa37bad1f8b3a25a89ce1a7c491dde | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline_parser.py#L47-L68 | train |
azogue/i2csense | i2csense/__main__.py | main_cli | def main_cli():
"""CLI minimal interface."""
# Get params
args = _cli_argument_parser()
delta_secs = args.delay
i2cbus = args.bus
i2c_address = args.address
sensor_key = args.sensor
sensor_params = args.params
params = {}
if sensor_params:
def _parse_param(str_param):
... | python | def main_cli():
"""CLI minimal interface."""
# Get params
args = _cli_argument_parser()
delta_secs = args.delay
i2cbus = args.bus
i2c_address = args.address
sensor_key = args.sensor
sensor_params = args.params
params = {}
if sensor_params:
def _parse_param(str_param):
... | [
"def",
"main_cli",
"(",
")",
":",
"args",
"=",
"_cli_argument_parser",
"(",
")",
"delta_secs",
"=",
"args",
".",
"delay",
"i2cbus",
"=",
"args",
".",
"bus",
"i2c_address",
"=",
"args",
".",
"address",
"sensor_key",
"=",
"args",
".",
"sensor",
"sensor_param... | CLI minimal interface. | [
"CLI",
"minimal",
"interface",
"."
] | ecc6806dcee9de827a5414a9e836d271fedca9b9 | https://github.com/azogue/i2csense/blob/ecc6806dcee9de827a5414a9e836d271fedca9b9/i2csense/__main__.py#L60-L139 | train |
BernardFW/bernard | examples/number_bot/src/number_bot/settings.py | extract_domain | def extract_domain(var_name, output):
"""
Extracts just the domain name from an URL and adds it to a list
"""
var = getenv(var_name)
if var:
p = urlparse(var)
output.append(p.hostname) | python | def extract_domain(var_name, output):
"""
Extracts just the domain name from an URL and adds it to a list
"""
var = getenv(var_name)
if var:
p = urlparse(var)
output.append(p.hostname) | [
"def",
"extract_domain",
"(",
"var_name",
",",
"output",
")",
":",
"var",
"=",
"getenv",
"(",
"var_name",
")",
"if",
"var",
":",
"p",
"=",
"urlparse",
"(",
"var",
")",
"output",
".",
"append",
"(",
"p",
".",
"hostname",
")"
] | Extracts just the domain name from an URL and adds it to a list | [
"Extracts",
"just",
"the",
"domain",
"name",
"from",
"an",
"URL",
"and",
"adds",
"it",
"to",
"a",
"list"
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/examples/number_bot/src/number_bot/settings.py#L11-L20 | train |
gesellkammer/sndfileio | sndfileio/util.py | numchannels | def numchannels(samples:np.ndarray) -> int:
"""
return the number of channels present in samples
samples: a numpy array as returned by sndread
for multichannel audio, samples is always interleaved,
meaning that samples[n] returns always a frame, which
is either a single scalar for mono audio, ... | python | def numchannels(samples:np.ndarray) -> int:
"""
return the number of channels present in samples
samples: a numpy array as returned by sndread
for multichannel audio, samples is always interleaved,
meaning that samples[n] returns always a frame, which
is either a single scalar for mono audio, ... | [
"def",
"numchannels",
"(",
"samples",
":",
"np",
".",
"ndarray",
")",
"->",
"int",
":",
"if",
"len",
"(",
"samples",
".",
"shape",
")",
"==",
"1",
":",
"return",
"1",
"else",
":",
"return",
"samples",
".",
"shape",
"[",
"1",
"]"
] | return the number of channels present in samples
samples: a numpy array as returned by sndread
for multichannel audio, samples is always interleaved,
meaning that samples[n] returns always a frame, which
is either a single scalar for mono audio, or an array
for multichannel audio. | [
"return",
"the",
"number",
"of",
"channels",
"present",
"in",
"samples"
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/util.py#L5-L19 | train |
klmitch/turnstile | turnstile/middleware.py | turnstile_filter | def turnstile_filter(global_conf, **local_conf):
"""
Factory function for turnstile.
Returns a function which, when passed the application, returns an
instance of the TurnstileMiddleware.
"""
# Select the appropriate middleware class to return
klass = TurnstileMiddleware
if 'turnstile'... | python | def turnstile_filter(global_conf, **local_conf):
"""
Factory function for turnstile.
Returns a function which, when passed the application, returns an
instance of the TurnstileMiddleware.
"""
# Select the appropriate middleware class to return
klass = TurnstileMiddleware
if 'turnstile'... | [
"def",
"turnstile_filter",
"(",
"global_conf",
",",
"**",
"local_conf",
")",
":",
"klass",
"=",
"TurnstileMiddleware",
"if",
"'turnstile'",
"in",
"local_conf",
":",
"klass",
"=",
"utils",
".",
"find_entrypoint",
"(",
"'turnstile.middleware'",
",",
"local_conf",
"[... | Factory function for turnstile.
Returns a function which, when passed the application, returns an
instance of the TurnstileMiddleware. | [
"Factory",
"function",
"for",
"turnstile",
"."
] | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/middleware.py#L133-L150 | train |
klmitch/turnstile | turnstile/middleware.py | TurnstileMiddleware.format_delay | def format_delay(self, delay, limit, bucket, environ, start_response):
"""
Formats the over-limit response for the request. May be
overridden in subclasses to allow alternate responses.
"""
# Set up the default status
status = self.conf.status
# Set up the retr... | python | def format_delay(self, delay, limit, bucket, environ, start_response):
"""
Formats the over-limit response for the request. May be
overridden in subclasses to allow alternate responses.
"""
# Set up the default status
status = self.conf.status
# Set up the retr... | [
"def",
"format_delay",
"(",
"self",
",",
"delay",
",",
"limit",
",",
"bucket",
",",
"environ",
",",
"start_response",
")",
":",
"status",
"=",
"self",
".",
"conf",
".",
"status",
"headers",
"=",
"HeadersDict",
"(",
"[",
"(",
"'Retry-After'",
",",
"\"%d\"... | Formats the over-limit response for the request. May be
overridden in subclasses to allow alternate responses. | [
"Formats",
"the",
"over",
"-",
"limit",
"response",
"for",
"the",
"request",
".",
"May",
"be",
"overridden",
"in",
"subclasses",
"to",
"allow",
"alternate",
"responses",
"."
] | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/middleware.py#L337-L355 | train |
klmitch/turnstile | turnstile/utils.py | find_entrypoint | def find_entrypoint(group, name, compat=True, required=False):
"""
Finds the first available entrypoint with the given name in the
given group.
:param group: The entrypoint group the name can be found in. If
None, the name is not presumed to be an entrypoint.
:param name: The nam... | python | def find_entrypoint(group, name, compat=True, required=False):
"""
Finds the first available entrypoint with the given name in the
given group.
:param group: The entrypoint group the name can be found in. If
None, the name is not presumed to be an entrypoint.
:param name: The nam... | [
"def",
"find_entrypoint",
"(",
"group",
",",
"name",
",",
"compat",
"=",
"True",
",",
"required",
"=",
"False",
")",
":",
"if",
"group",
"is",
"None",
"or",
"(",
"compat",
"and",
"':'",
"in",
"name",
")",
":",
"try",
":",
"return",
"pkg_resources",
"... | Finds the first available entrypoint with the given name in the
given group.
:param group: The entrypoint group the name can be found in. If
None, the name is not presumed to be an entrypoint.
:param name: The name of the entrypoint.
:param compat: If True, and if the name parameter ... | [
"Finds",
"the",
"first",
"available",
"entrypoint",
"with",
"the",
"given",
"name",
"in",
"the",
"given",
"group",
"."
] | 8fe9a359b45e505d3192ab193ecf9be177ab1a17 | https://github.com/klmitch/turnstile/blob/8fe9a359b45e505d3192ab193ecf9be177ab1a17/turnstile/utils.py#L21-L60 | train |
COALAIP/pycoalaip | coalaip/entities.py | TransferrableEntity.transfer | def transfer(self, transfer_payload=None, *, from_user, to_user):
"""Transfer this entity to another owner on the backing
persistence layer
Args:
transfer_payload (dict): Payload for the transfer
from_user (any): A user based on the model specified by the
... | python | def transfer(self, transfer_payload=None, *, from_user, to_user):
"""Transfer this entity to another owner on the backing
persistence layer
Args:
transfer_payload (dict): Payload for the transfer
from_user (any): A user based on the model specified by the
... | [
"def",
"transfer",
"(",
"self",
",",
"transfer_payload",
"=",
"None",
",",
"*",
",",
"from_user",
",",
"to_user",
")",
":",
"if",
"self",
".",
"persist_id",
"is",
"None",
":",
"raise",
"EntityNotYetPersistedError",
"(",
"(",
"'Entities cannot be transferred '",
... | Transfer this entity to another owner on the backing
persistence layer
Args:
transfer_payload (dict): Payload for the transfer
from_user (any): A user based on the model specified by the
persistence layer
to_user (any): A user based on the model speci... | [
"Transfer",
"this",
"entity",
"to",
"another",
"owner",
"on",
"the",
"backing",
"persistence",
"layer"
] | cecc8f6ff4733f0525fafcee63647753e832f0be | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/entities.py#L409-L442 | train |
COALAIP/pycoalaip | coalaip/entities.py | Right.transfer | def transfer(self, rights_assignment_data=None, *, from_user, to_user,
rights_assignment_format='jsonld'):
"""Transfer this Right to another owner on the backing
persistence layer.
Args:
rights_assignment_data (dict): Model data for the resulting
:cl... | python | def transfer(self, rights_assignment_data=None, *, from_user, to_user,
rights_assignment_format='jsonld'):
"""Transfer this Right to another owner on the backing
persistence layer.
Args:
rights_assignment_data (dict): Model data for the resulting
:cl... | [
"def",
"transfer",
"(",
"self",
",",
"rights_assignment_data",
"=",
"None",
",",
"*",
",",
"from_user",
",",
"to_user",
",",
"rights_assignment_format",
"=",
"'jsonld'",
")",
":",
"rights_assignment",
"=",
"RightsAssignment",
".",
"from_data",
"(",
"rights_assignm... | Transfer this Right to another owner on the backing
persistence layer.
Args:
rights_assignment_data (dict): Model data for the resulting
:class:`~.RightsAssignment`
from_user (any, keyword): A user based on the model specified
by the persistence l... | [
"Transfer",
"this",
"Right",
"to",
"another",
"owner",
"on",
"the",
"backing",
"persistence",
"layer",
"."
] | cecc8f6ff4733f0525fafcee63647753e832f0be | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/entities.py#L506-L542 | train |
rsgalloway/grit | grit/repo/base.py | Repo._set_repo | def _set_repo(self, url):
"""sets the underlying repo object"""
if url.startswith('http'):
try:
self.repo = Proxy(url)
except ProxyError, e:
log.exception('Error setting repo: %s' % url)
raise GritError(e)
else:
... | python | def _set_repo(self, url):
"""sets the underlying repo object"""
if url.startswith('http'):
try:
self.repo = Proxy(url)
except ProxyError, e:
log.exception('Error setting repo: %s' % url)
raise GritError(e)
else:
... | [
"def",
"_set_repo",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
".",
"startswith",
"(",
"'http'",
")",
":",
"try",
":",
"self",
".",
"repo",
"=",
"Proxy",
"(",
"url",
")",
"except",
"ProxyError",
",",
"e",
":",
"log",
".",
"exception",
"(",
"... | sets the underlying repo object | [
"sets",
"the",
"underlying",
"repo",
"object"
] | e6434ad8a1f4ac5d0903ebad630c81f8a5164d78 | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/base.py#L73-L88 | train |
rsgalloway/grit | grit/repo/base.py | Repo.new | def new(self, url, clone_from=None, bare=True):
"""
Creates a new Repo instance.
:param url: Path or remote URL of new repo.
:param clone_from: Path or URL of repo to clone from.
:param bare: Create as bare repo.
:returns: grit.Repo instance.
For example:
... | python | def new(self, url, clone_from=None, bare=True):
"""
Creates a new Repo instance.
:param url: Path or remote URL of new repo.
:param clone_from: Path or URL of repo to clone from.
:param bare: Create as bare repo.
:returns: grit.Repo instance.
For example:
... | [
"def",
"new",
"(",
"self",
",",
"url",
",",
"clone_from",
"=",
"None",
",",
"bare",
"=",
"True",
")",
":",
"if",
"clone_from",
":",
"self",
".",
"clone",
"(",
"path",
"=",
"url",
",",
"bare",
"=",
"bare",
")",
"else",
":",
"if",
"url",
".",
"st... | Creates a new Repo instance.
:param url: Path or remote URL of new repo.
:param clone_from: Path or URL of repo to clone from.
:param bare: Create as bare repo.
:returns: grit.Repo instance.
For example:
>>> r = Repo.new('/tmp/projects')
>>> r
... | [
"Creates",
"a",
"new",
"Repo",
"instance",
"."
] | e6434ad8a1f4ac5d0903ebad630c81f8a5164d78 | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/repo/base.py#L91-L117 | train |
xypnox/email_purifier | epurifier/email_checker.py | EmailPurifier.CheckEmails | def CheckEmails(self, checkTypo=False, fillWrong=True):
'''Checks Emails in List Wether they are Correct or not'''
self.wrong_emails = []
for email in self.emails:
if self.CheckEmail(email, checkTypo) is False:
self.wrong_emails.append(email) | python | def CheckEmails(self, checkTypo=False, fillWrong=True):
'''Checks Emails in List Wether they are Correct or not'''
self.wrong_emails = []
for email in self.emails:
if self.CheckEmail(email, checkTypo) is False:
self.wrong_emails.append(email) | [
"def",
"CheckEmails",
"(",
"self",
",",
"checkTypo",
"=",
"False",
",",
"fillWrong",
"=",
"True",
")",
":",
"self",
".",
"wrong_emails",
"=",
"[",
"]",
"for",
"email",
"in",
"self",
".",
"emails",
":",
"if",
"self",
".",
"CheckEmail",
"(",
"email",
"... | Checks Emails in List Wether they are Correct or not | [
"Checks",
"Emails",
"in",
"List",
"Wether",
"they",
"are",
"Correct",
"or",
"not"
] | a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L31-L36 | train |
xypnox/email_purifier | epurifier/email_checker.py | EmailPurifier.CheckEmail | def CheckEmail(self, email, checkTypo=False):
'''Checks a Single email if it is correct'''
contents = email.split('@')
if len(contents) == 2:
if contents[1] in self.valid:
return True
return False | python | def CheckEmail(self, email, checkTypo=False):
'''Checks a Single email if it is correct'''
contents = email.split('@')
if len(contents) == 2:
if contents[1] in self.valid:
return True
return False | [
"def",
"CheckEmail",
"(",
"self",
",",
"email",
",",
"checkTypo",
"=",
"False",
")",
":",
"contents",
"=",
"email",
".",
"split",
"(",
"'@'",
")",
"if",
"len",
"(",
"contents",
")",
"==",
"2",
":",
"if",
"contents",
"[",
"1",
"]",
"in",
"self",
"... | Checks a Single email if it is correct | [
"Checks",
"a",
"Single",
"email",
"if",
"it",
"is",
"correct"
] | a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L38-L44 | train |
xypnox/email_purifier | epurifier/email_checker.py | EmailPurifier.CorrectWrongEmails | def CorrectWrongEmails(self, askInput=True):
'''Corrects Emails in wrong_emails'''
for email in self.wrong_emails:
corrected_email = self.CorrectEmail(email)
self.emails[self.emails.index(email)] = corrected_email
self.wrong_emails = [] | python | def CorrectWrongEmails(self, askInput=True):
'''Corrects Emails in wrong_emails'''
for email in self.wrong_emails:
corrected_email = self.CorrectEmail(email)
self.emails[self.emails.index(email)] = corrected_email
self.wrong_emails = [] | [
"def",
"CorrectWrongEmails",
"(",
"self",
",",
"askInput",
"=",
"True",
")",
":",
"for",
"email",
"in",
"self",
".",
"wrong_emails",
":",
"corrected_email",
"=",
"self",
".",
"CorrectEmail",
"(",
"email",
")",
"self",
".",
"emails",
"[",
"self",
".",
"em... | Corrects Emails in wrong_emails | [
"Corrects",
"Emails",
"in",
"wrong_emails"
] | a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L46-L52 | train |
xypnox/email_purifier | epurifier/email_checker.py | EmailPurifier.CorrectEmail | def CorrectEmail(self, email):
'''Returns a Corrected email USER INPUT REQUIRED'''
print("Wrong Email : "+email)
contents = email.split('@')
if len(contents) == 2:
domain_data = contents[1].split('.')
for vemail in self.valid:
alters = perms(vemai... | python | def CorrectEmail(self, email):
'''Returns a Corrected email USER INPUT REQUIRED'''
print("Wrong Email : "+email)
contents = email.split('@')
if len(contents) == 2:
domain_data = contents[1].split('.')
for vemail in self.valid:
alters = perms(vemai... | [
"def",
"CorrectEmail",
"(",
"self",
",",
"email",
")",
":",
"print",
"(",
"\"Wrong Email : \"",
"+",
"email",
")",
"contents",
"=",
"email",
".",
"split",
"(",
"'@'",
")",
"if",
"len",
"(",
"contents",
")",
"==",
"2",
":",
"domain_data",
"=",
"contents... | Returns a Corrected email USER INPUT REQUIRED | [
"Returns",
"a",
"Corrected",
"email",
"USER",
"INPUT",
"REQUIRED"
] | a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f | https://github.com/xypnox/email_purifier/blob/a9ecde9c5293b5c283e0c5b4cf8744c76418fb6f/epurifier/email_checker.py#L54-L80 | train |
frostming/marko | marko/parser.py | Parser.add_element | def add_element(self, element, override=False):
"""Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__i... | python | def add_element(self, element, override=False):
"""Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__i... | [
"def",
"add_element",
"(",
"self",
",",
"element",
",",
"override",
"=",
"False",
")",
":",
"if",
"issubclass",
"(",
"element",
",",
"inline",
".",
"InlineElement",
")",
":",
"dest",
"=",
"self",
".",
"inline_elements",
"elif",
"issubclass",
"(",
"element"... | Add an element to the parser.
:param element: the element class.
:param override: whether to replace the default element based on.
.. note:: If one needs to call it inside ``__init__()``, please call it after
``super().__init__()`` is called. | [
"Add",
"an",
"element",
"to",
"the",
"parser",
"."
] | 1cd030b665fa37bad1f8b3a25a89ce1a7c491dde | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L37-L63 | train |
frostming/marko | marko/parser.py | Parser.parse | def parse(self, source_or_text):
"""Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and retu... | python | def parse(self, source_or_text):
"""Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and retu... | [
"def",
"parse",
"(",
"self",
",",
"source_or_text",
")",
":",
"if",
"isinstance",
"(",
"source_or_text",
",",
"string_types",
")",
":",
"block",
".",
"parser",
"=",
"self",
"inline",
".",
"parser",
"=",
"self",
"return",
"self",
".",
"block_elements",
"[",... | Do the actual parsing and returns an AST or parsed element.
:param source_or_text: the text or source object.
Based on the type, it will do following:
- text: returns the parsed Document element.
- source: parse the source and returns the parsed children as a list. | [
"Do",
"the",
"actual",
"parsing",
"and",
"returns",
"an",
"AST",
"or",
"parsed",
"element",
"."
] | 1cd030b665fa37bad1f8b3a25a89ce1a7c491dde | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L65-L90 | train |
frostming/marko | marko/parser.py | Parser.parse_inline | def parse_inline(self, text):
"""Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements.
"""
element_lis... | python | def parse_inline(self, text):
"""Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements.
"""
element_lis... | [
"def",
"parse_inline",
"(",
"self",
",",
"text",
")",
":",
"element_list",
"=",
"self",
".",
"_build_inline_element_list",
"(",
")",
"return",
"inline_parser",
".",
"parse",
"(",
"text",
",",
"element_list",
",",
"fallback",
"=",
"self",
".",
"inline_elements"... | Parses text into inline elements.
RawText is not considered in parsing but created as a wrapper of holes
that don't match any other elements.
:param text: the text to be parsed.
:returns: a list of inline elements. | [
"Parses",
"text",
"into",
"inline",
"elements",
".",
"RawText",
"is",
"not",
"considered",
"in",
"parsing",
"but",
"created",
"as",
"a",
"wrapper",
"of",
"holes",
"that",
"don",
"t",
"match",
"any",
"other",
"elements",
"."
] | 1cd030b665fa37bad1f8b3a25a89ce1a7c491dde | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L92-L103 | train |
frostming/marko | marko/parser.py | Parser._build_block_element_list | def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
) | python | def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
) | [
"def",
"_build_block_element_list",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"[",
"e",
"for",
"e",
"in",
"self",
".",
"block_elements",
".",
"values",
"(",
")",
"if",
"not",
"e",
".",
"virtual",
"]",
",",
"key",
"=",
"lambda",
"e",
":",
"e",
... | Return a list of block elements, ordered from highest priority to lowest. | [
"Return",
"a",
"list",
"of",
"block",
"elements",
"ordered",
"from",
"highest",
"priority",
"to",
"lowest",
"."
] | 1cd030b665fa37bad1f8b3a25a89ce1a7c491dde | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/parser.py#L105-L112 | train |
rsgalloway/grit | grit/server/server.py | make_app | def make_app(*args, **kw):
'''
Assembles basic WSGI-compatible application providing functionality of git-http-backend.
content_path (Defaults to '.' = "current" directory)
The path to the folder that will be the root of served files. Accepts relative paths.
uri_marker (Defaults to '')
... | python | def make_app(*args, **kw):
'''
Assembles basic WSGI-compatible application providing functionality of git-http-backend.
content_path (Defaults to '.' = "current" directory)
The path to the folder that will be the root of served files. Accepts relative paths.
uri_marker (Defaults to '')
... | [
"def",
"make_app",
"(",
"*",
"args",
",",
"**",
"kw",
")",
":",
"default_options",
"=",
"[",
"[",
"'content_path'",
",",
"'.'",
"]",
",",
"[",
"'uri_marker'",
",",
"''",
"]",
"]",
"args",
"=",
"list",
"(",
"args",
")",
"options",
"=",
"dict",
"(",
... | Assembles basic WSGI-compatible application providing functionality of git-http-backend.
content_path (Defaults to '.' = "current" directory)
The path to the folder that will be the root of served files. Accepts relative paths.
uri_marker (Defaults to '')
Acts as a "virtual folder" separator b... | [
"Assembles",
"basic",
"WSGI",
"-",
"compatible",
"application",
"providing",
"functionality",
"of",
"git",
"-",
"http",
"-",
"backend",
"."
] | e6434ad8a1f4ac5d0903ebad630c81f8a5164d78 | https://github.com/rsgalloway/grit/blob/e6434ad8a1f4ac5d0903ebad630c81f8a5164d78/grit/server/server.py#L41-L116 | train |
polyaxon/hestia | hestia/tz_utils.py | now | def now(tzinfo=True):
"""
Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if dj_now:
return dj_now()
if tzinfo:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
return datetime.now() | python | def now(tzinfo=True):
"""
Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if dj_now:
return dj_now()
if tzinfo:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
return datetime.now() | [
"def",
"now",
"(",
"tzinfo",
"=",
"True",
")",
":",
"if",
"dj_now",
":",
"return",
"dj_now",
"(",
")",
"if",
"tzinfo",
":",
"return",
"datetime",
".",
"utcnow",
"(",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"utc",
")",
"return",
"datetime",
".",
"n... | Return an aware or naive datetime.datetime, depending on settings.USE_TZ. | [
"Return",
"an",
"aware",
"or",
"naive",
"datetime",
".",
"datetime",
"depending",
"on",
"settings",
".",
"USE_TZ",
"."
] | 382ed139cff8bf35c987cfc30a31b72c0d6b808e | https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/tz_utils.py#L21-L31 | train |
inveniosoftware/invenio-query-parser | invenio_query_parser/walkers/match_unit.py | match_unit | def match_unit(data, p, m='a'):
"""Match data to basic match unit."""
if data is None:
return p is None
# compile search value only once for non exact search
if m != 'e' and isinstance(p, six.string_types):
p = re.compile(p)
if isinstance(data, Sequence) and not isinstance(data, si... | python | def match_unit(data, p, m='a'):
"""Match data to basic match unit."""
if data is None:
return p is None
# compile search value only once for non exact search
if m != 'e' and isinstance(p, six.string_types):
p = re.compile(p)
if isinstance(data, Sequence) and not isinstance(data, si... | [
"def",
"match_unit",
"(",
"data",
",",
"p",
",",
"m",
"=",
"'a'",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"p",
"is",
"None",
"if",
"m",
"!=",
"'e'",
"and",
"isinstance",
"(",
"p",
",",
"six",
".",
"string_types",
")",
":",
"p",
"="... | Match data to basic match unit. | [
"Match",
"data",
"to",
"basic",
"match",
"unit",
"."
] | 21a2c36318003ff52d2e18e7196bb420db8ecb4b | https://github.com/inveniosoftware/invenio-query-parser/blob/21a2c36318003ff52d2e18e7196bb420db8ecb4b/invenio_query_parser/walkers/match_unit.py#L57-L80 | train |
GuiltyTargets/ppi-network-annotation | src/ppi_network_annotation/pipeline.py | generate_ppi_network | def generate_ppi_network(
ppi_graph_path: str,
dge_list: List[Gene],
max_adj_p: float,
max_log2_fold_change: float,
min_log2_fold_change: float,
ppi_edge_min_confidence: Optional[float] = None,
current_disease_ids_path: Optional[str] = None,
disease_associ... | python | def generate_ppi_network(
ppi_graph_path: str,
dge_list: List[Gene],
max_adj_p: float,
max_log2_fold_change: float,
min_log2_fold_change: float,
ppi_edge_min_confidence: Optional[float] = None,
current_disease_ids_path: Optional[str] = None,
disease_associ... | [
"def",
"generate_ppi_network",
"(",
"ppi_graph_path",
":",
"str",
",",
"dge_list",
":",
"List",
"[",
"Gene",
"]",
",",
"max_adj_p",
":",
"float",
",",
"max_log2_fold_change",
":",
"float",
",",
"min_log2_fold_change",
":",
"float",
",",
"ppi_edge_min_confidence",
... | Generate the protein-protein interaction network.
:return Network: Protein-protein interaction network with information on differential expression. | [
"Generate",
"the",
"protein",
"-",
"protein",
"interaction",
"network",
"."
] | 4d7b6713485f2d0a0957e6457edc1b1b5a237460 | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/pipeline.py#L20-L54 | train |
GuiltyTargets/ppi-network-annotation | src/ppi_network_annotation/pipeline.py | parse_dge | def parse_dge(
dge_path: str,
entrez_id_header: str,
log2_fold_change_header: str,
adj_p_header: str,
entrez_delimiter: str,
base_mean_header: Optional[str] = None
) -> List[Gene]:
"""Parse a differential expression file.
:param dge_path: Path to the file.
:p... | python | def parse_dge(
dge_path: str,
entrez_id_header: str,
log2_fold_change_header: str,
adj_p_header: str,
entrez_delimiter: str,
base_mean_header: Optional[str] = None
) -> List[Gene]:
"""Parse a differential expression file.
:param dge_path: Path to the file.
:p... | [
"def",
"parse_dge",
"(",
"dge_path",
":",
"str",
",",
"entrez_id_header",
":",
"str",
",",
"log2_fold_change_header",
":",
"str",
",",
"adj_p_header",
":",
"str",
",",
"entrez_delimiter",
":",
"str",
",",
"base_mean_header",
":",
"Optional",
"[",
"str",
"]",
... | Parse a differential expression file.
:param dge_path: Path to the file.
:param entrez_id_header: Header for the Entrez identifier column
:param log2_fold_change_header: Header for the log2 fold change column
:param adj_p_header: Header for the adjusted p-value column
:param entrez_delimiter: Delim... | [
"Parse",
"a",
"differential",
"expression",
"file",
"."
] | 4d7b6713485f2d0a0957e6457edc1b1b5a237460 | https://github.com/GuiltyTargets/ppi-network-annotation/blob/4d7b6713485f2d0a0957e6457edc1b1b5a237460/src/ppi_network_annotation/pipeline.py#L57-L106 | train |
BernardFW/bernard | src/bernard/conf/loader.py | Settings._load | def _load(self, file_path: Text) -> None:
"""
Load the configuration from a plain Python file. This file is executed
on its own.
Only keys matching the CONFIG_ATTR will be loaded. Basically, it's
CONFIG_KEYS_LIKE_THIS.
:param file_path: Path to the file to load
... | python | def _load(self, file_path: Text) -> None:
"""
Load the configuration from a plain Python file. This file is executed
on its own.
Only keys matching the CONFIG_ATTR will be loaded. Basically, it's
CONFIG_KEYS_LIKE_THIS.
:param file_path: Path to the file to load
... | [
"def",
"_load",
"(",
"self",
",",
"file_path",
":",
"Text",
")",
"->",
"None",
":",
"module_",
"=",
"types",
".",
"ModuleType",
"(",
"'settings'",
")",
"module_",
".",
"__file__",
"=",
"file_path",
"try",
":",
"with",
"open",
"(",
"file_path",
",",
"en... | Load the configuration from a plain Python file. This file is executed
on its own.
Only keys matching the CONFIG_ATTR will be loaded. Basically, it's
CONFIG_KEYS_LIKE_THIS.
:param file_path: Path to the file to load | [
"Load",
"the",
"configuration",
"from",
"a",
"plain",
"Python",
"file",
".",
"This",
"file",
"is",
"executed",
"on",
"its",
"own",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/conf/loader.py#L38-L63 | train |
BernardFW/bernard | src/bernard/conf/loader.py | LazySettings._settings | def _settings(self) -> Settings:
"""
Return the actual settings object, or create it if missing.
"""
if self.__dict__['__settings'] is None:
self.__dict__['__settings'] = Settings()
for file_path in self._get_files():
if file_path:
... | python | def _settings(self) -> Settings:
"""
Return the actual settings object, or create it if missing.
"""
if self.__dict__['__settings'] is None:
self.__dict__['__settings'] = Settings()
for file_path in self._get_files():
if file_path:
... | [
"def",
"_settings",
"(",
"self",
")",
"->",
"Settings",
":",
"if",
"self",
".",
"__dict__",
"[",
"'__settings'",
"]",
"is",
"None",
":",
"self",
".",
"__dict__",
"[",
"'__settings'",
"]",
"=",
"Settings",
"(",
")",
"for",
"file_path",
"in",
"self",
"."... | Return the actual settings object, or create it if missing. | [
"Return",
"the",
"actual",
"settings",
"object",
"or",
"create",
"it",
"if",
"missing",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/conf/loader.py#L84-L94 | train |
BernardFW/bernard | src/bernard/storage/register/redis.py | RedisRegisterStore._start | async def _start(self, key: Text) -> None:
"""
Start the lock.
Here we use a SETNX-based algorithm. It's quite shitty, change it.
"""
for _ in range(0, 1000):
with await self.pool as r:
just_set = await r.set(
self.lock_key(key),
... | python | async def _start(self, key: Text) -> None:
"""
Start the lock.
Here we use a SETNX-based algorithm. It's quite shitty, change it.
"""
for _ in range(0, 1000):
with await self.pool as r:
just_set = await r.set(
self.lock_key(key),
... | [
"async",
"def",
"_start",
"(",
"self",
",",
"key",
":",
"Text",
")",
"->",
"None",
":",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"1000",
")",
":",
"with",
"await",
"self",
".",
"pool",
"as",
"r",
":",
"just_set",
"=",
"await",
"r",
".",
"set",... | Start the lock.
Here we use a SETNX-based algorithm. It's quite shitty, change it. | [
"Start",
"the",
"lock",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L42-L60 | train |
BernardFW/bernard | src/bernard/storage/register/redis.py | RedisRegisterStore._get | async def _get(self, key: Text) -> Dict[Text, Any]:
"""
Get the value for the key. It is automatically deserialized from JSON
and returns an empty dictionary by default.
"""
try:
with await self.pool as r:
return ujson.loads(await r.get(self.register_... | python | async def _get(self, key: Text) -> Dict[Text, Any]:
"""
Get the value for the key. It is automatically deserialized from JSON
and returns an empty dictionary by default.
"""
try:
with await self.pool as r:
return ujson.loads(await r.get(self.register_... | [
"async",
"def",
"_get",
"(",
"self",
",",
"key",
":",
"Text",
")",
"->",
"Dict",
"[",
"Text",
",",
"Any",
"]",
":",
"try",
":",
"with",
"await",
"self",
".",
"pool",
"as",
"r",
":",
"return",
"ujson",
".",
"loads",
"(",
"await",
"r",
".",
"get"... | Get the value for the key. It is automatically deserialized from JSON
and returns an empty dictionary by default. | [
"Get",
"the",
"value",
"for",
"the",
"key",
".",
"It",
"is",
"automatically",
"deserialized",
"from",
"JSON",
"and",
"returns",
"an",
"empty",
"dictionary",
"by",
"default",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L70-L80 | train |
BernardFW/bernard | src/bernard/storage/register/redis.py | RedisRegisterStore._replace | async def _replace(self, key: Text, data: Dict[Text, Any]) -> None:
"""
Replace the register with a new value.
"""
with await self.pool as r:
await r.set(self.register_key(key), ujson.dumps(data)) | python | async def _replace(self, key: Text, data: Dict[Text, Any]) -> None:
"""
Replace the register with a new value.
"""
with await self.pool as r:
await r.set(self.register_key(key), ujson.dumps(data)) | [
"async",
"def",
"_replace",
"(",
"self",
",",
"key",
":",
"Text",
",",
"data",
":",
"Dict",
"[",
"Text",
",",
"Any",
"]",
")",
"->",
"None",
":",
"with",
"await",
"self",
".",
"pool",
"as",
"r",
":",
"await",
"r",
".",
"set",
"(",
"self",
".",
... | Replace the register with a new value. | [
"Replace",
"the",
"register",
"with",
"a",
"new",
"value",
"."
] | 9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/storage/register/redis.py#L82-L88 | train |
giancosta86/Iris | info/gianlucacosta/iris/maven.py | MavenArtifact.getFileName | def getFileName(self, suffix=None, extension="jar"):
"""
Returns the basename of the artifact's file, using Maven's conventions.
In particular, it will be:
<artifactId>-<version>[-<suffix>][.<extension>]
"""
assert (self._artifactId is not None)
assert (sel... | python | def getFileName(self, suffix=None, extension="jar"):
"""
Returns the basename of the artifact's file, using Maven's conventions.
In particular, it will be:
<artifactId>-<version>[-<suffix>][.<extension>]
"""
assert (self._artifactId is not None)
assert (sel... | [
"def",
"getFileName",
"(",
"self",
",",
"suffix",
"=",
"None",
",",
"extension",
"=",
"\"jar\"",
")",
":",
"assert",
"(",
"self",
".",
"_artifactId",
"is",
"not",
"None",
")",
"assert",
"(",
"self",
".",
"_version",
"is",
"not",
"None",
")",
"return",
... | Returns the basename of the artifact's file, using Maven's conventions.
In particular, it will be:
<artifactId>-<version>[-<suffix>][.<extension>] | [
"Returns",
"the",
"basename",
"of",
"the",
"artifact",
"s",
"file",
"using",
"Maven",
"s",
"conventions",
"."
] | b3d92cca5cce3653519bd032346b211c46a57d05 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/maven.py#L50-L67 | train |
giancosta86/Iris | info/gianlucacosta/iris/maven.py | MavenArtifact.getPath | def getPath(self, suffix=None, extension="jar", separator=os.sep):
"""
Returns the full path, relative to the root of a Maven repository,
of the current artifact, using Maven's conventions.
In particular, it will be:
<groupId with "." replaced by <separator>>[<separator><ar... | python | def getPath(self, suffix=None, extension="jar", separator=os.sep):
"""
Returns the full path, relative to the root of a Maven repository,
of the current artifact, using Maven's conventions.
In particular, it will be:
<groupId with "." replaced by <separator>>[<separator><ar... | [
"def",
"getPath",
"(",
"self",
",",
"suffix",
"=",
"None",
",",
"extension",
"=",
"\"jar\"",
",",
"separator",
"=",
"os",
".",
"sep",
")",
":",
"assert",
"(",
"self",
".",
"_groupId",
"is",
"not",
"None",
")",
"resultComponents",
"=",
"[",
"self",
".... | Returns the full path, relative to the root of a Maven repository,
of the current artifact, using Maven's conventions.
In particular, it will be:
<groupId with "." replaced by <separator>>[<separator><artifactId><separator>[<version><separator><basename obtained via getFileName()>]]
... | [
"Returns",
"the",
"full",
"path",
"relative",
"to",
"the",
"root",
"of",
"a",
"Maven",
"repository",
"of",
"the",
"current",
"artifact",
"using",
"Maven",
"s",
"conventions",
"."
] | b3d92cca5cce3653519bd032346b211c46a57d05 | https://github.com/giancosta86/Iris/blob/b3d92cca5cce3653519bd032346b211c46a57d05/info/gianlucacosta/iris/maven.py#L70-L96 | train |
openvax/varlens | varlens/support.py | allele_support_df | def allele_support_df(loci, sources):
"""
Returns a DataFrame of allele counts for all given loci in the read sources
"""
return pandas.DataFrame(
allele_support_rows(loci, sources),
columns=EXPECTED_COLUMNS) | python | def allele_support_df(loci, sources):
"""
Returns a DataFrame of allele counts for all given loci in the read sources
"""
return pandas.DataFrame(
allele_support_rows(loci, sources),
columns=EXPECTED_COLUMNS) | [
"def",
"allele_support_df",
"(",
"loci",
",",
"sources",
")",
":",
"return",
"pandas",
".",
"DataFrame",
"(",
"allele_support_rows",
"(",
"loci",
",",
"sources",
")",
",",
"columns",
"=",
"EXPECTED_COLUMNS",
")"
] | Returns a DataFrame of allele counts for all given loci in the read sources | [
"Returns",
"a",
"DataFrame",
"of",
"allele",
"counts",
"for",
"all",
"given",
"loci",
"in",
"the",
"read",
"sources"
] | 715d3ede5893757b2fcba4117515621bca7b1e5d | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/support.py#L29-L35 | train |
openvax/varlens | varlens/support.py | variant_support | def variant_support(variants, allele_support_df, ignore_missing=False):
'''
Collect the read evidence support for the given variants.
Parameters
----------
variants : iterable of varcode.Variant
allele_support_df : dataframe
Allele support dataframe, as output by the varlens-allele-su... | python | def variant_support(variants, allele_support_df, ignore_missing=False):
'''
Collect the read evidence support for the given variants.
Parameters
----------
variants : iterable of varcode.Variant
allele_support_df : dataframe
Allele support dataframe, as output by the varlens-allele-su... | [
"def",
"variant_support",
"(",
"variants",
",",
"allele_support_df",
",",
"ignore_missing",
"=",
"False",
")",
":",
"missing",
"=",
"[",
"c",
"for",
"c",
"in",
"EXPECTED_COLUMNS",
"if",
"c",
"not",
"in",
"allele_support_df",
".",
"columns",
"]",
"if",
"missi... | Collect the read evidence support for the given variants.
Parameters
----------
variants : iterable of varcode.Variant
allele_support_df : dataframe
Allele support dataframe, as output by the varlens-allele-support tool.
It should have columns: source, contig, interbase_start, interba... | [
"Collect",
"the",
"read",
"evidence",
"support",
"for",
"the",
"given",
"variants",
"."
] | 715d3ede5893757b2fcba4117515621bca7b1e5d | https://github.com/openvax/varlens/blob/715d3ede5893757b2fcba4117515621bca7b1e5d/varlens/support.py#L57-L153 | train |
gesellkammer/sndfileio | sndfileio/sndfileio.py | sndinfo | def sndinfo(path:str) -> SndInfo:
"""
Get info about a soundfile
path (str): the path to a soundfile
RETURNS --> an instance of SndInfo: samplerate, nframes, channels, encoding, fileformat
"""
backend = _getBackend(path)
logger.debug(f"sndinfo: using backend {backend.name}")
return bac... | python | def sndinfo(path:str) -> SndInfo:
"""
Get info about a soundfile
path (str): the path to a soundfile
RETURNS --> an instance of SndInfo: samplerate, nframes, channels, encoding, fileformat
"""
backend = _getBackend(path)
logger.debug(f"sndinfo: using backend {backend.name}")
return bac... | [
"def",
"sndinfo",
"(",
"path",
":",
"str",
")",
"->",
"SndInfo",
":",
"backend",
"=",
"_getBackend",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"f\"sndinfo: using backend {backend.name}\"",
")",
"return",
"backend",
".",
"getinfo",
"(",
"path",
")"
] | Get info about a soundfile
path (str): the path to a soundfile
RETURNS --> an instance of SndInfo: samplerate, nframes, channels, encoding, fileformat | [
"Get",
"info",
"about",
"a",
"soundfile"
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L215-L225 | train |
gesellkammer/sndfileio | sndfileio/sndfileio.py | asmono | def asmono(samples:np.ndarray, channel:Union[int, str]=0) -> np.ndarray:
"""
convert samples to mono if they are not mono already.
The returned array will always have the shape (numframes,)
channel: the channel number to use, or 'mix' to mix-down
all channels
"""
if numchannels(sa... | python | def asmono(samples:np.ndarray, channel:Union[int, str]=0) -> np.ndarray:
"""
convert samples to mono if they are not mono already.
The returned array will always have the shape (numframes,)
channel: the channel number to use, or 'mix' to mix-down
all channels
"""
if numchannels(sa... | [
"def",
"asmono",
"(",
"samples",
":",
"np",
".",
"ndarray",
",",
"channel",
":",
"Union",
"[",
"int",
",",
"str",
"]",
"=",
"0",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"numchannels",
"(",
"samples",
")",
"==",
"1",
":",
"if",
"isinstance",
"... | convert samples to mono if they are not mono already.
The returned array will always have the shape (numframes,)
channel: the channel number to use, or 'mix' to mix-down
all channels | [
"convert",
"samples",
"to",
"mono",
"if",
"they",
"are",
"not",
"mono",
"already",
"."
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L298-L322 | train |
gesellkammer/sndfileio | sndfileio/sndfileio.py | getchannel | def getchannel(samples: np.ndarray, ch:int) -> np.ndarray:
"""
Returns a view into a channel of samples.
samples : a numpy array representing the audio data
ch : the channel to extract (channels begin with 0)
"""
N = numchannels(samples)
if ch > (N - 1):
raise ValueError(... | python | def getchannel(samples: np.ndarray, ch:int) -> np.ndarray:
"""
Returns a view into a channel of samples.
samples : a numpy array representing the audio data
ch : the channel to extract (channels begin with 0)
"""
N = numchannels(samples)
if ch > (N - 1):
raise ValueError(... | [
"def",
"getchannel",
"(",
"samples",
":",
"np",
".",
"ndarray",
",",
"ch",
":",
"int",
")",
"->",
"np",
".",
"ndarray",
":",
"N",
"=",
"numchannels",
"(",
"samples",
")",
"if",
"ch",
">",
"(",
"N",
"-",
"1",
")",
":",
"raise",
"ValueError",
"(",
... | Returns a view into a channel of samples.
samples : a numpy array representing the audio data
ch : the channel to extract (channels begin with 0) | [
"Returns",
"a",
"view",
"into",
"a",
"channel",
"of",
"samples",
"."
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L325-L337 | train |
gesellkammer/sndfileio | sndfileio/sndfileio.py | bitdepth | def bitdepth(data:np.ndarray, snap:bool=True) -> int:
"""
returns the number of bits actually used to represent the data.
data: a numpy.array (mono or multi-channel)
snap: snap to 8, 16, 24 or 32 bits.
"""
data = asmono(data)
maxitems = min(4096, data.shape[0])
maxbits = max(x.as_intege... | python | def bitdepth(data:np.ndarray, snap:bool=True) -> int:
"""
returns the number of bits actually used to represent the data.
data: a numpy.array (mono or multi-channel)
snap: snap to 8, 16, 24 or 32 bits.
"""
data = asmono(data)
maxitems = min(4096, data.shape[0])
maxbits = max(x.as_intege... | [
"def",
"bitdepth",
"(",
"data",
":",
"np",
".",
"ndarray",
",",
"snap",
":",
"bool",
"=",
"True",
")",
"->",
"int",
":",
"data",
"=",
"asmono",
"(",
"data",
")",
"maxitems",
"=",
"min",
"(",
"4096",
",",
"data",
".",
"shape",
"[",
"0",
"]",
")"... | returns the number of bits actually used to represent the data.
data: a numpy.array (mono or multi-channel)
snap: snap to 8, 16, 24 or 32 bits. | [
"returns",
"the",
"number",
"of",
"bits",
"actually",
"used",
"to",
"represent",
"the",
"data",
"."
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L340-L362 | train |
gesellkammer/sndfileio | sndfileio/sndfileio.py | sndwrite_like | def sndwrite_like(samples:np.ndarray, likefile:str, outfile:str) -> None:
"""
Write samples to outfile with samplerate and encoding
taken from likefile
"""
info = sndinfo(likefile)
sndwrite(samples, info.samplerate, outfile, encoding=info.encoding) | python | def sndwrite_like(samples:np.ndarray, likefile:str, outfile:str) -> None:
"""
Write samples to outfile with samplerate and encoding
taken from likefile
"""
info = sndinfo(likefile)
sndwrite(samples, info.samplerate, outfile, encoding=info.encoding) | [
"def",
"sndwrite_like",
"(",
"samples",
":",
"np",
".",
"ndarray",
",",
"likefile",
":",
"str",
",",
"outfile",
":",
"str",
")",
"->",
"None",
":",
"info",
"=",
"sndinfo",
"(",
"likefile",
")",
"sndwrite",
"(",
"samples",
",",
"info",
".",
"samplerate"... | Write samples to outfile with samplerate and encoding
taken from likefile | [
"Write",
"samples",
"to",
"outfile",
"with",
"samplerate",
"and",
"encoding",
"taken",
"from",
"likefile"
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L365-L371 | train |
gesellkammer/sndfileio | sndfileio/sndfileio.py | _wavReadData | def _wavReadData(fid,
size:int,
channels:int,
encoding:str,
bigendian:bool) -> np.ndarray:
"""
adapted from scipy.io.wavfile._read_data_chunk
assume we are at the data (after having read the size)
"""
bits = int(encoding[3:])
... | python | def _wavReadData(fid,
size:int,
channels:int,
encoding:str,
bigendian:bool) -> np.ndarray:
"""
adapted from scipy.io.wavfile._read_data_chunk
assume we are at the data (after having read the size)
"""
bits = int(encoding[3:])
... | [
"def",
"_wavReadData",
"(",
"fid",
",",
"size",
":",
"int",
",",
"channels",
":",
"int",
",",
"encoding",
":",
"str",
",",
"bigendian",
":",
"bool",
")",
"->",
"np",
".",
"ndarray",
":",
"bits",
"=",
"int",
"(",
"encoding",
"[",
"3",
":",
"]",
")... | adapted from scipy.io.wavfile._read_data_chunk
assume we are at the data (after having read the size) | [
"adapted",
"from",
"scipy",
".",
"io",
".",
"wavfile",
".",
"_read_data_chunk"
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L788-L832 | train |
gesellkammer/sndfileio | sndfileio/sndfileio.py | _wavGetInfo | def _wavGetInfo(f:Union[IO, str]) -> Tuple[SndInfo, Dict[str, Any]]:
"""
Read the info of a wav file. taken mostly from scipy.io.wavfile
if extended: returns also fsize and bigendian
"""
if isinstance(f, (str, bytes)):
f = open(f, 'rb')
needsclosing = True
else:
needsclo... | python | def _wavGetInfo(f:Union[IO, str]) -> Tuple[SndInfo, Dict[str, Any]]:
"""
Read the info of a wav file. taken mostly from scipy.io.wavfile
if extended: returns also fsize and bigendian
"""
if isinstance(f, (str, bytes)):
f = open(f, 'rb')
needsclosing = True
else:
needsclo... | [
"def",
"_wavGetInfo",
"(",
"f",
":",
"Union",
"[",
"IO",
",",
"str",
"]",
")",
"->",
"Tuple",
"[",
"SndInfo",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"if",
"isinstance",
"(",
"f",
",",
"(",
"str",
",",
"bytes",
")",
")",
":",
"f",... | Read the info of a wav file. taken mostly from scipy.io.wavfile
if extended: returns also fsize and bigendian | [
"Read",
"the",
"info",
"of",
"a",
"wav",
"file",
".",
"taken",
"mostly",
"from",
"scipy",
".",
"io",
".",
"wavfile"
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/sndfileio.py#L866-L896 | train |
bacher09/xrcon | xrcon/client.py | QuakeProtocol.connect | def connect(self):
"Create connection to server"
family, stype, proto, cname, sockaddr = self.best_connection_params(
self.host, self.port)
self.sock = socket.socket(family, stype)
self.sock.settimeout(self.timeout)
self.sock.connect(sockaddr) | python | def connect(self):
"Create connection to server"
family, stype, proto, cname, sockaddr = self.best_connection_params(
self.host, self.port)
self.sock = socket.socket(family, stype)
self.sock.settimeout(self.timeout)
self.sock.connect(sockaddr) | [
"def",
"connect",
"(",
"self",
")",
":",
"\"Create connection to server\"",
"family",
",",
"stype",
",",
"proto",
",",
"cname",
",",
"sockaddr",
"=",
"self",
".",
"best_connection_params",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
"self",
".... | Create connection to server | [
"Create",
"connection",
"to",
"server"
] | 6a883f780265cbca31af7a379dc7cb28fdd8b73f | https://github.com/bacher09/xrcon/blob/6a883f780265cbca31af7a379dc7cb28fdd8b73f/xrcon/client.py#L53-L59 | train |
bacher09/xrcon | xrcon/client.py | QuakeProtocol.getchallenge | def getchallenge(self):
"Return server challenge"
self.sock.send(CHALLENGE_PACKET)
# wait challenge response
for packet in self.read_iterator(self.CHALLENGE_TIMEOUT):
if packet.startswith(CHALLENGE_RESPONSE_HEADER):
return parse_challenge_response(packet) | python | def getchallenge(self):
"Return server challenge"
self.sock.send(CHALLENGE_PACKET)
# wait challenge response
for packet in self.read_iterator(self.CHALLENGE_TIMEOUT):
if packet.startswith(CHALLENGE_RESPONSE_HEADER):
return parse_challenge_response(packet) | [
"def",
"getchallenge",
"(",
"self",
")",
":",
"\"Return server challenge\"",
"self",
".",
"sock",
".",
"send",
"(",
"CHALLENGE_PACKET",
")",
"for",
"packet",
"in",
"self",
".",
"read_iterator",
"(",
"self",
".",
"CHALLENGE_TIMEOUT",
")",
":",
"if",
"packet",
... | Return server challenge | [
"Return",
"server",
"challenge"
] | 6a883f780265cbca31af7a379dc7cb28fdd8b73f | https://github.com/bacher09/xrcon/blob/6a883f780265cbca31af7a379dc7cb28fdd8b73f/xrcon/client.py#L86-L92 | train |
bacher09/xrcon | xrcon/client.py | XRcon.send | def send(self, command):
"Send rcon command to server"
if self.secure_rcon == self.RCON_NOSECURE:
self.sock.send(rcon_nosecure_packet(self.password, command))
elif self.secure_rcon == self.RCON_SECURE_TIME:
self.sock.send(rcon_secure_time_packet(self.password, command))
... | python | def send(self, command):
"Send rcon command to server"
if self.secure_rcon == self.RCON_NOSECURE:
self.sock.send(rcon_nosecure_packet(self.password, command))
elif self.secure_rcon == self.RCON_SECURE_TIME:
self.sock.send(rcon_secure_time_packet(self.password, command))
... | [
"def",
"send",
"(",
"self",
",",
"command",
")",
":",
"\"Send rcon command to server\"",
"if",
"self",
".",
"secure_rcon",
"==",
"self",
".",
"RCON_NOSECURE",
":",
"self",
".",
"sock",
".",
"send",
"(",
"rcon_nosecure_packet",
"(",
"self",
".",
"password",
"... | Send rcon command to server | [
"Send",
"rcon",
"command",
"to",
"server"
] | 6a883f780265cbca31af7a379dc7cb28fdd8b73f | https://github.com/bacher09/xrcon/blob/6a883f780265cbca31af7a379dc7cb28fdd8b73f/xrcon/client.py#L174-L185 | train |
romankoblov/leaf | leaf/__init__.py | parse | def parse(html_string, wrapper=Parser, *args, **kwargs):
""" Parse html with wrapper """
return Parser(lxml.html.fromstring(html_string), *args, **kwargs) | python | def parse(html_string, wrapper=Parser, *args, **kwargs):
""" Parse html with wrapper """
return Parser(lxml.html.fromstring(html_string), *args, **kwargs) | [
"def",
"parse",
"(",
"html_string",
",",
"wrapper",
"=",
"Parser",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"Parser",
"(",
"lxml",
".",
"html",
".",
"fromstring",
"(",
"html_string",
")",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] | Parse html with wrapper | [
"Parse",
"html",
"with",
"wrapper"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L112-L114 | train |
romankoblov/leaf | leaf/__init__.py | str2int | def str2int(string_with_int):
""" Collect digits from a string """
return int("".join([char for char in string_with_int if char in string.digits]) or 0) | python | def str2int(string_with_int):
""" Collect digits from a string """
return int("".join([char for char in string_with_int if char in string.digits]) or 0) | [
"def",
"str2int",
"(",
"string_with_int",
")",
":",
"return",
"int",
"(",
"\"\"",
".",
"join",
"(",
"[",
"char",
"for",
"char",
"in",
"string_with_int",
"if",
"char",
"in",
"string",
".",
"digits",
"]",
")",
"or",
"0",
")"
] | Collect digits from a string | [
"Collect",
"digits",
"from",
"a",
"string"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L117-L119 | train |
romankoblov/leaf | leaf/__init__.py | to_unicode | def to_unicode(obj, encoding='utf-8'):
""" Convert string to unicode string """
if isinstance(obj, string_types) or isinstance(obj, binary_type):
if not isinstance(obj, text_type):
obj = text_type(obj, encoding)
return obj | python | def to_unicode(obj, encoding='utf-8'):
""" Convert string to unicode string """
if isinstance(obj, string_types) or isinstance(obj, binary_type):
if not isinstance(obj, text_type):
obj = text_type(obj, encoding)
return obj | [
"def",
"to_unicode",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
"or",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"text_type",
... | Convert string to unicode string | [
"Convert",
"string",
"to",
"unicode",
"string"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L122-L127 | train |
romankoblov/leaf | leaf/__init__.py | strip_spaces | def strip_spaces(s):
""" Strip excess spaces from a string """
return u" ".join([c for c in s.split(u' ') if c]) | python | def strip_spaces(s):
""" Strip excess spaces from a string """
return u" ".join([c for c in s.split(u' ') if c]) | [
"def",
"strip_spaces",
"(",
"s",
")",
":",
"return",
"u\" \"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"s",
".",
"split",
"(",
"u' '",
")",
"if",
"c",
"]",
")"
] | Strip excess spaces from a string | [
"Strip",
"excess",
"spaces",
"from",
"a",
"string"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L162-L164 | train |
romankoblov/leaf | leaf/__init__.py | strip_linebreaks | def strip_linebreaks(s):
""" Strip excess line breaks from a string """
return u"\n".join([c for c in s.split(u'\n') if c]) | python | def strip_linebreaks(s):
""" Strip excess line breaks from a string """
return u"\n".join([c for c in s.split(u'\n') if c]) | [
"def",
"strip_linebreaks",
"(",
"s",
")",
":",
"return",
"u\"\\n\"",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"s",
".",
"split",
"(",
"u'\\n'",
")",
"if",
"c",
"]",
")"
] | Strip excess line breaks from a string | [
"Strip",
"excess",
"line",
"breaks",
"from",
"a",
"string"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L167-L169 | train |
romankoblov/leaf | leaf/__init__.py | Parser.get | def get(self, selector, index=0, default=None):
""" Get first element from CSSSelector """
elements = self(selector)
if elements:
try:
return elements[index]
except (IndexError):
pass
return default | python | def get(self, selector, index=0, default=None):
""" Get first element from CSSSelector """
elements = self(selector)
if elements:
try:
return elements[index]
except (IndexError):
pass
return default | [
"def",
"get",
"(",
"self",
",",
"selector",
",",
"index",
"=",
"0",
",",
"default",
"=",
"None",
")",
":",
"elements",
"=",
"self",
"(",
"selector",
")",
"if",
"elements",
":",
"try",
":",
"return",
"elements",
"[",
"index",
"]",
"except",
"(",
"In... | Get first element from CSSSelector | [
"Get",
"first",
"element",
"from",
"CSSSelector"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L26-L34 | train |
romankoblov/leaf | leaf/__init__.py | Parser.html | def html(self, unicode=False):
""" Return HTML of element """
html = lxml.html.tostring(self.element, encoding=self.encoding)
if unicode:
html = html.decode(self.encoding)
return html | python | def html(self, unicode=False):
""" Return HTML of element """
html = lxml.html.tostring(self.element, encoding=self.encoding)
if unicode:
html = html.decode(self.encoding)
return html | [
"def",
"html",
"(",
"self",
",",
"unicode",
"=",
"False",
")",
":",
"html",
"=",
"lxml",
".",
"html",
".",
"tostring",
"(",
"self",
".",
"element",
",",
"encoding",
"=",
"self",
".",
"encoding",
")",
"if",
"unicode",
":",
"html",
"=",
"html",
".",
... | Return HTML of element | [
"Return",
"HTML",
"of",
"element"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L36-L41 | train |
romankoblov/leaf | leaf/__init__.py | Parser.parse | def parse(self, func, *args, **kwargs):
""" Parse element with given function"""
result = []
for element in self.xpath('child::node()'):
if isinstance(element, Parser):
children = element.parse(func, *args, **kwargs)
element_result = func(element, chil... | python | def parse(self, func, *args, **kwargs):
""" Parse element with given function"""
result = []
for element in self.xpath('child::node()'):
if isinstance(element, Parser):
children = element.parse(func, *args, **kwargs)
element_result = func(element, chil... | [
"def",
"parse",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"element",
"in",
"self",
".",
"xpath",
"(",
"'child::node()'",
")",
":",
"if",
"isinstance",
"(",
"element",
",",
"Parser",
"... | Parse element with given function | [
"Parse",
"element",
"with",
"given",
"function"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L55-L66 | train |
romankoblov/leaf | leaf/__init__.py | Parser._wrap_result | def _wrap_result(self, func):
""" Wrap result in Parser instance """
def wrapper(*args):
result = func(*args)
if hasattr(result, '__iter__') and not isinstance(result, etree._Element):
return [self._wrap_element(element) for element in result]
else:
... | python | def _wrap_result(self, func):
""" Wrap result in Parser instance """
def wrapper(*args):
result = func(*args)
if hasattr(result, '__iter__') and not isinstance(result, etree._Element):
return [self._wrap_element(element) for element in result]
else:
... | [
"def",
"_wrap_result",
"(",
"self",
",",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"result",
"=",
"func",
"(",
"*",
"args",
")",
"if",
"hasattr",
"(",
"result",
",",
"'__iter__'",
")",
"and",
"not",
"isinstance",
"(",
"result",
... | Wrap result in Parser instance | [
"Wrap",
"result",
"in",
"Parser",
"instance"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L68-L76 | train |
romankoblov/leaf | leaf/__init__.py | Parser._wrap_element | def _wrap_element(self, result):
""" Wrap single element in Parser instance """
if isinstance(result, lxml.html.HtmlElement):
return Parser(result)
else:
return result | python | def _wrap_element(self, result):
""" Wrap single element in Parser instance """
if isinstance(result, lxml.html.HtmlElement):
return Parser(result)
else:
return result | [
"def",
"_wrap_element",
"(",
"self",
",",
"result",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"lxml",
".",
"html",
".",
"HtmlElement",
")",
":",
"return",
"Parser",
"(",
"result",
")",
"else",
":",
"return",
"result"
] | Wrap single element in Parser instance | [
"Wrap",
"single",
"element",
"in",
"Parser",
"instance"
] | e042d91ec462c834318d03f199fcc4a9f565cb84 | https://github.com/romankoblov/leaf/blob/e042d91ec462c834318d03f199fcc4a9f565cb84/leaf/__init__.py#L78-L83 | train |
frostming/marko | marko/block.py | BlockElement.parse_inline | def parse_inline(self):
"""Inline parsing is postponed so that all link references
are seen before that.
"""
if self.inline_children:
self.children = parser.parse_inline(self.children)
elif isinstance(getattr(self, 'children', None), list):
for child in se... | python | def parse_inline(self):
"""Inline parsing is postponed so that all link references
are seen before that.
"""
if self.inline_children:
self.children = parser.parse_inline(self.children)
elif isinstance(getattr(self, 'children', None), list):
for child in se... | [
"def",
"parse_inline",
"(",
"self",
")",
":",
"if",
"self",
".",
"inline_children",
":",
"self",
".",
"children",
"=",
"parser",
".",
"parse_inline",
"(",
"self",
".",
"children",
")",
"elif",
"isinstance",
"(",
"getattr",
"(",
"self",
",",
"'children'",
... | Inline parsing is postponed so that all link references
are seen before that. | [
"Inline",
"parsing",
"is",
"postponed",
"so",
"that",
"all",
"link",
"references",
"are",
"seen",
"before",
"that",
"."
] | 1cd030b665fa37bad1f8b3a25a89ce1a7c491dde | https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/block.py#L59-L68 | train |
COALAIP/pycoalaip | coalaip/models.py | work_model_factory | def work_model_factory(*, validator=validators.is_work_model, **kwargs):
"""Generate a Work model.
Expects ``data``, ``validator``, ``model_cls``, and ``ld_context``
as keyword arguments.
Raises:
:exc:`ModelError`: If a non-'AbstractWork' ``ld_type`` keyword
argument is given.
... | python | def work_model_factory(*, validator=validators.is_work_model, **kwargs):
"""Generate a Work model.
Expects ``data``, ``validator``, ``model_cls``, and ``ld_context``
as keyword arguments.
Raises:
:exc:`ModelError`: If a non-'AbstractWork' ``ld_type`` keyword
argument is given.
... | [
"def",
"work_model_factory",
"(",
"*",
",",
"validator",
"=",
"validators",
".",
"is_work_model",
",",
"**",
"kwargs",
")",
":",
"kwargs",
"[",
"'ld_type'",
"]",
"=",
"'AbstractWork'",
"return",
"_model_factory",
"(",
"validator",
"=",
"validator",
",",
"**",
... | Generate a Work model.
Expects ``data``, ``validator``, ``model_cls``, and ``ld_context``
as keyword arguments.
Raises:
:exc:`ModelError`: If a non-'AbstractWork' ``ld_type`` keyword
argument is given. | [
"Generate",
"a",
"Work",
"model",
"."
] | cecc8f6ff4733f0525fafcee63647753e832f0be | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L241-L252 | train |
COALAIP/pycoalaip | coalaip/models.py | manifestation_model_factory | def manifestation_model_factory(*, validator=validators.is_manifestation_model,
ld_type='CreativeWork', **kwargs):
"""Generate a Manifestation model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments.
"""
return _mod... | python | def manifestation_model_factory(*, validator=validators.is_manifestation_model,
ld_type='CreativeWork', **kwargs):
"""Generate a Manifestation model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments.
"""
return _mod... | [
"def",
"manifestation_model_factory",
"(",
"*",
",",
"validator",
"=",
"validators",
".",
"is_manifestation_model",
",",
"ld_type",
"=",
"'CreativeWork'",
",",
"**",
"kwargs",
")",
":",
"return",
"_model_factory",
"(",
"validator",
"=",
"validator",
",",
"ld_type"... | Generate a Manifestation model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments. | [
"Generate",
"a",
"Manifestation",
"model",
"."
] | cecc8f6ff4733f0525fafcee63647753e832f0be | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L255-L262 | train |
COALAIP/pycoalaip | coalaip/models.py | right_model_factory | def right_model_factory(*, validator=validators.is_right_model,
ld_type='Right', **kwargs):
"""Generate a Right model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments.
"""
return _model_factory(validator=validator, ld_type... | python | def right_model_factory(*, validator=validators.is_right_model,
ld_type='Right', **kwargs):
"""Generate a Right model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments.
"""
return _model_factory(validator=validator, ld_type... | [
"def",
"right_model_factory",
"(",
"*",
",",
"validator",
"=",
"validators",
".",
"is_right_model",
",",
"ld_type",
"=",
"'Right'",
",",
"**",
"kwargs",
")",
":",
"return",
"_model_factory",
"(",
"validator",
"=",
"validator",
",",
"ld_type",
"=",
"ld_type",
... | Generate a Right model.
Expects ``data``, ``validator``, ``model_cls``, ``ld_type``, and
``ld_context`` as keyword arguments. | [
"Generate",
"a",
"Right",
"model",
"."
] | cecc8f6ff4733f0525fafcee63647753e832f0be | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L265-L272 | train |
COALAIP/pycoalaip | coalaip/models.py | copyright_model_factory | def copyright_model_factory(*, validator=validators.is_copyright_model,
**kwargs):
"""Generate a Copyright model.
Expects ``data``, ``validator``, ``model_cls``, and ``ld_context``
as keyword arguments.
Raises:
:exc:`ModelError`: If a non-'Copyright' ``ld_type`` key... | python | def copyright_model_factory(*, validator=validators.is_copyright_model,
**kwargs):
"""Generate a Copyright model.
Expects ``data``, ``validator``, ``model_cls``, and ``ld_context``
as keyword arguments.
Raises:
:exc:`ModelError`: If a non-'Copyright' ``ld_type`` key... | [
"def",
"copyright_model_factory",
"(",
"*",
",",
"validator",
"=",
"validators",
".",
"is_copyright_model",
",",
"**",
"kwargs",
")",
":",
"kwargs",
"[",
"'ld_type'",
"]",
"=",
"'Copyright'",
"return",
"_model_factory",
"(",
"validator",
"=",
"validator",
",",
... | Generate a Copyright model.
Expects ``data``, ``validator``, ``model_cls``, and ``ld_context``
as keyword arguments.
Raises:
:exc:`ModelError`: If a non-'Copyright' ``ld_type`` keyword
argument is given. | [
"Generate",
"a",
"Copyright",
"model",
"."
] | cecc8f6ff4733f0525fafcee63647753e832f0be | https://github.com/COALAIP/pycoalaip/blob/cecc8f6ff4733f0525fafcee63647753e832f0be/coalaip/models.py#L276-L288 | train |
Pylons/pyramid_retry | src/pyramid_retry/__init__.py | mark_error_retryable | def mark_error_retryable(error):
"""
Mark an exception instance or type as retryable. If this exception
is caught by ``pyramid_retry`` then it may retry the request.
"""
if isinstance(error, Exception):
alsoProvides(error, IRetryableError)
elif inspect.isclass(error) and issubclass(erro... | python | def mark_error_retryable(error):
"""
Mark an exception instance or type as retryable. If this exception
is caught by ``pyramid_retry`` then it may retry the request.
"""
if isinstance(error, Exception):
alsoProvides(error, IRetryableError)
elif inspect.isclass(error) and issubclass(erro... | [
"def",
"mark_error_retryable",
"(",
"error",
")",
":",
"if",
"isinstance",
"(",
"error",
",",
"Exception",
")",
":",
"alsoProvides",
"(",
"error",
",",
"IRetryableError",
")",
"elif",
"inspect",
".",
"isclass",
"(",
"error",
")",
"and",
"issubclass",
"(",
... | Mark an exception instance or type as retryable. If this exception
is caught by ``pyramid_retry`` then it may retry the request. | [
"Mark",
"an",
"exception",
"instance",
"or",
"type",
"as",
"retryable",
".",
"If",
"this",
"exception",
"is",
"caught",
"by",
"pyramid_retry",
"then",
"it",
"may",
"retry",
"the",
"request",
"."
] | 4518d0655159fcf5cf79c0d7d4c86e8315f16082 | https://github.com/Pylons/pyramid_retry/blob/4518d0655159fcf5cf79c0d7d4c86e8315f16082/src/pyramid_retry/__init__.py#L149-L161 | train |
Pylons/pyramid_retry | src/pyramid_retry/__init__.py | is_last_attempt | def is_last_attempt(request):
"""
Return ``True`` if the request is on its last attempt, meaning that
``pyramid_retry`` will not be issuing any new attempts, regardless of
what happens when executing this request.
This will return ``True`` if ``pyramid_retry`` is inactive for the
request.
... | python | def is_last_attempt(request):
"""
Return ``True`` if the request is on its last attempt, meaning that
``pyramid_retry`` will not be issuing any new attempts, regardless of
what happens when executing this request.
This will return ``True`` if ``pyramid_retry`` is inactive for the
request.
... | [
"def",
"is_last_attempt",
"(",
"request",
")",
":",
"environ",
"=",
"request",
".",
"environ",
"attempt",
"=",
"environ",
".",
"get",
"(",
"'retry.attempt'",
")",
"attempts",
"=",
"environ",
".",
"get",
"(",
"'retry.attempts'",
")",
"if",
"attempt",
"is",
... | Return ``True`` if the request is on its last attempt, meaning that
``pyramid_retry`` will not be issuing any new attempts, regardless of
what happens when executing this request.
This will return ``True`` if ``pyramid_retry`` is inactive for the
request. | [
"Return",
"True",
"if",
"the",
"request",
"is",
"on",
"its",
"last",
"attempt",
"meaning",
"that",
"pyramid_retry",
"will",
"not",
"be",
"issuing",
"any",
"new",
"attempts",
"regardless",
"of",
"what",
"happens",
"when",
"executing",
"this",
"request",
"."
] | 4518d0655159fcf5cf79c0d7d4c86e8315f16082 | https://github.com/Pylons/pyramid_retry/blob/4518d0655159fcf5cf79c0d7d4c86e8315f16082/src/pyramid_retry/__init__.py#L182-L198 | train |
Pylons/pyramid_retry | src/pyramid_retry/__init__.py | includeme | def includeme(config):
"""
Activate the ``pyramid_retry`` execution policy in your application.
This will add the :func:`pyramid_retry.RetryableErrorPolicy` with
``attempts`` pulled from the ``retry.attempts`` setting.
The ``last_retry_attempt`` and ``retryable_error`` view predicates
are regi... | python | def includeme(config):
"""
Activate the ``pyramid_retry`` execution policy in your application.
This will add the :func:`pyramid_retry.RetryableErrorPolicy` with
``attempts`` pulled from the ``retry.attempts`` setting.
The ``last_retry_attempt`` and ``retryable_error`` view predicates
are regi... | [
"def",
"includeme",
"(",
"config",
")",
":",
"settings",
"=",
"config",
".",
"get_settings",
"(",
")",
"config",
".",
"add_view_predicate",
"(",
"'last_retry_attempt'",
",",
"LastAttemptPredicate",
")",
"config",
".",
"add_view_predicate",
"(",
"'retryable_error'",
... | Activate the ``pyramid_retry`` execution policy in your application.
This will add the :func:`pyramid_retry.RetryableErrorPolicy` with
``attempts`` pulled from the ``retry.attempts`` setting.
The ``last_retry_attempt`` and ``retryable_error`` view predicates
are registered.
This should be include... | [
"Activate",
"the",
"pyramid_retry",
"execution",
"policy",
"in",
"your",
"application",
"."
] | 4518d0655159fcf5cf79c0d7d4c86e8315f16082 | https://github.com/Pylons/pyramid_retry/blob/4518d0655159fcf5cf79c0d7d4c86e8315f16082/src/pyramid_retry/__init__.py#L259-L292 | train |
gesellkammer/sndfileio | sndfileio/dsp.py | filter_butter_coeffs | def filter_butter_coeffs(filtertype, freq, samplerate, order=5):
# type: (str, Union[float, Tuple[float, float]], int, int) -> Tuple[np.ndarray, np.ndarray]
"""
calculates the coefficients for a digital butterworth filter
filtertype: 'low', 'high', 'band'
freq : cutoff freq.
in... | python | def filter_butter_coeffs(filtertype, freq, samplerate, order=5):
# type: (str, Union[float, Tuple[float, float]], int, int) -> Tuple[np.ndarray, np.ndarray]
"""
calculates the coefficients for a digital butterworth filter
filtertype: 'low', 'high', 'band'
freq : cutoff freq.
in... | [
"def",
"filter_butter_coeffs",
"(",
"filtertype",
",",
"freq",
",",
"samplerate",
",",
"order",
"=",
"5",
")",
":",
"assert",
"filtertype",
"in",
"(",
"'low'",
",",
"'high'",
",",
"'band'",
")",
"nyq",
"=",
"0.5",
"*",
"samplerate",
"if",
"isinstance",
"... | calculates the coefficients for a digital butterworth filter
filtertype: 'low', 'high', 'band'
freq : cutoff freq.
in the case of 'band': (low, high)
Returns --> (b, a) | [
"calculates",
"the",
"coefficients",
"for",
"a",
"digital",
"butterworth",
"filter"
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/dsp.py#L63-L85 | train |
gesellkammer/sndfileio | sndfileio/dsp.py | filter_butter | def filter_butter(samples, samplerate, filtertype, freq, order=5):
# type: (np.ndarray, int, str, float, int) -> np.ndarray
"""
Filters the samples with a digital butterworth filter
samples : mono samples
filtertype: 'low', 'band', 'high'
freq : for low or high, the cutoff freq
... | python | def filter_butter(samples, samplerate, filtertype, freq, order=5):
# type: (np.ndarray, int, str, float, int) -> np.ndarray
"""
Filters the samples with a digital butterworth filter
samples : mono samples
filtertype: 'low', 'band', 'high'
freq : for low or high, the cutoff freq
... | [
"def",
"filter_butter",
"(",
"samples",
",",
"samplerate",
",",
"filtertype",
",",
"freq",
",",
"order",
"=",
"5",
")",
":",
"assert",
"filtertype",
"in",
"(",
"'low'",
",",
"'high'",
",",
"'band'",
")",
"b",
",",
"a",
"=",
"filter_butter_coeffs",
"(",
... | Filters the samples with a digital butterworth filter
samples : mono samples
filtertype: 'low', 'band', 'high'
freq : for low or high, the cutoff freq
for band, (low, high)
samplerate: the sampling-rate
order : the order of the butterworth filter
Returns --> the filt... | [
"Filters",
"the",
"samples",
"with",
"a",
"digital",
"butterworth",
"filter"
] | 8e2b264cadb652f09d2e775f54090c0a3cb2ced2 | https://github.com/gesellkammer/sndfileio/blob/8e2b264cadb652f09d2e775f54090c0a3cb2ced2/sndfileio/dsp.py#L88-L106 | train |
johnnoone/aioconsul | aioconsul/api.py | token_middleware | def token_middleware(ctx, get_response):
"""Reinject token and consistency into requests.
"""
async def middleware(request):
params = request.setdefault('params', {})
if params.get("token") is None:
params['token'] = ctx.token
return await get_response(request)
return... | python | def token_middleware(ctx, get_response):
"""Reinject token and consistency into requests.
"""
async def middleware(request):
params = request.setdefault('params', {})
if params.get("token") is None:
params['token'] = ctx.token
return await get_response(request)
return... | [
"def",
"token_middleware",
"(",
"ctx",
",",
"get_response",
")",
":",
"async",
"def",
"middleware",
"(",
"request",
")",
":",
"params",
"=",
"request",
".",
"setdefault",
"(",
"'params'",
",",
"{",
"}",
")",
"if",
"params",
".",
"get",
"(",
"\"token\"",
... | Reinject token and consistency into requests. | [
"Reinject",
"token",
"and",
"consistency",
"into",
"requests",
"."
] | 02f7a529d7dc2e49bed942111067aa5faf320e90 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/api.py#L212-L220 | train |
bitesofcode/projexui | projexui/widgets/xganttwidget/xganttdepitem.py | XGanttDepItem.rebuild | def rebuild( self ):
"""
Rebuilds the dependency path for this item.
"""
scene = self.scene()
if ( not scene ):
return
sourcePos = self.sourceItem().viewItem().pos()
sourceRect = self.sourceItem().viewItem().rect()
... | python | def rebuild( self ):
"""
Rebuilds the dependency path for this item.
"""
scene = self.scene()
if ( not scene ):
return
sourcePos = self.sourceItem().viewItem().pos()
sourceRect = self.sourceItem().viewItem().rect()
... | [
"def",
"rebuild",
"(",
"self",
")",
":",
"scene",
"=",
"self",
".",
"scene",
"(",
")",
"if",
"(",
"not",
"scene",
")",
":",
"return",
"sourcePos",
"=",
"self",
".",
"sourceItem",
"(",
")",
".",
"viewItem",
"(",
")",
".",
"pos",
"(",
")",
"sourceR... | Rebuilds the dependency path for this item. | [
"Rebuilds",
"the",
"dependency",
"path",
"for",
"this",
"item",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttdepitem.py#L60-L95 | train |
starling-lab/rnlp | rnlp/parse.py | _writeBlock | def _writeBlock(block, blockID):
'''writes the block to a file with the id'''
with open("blockIDs.txt", "a") as fp:
fp.write("blockID: " + str(blockID) + "\n")
sentences = ""
for sentence in block:
sentences += sentence+","
fp.write("block sentences: "+sentences[:-1]+... | python | def _writeBlock(block, blockID):
'''writes the block to a file with the id'''
with open("blockIDs.txt", "a") as fp:
fp.write("blockID: " + str(blockID) + "\n")
sentences = ""
for sentence in block:
sentences += sentence+","
fp.write("block sentences: "+sentences[:-1]+... | [
"def",
"_writeBlock",
"(",
"block",
",",
"blockID",
")",
":",
"with",
"open",
"(",
"\"blockIDs.txt\"",
",",
"\"a\"",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"\"blockID: \"",
"+",
"str",
"(",
"blockID",
")",
"+",
"\"\\n\"",
")",
"sentences",
"=",... | writes the block to a file with the id | [
"writes",
"the",
"block",
"to",
"a",
"file",
"with",
"the",
"id"
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L38-L46 | train |
starling-lab/rnlp | rnlp/parse.py | _writeSentenceInBlock | def _writeSentenceInBlock(sentence, blockID, sentenceID):
'''writes the sentence in a block to a file with the id'''
with open("sentenceIDs.txt", "a") as fp:
fp.write("sentenceID: "+str(blockID)+"_"+str(sentenceID)+"\n")
fp.write("sentence string: "+sentence+"\n")
fp.write("\n") | python | def _writeSentenceInBlock(sentence, blockID, sentenceID):
'''writes the sentence in a block to a file with the id'''
with open("sentenceIDs.txt", "a") as fp:
fp.write("sentenceID: "+str(blockID)+"_"+str(sentenceID)+"\n")
fp.write("sentence string: "+sentence+"\n")
fp.write("\n") | [
"def",
"_writeSentenceInBlock",
"(",
"sentence",
",",
"blockID",
",",
"sentenceID",
")",
":",
"with",
"open",
"(",
"\"sentenceIDs.txt\"",
",",
"\"a\"",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"\"sentenceID: \"",
"+",
"str",
"(",
"blockID",
")",
"+",... | writes the sentence in a block to a file with the id | [
"writes",
"the",
"sentence",
"in",
"a",
"block",
"to",
"a",
"file",
"with",
"the",
"id"
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L49-L54 | train |
starling-lab/rnlp | rnlp/parse.py | _writeWordFromSentenceInBlock | def _writeWordFromSentenceInBlock(word, blockID, sentenceID, wordID):
'''writes the word from a sentence in a block to a file with the id'''
with open("wordIDs.txt", "a") as fp:
fp.write("wordID: " + str(blockID) + "_" +
str(sentenceID) + "_" + str(wordID) + "\n")
fp.write("word... | python | def _writeWordFromSentenceInBlock(word, blockID, sentenceID, wordID):
'''writes the word from a sentence in a block to a file with the id'''
with open("wordIDs.txt", "a") as fp:
fp.write("wordID: " + str(blockID) + "_" +
str(sentenceID) + "_" + str(wordID) + "\n")
fp.write("word... | [
"def",
"_writeWordFromSentenceInBlock",
"(",
"word",
",",
"blockID",
",",
"sentenceID",
",",
"wordID",
")",
":",
"with",
"open",
"(",
"\"wordIDs.txt\"",
",",
"\"a\"",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"\"wordID: \"",
"+",
"str",
"(",
"blockID"... | writes the word from a sentence in a block to a file with the id | [
"writes",
"the",
"word",
"from",
"a",
"sentence",
"in",
"a",
"block",
"to",
"a",
"file",
"with",
"the",
"id"
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L57-L63 | train |
starling-lab/rnlp | rnlp/parse.py | _writeBk | def _writeBk(target="sentenceContainsTarget(+SID,+WID).", treeDepth="3",
nodeSize="3", numOfClauses="8"):
"""
Writes a background file to disk.
:param target: Target predicate with modes.
:type target: str.
:param treeDepth: Depth of the tree.
:type treeDepth: str.
:param nodeS... | python | def _writeBk(target="sentenceContainsTarget(+SID,+WID).", treeDepth="3",
nodeSize="3", numOfClauses="8"):
"""
Writes a background file to disk.
:param target: Target predicate with modes.
:type target: str.
:param treeDepth: Depth of the tree.
:type treeDepth: str.
:param nodeS... | [
"def",
"_writeBk",
"(",
"target",
"=",
"\"sentenceContainsTarget(+SID,+WID).\"",
",",
"treeDepth",
"=",
"\"3\"",
",",
"nodeSize",
"=",
"\"3\"",
",",
"numOfClauses",
"=",
"\"8\"",
")",
":",
"with",
"open",
"(",
"'bk.txt'",
",",
"'w'",
")",
"as",
"bk",
":",
... | Writes a background file to disk.
:param target: Target predicate with modes.
:type target: str.
:param treeDepth: Depth of the tree.
:type treeDepth: str.
:param nodeSize: Maximum size of each node in the tree.
:type nodeSize: str.
:param numOfClauses: Number of clauses in total.
:type... | [
"Writes",
"a",
"background",
"file",
"to",
"disk",
"."
] | 72054cc2c0cbaea1d281bf3d56b271d4da29fc4a | https://github.com/starling-lab/rnlp/blob/72054cc2c0cbaea1d281bf3d56b271d4da29fc4a/rnlp/parse.py#L72-L111 | train |
mikhaildubov/AST-text-analysis | east/asts/easa.py | EnhancedAnnotatedSuffixArray.traverse_depth_first_pre_order | def traverse_depth_first_pre_order(self, callback):
"""Visits the internal "nodes" of the enhanced suffix array in depth-first pre-order.
Based on Abouelhoda et al. (2004).
"""
n = len(self.suftab)
root = [0, 0, n - 1, ""] # <l, i, j, char>
def _traverse_top_down(inter... | python | def traverse_depth_first_pre_order(self, callback):
"""Visits the internal "nodes" of the enhanced suffix array in depth-first pre-order.
Based on Abouelhoda et al. (2004).
"""
n = len(self.suftab)
root = [0, 0, n - 1, ""] # <l, i, j, char>
def _traverse_top_down(inter... | [
"def",
"traverse_depth_first_pre_order",
"(",
"self",
",",
"callback",
")",
":",
"n",
"=",
"len",
"(",
"self",
".",
"suftab",
")",
"root",
"=",
"[",
"0",
",",
"0",
",",
"n",
"-",
"1",
",",
"\"\"",
"]",
"def",
"_traverse_top_down",
"(",
"interval",
")... | Visits the internal "nodes" of the enhanced suffix array in depth-first pre-order.
Based on Abouelhoda et al. (2004). | [
"Visits",
"the",
"internal",
"nodes",
"of",
"the",
"enhanced",
"suffix",
"array",
"in",
"depth",
"-",
"first",
"pre",
"-",
"order",
"."
] | 055ad8d2492c100bbbaa25309ec1074bdf1dfaa5 | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/easa.py#L38-L55 | train |
mikhaildubov/AST-text-analysis | east/asts/easa.py | EnhancedAnnotatedSuffixArray.traverse_depth_first_post_order | def traverse_depth_first_post_order(self, callback):
"""Visits the internal "nodes" of the enhanced suffix array in depth-first post-order.
Kasai et. al. (2001), Abouelhoda et al. (2004).
"""
# a. Reimplement without python lists?..
# b. Interface will require it to have not int... | python | def traverse_depth_first_post_order(self, callback):
"""Visits the internal "nodes" of the enhanced suffix array in depth-first post-order.
Kasai et. al. (2001), Abouelhoda et al. (2004).
"""
# a. Reimplement without python lists?..
# b. Interface will require it to have not int... | [
"def",
"traverse_depth_first_post_order",
"(",
"self",
",",
"callback",
")",
":",
"last_interval",
"=",
"None",
"n",
"=",
"len",
"(",
"self",
".",
"suftab",
")",
"stack",
"=",
"[",
"[",
"0",
",",
"0",
",",
"None",
",",
"[",
"]",
"]",
"]",
"for",
"i... | Visits the internal "nodes" of the enhanced suffix array in depth-first post-order.
Kasai et. al. (2001), Abouelhoda et al. (2004). | [
"Visits",
"the",
"internal",
"nodes",
"of",
"the",
"enhanced",
"suffix",
"array",
"in",
"depth",
"-",
"first",
"post",
"-",
"order",
"."
] | 055ad8d2492c100bbbaa25309ec1074bdf1dfaa5 | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/easa.py#L57-L85 | train |
talkincode/txradius | txradius/radius/packet.py | Packet._DecodeKey | def _DecodeKey(self, key):
"""Turn a key into a string if possible"""
if self.dict.attrindex.HasBackward(key):
return self.dict.attrindex.GetBackward(key)
return key | python | def _DecodeKey(self, key):
"""Turn a key into a string if possible"""
if self.dict.attrindex.HasBackward(key):
return self.dict.attrindex.GetBackward(key)
return key | [
"def",
"_DecodeKey",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"dict",
".",
"attrindex",
".",
"HasBackward",
"(",
"key",
")",
":",
"return",
"self",
".",
"dict",
".",
"attrindex",
".",
"GetBackward",
"(",
"key",
")",
"return",
"key"
] | Turn a key into a string if possible | [
"Turn",
"a",
"key",
"into",
"a",
"string",
"if",
"possible"
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L146-L151 | train |
talkincode/txradius | txradius/radius/packet.py | Packet.AddAttribute | def AddAttribute(self, key, value):
"""Add an attribute to the packet.
:param key: attribute name or identification
:type key: string, attribute code or (vendor code, attribute code)
tuple
:param value: value
:type value: depends on type of attribute
... | python | def AddAttribute(self, key, value):
"""Add an attribute to the packet.
:param key: attribute name or identification
:type key: string, attribute code or (vendor code, attribute code)
tuple
:param value: value
:type value: depends on type of attribute
... | [
"def",
"AddAttribute",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"values",
"=",
"value",
"else",
":",
"values",
"=",
"[",
"value",
"]",
"(",
"key",
",",
"values",
")",
"=",
"self",
"... | Add an attribute to the packet.
:param key: attribute name or identification
:type key: string, attribute code or (vendor code, attribute code)
tuple
:param value: value
:type value: depends on type of attribute | [
"Add",
"an",
"attribute",
"to",
"the",
"packet",
"."
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L153-L167 | train |
talkincode/txradius | txradius/radius/packet.py | Packet.CreateAuthenticator | def CreateAuthenticator():
"""Create a packet autenticator. All RADIUS packets contain a sixteen
byte authenticator which is used to authenticate replies from the
RADIUS server and in the password hiding algorithm. This function
returns a suitable random string that can be used as an aut... | python | def CreateAuthenticator():
"""Create a packet autenticator. All RADIUS packets contain a sixteen
byte authenticator which is used to authenticate replies from the
RADIUS server and in the password hiding algorithm. This function
returns a suitable random string that can be used as an aut... | [
"def",
"CreateAuthenticator",
"(",
")",
":",
"data",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"16",
")",
":",
"data",
".",
"append",
"(",
"random_generator",
".",
"randrange",
"(",
"0",
",",
"256",
")",
")",
"if",
"six",
".",
"PY3",
":",
"r... | Create a packet autenticator. All RADIUS packets contain a sixteen
byte authenticator which is used to authenticate replies from the
RADIUS server and in the password hiding algorithm. This function
returns a suitable random string that can be used as an authenticator.
:return: valid pa... | [
"Create",
"a",
"packet",
"autenticator",
".",
"All",
"RADIUS",
"packets",
"contain",
"a",
"sixteen",
"byte",
"authenticator",
"which",
"is",
"used",
"to",
"authenticate",
"replies",
"from",
"the",
"RADIUS",
"server",
"and",
"in",
"the",
"password",
"hiding",
"... | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L208-L224 | train |
talkincode/txradius | txradius/radius/packet.py | Packet.DecodePacket | def DecodePacket(self, packet):
"""Initialize the object from raw packet data. Decode a packet as
received from the network and decode it.
:param packet: raw packet
:type packet: string"""
try:
(self.code, self.id, length, self.authenticator) = \
... | python | def DecodePacket(self, packet):
"""Initialize the object from raw packet data. Decode a packet as
received from the network and decode it.
:param packet: raw packet
:type packet: string"""
try:
(self.code, self.id, length, self.authenticator) = \
... | [
"def",
"DecodePacket",
"(",
"self",
",",
"packet",
")",
":",
"try",
":",
"(",
"self",
".",
"code",
",",
"self",
".",
"id",
",",
"length",
",",
"self",
".",
"authenticator",
")",
"=",
"struct",
".",
"unpack",
"(",
"'!BBH16s'",
",",
"packet",
"[",
"0... | Initialize the object from raw packet data. Decode a packet as
received from the network and decode it.
:param packet: raw packet
:type packet: string | [
"Initialize",
"the",
"object",
"from",
"raw",
"packet",
"data",
".",
"Decode",
"a",
"packet",
"as",
"received",
"from",
"the",
"network",
"and",
"decode",
"it",
"."
] | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L308-L350 | train |
talkincode/txradius | txradius/radius/packet.py | AuthPacket.PwDecrypt | def PwDecrypt(self, password):
"""Unobfuscate a RADIUS password. RADIUS hides passwords in packets by
using an algorithm based on the MD5 hash of the packet authenticator
and RADIUS secret. This function reverses the obfuscation process.
:param password: obfuscated form of password
... | python | def PwDecrypt(self, password):
"""Unobfuscate a RADIUS password. RADIUS hides passwords in packets by
using an algorithm based on the MD5 hash of the packet authenticator
and RADIUS secret. This function reverses the obfuscation process.
:param password: obfuscated form of password
... | [
"def",
"PwDecrypt",
"(",
"self",
",",
"password",
")",
":",
"buf",
"=",
"password",
"pw",
"=",
"six",
".",
"b",
"(",
"''",
")",
"last",
"=",
"self",
".",
"authenticator",
"while",
"buf",
":",
"hash",
"=",
"md5_constructor",
"(",
"self",
".",
"secret"... | Unobfuscate a RADIUS password. RADIUS hides passwords in packets by
using an algorithm based on the MD5 hash of the packet authenticator
and RADIUS secret. This function reverses the obfuscation process.
:param password: obfuscated form of password
:type password: binary string
... | [
"Unobfuscate",
"a",
"RADIUS",
"password",
".",
"RADIUS",
"hides",
"passwords",
"in",
"packets",
"by",
"using",
"an",
"algorithm",
"based",
"on",
"the",
"MD5",
"hash",
"of",
"the",
"packet",
"authenticator",
"and",
"RADIUS",
"secret",
".",
"This",
"function",
... | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L404-L432 | train |
talkincode/txradius | txradius/radius/packet.py | AuthPacket.PwCrypt | def PwCrypt(self, password):
"""Obfuscate password.
RADIUS hides passwords in packets by using an algorithm
based on the MD5 hash of the packet authenticator and RADIUS
secret. If no authenticator has been set before calling PwCrypt
one is created automatically. Changing the auth... | python | def PwCrypt(self, password):
"""Obfuscate password.
RADIUS hides passwords in packets by using an algorithm
based on the MD5 hash of the packet authenticator and RADIUS
secret. If no authenticator has been set before calling PwCrypt
one is created automatically. Changing the auth... | [
"def",
"PwCrypt",
"(",
"self",
",",
"password",
")",
":",
"if",
"self",
".",
"authenticator",
"is",
"None",
":",
"self",
".",
"authenticator",
"=",
"self",
".",
"CreateAuthenticator",
"(",
")",
"if",
"isinstance",
"(",
"password",
",",
"six",
".",
"text_... | Obfuscate password.
RADIUS hides passwords in packets by using an algorithm
based on the MD5 hash of the packet authenticator and RADIUS
secret. If no authenticator has been set before calling PwCrypt
one is created automatically. Changing the authenticator after
setting a passwo... | [
"Obfuscate",
"password",
".",
"RADIUS",
"hides",
"passwords",
"in",
"packets",
"by",
"using",
"an",
"algorithm",
"based",
"on",
"the",
"MD5",
"hash",
"of",
"the",
"packet",
"authenticator",
"and",
"RADIUS",
"secret",
".",
"If",
"no",
"authenticator",
"has",
... | b86fdbc9be41183680b82b07d3a8e8ea10926e01 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/radius/packet.py#L434-L474 | train |
bitesofcode/projexui | projexui/widgets/xtoolbar.py | XToolBar.clear | def clear(self):
"""
Clears out this toolbar from the system.
"""
# preserve the collapse button
super(XToolBar, self).clear()
# clears out the toolbar
if self.isCollapsable():
self._collapseButton = QToolButton(self)
self._collaps... | python | def clear(self):
"""
Clears out this toolbar from the system.
"""
# preserve the collapse button
super(XToolBar, self).clear()
# clears out the toolbar
if self.isCollapsable():
self._collapseButton = QToolButton(self)
self._collaps... | [
"def",
"clear",
"(",
"self",
")",
":",
"super",
"(",
"XToolBar",
",",
"self",
")",
".",
"clear",
"(",
")",
"if",
"self",
".",
"isCollapsable",
"(",
")",
":",
"self",
".",
"_collapseButton",
"=",
"QToolButton",
"(",
"self",
")",
"self",
".",
"_collaps... | Clears out this toolbar from the system. | [
"Clears",
"out",
"this",
"toolbar",
"from",
"the",
"system",
"."
] | f18a73bec84df90b034ca69b9deea118dbedfc4d | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtoolbar.py#L64-L87 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.