repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
RockFeng0/rtsf-web | webuidriver/actions.py | WebActions.Alt | def Alt(cls, key):
""" 在指定元素上执行alt组合事件
@note: key event -> alt + key
@param key: 如'X'
"""
element = cls._element()
element.send_keys(Keys.ALT, key) | python | def Alt(cls, key):
""" 在指定元素上执行alt组合事件
@note: key event -> alt + key
@param key: 如'X'
"""
element = cls._element()
element.send_keys(Keys.ALT, key) | [
"def",
"Alt",
"(",
"cls",
",",
"key",
")",
":",
"element",
"=",
"cls",
".",
"_element",
"(",
")",
"element",
".",
"send_keys",
"(",
"Keys",
".",
"ALT",
",",
"key",
")"
] | 在指定元素上执行alt组合事件
@note: key event -> alt + key
@param key: 如'X' | [
"在指定元素上执行alt组合事件"
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/actions.py#L647-L653 | train |
RockFeng0/rtsf-web | webuidriver/actions.py | WebActions.Focus | def Focus(cls):
""" 在指定输入框发送 Null, 用于设置焦点
@note: key event -> NULL
"""
element = cls._element()
# element.send_keys(Keys.NULL)
action = ActionChains(Web.driver)
action.send_keys_to_element(element, Keys.NULL)
actio... | python | def Focus(cls):
""" 在指定输入框发送 Null, 用于设置焦点
@note: key event -> NULL
"""
element = cls._element()
# element.send_keys(Keys.NULL)
action = ActionChains(Web.driver)
action.send_keys_to_element(element, Keys.NULL)
actio... | [
"def",
"Focus",
"(",
"cls",
")",
":",
"element",
"=",
"cls",
".",
"_element",
"(",
")",
"# element.send_keys(Keys.NULL) \r",
"action",
"=",
"ActionChains",
"(",
"Web",
".",
"driver",
")",
"action",
".",
"send_keys_to_element",
"(",
"element",
",",... | 在指定输入框发送 Null, 用于设置焦点
@note: key event -> NULL | [
"在指定输入框发送",
"Null,",
"用于设置焦点"
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/actions.py#L693-L702 | train |
RockFeng0/rtsf-web | webuidriver/actions.py | WebActions.Upload | def Upload(cls, filename):
""" 文件上传, 非原生input
@todo: some upload.exe not prepared
@param file: 文件名(文件必须存在在工程resource目录下), upload.exe工具放在工程tools目录下
"""
raise Exception("to do")
TOOLS_PATH = ""
RESOURCE_PATH = ""
tool_4path = os.path.... | python | def Upload(cls, filename):
""" 文件上传, 非原生input
@todo: some upload.exe not prepared
@param file: 文件名(文件必须存在在工程resource目录下), upload.exe工具放在工程tools目录下
"""
raise Exception("to do")
TOOLS_PATH = ""
RESOURCE_PATH = ""
tool_4path = os.path.... | [
"def",
"Upload",
"(",
"cls",
",",
"filename",
")",
":",
"raise",
"Exception",
"(",
"\"to do\"",
")",
"TOOLS_PATH",
"=",
"\"\"",
"RESOURCE_PATH",
"=",
"\"\"",
"tool_4path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"TOOLS_PATH",
",",
"\"upload.exe\"",
")",
... | 文件上传, 非原生input
@todo: some upload.exe not prepared
@param file: 文件名(文件必须存在在工程resource目录下), upload.exe工具放在工程tools目录下 | [
"文件上传,",
"非原生input"
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/actions.py#L706-L723 | train |
RockFeng0/rtsf-web | webuidriver/actions.py | WebActions.UploadType | def UploadType(cls, file_path):
""" 上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-image-file" name="test" accept="image/gif">,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径
@param file_name: 文件名(文件必须存在在工程resource目录下)
"""
if not os.path.isabs(file_path):
... | python | def UploadType(cls, file_path):
""" 上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-image-file" name="test" accept="image/gif">,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径
@param file_name: 文件名(文件必须存在在工程resource目录下)
"""
if not os.path.isabs(file_path):
... | [
"def",
"UploadType",
"(",
"cls",
",",
"file_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"file_path",
")",
":",
"return",
"False",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"cls",
".",
"SendKeys",
"(... | 上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-image-file" name="test" accept="image/gif">,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径
@param file_name: 文件名(文件必须存在在工程resource目录下) | [
"上传,",
"一般,上传页面如果是input",
"原生file文件框",
"如:",
"<input",
"type",
"=",
"file",
"id",
"=",
"test",
"-",
"image",
"-",
"file",
"name",
"=",
"test",
"accept",
"=",
"image",
"/",
"gif",
">",
",像这样的,定位到该元素,然后使用",
"send_keys",
"上传的文件的绝对路径"
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/actions.py#L726-L736 | train |
BlackEarth/bl | bl/dict.py | Dict.update | def update(xCqNck7t, **kwargs):
"""Updates the Dict with the given values. Turns internal dicts into Dicts."""
def dict_list_val(inlist):
l = []
for i in inlist:
if type(i)==dict:
l.append(Dict(**i))
elif type(i)==list:
... | python | def update(xCqNck7t, **kwargs):
"""Updates the Dict with the given values. Turns internal dicts into Dicts."""
def dict_list_val(inlist):
l = []
for i in inlist:
if type(i)==dict:
l.append(Dict(**i))
elif type(i)==list:
... | [
"def",
"update",
"(",
"xCqNck7t",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"dict_list_val",
"(",
"inlist",
")",
":",
"l",
"=",
"[",
"]",
"for",
"i",
"in",
"inlist",
":",
"if",
"type",
"(",
"i",
")",
"==",
"dict",
":",
"l",
".",
"append",
"(",
... | Updates the Dict with the given values. Turns internal dicts into Dicts. | [
"Updates",
"the",
"Dict",
"with",
"the",
"given",
"values",
".",
"Turns",
"internal",
"dicts",
"into",
"Dicts",
"."
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/dict.py#L48-L68 | train |
BlackEarth/bl | bl/dict.py | Dict.keys | def keys(self, key=None, reverse=False):
"""sort the keys before returning them"""
ks = sorted(list(dict.keys(self)), key=key, reverse=reverse)
return ks | python | def keys(self, key=None, reverse=False):
"""sort the keys before returning them"""
ks = sorted(list(dict.keys(self)), key=key, reverse=reverse)
return ks | [
"def",
"keys",
"(",
"self",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"ks",
"=",
"sorted",
"(",
"list",
"(",
"dict",
".",
"keys",
"(",
"self",
")",
")",
",",
"key",
"=",
"key",
",",
"reverse",
"=",
"reverse",
")",
"return... | sort the keys before returning them | [
"sort",
"the",
"keys",
"before",
"returning",
"them"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/dict.py#L83-L86 | train |
RockFeng0/rtsf-web | webuidriver/remote/SeleniumJar.py | SeleniumJar.hub | def hub(self, port):
''' java -jar selenium-server.jar -role hub -port 4444
@param port: listen port of selenium hub
'''
self._ip = "localhost"
self._port = port
self.command = [self._conf["java_path"], "-jar", self._conf["jar_path"], "-port", str(port), "-role",... | python | def hub(self, port):
''' java -jar selenium-server.jar -role hub -port 4444
@param port: listen port of selenium hub
'''
self._ip = "localhost"
self._port = port
self.command = [self._conf["java_path"], "-jar", self._conf["jar_path"], "-port", str(port), "-role",... | [
"def",
"hub",
"(",
"self",
",",
"port",
")",
":",
"self",
".",
"_ip",
"=",
"\"localhost\"",
"self",
".",
"_port",
"=",
"port",
"self",
".",
"command",
"=",
"[",
"self",
".",
"_conf",
"[",
"\"java_path\"",
"]",
",",
"\"-jar\"",
",",
"self",
".",
"_c... | java -jar selenium-server.jar -role hub -port 4444
@param port: listen port of selenium hub | [
"java",
"-",
"jar",
"selenium",
"-",
"server",
".",
"jar",
"-",
"role",
"hub",
"-",
"port",
"4444"
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/remote/SeleniumJar.py#L31-L38 | train |
RockFeng0/rtsf-web | webuidriver/remote/SeleniumJar.py | SeleniumJar.node | def node(self,port, hub_address=("localhost", 4444)):
''' java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/
@param port: listen port of selenium node
@param hub_address: hub address which node will connect to
'''
self._ip, self._... | python | def node(self,port, hub_address=("localhost", 4444)):
''' java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/
@param port: listen port of selenium node
@param hub_address: hub address which node will connect to
'''
self._ip, self._... | [
"def",
"node",
"(",
"self",
",",
"port",
",",
"hub_address",
"=",
"(",
"\"localhost\"",
",",
"4444",
")",
")",
":",
"self",
".",
"_ip",
",",
"self",
".",
"_port",
"=",
"hub_address",
"self",
".",
"command",
"=",
"[",
"self",
".",
"_conf",
"[",
"\"j... | java -jar selenium-server.jar -role node -port 5555 -hub http://127.0.0.1:4444/grid/register/
@param port: listen port of selenium node
@param hub_address: hub address which node will connect to | [
"java",
"-",
"jar",
"selenium",
"-",
"server",
".",
"jar",
"-",
"role",
"node",
"-",
"port",
"5555",
"-",
"hub",
"http",
":",
"//",
"127",
".",
"0",
".",
"0",
".",
"1",
":",
"4444",
"/",
"grid",
"/",
"register",
"/"
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/remote/SeleniumJar.py#L40-L47 | train |
RockFeng0/rtsf-web | webuidriver/remote/SeleniumJar.py | SeleniumJar.start_server | def start_server(self):
"""start the selenium Remote Server."""
self.__subp = subprocess.Popen(self.command)
#print("\tselenium jar pid[%s] is running." %self.__subp.pid)
time.sleep(2) | python | def start_server(self):
"""start the selenium Remote Server."""
self.__subp = subprocess.Popen(self.command)
#print("\tselenium jar pid[%s] is running." %self.__subp.pid)
time.sleep(2) | [
"def",
"start_server",
"(",
"self",
")",
":",
"self",
".",
"__subp",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"command",
")",
"#print(\"\\tselenium jar pid[%s] is running.\" %self.__subp.pid) \r",
"time",
".",
"sleep",
"(",
"2",
")"
] | start the selenium Remote Server. | [
"start",
"the",
"selenium",
"Remote",
"Server",
"."
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/remote/SeleniumJar.py#L49-L53 | train |
RockFeng0/rtsf-web | webuidriver/remote/SeleniumJar.py | SeleniumJar.is_runnnig | def is_runnnig(self):
"""Determine whether hub server is running
:return:True or False
"""
resp = None
try:
resp = requests.get("http://%s:%s" %(self._ip, self._port))
if resp.status_code == 200:
return True
else:
... | python | def is_runnnig(self):
"""Determine whether hub server is running
:return:True or False
"""
resp = None
try:
resp = requests.get("http://%s:%s" %(self._ip, self._port))
if resp.status_code == 200:
return True
else:
... | [
"def",
"is_runnnig",
"(",
"self",
")",
":",
"resp",
"=",
"None",
"try",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"\"http://%s:%s\"",
"%",
"(",
"self",
".",
"_ip",
",",
"self",
".",
"_port",
")",
")",
"if",
"resp",
".",
"status_code",
"==",
"2... | Determine whether hub server is running
:return:True or False | [
"Determine",
"whether",
"hub",
"server",
"is",
"running",
":",
"return",
":",
"True",
"or",
"False"
] | ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71 | https://github.com/RockFeng0/rtsf-web/blob/ceabcf62ddf1c969a97b5c7a4a4c547198b6ea71/webuidriver/remote/SeleniumJar.py#L67-L80 | train |
mvcisback/py-aiger-bv | aigerbv/common.py | negate_gate | def negate_gate(wordlen, input='x', output='~x'):
"""Implements two's complement negation."""
neg = bitwise_negate(wordlen, input, "tmp")
inc = inc_gate(wordlen, "tmp", output)
return neg >> inc | python | def negate_gate(wordlen, input='x', output='~x'):
"""Implements two's complement negation."""
neg = bitwise_negate(wordlen, input, "tmp")
inc = inc_gate(wordlen, "tmp", output)
return neg >> inc | [
"def",
"negate_gate",
"(",
"wordlen",
",",
"input",
"=",
"'x'",
",",
"output",
"=",
"'~x'",
")",
":",
"neg",
"=",
"bitwise_negate",
"(",
"wordlen",
",",
"input",
",",
"\"tmp\"",
")",
"inc",
"=",
"inc_gate",
"(",
"wordlen",
",",
"\"tmp\"",
",",
"output"... | Implements two's complement negation. | [
"Implements",
"two",
"s",
"complement",
"negation",
"."
] | 855819844c429c35cdd8dc0b134bcd11f7b2fda3 | https://github.com/mvcisback/py-aiger-bv/blob/855819844c429c35cdd8dc0b134bcd11f7b2fda3/aigerbv/common.py#L268-L272 | train |
mvcisback/py-aiger-bv | aigerbv/common.py | kmodels | def kmodels(wordlen: int, k: int, input=None, output=None):
"""Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Ch... | python | def kmodels(wordlen: int, k: int, input=None, output=None):
"""Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Ch... | [
"def",
"kmodels",
"(",
"wordlen",
":",
"int",
",",
"k",
":",
"int",
",",
"input",
"=",
"None",
",",
"output",
"=",
"None",
")",
":",
"assert",
"0",
"<=",
"k",
"<",
"2",
"**",
"wordlen",
"if",
"output",
"is",
"None",
":",
"output",
"=",
"_fresh",
... | Return a circuit taking a wordlen bitvector where only k
valuations return True. Uses encoding from [1].
Note that this is equivalent to (~x < k).
- TODO: Add automated simplification so that the circuits
are equiv.
[1]: Chakraborty, Supratik, et al. "From Weighted to Unweighted Model
... | [
"Return",
"a",
"circuit",
"taking",
"a",
"wordlen",
"bitvector",
"where",
"only",
"k",
"valuations",
"return",
"True",
".",
"Uses",
"encoding",
"from",
"[",
"1",
"]",
"."
] | 855819844c429c35cdd8dc0b134bcd11f7b2fda3 | https://github.com/mvcisback/py-aiger-bv/blob/855819844c429c35cdd8dc0b134bcd11f7b2fda3/aigerbv/common.py#L430-L464 | train |
pmacosta/pmisc | pmisc/misc.py | flatten_list | def flatten_list(lobj):
"""
Recursively flattens a list.
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
ret = []
for item in lobj:
... | python | def flatten_list(lobj):
"""
Recursively flattens a list.
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7]
"""
ret = []
for item in lobj:
... | [
"def",
"flatten_list",
"(",
"lobj",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"item",
"in",
"lobj",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"for",
"sub_item",
"in",
"flatten_list",
"(",
"item",
")",
":",
"ret",
".",
"append",
"(",... | Recursively flattens a list.
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7] | [
"Recursively",
"flattens",
"a",
"list",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/misc.py#L10-L32 | train |
CogSciUOS/StudDP | studdp/config.py | Config.auth | def auth(self):
"""
tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the
configuration file.
"""
username = self._settings["username"]
if not username:
raise ValueError("Use... | python | def auth(self):
"""
tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the
configuration file.
"""
username = self._settings["username"]
if not username:
raise ValueError("Use... | [
"def",
"auth",
"(",
"self",
")",
":",
"username",
"=",
"self",
".",
"_settings",
"[",
"\"username\"",
"]",
"if",
"not",
"username",
":",
"raise",
"ValueError",
"(",
"\"Username was not configured in %s\"",
"%",
"CONFIG_FILE",
")",
"if",
"self",
".",
"_settings... | tuple of (username, password). if use_keyring is set to true the password will be queried from the local keyring instead of taken from the
configuration file. | [
"tuple",
"of",
"(",
"username",
"password",
")",
".",
"if",
"use_keyring",
"is",
"set",
"to",
"true",
"the",
"password",
"will",
"be",
"queried",
"from",
"the",
"local",
"keyring",
"instead",
"of",
"taken",
"from",
"the",
"configuration",
"file",
"."
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/config.py#L98-L116 | train |
CogSciUOS/StudDP | studdp/config.py | Config.load | def load(self, file=CONFIG_FILE):
"""
load a configuration file. loads default config if file is not found
"""
if not os.path.exists(file):
print("Config file was not found under %s. Default file has been created" % CONFIG_FILE)
self._settings = yaml.load(DEFAULT_... | python | def load(self, file=CONFIG_FILE):
"""
load a configuration file. loads default config if file is not found
"""
if not os.path.exists(file):
print("Config file was not found under %s. Default file has been created" % CONFIG_FILE)
self._settings = yaml.load(DEFAULT_... | [
"def",
"load",
"(",
"self",
",",
"file",
"=",
"CONFIG_FILE",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file",
")",
":",
"print",
"(",
"\"Config file was not found under %s. Default file has been created\"",
"%",
"CONFIG_FILE",
")",
"self",
... | load a configuration file. loads default config if file is not found | [
"load",
"a",
"configuration",
"file",
".",
"loads",
"default",
"config",
"if",
"file",
"is",
"not",
"found"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/config.py#L137-L147 | train |
CogSciUOS/StudDP | studdp/config.py | Config.save | def save(self, file=CONFIG_FILE):
"""
Save configuration to provided path as a yaml file
"""
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "w") as f:
yaml.dump(self._settings, f, Dumper=yaml.RoundTripDumper, width=float("inf")) | python | def save(self, file=CONFIG_FILE):
"""
Save configuration to provided path as a yaml file
"""
os.makedirs(os.path.dirname(file), exist_ok=True)
with open(file, "w") as f:
yaml.dump(self._settings, f, Dumper=yaml.RoundTripDumper, width=float("inf")) | [
"def",
"save",
"(",
"self",
",",
"file",
"=",
"CONFIG_FILE",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"file",
")",
",",
"exist_ok",
"=",
"True",
")",
"with",
"open",
"(",
"file",
",",
"\"w\"",
")",
"as",
"f",
... | Save configuration to provided path as a yaml file | [
"Save",
"configuration",
"to",
"provided",
"path",
"as",
"a",
"yaml",
"file"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/config.py#L149-L155 | train |
CogSciUOS/StudDP | studdp/config.py | Config.selection_dialog | def selection_dialog(self, courses):
"""
opens a curses/picker based interface to select courses that should be downloaded.
"""
selected = list(filter(lambda x: x.course.id in self._settings["selected_courses"], courses))
selection = Picker(
title="Select courses to d... | python | def selection_dialog(self, courses):
"""
opens a curses/picker based interface to select courses that should be downloaded.
"""
selected = list(filter(lambda x: x.course.id in self._settings["selected_courses"], courses))
selection = Picker(
title="Select courses to d... | [
"def",
"selection_dialog",
"(",
"self",
",",
"courses",
")",
":",
"selected",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"course",
".",
"id",
"in",
"self",
".",
"_settings",
"[",
"\"selected_courses\"",
"]",
",",
"courses",
")",
")"... | opens a curses/picker based interface to select courses that should be downloaded. | [
"opens",
"a",
"curses",
"/",
"picker",
"based",
"interface",
"to",
"select",
"courses",
"that",
"should",
"be",
"downloaded",
"."
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/config.py#L172-L184 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.create | def create(self):
"""Create the corresponding index. Will overwrite existing indexes of the same name."""
body = dict()
if self.mapping is not None:
body['mappings'] = self.mapping
if self.settings is not None:
body['settings'] = self.settings
else:
... | python | def create(self):
"""Create the corresponding index. Will overwrite existing indexes of the same name."""
body = dict()
if self.mapping is not None:
body['mappings'] = self.mapping
if self.settings is not None:
body['settings'] = self.settings
else:
... | [
"def",
"create",
"(",
"self",
")",
":",
"body",
"=",
"dict",
"(",
")",
"if",
"self",
".",
"mapping",
"is",
"not",
"None",
":",
"body",
"[",
"'mappings'",
"]",
"=",
"self",
".",
"mapping",
"if",
"self",
".",
"settings",
"is",
"not",
"None",
":",
"... | Create the corresponding index. Will overwrite existing indexes of the same name. | [
"Create",
"the",
"corresponding",
"index",
".",
"Will",
"overwrite",
"existing",
"indexes",
"of",
"the",
"same",
"name",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L75-L84 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.search | def search(self, query=None, size=100, unpack=True):
"""Search the index with a query.
Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned.
The default number of hits returned is 100.
"""
logging.in... | python | def search(self, query=None, size=100, unpack=True):
"""Search the index with a query.
Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned.
The default number of hits returned is 100.
"""
logging.in... | [
"def",
"search",
"(",
"self",
",",
"query",
"=",
"None",
",",
"size",
"=",
"100",
",",
"unpack",
"=",
"True",
")",
":",
"logging",
".",
"info",
"(",
"'Download all documents from index %s.'",
",",
"self",
".",
"index",
")",
"if",
"query",
"is",
"None",
... | Search the index with a query.
Can at most return 10'000 results from a search. If the search would yield more than 10'000 hits, only the first 10'000 are returned.
The default number of hits returned is 100. | [
"Search",
"the",
"index",
"with",
"a",
"query",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L93-L112 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.scan_index | def scan_index(self, query: Union[Dict[str, str], None] = None) -> List[Dict[str, str]]:
"""Scan the index with the query.
Will return any number of results above 10'000. Important to note is, that
all the data is loaded into memory at once and returned. This works only with small
data ... | python | def scan_index(self, query: Union[Dict[str, str], None] = None) -> List[Dict[str, str]]:
"""Scan the index with the query.
Will return any number of results above 10'000. Important to note is, that
all the data is loaded into memory at once and returned. This works only with small
data ... | [
"def",
"scan_index",
"(",
"self",
",",
"query",
":",
"Union",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
",",
"None",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"if",
"query",
"is",
"None",
":",
"q... | Scan the index with the query.
Will return any number of results above 10'000. Important to note is, that
all the data is loaded into memory at once and returned. This works only with small
data sets. Use scroll otherwise which returns a generator to cycle through the resources
in set c... | [
"Scan",
"the",
"index",
"with",
"the",
"query",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L114-L135 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.scroll | def scroll(self, query=None, scroll='5m', size=100, unpack=True):
"""Scroll an index with the specified search query.
Works as a generator. Will yield `size` results per iteration until all hits are returned.
"""
query = self.match_all if query is None else query
response = self... | python | def scroll(self, query=None, scroll='5m', size=100, unpack=True):
"""Scroll an index with the specified search query.
Works as a generator. Will yield `size` results per iteration until all hits are returned.
"""
query = self.match_all if query is None else query
response = self... | [
"def",
"scroll",
"(",
"self",
",",
"query",
"=",
"None",
",",
"scroll",
"=",
"'5m'",
",",
"size",
"=",
"100",
",",
"unpack",
"=",
"True",
")",
":",
"query",
"=",
"self",
".",
"match_all",
"if",
"query",
"is",
"None",
"else",
"query",
"response",
"=... | Scroll an index with the specified search query.
Works as a generator. Will yield `size` results per iteration until all hits are returned. | [
"Scroll",
"an",
"index",
"with",
"the",
"specified",
"search",
"query",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L137-L151 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.get | def get(self, identifier):
"""Fetch document by _id.
Returns None if it is not found. (Will log a warning if not found as well. Should not be used
to search an id.)"""
logging.info('Download document with id ' + str(identifier) + '.')
try:
record = self.instance.get(... | python | def get(self, identifier):
"""Fetch document by _id.
Returns None if it is not found. (Will log a warning if not found as well. Should not be used
to search an id.)"""
logging.info('Download document with id ' + str(identifier) + '.')
try:
record = self.instance.get(... | [
"def",
"get",
"(",
"self",
",",
"identifier",
")",
":",
"logging",
".",
"info",
"(",
"'Download document with id '",
"+",
"str",
"(",
"identifier",
")",
"+",
"'.'",
")",
"try",
":",
"record",
"=",
"self",
".",
"instance",
".",
"get",
"(",
"index",
"=",... | Fetch document by _id.
Returns None if it is not found. (Will log a warning if not found as well. Should not be used
to search an id.) | [
"Fetch",
"document",
"by",
"_id",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L153-L166 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.index_into | def index_into(self, document, id) -> bool:
"""Index a single document into the index."""
try:
self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id)
except RequestError as ex:
logging.error(ex)
retu... | python | def index_into(self, document, id) -> bool:
"""Index a single document into the index."""
try:
self.instance.index(index=self.index, doc_type=self.doc_type, body=json.dumps(document, ensure_ascii=False), id=id)
except RequestError as ex:
logging.error(ex)
retu... | [
"def",
"index_into",
"(",
"self",
",",
"document",
",",
"id",
")",
"->",
"bool",
":",
"try",
":",
"self",
".",
"instance",
".",
"index",
"(",
"index",
"=",
"self",
".",
"index",
",",
"doc_type",
"=",
"self",
".",
"doc_type",
",",
"body",
"=",
"json... | Index a single document into the index. | [
"Index",
"a",
"single",
"document",
"into",
"the",
"index",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L168-L176 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.delete | def delete(self, doc_id: str) -> bool:
"""Delete a document with id."""
try:
self.instance.delete(self.index, self.doc_type, doc_id)
except RequestError as ex:
logging.error(ex)
return False
else:
return True | python | def delete(self, doc_id: str) -> bool:
"""Delete a document with id."""
try:
self.instance.delete(self.index, self.doc_type, doc_id)
except RequestError as ex:
logging.error(ex)
return False
else:
return True | [
"def",
"delete",
"(",
"self",
",",
"doc_id",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"self",
".",
"instance",
".",
"delete",
"(",
"self",
".",
"index",
",",
"self",
".",
"doc_type",
",",
"doc_id",
")",
"except",
"RequestError",
"as",
"ex",
... | Delete a document with id. | [
"Delete",
"a",
"document",
"with",
"id",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L178-L187 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.update | def update(self, doc: dict, doc_id: str):
"""Partial update to a single document.
Uses the Update API with the specified partial document.
"""
body = {
'doc': doc
}
self.instance.update(self.index, self.doc_type, doc_id, body=body) | python | def update(self, doc: dict, doc_id: str):
"""Partial update to a single document.
Uses the Update API with the specified partial document.
"""
body = {
'doc': doc
}
self.instance.update(self.index, self.doc_type, doc_id, body=body) | [
"def",
"update",
"(",
"self",
",",
"doc",
":",
"dict",
",",
"doc_id",
":",
"str",
")",
":",
"body",
"=",
"{",
"'doc'",
":",
"doc",
"}",
"self",
".",
"instance",
".",
"update",
"(",
"self",
".",
"index",
",",
"self",
".",
"doc_type",
",",
"doc_id"... | Partial update to a single document.
Uses the Update API with the specified partial document. | [
"Partial",
"update",
"to",
"a",
"single",
"document",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L189-L197 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.script_update | def script_update(self, script: str, params: Union[dict, None], doc_id: str):
"""Uses painless script to update a document.
See documentation for more information.
"""
body = {
'script': {
'source': script,
'lang': 'painless'
}
... | python | def script_update(self, script: str, params: Union[dict, None], doc_id: str):
"""Uses painless script to update a document.
See documentation for more information.
"""
body = {
'script': {
'source': script,
'lang': 'painless'
}
... | [
"def",
"script_update",
"(",
"self",
",",
"script",
":",
"str",
",",
"params",
":",
"Union",
"[",
"dict",
",",
"None",
"]",
",",
"doc_id",
":",
"str",
")",
":",
"body",
"=",
"{",
"'script'",
":",
"{",
"'source'",
":",
"script",
",",
"'lang'",
":",
... | Uses painless script to update a document.
See documentation for more information. | [
"Uses",
"painless",
"script",
"to",
"update",
"a",
"document",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L199-L212 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.bulk | def bulk(self, data: List[Dict[str, str]], identifier_key: str, op_type='index', upsert=False, keep_id_key=False) -> bool:
"""
Takes a list of dictionaries and an identifier key and indexes everything into this index.
:param data: List of dictionaries containing the data to be indexe... | python | def bulk(self, data: List[Dict[str, str]], identifier_key: str, op_type='index', upsert=False, keep_id_key=False) -> bool:
"""
Takes a list of dictionaries and an identifier key and indexes everything into this index.
:param data: List of dictionaries containing the data to be indexe... | [
"def",
"bulk",
"(",
"self",
",",
"data",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
",",
"identifier_key",
":",
"str",
",",
"op_type",
"=",
"'index'",
",",
"upsert",
"=",
"False",
",",
"keep_id_key",
"=",
"False",
")",
"->",
"bool"... | Takes a list of dictionaries and an identifier key and indexes everything into this index.
:param data: List of dictionaries containing the data to be indexed.
:param identifier_key: The name of the dictionary element which should be used as _id. This will be removed from
... | [
"Takes",
"a",
"list",
"of",
"dictionaries",
"and",
"an",
"identifier",
"key",
"and",
"indexes",
"everything",
"into",
"this",
"index",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L214-L257 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.reindex | def reindex(self, new_index_name: str, identifier_key: str, **kwargs) -> 'ElasticIndex':
"""Reindex the entire index.
Scrolls the old index and bulk indexes all data into the new index.
:param new_index_name:
:param identifier_key:
:param kwargs: Overwrite ElasticIndex... | python | def reindex(self, new_index_name: str, identifier_key: str, **kwargs) -> 'ElasticIndex':
"""Reindex the entire index.
Scrolls the old index and bulk indexes all data into the new index.
:param new_index_name:
:param identifier_key:
:param kwargs: Overwrite ElasticIndex... | [
"def",
"reindex",
"(",
"self",
",",
"new_index_name",
":",
"str",
",",
"identifier_key",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"'ElasticIndex'",
":",
"if",
"'url'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'url'",
"]",
"=",
"self",
".",
... | Reindex the entire index.
Scrolls the old index and bulk indexes all data into the new index.
:param new_index_name:
:param identifier_key:
:param kwargs: Overwrite ElasticIndex __init__ params.
:return: | [
"Reindex",
"the",
"entire",
"index",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L259-L279 | train |
UB-UNIBAS/simple-elastic | simple_elastic/index.py | ElasticIndex.dump | def dump(self, path: str, file_name: str = "", **kwargs: dict):
"""
Dumps the entire index into a json file.
:param path: The path to directory where the dump should be stored.
:param file_name: Name of the file the dump should be stored in. If empty the index name is used.
:pa... | python | def dump(self, path: str, file_name: str = "", **kwargs: dict):
"""
Dumps the entire index into a json file.
:param path: The path to directory where the dump should be stored.
:param file_name: Name of the file the dump should be stored in. If empty the index name is used.
:pa... | [
"def",
"dump",
"(",
"self",
",",
"path",
":",
"str",
",",
"file_name",
":",
"str",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
":",
"dict",
")",
":",
"export",
"=",
"list",
"(",
")",
"for",
"results",
"in",
"self",
".",
"scroll",
"(",
")",
":",
"expo... | Dumps the entire index into a json file.
:param path: The path to directory where the dump should be stored.
:param file_name: Name of the file the dump should be stored in. If empty the index name is used.
:param kwargs: Keyword arguments for the json converter. (ex. indent=4, ensure_ascii=Fa... | [
"Dumps",
"the",
"entire",
"index",
"into",
"a",
"json",
"file",
"."
] | 54f2fdd3405a7eafbf8873f337da263b8d47532a | https://github.com/UB-UNIBAS/simple-elastic/blob/54f2fdd3405a7eafbf8873f337da263b8d47532a/simple_elastic/index.py#L281-L306 | train |
CogSciUOS/StudDP | studdp/studdp.py | main | def main():
"""
parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon
"""
(options, _) = _parse_args()
if options.change_password:
c.keyring_set_password(c["username"])
sys.exit(0)
if options.select:
courses... | python | def main():
"""
parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon
"""
(options, _) = _parse_args()
if options.change_password:
c.keyring_set_password(c["username"])
sys.exit(0)
if options.select:
courses... | [
"def",
"main",
"(",
")",
":",
"(",
"options",
",",
"_",
")",
"=",
"_parse_args",
"(",
")",
"if",
"options",
".",
"change_password",
":",
"c",
".",
"keyring_set_password",
"(",
"c",
"[",
"\"username\"",
"]",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"... | parse command line options and either launch some configuration dialog or start an instance of _MainLoop as a daemon | [
"parse",
"command",
"line",
"options",
"and",
"either",
"launch",
"some",
"configuration",
"dialog",
"or",
"start",
"an",
"instance",
"of",
"_MainLoop",
"as",
"a",
"daemon"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/studdp.py#L71-L102 | train |
willkg/socorro-siggen | siggen/generator.py | SignatureGenerator.generate | def generate(self, signature_data):
"""Takes data and returns a signature
:arg dict signature_data: data to use to generate a signature
:returns: ``Result`` instance
"""
result = Result()
for rule in self.pipeline:
rule_name = rule.__class__.__name__
... | python | def generate(self, signature_data):
"""Takes data and returns a signature
:arg dict signature_data: data to use to generate a signature
:returns: ``Result`` instance
"""
result = Result()
for rule in self.pipeline:
rule_name = rule.__class__.__name__
... | [
"def",
"generate",
"(",
"self",
",",
"signature_data",
")",
":",
"result",
"=",
"Result",
"(",
")",
"for",
"rule",
"in",
"self",
".",
"pipeline",
":",
"rule_name",
"=",
"rule",
".",
"__class__",
".",
"__name__",
"try",
":",
"if",
"rule",
".",
"predicat... | Takes data and returns a signature
:arg dict signature_data: data to use to generate a signature
:returns: ``Result`` instance | [
"Takes",
"data",
"and",
"returns",
"a",
"signature"
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/generator.py#L74-L100 | train |
mvcisback/py-aiger-bv | aigerbv/aigbv.py | _blast | def _blast(bvname2vals, name_map):
"""Helper function to expand (blast) str -> int map into str ->
bool map. This is used to send word level inputs to aiger."""
if len(name_map) == 0:
return dict()
return fn.merge(*(dict(zip(names, bvname2vals[bvname]))
for bvname, names in... | python | def _blast(bvname2vals, name_map):
"""Helper function to expand (blast) str -> int map into str ->
bool map. This is used to send word level inputs to aiger."""
if len(name_map) == 0:
return dict()
return fn.merge(*(dict(zip(names, bvname2vals[bvname]))
for bvname, names in... | [
"def",
"_blast",
"(",
"bvname2vals",
",",
"name_map",
")",
":",
"if",
"len",
"(",
"name_map",
")",
"==",
"0",
":",
"return",
"dict",
"(",
")",
"return",
"fn",
".",
"merge",
"(",
"*",
"(",
"dict",
"(",
"zip",
"(",
"names",
",",
"bvname2vals",
"[",
... | Helper function to expand (blast) str -> int map into str ->
bool map. This is used to send word level inputs to aiger. | [
"Helper",
"function",
"to",
"expand",
"(",
"blast",
")",
"str",
"-",
">",
"int",
"map",
"into",
"str",
"-",
">",
"bool",
"map",
".",
"This",
"is",
"used",
"to",
"send",
"word",
"level",
"inputs",
"to",
"aiger",
"."
] | 855819844c429c35cdd8dc0b134bcd11f7b2fda3 | https://github.com/mvcisback/py-aiger-bv/blob/855819844c429c35cdd8dc0b134bcd11f7b2fda3/aigerbv/aigbv.py#L13-L19 | train |
mvcisback/py-aiger-bv | aigerbv/aigbv.py | _unblast | def _unblast(name2vals, name_map):
"""Helper function to lift str -> bool maps used by aiger
to the word level. Dual of the `_blast` function."""
def _collect(names):
return tuple(name2vals[n] for n in names)
return {bvname: _collect(names) for bvname, names in name_map} | python | def _unblast(name2vals, name_map):
"""Helper function to lift str -> bool maps used by aiger
to the word level. Dual of the `_blast` function."""
def _collect(names):
return tuple(name2vals[n] for n in names)
return {bvname: _collect(names) for bvname, names in name_map} | [
"def",
"_unblast",
"(",
"name2vals",
",",
"name_map",
")",
":",
"def",
"_collect",
"(",
"names",
")",
":",
"return",
"tuple",
"(",
"name2vals",
"[",
"n",
"]",
"for",
"n",
"in",
"names",
")",
"return",
"{",
"bvname",
":",
"_collect",
"(",
"names",
")"... | Helper function to lift str -> bool maps used by aiger
to the word level. Dual of the `_blast` function. | [
"Helper",
"function",
"to",
"lift",
"str",
"-",
">",
"bool",
"maps",
"used",
"by",
"aiger",
"to",
"the",
"word",
"level",
".",
"Dual",
"of",
"the",
"_blast",
"function",
"."
] | 855819844c429c35cdd8dc0b134bcd11f7b2fda3 | https://github.com/mvcisback/py-aiger-bv/blob/855819844c429c35cdd8dc0b134bcd11f7b2fda3/aigerbv/aigbv.py#L22-L28 | train |
RobotStudio/bors | bors/app/log.py | LoggerMixin.create_logger | def create_logger(self):
"""Generates a logger instance from the singleton"""
name = "bors"
if hasattr(self, "name"):
name = self.name
self.log = logging.getLogger(name)
try:
lvl = self.conf.get_log_level()
except AttributeError:
lvl =... | python | def create_logger(self):
"""Generates a logger instance from the singleton"""
name = "bors"
if hasattr(self, "name"):
name = self.name
self.log = logging.getLogger(name)
try:
lvl = self.conf.get_log_level()
except AttributeError:
lvl =... | [
"def",
"create_logger",
"(",
"self",
")",
":",
"name",
"=",
"\"bors\"",
"if",
"hasattr",
"(",
"self",
",",
"\"name\"",
")",
":",
"name",
"=",
"self",
".",
"name",
"self",
".",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"try",
":",
"... | Generates a logger instance from the singleton | [
"Generates",
"a",
"logger",
"instance",
"from",
"the",
"singleton"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/log.py#L8-L20 | train |
20c/facsimile | facsimile/facs.py | get_cls | def get_cls(project_name, project_data):
"""
gets class from name and data, sets base level attrs
defaults to facsimile.base.Facsimile
"""
if project_name:
cls = getattr(facsimile.base, project_data.get('class', 'Facsimile'))
cls.name = project_name
else:
cls = facsimile.... | python | def get_cls(project_name, project_data):
"""
gets class from name and data, sets base level attrs
defaults to facsimile.base.Facsimile
"""
if project_name:
cls = getattr(facsimile.base, project_data.get('class', 'Facsimile'))
cls.name = project_name
else:
cls = facsimile.... | [
"def",
"get_cls",
"(",
"project_name",
",",
"project_data",
")",
":",
"if",
"project_name",
":",
"cls",
"=",
"getattr",
"(",
"facsimile",
".",
"base",
",",
"project_data",
".",
"get",
"(",
"'class'",
",",
"'Facsimile'",
")",
")",
"cls",
".",
"name",
"=",... | gets class from name and data, sets base level attrs
defaults to facsimile.base.Facsimile | [
"gets",
"class",
"from",
"name",
"and",
"data",
"sets",
"base",
"level",
"attrs",
"defaults",
"to",
"facsimile",
".",
"base",
".",
"Facsimile"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/facs.py#L29-L39 | train |
lotrekagency/djlotrek | djlotrek/decorators.py | check_recaptcha | def check_recaptcha(view_func):
"""Chech that the entered recaptcha data is correct"""
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
... | python | def check_recaptcha(view_func):
"""Chech that the entered recaptcha data is correct"""
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recaptcha-response')
... | [
"def",
"check_recaptcha",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
")",
"def",
"_wrapped_view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
".",
"recaptcha_is_valid",
"=",
"None",
"if",
"request",
".... | Chech that the entered recaptcha data is correct | [
"Chech",
"that",
"the",
"entered",
"recaptcha",
"data",
"is",
"correct"
] | 10a304103768c3d59bdb8859eba86ef3327c9598 | https://github.com/lotrekagency/djlotrek/blob/10a304103768c3d59bdb8859eba86ef3327c9598/djlotrek/decorators.py#L7-L31 | train |
MonsieurV/SafecastPy | SafecastPy/api.py | SafecastPy._request | def _request(self, url, method="GET", params=None, api_call=None):
"""Internal request method"""
method = method.lower()
params = params or {}
func = getattr(requests, method)
requests_args = {}
if method == "get" or method == "delete":
requests_args["params"]... | python | def _request(self, url, method="GET", params=None, api_call=None):
"""Internal request method"""
method = method.lower()
params = params or {}
func = getattr(requests, method)
requests_args = {}
if method == "get" or method == "delete":
requests_args["params"]... | [
"def",
"_request",
"(",
"self",
",",
"url",
",",
"method",
"=",
"\"GET\"",
",",
"params",
"=",
"None",
",",
"api_call",
"=",
"None",
")",
":",
"method",
"=",
"method",
".",
"lower",
"(",
")",
"params",
"=",
"params",
"or",
"{",
"}",
"func",
"=",
... | Internal request method | [
"Internal",
"request",
"method"
] | 8d35370dac0b52349af334c80f95f7dc6293e360 | https://github.com/MonsieurV/SafecastPy/blob/8d35370dac0b52349af334c80f95f7dc6293e360/SafecastPy/api.py#L38-L74 | train |
MonsieurV/SafecastPy | SafecastPy/api.py | SafecastPy.request | def request(self, endpoint, method="GET", params=None):
"""Return dict of response received from Safecast's API
:param endpoint: (required) Full url or Safecast API endpoint
(e.g. measurements/users)
:type endpoint: string
:param method: (optional) Method of acce... | python | def request(self, endpoint, method="GET", params=None):
"""Return dict of response received from Safecast's API
:param endpoint: (required) Full url or Safecast API endpoint
(e.g. measurements/users)
:type endpoint: string
:param method: (optional) Method of acce... | [
"def",
"request",
"(",
"self",
",",
"endpoint",
",",
"method",
"=",
"\"GET\"",
",",
"params",
"=",
"None",
")",
":",
"# In case they want to pass a full Safecast URL",
"# i.e. https://api.safecast.org/measurements.json",
"if",
"endpoint",
".",
"startswith",
"(",
"\"http... | Return dict of response received from Safecast's API
:param endpoint: (required) Full url or Safecast API endpoint
(e.g. measurements/users)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST, PUT or DELETE.... | [
"Return",
"dict",
"of",
"response",
"received",
"from",
"Safecast",
"s",
"API",
":",
"param",
"endpoint",
":",
"(",
"required",
")",
"Full",
"url",
"or",
"Safecast",
"API",
"endpoint",
"(",
"e",
".",
"g",
".",
"measurements",
"/",
"users",
")",
":",
"t... | 8d35370dac0b52349af334c80f95f7dc6293e360 | https://github.com/MonsieurV/SafecastPy/blob/8d35370dac0b52349af334c80f95f7dc6293e360/SafecastPy/api.py#L76-L104 | train |
greenelab/django-genes | genes/api.py | GeneResource.post_list | def post_list(self, request, **kwargs):
"""
(Copied from implementation in
https://github.com/greenelab/adage-server/blob/master/adage/analyze/api.py)
Handle an incoming POST as a GET to work around URI length limitations
"""
# The convert_post_to_VERB() technique is bor... | python | def post_list(self, request, **kwargs):
"""
(Copied from implementation in
https://github.com/greenelab/adage-server/blob/master/adage/analyze/api.py)
Handle an incoming POST as a GET to work around URI length limitations
"""
# The convert_post_to_VERB() technique is bor... | [
"def",
"post_list",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# The convert_post_to_VERB() technique is borrowed from",
"# resources.py in tastypie source. This helps us to convert the POST",
"# to a GET in the proper way internally.",
"request",
".",
"method... | (Copied from implementation in
https://github.com/greenelab/adage-server/blob/master/adage/analyze/api.py)
Handle an incoming POST as a GET to work around URI length limitations | [
"(",
"Copied",
"from",
"implementation",
"in",
"https",
":",
"//",
"github",
".",
"com",
"/",
"greenelab",
"/",
"adage",
"-",
"server",
"/",
"blob",
"/",
"master",
"/",
"adage",
"/",
"analyze",
"/",
"api",
".",
"py",
")"
] | 298939adcb115031acfc11cfcef60ea0b596fae5 | https://github.com/greenelab/django-genes/blob/298939adcb115031acfc11cfcef60ea0b596fae5/genes/api.py#L202-L214 | train |
RobotStudio/bors | bors/app/strategy.py | Strategy.execute | def execute(self, context):
"""Execute the strategies on the given context"""
for ware in self.middleware:
ware.premessage(context)
context = ware.bind(context)
ware.postmessage(context)
return context | python | def execute(self, context):
"""Execute the strategies on the given context"""
for ware in self.middleware:
ware.premessage(context)
context = ware.bind(context)
ware.postmessage(context)
return context | [
"def",
"execute",
"(",
"self",
",",
"context",
")",
":",
"for",
"ware",
"in",
"self",
".",
"middleware",
":",
"ware",
".",
"premessage",
"(",
"context",
")",
"context",
"=",
"ware",
".",
"bind",
"(",
"context",
")",
"ware",
".",
"postmessage",
"(",
"... | Execute the strategies on the given context | [
"Execute",
"the",
"strategies",
"on",
"the",
"given",
"context"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/strategy.py#L24-L30 | train |
RobotStudio/bors | bors/app/strategy.py | Strategy.shutdown | def shutdown(self):
"""Perform cleanup! We're goin' down!!!"""
for ware in self.middleware:
ware.preshutdown()
self._shutdown()
ware.postshutdown() | python | def shutdown(self):
"""Perform cleanup! We're goin' down!!!"""
for ware in self.middleware:
ware.preshutdown()
self._shutdown()
ware.postshutdown() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"for",
"ware",
"in",
"self",
".",
"middleware",
":",
"ware",
".",
"preshutdown",
"(",
")",
"self",
".",
"_shutdown",
"(",
")",
"ware",
".",
"postshutdown",
"(",
")"
] | Perform cleanup! We're goin' down!!! | [
"Perform",
"cleanup!",
"We",
"re",
"goin",
"down!!!"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/strategy.py#L35-L40 | train |
willkg/socorro-siggen | siggen/cmd_doc.py | main | def main(argv=None):
"""Generates documentation for signature generation pipeline"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'pipeline',
help='Python dotted path to rules pipeline to document'
)
parser.add_argument('output', help='output file')
... | python | def main(argv=None):
"""Generates documentation for signature generation pipeline"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'pipeline',
help='Python dotted path to rules pipeline to document'
)
parser.add_argument('output', help='output file')
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"DESCRIPTION",
")",
"parser",
".",
"add_argument",
"(",
"'pipeline'",
",",
"help",
"=",
"'Python dotted path to rules pipeline to document... | Generates documentation for signature generation pipeline | [
"Generates",
"documentation",
"for",
"signature",
"generation",
"pipeline"
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_doc.py#L68-L107 | train |
greenelab/django-organisms | organisms/management/commands/organisms_create_or_update.py | Command.handle | def handle(self, *args, **options):
"""This function is called by the Django API to specify how this object
will be saved to the database.
"""
taxonomy_id = options['taxonomy_id']
# Remove leading and trailing blank characters in "common_name"
# and "scientific_name
... | python | def handle(self, *args, **options):
"""This function is called by the Django API to specify how this object
will be saved to the database.
"""
taxonomy_id = options['taxonomy_id']
# Remove leading and trailing blank characters in "common_name"
# and "scientific_name
... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"taxonomy_id",
"=",
"options",
"[",
"'taxonomy_id'",
"]",
"# Remove leading and trailing blank characters in \"common_name\"",
"# and \"scientific_name",
"common_name",
"=",
"options",
... | This function is called by the Django API to specify how this object
will be saved to the database. | [
"This",
"function",
"is",
"called",
"by",
"the",
"Django",
"API",
"to",
"specify",
"how",
"this",
"object",
"will",
"be",
"saved",
"to",
"the",
"database",
"."
] | 4ec5893e8b9d143fe3aa2be484b2d9c3b931016b | https://github.com/greenelab/django-organisms/blob/4ec5893e8b9d143fe3aa2be484b2d9c3b931016b/organisms/management/commands/organisms_create_or_update.py#L51-L91 | train |
KnorrFG/pyparadigm | pyparadigm/misc.py | init | def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False):
"""Creates a window of given resolution.
:param resolution: the resolution of the windows as (width, height) in
pixels
:type resolution: tuple
:param pygame_flags: modify the creation of the window.
For fu... | python | def init(resolution, pygame_flags=0, display_pos=(0, 0), interactive_mode=False):
"""Creates a window of given resolution.
:param resolution: the resolution of the windows as (width, height) in
pixels
:type resolution: tuple
:param pygame_flags: modify the creation of the window.
For fu... | [
"def",
"init",
"(",
"resolution",
",",
"pygame_flags",
"=",
"0",
",",
"display_pos",
"=",
"(",
"0",
",",
"0",
")",
",",
"interactive_mode",
"=",
"False",
")",
":",
"os",
".",
"environ",
"[",
"'SDL_VIDEO_WINDOW_POS'",
"]",
"=",
"\"{}, {}\"",
".",
"format"... | Creates a window of given resolution.
:param resolution: the resolution of the windows as (width, height) in
pixels
:type resolution: tuple
:param pygame_flags: modify the creation of the window.
For further information see :ref:`creating_a_window`
:type pygame_flags: int
:param dis... | [
"Creates",
"a",
"window",
"of",
"given",
"resolution",
"."
] | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L32-L68 | train |
KnorrFG/pyparadigm | pyparadigm/misc.py | display | def display(surface):
"""Displays a pygame.Surface in the window.
in pygame the window is represented through a surface, on which you can draw
as on any other pygame.Surface. A refernce to to the screen can be optained
via the :py:func:`pygame.display.get_surface` function. To display the
conte... | python | def display(surface):
"""Displays a pygame.Surface in the window.
in pygame the window is represented through a surface, on which you can draw
as on any other pygame.Surface. A refernce to to the screen can be optained
via the :py:func:`pygame.display.get_surface` function. To display the
conte... | [
"def",
"display",
"(",
"surface",
")",
":",
"screen",
"=",
"pygame",
".",
"display",
".",
"get_surface",
"(",
")",
"screen",
".",
"blit",
"(",
"surface",
",",
"(",
"0",
",",
"0",
")",
")",
"pygame",
".",
"display",
".",
"flip",
"(",
")"
] | Displays a pygame.Surface in the window.
in pygame the window is represented through a surface, on which you can draw
as on any other pygame.Surface. A refernce to to the screen can be optained
via the :py:func:`pygame.display.get_surface` function. To display the
contents of the screen surface in ... | [
"Displays",
"a",
"pygame",
".",
"Surface",
"in",
"the",
"window",
".",
"in",
"pygame",
"the",
"window",
"is",
"represented",
"through",
"a",
"surface",
"on",
"which",
"you",
"can",
"draw",
"as",
"on",
"any",
"other",
"pygame",
".",
"Surface",
".",
"A",
... | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L70-L87 | train |
KnorrFG/pyparadigm | pyparadigm/misc.py | empty_surface | def empty_surface(fill_color, size=None):
"""Returns an empty surface filled with fill_color.
:param fill_color: color to fill the surface with
:type fill_color: pygame.Color
:param size: the size of the new surface, if None its created
to be the same size as the screen
:type size: int-2-t... | python | def empty_surface(fill_color, size=None):
"""Returns an empty surface filled with fill_color.
:param fill_color: color to fill the surface with
:type fill_color: pygame.Color
:param size: the size of the new surface, if None its created
to be the same size as the screen
:type size: int-2-t... | [
"def",
"empty_surface",
"(",
"fill_color",
",",
"size",
"=",
"None",
")",
":",
"sr",
"=",
"pygame",
".",
"display",
".",
"get_surface",
"(",
")",
".",
"get_rect",
"(",
")",
"surf",
"=",
"pygame",
".",
"Surface",
"(",
"size",
"or",
"(",
"sr",
".",
"... | Returns an empty surface filled with fill_color.
:param fill_color: color to fill the surface with
:type fill_color: pygame.Color
:param size: the size of the new surface, if None its created
to be the same size as the screen
:type size: int-2-tuple | [
"Returns",
"an",
"empty",
"surface",
"filled",
"with",
"fill_color",
"."
] | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L114-L127 | train |
KnorrFG/pyparadigm | pyparadigm/misc.py | process_char | def process_char(buffer: str, char: str, mappings=_char_mappings):
"""This is a convinience method for use with
EventListener.wait_for_unicode_char(). In most cases it simply appends
char to buffer. Some replacements are done because presing return will
produce '\\r' but for most cases '\\n' would be ... | python | def process_char(buffer: str, char: str, mappings=_char_mappings):
"""This is a convinience method for use with
EventListener.wait_for_unicode_char(). In most cases it simply appends
char to buffer. Some replacements are done because presing return will
produce '\\r' but for most cases '\\n' would be ... | [
"def",
"process_char",
"(",
"buffer",
":",
"str",
",",
"char",
":",
"str",
",",
"mappings",
"=",
"_char_mappings",
")",
":",
"if",
"char",
"in",
"mappings",
":",
"return",
"buffer",
"+",
"mappings",
"[",
"char",
"]",
"elif",
"char",
"==",
"\"\\u0008\"",
... | This is a convinience method for use with
EventListener.wait_for_unicode_char(). In most cases it simply appends
char to buffer. Some replacements are done because presing return will
produce '\\r' but for most cases '\\n' would be desireable.
Also backspace cant just be added to a string either, ther... | [
"This",
"is",
"a",
"convinience",
"method",
"for",
"use",
"with",
"EventListener",
".",
"wait_for_unicode_char",
"()",
".",
"In",
"most",
"cases",
"it",
"simply",
"appends",
"char",
"to",
"buffer",
".",
"Some",
"replacements",
"are",
"done",
"because",
"presin... | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/misc.py#L135-L160 | train |
RobotStudio/bors | bors/api/adapter/socketcluster.py | SCAdapter.run | def run(self):
"""
Called by internal API subsystem to initialize websockets connections
in the API interface
"""
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
def on_ws_connect(*args, **kwargs):... | python | def run(self):
"""
Called by internal API subsystem to initialize websockets connections
in the API interface
"""
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
def on_ws_connect(*args, **kwargs):... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"api",
"=",
"self",
".",
"context",
".",
"get",
"(",
"\"cls\"",
")",
"(",
"self",
".",
"context",
")",
"self",
".",
"context",
"[",
"\"inst\"",
"]",
".",
"append",
"(",
"self",
")",
"# Adapters used... | Called by internal API subsystem to initialize websockets connections
in the API interface | [
"Called",
"by",
"internal",
"API",
"subsystem",
"to",
"initialize",
"websockets",
"connections",
"in",
"the",
"API",
"interface"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/socketcluster.py#L17-L42 | train |
RobotStudio/bors | bors/api/adapter/socketcluster.py | SCAdapter.add_channels | def add_channels(self, channels):
"""
Take a list of SockChannel objects and extend the websock listener
"""
chans = [
SockChannel(chan, res, self._generate_result)
for chan, res in channels.items()
]
self.api.channels.extend(chans)
self.ap... | python | def add_channels(self, channels):
"""
Take a list of SockChannel objects and extend the websock listener
"""
chans = [
SockChannel(chan, res, self._generate_result)
for chan, res in channels.items()
]
self.api.channels.extend(chans)
self.ap... | [
"def",
"add_channels",
"(",
"self",
",",
"channels",
")",
":",
"chans",
"=",
"[",
"SockChannel",
"(",
"chan",
",",
"res",
",",
"self",
".",
"_generate_result",
")",
"for",
"chan",
",",
"res",
"in",
"channels",
".",
"items",
"(",
")",
"]",
"self",
"."... | Take a list of SockChannel objects and extend the websock listener | [
"Take",
"a",
"list",
"of",
"SockChannel",
"objects",
"and",
"extend",
"the",
"websock",
"listener"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/socketcluster.py#L48-L57 | train |
RobotStudio/bors | bors/api/adapter/socketcluster.py | SCAdapter._generate_result | def _generate_result(self, res_type, channel, result):
"""Generate the result object"""
schema = self.api.ws_result_schema()
schema.context['channel'] = channel
schema.context['response_type'] = res_type
self.callback(schema.load(result), self.context) | python | def _generate_result(self, res_type, channel, result):
"""Generate the result object"""
schema = self.api.ws_result_schema()
schema.context['channel'] = channel
schema.context['response_type'] = res_type
self.callback(schema.load(result), self.context) | [
"def",
"_generate_result",
"(",
"self",
",",
"res_type",
",",
"channel",
",",
"result",
")",
":",
"schema",
"=",
"self",
".",
"api",
".",
"ws_result_schema",
"(",
")",
"schema",
".",
"context",
"[",
"'channel'",
"]",
"=",
"channel",
"schema",
".",
"conte... | Generate the result object | [
"Generate",
"the",
"result",
"object"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/socketcluster.py#L59-L64 | train |
KnorrFG/pyparadigm | doc/examples/stroop.py | rand_elem | def rand_elem(seq, n=None):
"""returns a random element from seq n times. If n is None, it continues indefinitly"""
return map(random.choice, repeat(seq, n) if n is not None else repeat(seq)) | python | def rand_elem(seq, n=None):
"""returns a random element from seq n times. If n is None, it continues indefinitly"""
return map(random.choice, repeat(seq, n) if n is not None else repeat(seq)) | [
"def",
"rand_elem",
"(",
"seq",
",",
"n",
"=",
"None",
")",
":",
"return",
"map",
"(",
"random",
".",
"choice",
",",
"repeat",
"(",
"seq",
",",
"n",
")",
"if",
"n",
"is",
"not",
"None",
"else",
"repeat",
"(",
"seq",
")",
")"
] | returns a random element from seq n times. If n is None, it continues indefinitly | [
"returns",
"a",
"random",
"element",
"from",
"seq",
"n",
"times",
".",
"If",
"n",
"is",
"None",
"it",
"continues",
"indefinitly"
] | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/doc/examples/stroop.py#L201-L203 | train |
theno/utlz | utlz/__init__.py | first_paragraph | def first_paragraph(multiline_str, without_trailing_dot=True, maxlength=None):
'''Return first paragraph of multiline_str as a oneliner.
When without_trailing_dot is True, the last char of the first paragraph
will be removed, if it is a dot ('.').
Examples:
>>> multiline_str = 'first line\\nse... | python | def first_paragraph(multiline_str, without_trailing_dot=True, maxlength=None):
'''Return first paragraph of multiline_str as a oneliner.
When without_trailing_dot is True, the last char of the first paragraph
will be removed, if it is a dot ('.').
Examples:
>>> multiline_str = 'first line\\nse... | [
"def",
"first_paragraph",
"(",
"multiline_str",
",",
"without_trailing_dot",
"=",
"True",
",",
"maxlength",
"=",
"None",
")",
":",
"stripped",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"multiline_str",
".",
... | Return first paragraph of multiline_str as a oneliner.
When without_trailing_dot is True, the last char of the first paragraph
will be removed, if it is a dot ('.').
Examples:
>>> multiline_str = 'first line\\nsecond line\\n\\nnext paragraph'
>>> print(first_paragraph(multiline_str))
... | [
"Return",
"first",
"paragraph",
"of",
"multiline_str",
"as",
"a",
"oneliner",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L67-L109 | train |
theno/utlz | utlz/__init__.py | print_doc1 | def print_doc1(*args, **kwargs):
'''Print the first paragraph of the docstring of the decorated function.
The paragraph will be printed as a oneliner.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, ``prefix`` of ``tail``
(eg.... | python | def print_doc1(*args, **kwargs):
'''Print the first paragraph of the docstring of the decorated function.
The paragraph will be printed as a oneliner.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, ``prefix`` of ``tail``
(eg.... | [
"def",
"print_doc1",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# output settings from kwargs or take defaults",
"color",
"=",
"kwargs",
".",
"get",
"(",
"'color'",
",",
"blue",
")",
"bold",
"=",
"kwargs",
".",
"get",
"(",
"'bold'",
",",
"False"... | Print the first paragraph of the docstring of the decorated function.
The paragraph will be printed as a oneliner.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, ``prefix`` of ``tail``
(eg. ``@print_doc1(color=utils.red, bold=Tru... | [
"Print",
"the",
"first",
"paragraph",
"of",
"the",
"docstring",
"of",
"the",
"decorated",
"function",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L114-L173 | train |
theno/utlz | utlz/__init__.py | print_full_name | def print_full_name(*args, **kwargs):
'''Decorator, print the full name of the decorated function.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, or ``prefix``
(eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``).
'''... | python | def print_full_name(*args, **kwargs):
'''Decorator, print the full name of the decorated function.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, or ``prefix``
(eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``).
'''... | [
"def",
"print_full_name",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"color",
"=",
"kwargs",
".",
"get",
"(",
"'color'",
",",
"default_color",
")",
"bold",
"=",
"kwargs",
".",
"get",
"(",
"'bold'",
",",
"False",
")",
"prefix",
"=",
"kwargs"... | Decorator, print the full name of the decorated function.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, or ``prefix``
(eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``). | [
"Decorator",
"print",
"the",
"full",
"name",
"of",
"the",
"decorated",
"function",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L177-L208 | train |
theno/utlz | utlz/__init__.py | filled_out_template_str | def filled_out_template_str(template, **substitutions):
'''Return str template with applied substitutions.
Example:
>>> template = 'Asyl for {{name}} {{surname}}!'
>>> filled_out_template_str(template, name='Edward', surname='Snowden')
'Asyl for Edward Snowden!'
>>> template = ... | python | def filled_out_template_str(template, **substitutions):
'''Return str template with applied substitutions.
Example:
>>> template = 'Asyl for {{name}} {{surname}}!'
>>> filled_out_template_str(template, name='Edward', surname='Snowden')
'Asyl for Edward Snowden!'
>>> template = ... | [
"def",
"filled_out_template_str",
"(",
"template",
",",
"*",
"*",
"substitutions",
")",
":",
"template",
"=",
"template",
".",
"replace",
"(",
"'{'",
",",
"'{{'",
")",
"template",
"=",
"template",
".",
"replace",
"(",
"'}'",
",",
"'}}'",
")",
"template",
... | Return str template with applied substitutions.
Example:
>>> template = 'Asyl for {{name}} {{surname}}!'
>>> filled_out_template_str(template, name='Edward', surname='Snowden')
'Asyl for Edward Snowden!'
>>> template = '[[[foo]]] was substituted by {{foo}}'
>>> filled_out_t... | [
"Return",
"str",
"template",
"with",
"applied",
"substitutions",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L278-L303 | train |
theno/utlz | utlz/__init__.py | filled_out_template | def filled_out_template(filename, **substitutions):
'''Return content of file filename with applied substitutions.'''
res = None
with open(filename, 'r') as fp:
template = fp.read()
res = filled_out_template_str(template, **substitutions)
return res | python | def filled_out_template(filename, **substitutions):
'''Return content of file filename with applied substitutions.'''
res = None
with open(filename, 'r') as fp:
template = fp.read()
res = filled_out_template_str(template, **substitutions)
return res | [
"def",
"filled_out_template",
"(",
"filename",
",",
"*",
"*",
"substitutions",
")",
":",
"res",
"=",
"None",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fp",
":",
"template",
"=",
"fp",
".",
"read",
"(",
")",
"res",
"=",
"filled_out_templa... | Return content of file filename with applied substitutions. | [
"Return",
"content",
"of",
"file",
"filename",
"with",
"applied",
"substitutions",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L307-L313 | train |
theno/utlz | utlz/__init__.py | update_or_append_line | def update_or_append_line(filename, prefix, new_line, keep_backup=True,
append=True):
'''Search in file 'filename' for a line starting with 'prefix' and replace
the line by 'new_line'.
If a line starting with 'prefix' not exists 'new_line' will be appended.
If the file not exi... | python | def update_or_append_line(filename, prefix, new_line, keep_backup=True,
append=True):
'''Search in file 'filename' for a line starting with 'prefix' and replace
the line by 'new_line'.
If a line starting with 'prefix' not exists 'new_line' will be appended.
If the file not exi... | [
"def",
"update_or_append_line",
"(",
"filename",
",",
"prefix",
",",
"new_line",
",",
"keep_backup",
"=",
"True",
",",
"append",
"=",
"True",
")",
":",
"same_line_exists",
",",
"line_updated",
"=",
"False",
",",
"False",
"filename",
"=",
"os",
".",
"path",
... | Search in file 'filename' for a line starting with 'prefix' and replace
the line by 'new_line'.
If a line starting with 'prefix' not exists 'new_line' will be appended.
If the file not exists, it will be created.
Return False if new_line was appended, else True (i.e. if the prefix was
found within... | [
"Search",
"in",
"file",
"filename",
"for",
"a",
"line",
"starting",
"with",
"prefix",
"and",
"replace",
"the",
"line",
"by",
"new_line",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L318-L354 | train |
theno/utlz | utlz/__init__.py | comment_out_line | def comment_out_line(filename, line, comment='#',
update_or_append_line=update_or_append_line):
'''Comment line out by putting a comment sign in front of the line.
If the file does not contain the line, the files content will not be
changed (but the file will be touched in every case).... | python | def comment_out_line(filename, line, comment='#',
update_or_append_line=update_or_append_line):
'''Comment line out by putting a comment sign in front of the line.
If the file does not contain the line, the files content will not be
changed (but the file will be touched in every case).... | [
"def",
"comment_out_line",
"(",
"filename",
",",
"line",
",",
"comment",
"=",
"'#'",
",",
"update_or_append_line",
"=",
"update_or_append_line",
")",
":",
"update_or_append_line",
"(",
"filename",
",",
"prefix",
"=",
"line",
",",
"new_line",
"=",
"comment",
"+",... | Comment line out by putting a comment sign in front of the line.
If the file does not contain the line, the files content will not be
changed (but the file will be touched in every case). | [
"Comment",
"line",
"out",
"by",
"putting",
"a",
"comment",
"sign",
"in",
"front",
"of",
"the",
"line",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L358-L366 | train |
theno/utlz | utlz/__init__.py | uncomment_or_update_or_append_line | def uncomment_or_update_or_append_line(filename, prefix, new_line, comment='#',
keep_backup=True,
update_or_append_line=update_or_append_line):
'''Remove the comment of an commented out line and make the line "active".
If such an com... | python | def uncomment_or_update_or_append_line(filename, prefix, new_line, comment='#',
keep_backup=True,
update_or_append_line=update_or_append_line):
'''Remove the comment of an commented out line and make the line "active".
If such an com... | [
"def",
"uncomment_or_update_or_append_line",
"(",
"filename",
",",
"prefix",
",",
"new_line",
",",
"comment",
"=",
"'#'",
",",
"keep_backup",
"=",
"True",
",",
"update_or_append_line",
"=",
"update_or_append_line",
")",
":",
"uncommented",
"=",
"update_or_append_line"... | Remove the comment of an commented out line and make the line "active".
If such an commented out line not exists it would be appended. | [
"Remove",
"the",
"comment",
"of",
"an",
"commented",
"out",
"line",
"and",
"make",
"the",
"line",
"active",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L370-L382 | train |
theno/utlz | utlz/__init__.py | convert_unicode_2_utf8 | def convert_unicode_2_utf8(input):
'''Return a copy of `input` with every str component encoded from unicode to
utf-8.
'''
if isinstance(input, dict):
try:
# python-2.6
return dict((convert_unicode_2_utf8(key), convert_unicode_2_utf8(value))
for ke... | python | def convert_unicode_2_utf8(input):
'''Return a copy of `input` with every str component encoded from unicode to
utf-8.
'''
if isinstance(input, dict):
try:
# python-2.6
return dict((convert_unicode_2_utf8(key), convert_unicode_2_utf8(value))
for ke... | [
"def",
"convert_unicode_2_utf8",
"(",
"input",
")",
":",
"if",
"isinstance",
"(",
"input",
",",
"dict",
")",
":",
"try",
":",
"# python-2.6",
"return",
"dict",
"(",
"(",
"convert_unicode_2_utf8",
"(",
"key",
")",
",",
"convert_unicode_2_utf8",
"(",
"value",
... | Return a copy of `input` with every str component encoded from unicode to
utf-8. | [
"Return",
"a",
"copy",
"of",
"input",
"with",
"every",
"str",
"component",
"encoded",
"from",
"unicode",
"to",
"utf",
"-",
"8",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L387-L417 | train |
theno/utlz | utlz/__init__.py | load_json | def load_json(filename, gzip_mode=False):
'''Return the json-file data, with all strings utf-8 encoded.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'rt') as fh:
data = json.load(fh)
data = convert_unicode_2_utf8(data)
... | python | def load_json(filename, gzip_mode=False):
'''Return the json-file data, with all strings utf-8 encoded.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'rt') as fh:
data = json.load(fh)
data = convert_unicode_2_utf8(data)
... | [
"def",
"load_json",
"(",
"filename",
",",
"gzip_mode",
"=",
"False",
")",
":",
"open_file",
"=",
"open",
"if",
"gzip_mode",
":",
"open_file",
"=",
"gzip",
".",
"open",
"try",
":",
"with",
"open_file",
"(",
"filename",
",",
"'rt'",
")",
"as",
"fh",
":",... | Return the json-file data, with all strings utf-8 encoded. | [
"Return",
"the",
"json",
"-",
"file",
"data",
"with",
"all",
"strings",
"utf",
"-",
"8",
"encoded",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L420-L438 | train |
theno/utlz | utlz/__init__.py | write_json | def write_json(data, filename, gzip_mode=False):
'''Write the python data structure as a json-Object to filename.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'wt') as fh:
json.dump(obj=data, fp=fh, sort_keys=True)
except Attribu... | python | def write_json(data, filename, gzip_mode=False):
'''Write the python data structure as a json-Object to filename.'''
open_file = open
if gzip_mode:
open_file = gzip.open
try:
with open_file(filename, 'wt') as fh:
json.dump(obj=data, fp=fh, sort_keys=True)
except Attribu... | [
"def",
"write_json",
"(",
"data",
",",
"filename",
",",
"gzip_mode",
"=",
"False",
")",
":",
"open_file",
"=",
"open",
"if",
"gzip_mode",
":",
"open_file",
"=",
"gzip",
".",
"open",
"try",
":",
"with",
"open_file",
"(",
"filename",
",",
"'wt'",
")",
"a... | Write the python data structure as a json-Object to filename. | [
"Write",
"the",
"python",
"data",
"structure",
"as",
"a",
"json",
"-",
"Object",
"to",
"filename",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L441-L455 | train |
theno/utlz | utlz/__init__.py | text_with_newlines | def text_with_newlines(text, line_length=78, newline='\n'):
'''Return text with a `newline` inserted after each `line_length` char.
Return `text` unchanged if line_length == 0.
'''
if line_length > 0:
if len(text) <= line_length:
return text
else:
return newline.... | python | def text_with_newlines(text, line_length=78, newline='\n'):
'''Return text with a `newline` inserted after each `line_length` char.
Return `text` unchanged if line_length == 0.
'''
if line_length > 0:
if len(text) <= line_length:
return text
else:
return newline.... | [
"def",
"text_with_newlines",
"(",
"text",
",",
"line_length",
"=",
"78",
",",
"newline",
"=",
"'\\n'",
")",
":",
"if",
"line_length",
">",
"0",
":",
"if",
"len",
"(",
"text",
")",
"<=",
"line_length",
":",
"return",
"text",
"else",
":",
"return",
"newl... | Return text with a `newline` inserted after each `line_length` char.
Return `text` unchanged if line_length == 0. | [
"Return",
"text",
"with",
"a",
"newline",
"inserted",
"after",
"each",
"line_length",
"char",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L468-L481 | train |
theno/utlz | utlz/__init__.py | lazy_val | def lazy_val(func, with_del_hook=False):
'''A memoize decorator for class properties.
Return a cached property that is calculated by function `func` on first
access.
'''
def hook_for(that):
try:
orig_del = that.__del__
except AttributeError:
orig_del = None
... | python | def lazy_val(func, with_del_hook=False):
'''A memoize decorator for class properties.
Return a cached property that is calculated by function `func` on first
access.
'''
def hook_for(that):
try:
orig_del = that.__del__
except AttributeError:
orig_del = None
... | [
"def",
"lazy_val",
"(",
"func",
",",
"with_del_hook",
"=",
"False",
")",
":",
"def",
"hook_for",
"(",
"that",
")",
":",
"try",
":",
"orig_del",
"=",
"that",
".",
"__del__",
"except",
"AttributeError",
":",
"orig_del",
"=",
"None",
"def",
"del_hook",
"(",... | A memoize decorator for class properties.
Return a cached property that is calculated by function `func` on first
access. | [
"A",
"memoize",
"decorator",
"for",
"class",
"properties",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/utlz/__init__.py#L492-L544 | train |
pmacosta/pmisc | pmisc/compat3.py | _readlines | def _readlines(fname, fpointer1=open, fpointer2=open): # pragma: no cover
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try:
with fpointer1(fname, "r") as fobj:
return fobj.readlines()
except UnicodeDecodeError: # pragma: no cover
with fpo... | python | def _readlines(fname, fpointer1=open, fpointer2=open): # pragma: no cover
"""Read all lines from file."""
# fpointer1, fpointer2 arguments to ease testing
try:
with fpointer1(fname, "r") as fobj:
return fobj.readlines()
except UnicodeDecodeError: # pragma: no cover
with fpo... | [
"def",
"_readlines",
"(",
"fname",
",",
"fpointer1",
"=",
"open",
",",
"fpointer2",
"=",
"open",
")",
":",
"# pragma: no cover",
"# fpointer1, fpointer2 arguments to ease testing",
"try",
":",
"with",
"fpointer1",
"(",
"fname",
",",
"\"r\"",
")",
"as",
"fobj",
"... | Read all lines from file. | [
"Read",
"all",
"lines",
"from",
"file",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/compat3.py#L30-L38 | train |
RobotStudio/bors | bors/api/requestor.py | Req.call | def call(self, callname, data=None, **args):
"""
Generic interface to REST apiGeneric interface to REST api
:param callname: query name
:param data: dictionary of inputs
:param args: keyword arguments added to the payload
:return:
"""
url = f"{self.u... | python | def call(self, callname, data=None, **args):
"""
Generic interface to REST apiGeneric interface to REST api
:param callname: query name
:param data: dictionary of inputs
:param args: keyword arguments added to the payload
:return:
"""
url = f"{self.u... | [
"def",
"call",
"(",
"self",
",",
"callname",
",",
"data",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"url",
"=",
"f\"{self.url_base}/{callname}\"",
"payload",
"=",
"self",
".",
"payload",
".",
"copy",
"(",
")",
"payload",
".",
"update",
"(",
"*",
... | Generic interface to REST apiGeneric interface to REST api
:param callname: query name
:param data: dictionary of inputs
:param args: keyword arguments added to the payload
:return: | [
"Generic",
"interface",
"to",
"REST",
"apiGeneric",
"interface",
"to",
"REST",
"api",
":",
"param",
"callname",
":",
"query",
"name",
":",
"param",
"data",
":",
"dictionary",
"of",
"inputs",
":",
"param",
"args",
":",
"keyword",
"arguments",
"added",
"to",
... | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/requestor.py#L20-L47 | train |
Eyepea/tanto | monitoring_agent/inputs/nagios_plugins.py | NagiosPlugins.launch_plugin | def launch_plugin(self):
'''
launch nagios_plugin command
'''
# nagios_plugins probes
for plugin in self.plugins:
# Construct the nagios_plugin command
command = ('%s%s' % (self.plugins[plugin]['path'], self.plugins[plugin]['command']))
try:
... | python | def launch_plugin(self):
'''
launch nagios_plugin command
'''
# nagios_plugins probes
for plugin in self.plugins:
# Construct the nagios_plugin command
command = ('%s%s' % (self.plugins[plugin]['path'], self.plugins[plugin]['command']))
try:
... | [
"def",
"launch_plugin",
"(",
"self",
")",
":",
"# nagios_plugins probes",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"# Construct the nagios_plugin command",
"command",
"=",
"(",
"'%s%s'",
"%",
"(",
"self",
".",
"plugins",
"[",
"plugin",
"]",
"[",
"'p... | launch nagios_plugin command | [
"launch",
"nagios_plugin",
"command"
] | ad8fd32e0fd3b7bc3dee5dabb984a2567ae46fe9 | https://github.com/Eyepea/tanto/blob/ad8fd32e0fd3b7bc3dee5dabb984a2567ae46fe9/monitoring_agent/inputs/nagios_plugins.py#L31-L64 | train |
BlackEarth/bl | bl/file.py | File.match | def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):
"""for a given path and regexp pattern, return the files that match"""
return sorted(
[
Class(fn=fn)
for fn in rglob(path, f"*{ext or ''}")
if re.search(pattern, os.path.basen... | python | def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):
"""for a given path and regexp pattern, return the files that match"""
return sorted(
[
Class(fn=fn)
for fn in rglob(path, f"*{ext or ''}")
if re.search(pattern, os.path.basen... | [
"def",
"match",
"(",
"Class",
",",
"path",
",",
"pattern",
",",
"flags",
"=",
"re",
".",
"I",
",",
"sortkey",
"=",
"None",
",",
"ext",
"=",
"None",
")",
":",
"return",
"sorted",
"(",
"[",
"Class",
"(",
"fn",
"=",
"fn",
")",
"for",
"fn",
"in",
... | for a given path and regexp pattern, return the files that match | [
"for",
"a",
"given",
"path",
"and",
"regexp",
"pattern",
"return",
"the",
"files",
"that",
"match"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/file.py#L57-L67 | train |
BlackEarth/bl | bl/file.py | File.copy | def copy(self, new_fn):
"""copy the file to the new_fn, preserving atime and mtime"""
new_file = self.__class__(fn=str(new_fn))
new_file.write(data=self.read())
new_file.utime(self.atime, self.mtime)
return new_file | python | def copy(self, new_fn):
"""copy the file to the new_fn, preserving atime and mtime"""
new_file = self.__class__(fn=str(new_fn))
new_file.write(data=self.read())
new_file.utime(self.atime, self.mtime)
return new_file | [
"def",
"copy",
"(",
"self",
",",
"new_fn",
")",
":",
"new_file",
"=",
"self",
".",
"__class__",
"(",
"fn",
"=",
"str",
"(",
"new_fn",
")",
")",
"new_file",
".",
"write",
"(",
"data",
"=",
"self",
".",
"read",
"(",
")",
")",
"new_file",
".",
"utim... | copy the file to the new_fn, preserving atime and mtime | [
"copy",
"the",
"file",
"to",
"the",
"new_fn",
"preserving",
"atime",
"and",
"mtime"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/file.py#L124-L129 | train |
BlackEarth/bl | bl/file.py | File.make_basename | def make_basename(self, fn=None, ext=None):
"""make a filesystem-compliant basename for this file"""
fb, oldext = os.path.splitext(os.path.basename(fn or self.fn))
ext = ext or oldext.lower()
fb = String(fb).hyphenify(ascii=True)
return ''.join([fb, ext]) | python | def make_basename(self, fn=None, ext=None):
"""make a filesystem-compliant basename for this file"""
fb, oldext = os.path.splitext(os.path.basename(fn or self.fn))
ext = ext or oldext.lower()
fb = String(fb).hyphenify(ascii=True)
return ''.join([fb, ext]) | [
"def",
"make_basename",
"(",
"self",
",",
"fn",
"=",
"None",
",",
"ext",
"=",
"None",
")",
":",
"fb",
",",
"oldext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"fn",
"or",
"self",
".",
"fn",
")",
")",... | make a filesystem-compliant basename for this file | [
"make",
"a",
"filesystem",
"-",
"compliant",
"basename",
"for",
"this",
"file"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/file.py#L140-L145 | train |
BlackEarth/bl | bl/file.py | File.tempfile | def tempfile(self, mode='wb', **args):
"write the contents of the file to a tempfile and return the tempfile filename"
tf = tempfile.NamedTemporaryFile(mode=mode)
self.write(tf.name, mode=mode, **args)
return tfn | python | def tempfile(self, mode='wb', **args):
"write the contents of the file to a tempfile and return the tempfile filename"
tf = tempfile.NamedTemporaryFile(mode=mode)
self.write(tf.name, mode=mode, **args)
return tfn | [
"def",
"tempfile",
"(",
"self",
",",
"mode",
"=",
"'wb'",
",",
"*",
"*",
"args",
")",
":",
"tf",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"mode",
")",
"self",
".",
"write",
"(",
"tf",
".",
"name",
",",
"mode",
"=",
"mode",
",... | write the contents of the file to a tempfile and return the tempfile filename | [
"write",
"the",
"contents",
"of",
"the",
"file",
"to",
"a",
"tempfile",
"and",
"return",
"the",
"tempfile",
"filename"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/file.py#L195-L199 | train |
BlackEarth/bl | bl/file.py | File.delete | def delete(self):
"""delete the file from the filesystem."""
if self.isfile:
os.remove(self.fn)
elif self.isdir:
shutil.rmtree(self.fn) | python | def delete(self):
"""delete the file from the filesystem."""
if self.isfile:
os.remove(self.fn)
elif self.isdir:
shutil.rmtree(self.fn) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"isfile",
":",
"os",
".",
"remove",
"(",
"self",
".",
"fn",
")",
"elif",
"self",
".",
"isdir",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"fn",
")"
] | delete the file from the filesystem. | [
"delete",
"the",
"file",
"from",
"the",
"filesystem",
"."
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/file.py#L230-L235 | train |
BlackEarth/bl | bl/file.py | File.readable_size | def readable_size(C, bytes, suffix='B', decimals=1, sep='\u00a0'):
"""given a number of bytes, return the file size in readable units"""
if bytes is None:
return
size = float(bytes)
for unit in C.SIZE_UNITS:
if abs(size) < 1024 or unit == C.SIZE_UNITS[-1]:
... | python | def readable_size(C, bytes, suffix='B', decimals=1, sep='\u00a0'):
"""given a number of bytes, return the file size in readable units"""
if bytes is None:
return
size = float(bytes)
for unit in C.SIZE_UNITS:
if abs(size) < 1024 or unit == C.SIZE_UNITS[-1]:
... | [
"def",
"readable_size",
"(",
"C",
",",
"bytes",
",",
"suffix",
"=",
"'B'",
",",
"decimals",
"=",
"1",
",",
"sep",
"=",
"'\\u00a0'",
")",
":",
"if",
"bytes",
"is",
"None",
":",
"return",
"size",
"=",
"float",
"(",
"bytes",
")",
"for",
"unit",
"in",
... | given a number of bytes, return the file size in readable units | [
"given",
"a",
"number",
"of",
"bytes",
"return",
"the",
"file",
"size",
"in",
"readable",
"units"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/file.py#L240-L254 | train |
BlackEarth/bl | bl/file.py | File.bytes_from_readable_size | def bytes_from_readable_size(C, size, suffix='B'):
"""given a readable_size (as produced by File.readable_size()), return the number of bytes."""
s = re.split("^([0-9\.]+)\s*([%s]?)%s?" % (''.join(C.SIZE_UNITS), suffix), size, flags=re.I)
bytes, unit = round(float(s[1])), s[2].upper()
wh... | python | def bytes_from_readable_size(C, size, suffix='B'):
"""given a readable_size (as produced by File.readable_size()), return the number of bytes."""
s = re.split("^([0-9\.]+)\s*([%s]?)%s?" % (''.join(C.SIZE_UNITS), suffix), size, flags=re.I)
bytes, unit = round(float(s[1])), s[2].upper()
wh... | [
"def",
"bytes_from_readable_size",
"(",
"C",
",",
"size",
",",
"suffix",
"=",
"'B'",
")",
":",
"s",
"=",
"re",
".",
"split",
"(",
"\"^([0-9\\.]+)\\s*([%s]?)%s?\"",
"%",
"(",
"''",
".",
"join",
"(",
"C",
".",
"SIZE_UNITS",
")",
",",
"suffix",
")",
",",
... | given a readable_size (as produced by File.readable_size()), return the number of bytes. | [
"given",
"a",
"readable_size",
"(",
"as",
"produced",
"by",
"File",
".",
"readable_size",
"()",
")",
"return",
"the",
"number",
"of",
"bytes",
"."
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/file.py#L257-L264 | train |
RobotStudio/bors | bors/app/api_factory.py | ApiMetaAdapter.run | def run(self):
"""Executed on startup of application"""
for wsock in self.wsocks:
wsock.run()
for api in self.apis:
api.run() | python | def run(self):
"""Executed on startup of application"""
for wsock in self.wsocks:
wsock.run()
for api in self.apis:
api.run() | [
"def",
"run",
"(",
"self",
")",
":",
"for",
"wsock",
"in",
"self",
".",
"wsocks",
":",
"wsock",
".",
"run",
"(",
")",
"for",
"api",
"in",
"self",
".",
"apis",
":",
"api",
".",
"run",
"(",
")"
] | Executed on startup of application | [
"Executed",
"on",
"startup",
"of",
"application"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/api_factory.py#L28-L33 | train |
RobotStudio/bors | bors/app/api_factory.py | ApiMetaAdapter.shutdown | def shutdown(self):
"""Executed on shutdown of application"""
for wsock in self.wsocks:
wsock.shutdown()
for api in self.apis:
api.shutdown() | python | def shutdown(self):
"""Executed on shutdown of application"""
for wsock in self.wsocks:
wsock.shutdown()
for api in self.apis:
api.shutdown() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"for",
"wsock",
"in",
"self",
".",
"wsocks",
":",
"wsock",
".",
"shutdown",
"(",
")",
"for",
"api",
"in",
"self",
".",
"apis",
":",
"api",
".",
"shutdown",
"(",
")"
] | Executed on shutdown of application | [
"Executed",
"on",
"shutdown",
"of",
"application"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/api_factory.py#L35-L40 | train |
michaeltcoelho/pagarme.py | pagarme/api.py | PagarmeApi.request | def request(self, url, method, data=None, headers=None):
"""Makes a HTTP call, formats response and does error handling.
"""
http_headers = merge_dict(self.default_headers, headers or {})
request_data = merge_dict({'api_key': self.apikey}, data or {})
logger.info('HTTP %s REQUES... | python | def request(self, url, method, data=None, headers=None):
"""Makes a HTTP call, formats response and does error handling.
"""
http_headers = merge_dict(self.default_headers, headers or {})
request_data = merge_dict({'api_key': self.apikey}, data or {})
logger.info('HTTP %s REQUES... | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"method",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"http_headers",
"=",
"merge_dict",
"(",
"self",
".",
"default_headers",
",",
"headers",
"or",
"{",
"}",
")",
"request_data",
"=",... | Makes a HTTP call, formats response and does error handling. | [
"Makes",
"a",
"HTTP",
"call",
"formats",
"response",
"and",
"does",
"error",
"handling",
"."
] | 469fdd6e61e7c24a9eaf23d474d25316c3b5450b | https://github.com/michaeltcoelho/pagarme.py/blob/469fdd6e61e7c24a9eaf23d474d25316c3b5450b/pagarme/api.py#L50-L71 | train |
michaeltcoelho/pagarme.py | pagarme/api.py | PagarmeApi.get | def get(self, action, params=None, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='GET', data=params,
headers=headers) | python | def get(self, action, params=None, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='GET', data=params,
headers=headers) | [
"def",
"get",
"(",
"self",
",",
"action",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"request",
"(",
"make_url",
"(",
"self",
".",
"endpoint",
",",
"action",
")",
",",
"method",
"=",
"'GET'",
",",
"dat... | Makes a GET request | [
"Makes",
"a",
"GET",
"request"
] | 469fdd6e61e7c24a9eaf23d474d25316c3b5450b | https://github.com/michaeltcoelho/pagarme.py/blob/469fdd6e61e7c24a9eaf23d474d25316c3b5450b/pagarme/api.py#L73-L77 | train |
michaeltcoelho/pagarme.py | pagarme/api.py | PagarmeApi.post | def post(self, action, data=None, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='POST', data=data,
headers=headers) | python | def post(self, action, data=None, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='POST', data=data,
headers=headers) | [
"def",
"post",
"(",
"self",
",",
"action",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"request",
"(",
"make_url",
"(",
"self",
".",
"endpoint",
",",
"action",
")",
",",
"method",
"=",
"'POST'",
",",
"dat... | Makes a GET request | [
"Makes",
"a",
"GET",
"request"
] | 469fdd6e61e7c24a9eaf23d474d25316c3b5450b | https://github.com/michaeltcoelho/pagarme.py/blob/469fdd6e61e7c24a9eaf23d474d25316c3b5450b/pagarme/api.py#L79-L83 | train |
michaeltcoelho/pagarme.py | pagarme/api.py | PagarmeApi.delete | def delete(self, action, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='DELETE',
headers=headers) | python | def delete(self, action, headers=None):
"""Makes a GET request
"""
return self.request(make_url(self.endpoint, action), method='DELETE',
headers=headers) | [
"def",
"delete",
"(",
"self",
",",
"action",
",",
"headers",
"=",
"None",
")",
":",
"return",
"self",
".",
"request",
"(",
"make_url",
"(",
"self",
".",
"endpoint",
",",
"action",
")",
",",
"method",
"=",
"'DELETE'",
",",
"headers",
"=",
"headers",
"... | Makes a GET request | [
"Makes",
"a",
"GET",
"request"
] | 469fdd6e61e7c24a9eaf23d474d25316c3b5450b | https://github.com/michaeltcoelho/pagarme.py/blob/469fdd6e61e7c24a9eaf23d474d25316c3b5450b/pagarme/api.py#L91-L95 | train |
JohnDoee/thomas | thomas/piece.py | calc_piece_size | def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
"""
Calculates a good piece size for a size
"""
logger.debug('Calculating piece size for %i' % size)
for i in range(min_piece_size, max_piece_size): # 20 = 1MB
if size / (2**i) < max_piece_count:
... | python | def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
"""
Calculates a good piece size for a size
"""
logger.debug('Calculating piece size for %i' % size)
for i in range(min_piece_size, max_piece_size): # 20 = 1MB
if size / (2**i) < max_piece_count:
... | [
"def",
"calc_piece_size",
"(",
"size",
",",
"min_piece_size",
"=",
"20",
",",
"max_piece_size",
"=",
"29",
",",
"max_piece_count",
"=",
"1000",
")",
":",
"logger",
".",
"debug",
"(",
"'Calculating piece size for %i'",
"%",
"size",
")",
"for",
"i",
"in",
"ran... | Calculates a good piece size for a size | [
"Calculates",
"a",
"good",
"piece",
"size",
"for",
"a",
"size"
] | 51916dd110098b189a1c2fbcb71794fd9ec94832 | https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/piece.py#L18-L27 | train |
JohnDoee/thomas | thomas/piece.py | split_pieces | def split_pieces(piece_list, segments, num):
"""
Prepare a list of all pieces grouped together
"""
piece_groups = []
pieces = list(piece_list)
while pieces:
for i in range(segments):
p = pieces[i::segments][:num]
if not p:
break
piece_g... | python | def split_pieces(piece_list, segments, num):
"""
Prepare a list of all pieces grouped together
"""
piece_groups = []
pieces = list(piece_list)
while pieces:
for i in range(segments):
p = pieces[i::segments][:num]
if not p:
break
piece_g... | [
"def",
"split_pieces",
"(",
"piece_list",
",",
"segments",
",",
"num",
")",
":",
"piece_groups",
"=",
"[",
"]",
"pieces",
"=",
"list",
"(",
"piece_list",
")",
"while",
"pieces",
":",
"for",
"i",
"in",
"range",
"(",
"segments",
")",
":",
"p",
"=",
"pi... | Prepare a list of all pieces grouped together | [
"Prepare",
"a",
"list",
"of",
"all",
"pieces",
"grouped",
"together"
] | 51916dd110098b189a1c2fbcb71794fd9ec94832 | https://github.com/JohnDoee/thomas/blob/51916dd110098b189a1c2fbcb71794fd9ec94832/thomas/piece.py#L30-L44 | train |
BlackEarth/bl | bl/rglob.py | rglob | def rglob(dirname, pattern, dirs=False, sort=True):
"""recursive glob, gets all files that match the pattern within the directory tree"""
fns = []
path = str(dirname)
if os.path.isdir(path):
fns = glob(os.path.join(escape(path), pattern))
dns = [fn for fn
in [os.p... | python | def rglob(dirname, pattern, dirs=False, sort=True):
"""recursive glob, gets all files that match the pattern within the directory tree"""
fns = []
path = str(dirname)
if os.path.isdir(path):
fns = glob(os.path.join(escape(path), pattern))
dns = [fn for fn
in [os.p... | [
"def",
"rglob",
"(",
"dirname",
",",
"pattern",
",",
"dirs",
"=",
"False",
",",
"sort",
"=",
"True",
")",
":",
"fns",
"=",
"[",
"]",
"path",
"=",
"str",
"(",
"dirname",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"fns",
... | recursive glob, gets all files that match the pattern within the directory tree | [
"recursive",
"glob",
"gets",
"all",
"files",
"that",
"match",
"the",
"pattern",
"within",
"the",
"directory",
"tree"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/rglob.py#L17-L35 | train |
teepark/junction | junction/futures.py | after | def after(parents, func=None):
'''Create a new Future whose completion depends on parent futures
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
... | python | def after(parents, func=None):
'''Create a new Future whose completion depends on parent futures
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
... | [
"def",
"after",
"(",
"parents",
",",
"func",
"=",
"None",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"lambda",
"f",
":",
"after",
"(",
"parents",
",",
"f",
")",
"dep",
"=",
"Dependent",
"(",
"parents",
",",
"func",
")",
"for",
"parent",
... | Create a new Future whose completion depends on parent futures
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
callback returns a future or list of... | [
"Create",
"a",
"new",
"Future",
"whose",
"completion",
"depends",
"on",
"parent",
"futures"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L339-L372 | train |
teepark/junction | junction/futures.py | wait_any | def wait_any(futures, timeout=None):
'''Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One o... | python | def wait_any(futures, timeout=None):
'''Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One o... | [
"def",
"wait_any",
"(",
"futures",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"fut",
"in",
"futures",
":",
"if",
"fut",
".",
"complete",
":",
"return",
"fut",
"wait",
"=",
"_Wait",
"(",
"futures",
")",
"for",
"fut",
"in",
"futures",
":",
"fut",
... | Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One of the futures from the provided list -- the ... | [
"Wait",
"for",
"the",
"completion",
"of",
"any",
"(",
"the",
"first",
")",
"one",
"of",
"multiple",
"futures"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L375-L401 | train |
teepark/junction | junction/futures.py | wait_all | def wait_all(futures, timeout=None):
'''Wait for the completion of all futures in a list
:param list future: a list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, can block indefinitely.
:type timeout: float or None
:raises WaitTimeout: if a timeout is provid... | python | def wait_all(futures, timeout=None):
'''Wait for the completion of all futures in a list
:param list future: a list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, can block indefinitely.
:type timeout: float or None
:raises WaitTimeout: if a timeout is provid... | [
"def",
"wait_all",
"(",
"futures",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"deadline",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"for",
"fut",
"in",
"futures",
":",
"fut",
".",
"wait",
"(",
"deadl... | Wait for the completion of all futures in a list
:param list future: a list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, can block indefinitely.
:type timeout: float or None
:raises WaitTimeout: if a timeout is provided and hit | [
"Wait",
"for",
"the",
"completion",
"of",
"all",
"futures",
"in",
"a",
"list"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L404-L420 | train |
teepark/junction | junction/futures.py | Future.value | def value(self):
'''The final value, if it has arrived
:raises: AttributeError, if not yet complete
:raises: an exception if the Future was :meth:`abort`\ed
'''
if not self._done.is_set():
raise AttributeError("value")
if self._failure:
raise self... | python | def value(self):
'''The final value, if it has arrived
:raises: AttributeError, if not yet complete
:raises: an exception if the Future was :meth:`abort`\ed
'''
if not self._done.is_set():
raise AttributeError("value")
if self._failure:
raise self... | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"raise",
"AttributeError",
"(",
"\"value\"",
")",
"if",
"self",
".",
"_failure",
":",
"raise",
"self",
".",
"_failure",
"[",
"0",
"]",
",",
"sel... | The final value, if it has arrived
:raises: AttributeError, if not yet complete
:raises: an exception if the Future was :meth:`abort`\ed | [
"The",
"final",
"value",
"if",
"it",
"has",
"arrived"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L38-L48 | train |
teepark/junction | junction/futures.py | Future.finish | def finish(self, value):
'''Give the future it's value and trigger any associated callbacks
:param value: the new value for the future
:raises:
:class:`AlreadyComplete <junction.errors.AlreadyComplete>` if
already complete
'''
if self._done.is_set():
... | python | def finish(self, value):
'''Give the future it's value and trigger any associated callbacks
:param value: the new value for the future
:raises:
:class:`AlreadyComplete <junction.errors.AlreadyComplete>` if
already complete
'''
if self._done.is_set():
... | [
"def",
"finish",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"raise",
"errors",
".",
"AlreadyComplete",
"(",
")",
"self",
".",
"_value",
"=",
"value",
"for",
"cb",
"in",
"self",
".",
"_cbacks",
":"... | Give the future it's value and trigger any associated callbacks
:param value: the new value for the future
:raises:
:class:`AlreadyComplete <junction.errors.AlreadyComplete>` if
already complete | [
"Give",
"the",
"future",
"it",
"s",
"value",
"and",
"trigger",
"any",
"associated",
"callbacks"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L50-L78 | train |
teepark/junction | junction/futures.py | Future.abort | def abort(self, klass, exc, tb=None):
'''Finish this future (maybe early) in an error state
Takes a standard exception triple as arguments (like returned by
``sys.exc_info``) and will re-raise them as the value.
Any :class:`Dependents` that are children of this one will also be
... | python | def abort(self, klass, exc, tb=None):
'''Finish this future (maybe early) in an error state
Takes a standard exception triple as arguments (like returned by
``sys.exc_info``) and will re-raise them as the value.
Any :class:`Dependents` that are children of this one will also be
... | [
"def",
"abort",
"(",
"self",
",",
"klass",
",",
"exc",
",",
"tb",
"=",
"None",
")",
":",
"if",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"raise",
"errors",
".",
"AlreadyComplete",
"(",
")",
"self",
".",
"_failure",
"=",
"(",
"klass",
",... | Finish this future (maybe early) in an error state
Takes a standard exception triple as arguments (like returned by
``sys.exc_info``) and will re-raise them as the value.
Any :class:`Dependents` that are children of this one will also be
aborted.
:param class klass: the class ... | [
"Finish",
"this",
"future",
"(",
"maybe",
"early",
")",
"in",
"an",
"error",
"state"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L80-L117 | train |
teepark/junction | junction/futures.py | Future.on_finish | def on_finish(self, func):
'''Assign a callback function to be run when successfully complete
:param function func:
A callback to run when complete. It will be given one argument (the
value that has arrived), and it's return value is ignored.
'''
if self._done.is... | python | def on_finish(self, func):
'''Assign a callback function to be run when successfully complete
:param function func:
A callback to run when complete. It will be given one argument (the
value that has arrived), and it's return value is ignored.
'''
if self._done.is... | [
"def",
"on_finish",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"if",
"self",
".",
"_failure",
"is",
"None",
":",
"backend",
".",
"schedule",
"(",
"func",
",",
"args",
"=",
"(",
"self",
".",
"_val... | Assign a callback function to be run when successfully complete
:param function func:
A callback to run when complete. It will be given one argument (the
value that has arrived), and it's return value is ignored. | [
"Assign",
"a",
"callback",
"function",
"to",
"be",
"run",
"when",
"successfully",
"complete"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L119-L130 | train |
teepark/junction | junction/futures.py | Future.on_abort | def on_abort(self, func):
'''Assign a callback function to be run when :meth:`abort`\ed
:param function func:
A callback to run when aborted. It will be given three arguments:
- ``klass``: the exception class
- ``exc``: the exception instance
... | python | def on_abort(self, func):
'''Assign a callback function to be run when :meth:`abort`\ed
:param function func:
A callback to run when aborted. It will be given three arguments:
- ``klass``: the exception class
- ``exc``: the exception instance
... | [
"def",
"on_abort",
"(",
"self",
",",
"func",
")",
":",
"if",
"self",
".",
"_done",
".",
"is_set",
"(",
")",
":",
"if",
"self",
".",
"_failure",
"is",
"not",
"None",
":",
"backend",
".",
"schedule",
"(",
"func",
",",
"args",
"=",
"self",
".",
"_fa... | Assign a callback function to be run when :meth:`abort`\ed
:param function func:
A callback to run when aborted. It will be given three arguments:
- ``klass``: the exception class
- ``exc``: the exception instance
- ``tb``: the traceback object assoc... | [
"Assign",
"a",
"callback",
"function",
"to",
"be",
"run",
"when",
":",
"meth",
":",
"abort",
"\\",
"ed"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L132-L146 | train |
teepark/junction | junction/futures.py | Future.after | def after(self, func=None, other_parents=None):
'''Create a new Future whose completion depends on this one
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in whic... | python | def after(self, func=None, other_parents=None):
'''Create a new Future whose completion depends on this one
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in whic... | [
"def",
"after",
"(",
"self",
",",
"func",
"=",
"None",
",",
"other_parents",
"=",
"None",
")",
":",
"parents",
"=",
"[",
"self",
"]",
"if",
"other_parents",
"is",
"not",
"None",
":",
"parents",
"+=",
"other_parents",
"return",
"after",
"(",
"parents",
... | Create a new Future whose completion depends on this one
The new future will have a function that it calls once all its parents
have completed, the return value of which will be its final value.
There is a special case, however, in which the dependent future's
callback returns a future ... | [
"Create",
"a",
"new",
"Future",
"whose",
"completion",
"depends",
"on",
"this",
"one"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L161-L188 | train |
teepark/junction | junction/futures.py | RPC.partial_results | def partial_results(self):
'''The results that the RPC has received *so far*
This may also be the complete results if :attr:`complete` is ``True``.
'''
results = []
for r in self._results:
if isinstance(r, Exception):
results.append(type(r)(*deepcopy(... | python | def partial_results(self):
'''The results that the RPC has received *so far*
This may also be the complete results if :attr:`complete` is ``True``.
'''
results = []
for r in self._results:
if isinstance(r, Exception):
results.append(type(r)(*deepcopy(... | [
"def",
"partial_results",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"_results",
":",
"if",
"isinstance",
"(",
"r",
",",
"Exception",
")",
":",
"results",
".",
"append",
"(",
"type",
"(",
"r",
")",
"(",
"*",
"... | The results that the RPC has received *so far*
This may also be the complete results if :attr:`complete` is ``True``. | [
"The",
"results",
"that",
"the",
"RPC",
"has",
"received",
"*",
"so",
"far",
"*"
] | 481d135d9e53acb55c72686e2eb4483432f35fa6 | https://github.com/teepark/junction/blob/481d135d9e53acb55c72686e2eb4483432f35fa6/junction/futures.py#L236-L250 | train |
20c/facsimile | facsimile/install.py | Install.os_path_transform | def os_path_transform(self, s, sep=os.path.sep):
""" transforms any os path into unix style """
if sep == '/':
return s
else:
return s.replace(sep, '/') | python | def os_path_transform(self, s, sep=os.path.sep):
""" transforms any os path into unix style """
if sep == '/':
return s
else:
return s.replace(sep, '/') | [
"def",
"os_path_transform",
"(",
"self",
",",
"s",
",",
"sep",
"=",
"os",
".",
"path",
".",
"sep",
")",
":",
"if",
"sep",
"==",
"'/'",
":",
"return",
"s",
"else",
":",
"return",
"s",
".",
"replace",
"(",
"sep",
",",
"'/'",
")"
] | transforms any os path into unix style | [
"transforms",
"any",
"os",
"path",
"into",
"unix",
"style"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/install.py#L96-L101 | train |
20c/facsimile | facsimile/install.py | Install.transform | def transform(self, tr_list, files):
"""
replaces $tokens$ with values
will be replaced with config rendering
"""
singular = False
if not isinstance(files, list) and not isinstance(files, tuple):
singular = True
files = [files]
for _find, ... | python | def transform(self, tr_list, files):
"""
replaces $tokens$ with values
will be replaced with config rendering
"""
singular = False
if not isinstance(files, list) and not isinstance(files, tuple):
singular = True
files = [files]
for _find, ... | [
"def",
"transform",
"(",
"self",
",",
"tr_list",
",",
"files",
")",
":",
"singular",
"=",
"False",
"if",
"not",
"isinstance",
"(",
"files",
",",
"list",
")",
"and",
"not",
"isinstance",
"(",
"files",
",",
"tuple",
")",
":",
"singular",
"=",
"True",
"... | replaces $tokens$ with values
will be replaced with config rendering | [
"replaces",
"$tokens$",
"with",
"values",
"will",
"be",
"replaced",
"with",
"config",
"rendering"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/install.py#L103-L119 | train |
20c/facsimile | facsimile/install.py | Install.resolve_dst | def resolve_dst(self, dst_dir, src):
"""
finds the destination based on source
if source is an absolute path, and there's no pattern, it copies the file to base dst_dir
"""
if os.path.isabs(src):
return os.path.join(dst_dir, os.path.basename(src))
return os.pa... | python | def resolve_dst(self, dst_dir, src):
"""
finds the destination based on source
if source is an absolute path, and there's no pattern, it copies the file to base dst_dir
"""
if os.path.isabs(src):
return os.path.join(dst_dir, os.path.basename(src))
return os.pa... | [
"def",
"resolve_dst",
"(",
"self",
",",
"dst_dir",
",",
"src",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"src",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"dst_dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"src",
... | finds the destination based on source
if source is an absolute path, and there's no pattern, it copies the file to base dst_dir | [
"finds",
"the",
"destination",
"based",
"on",
"source",
"if",
"source",
"is",
"an",
"absolute",
"path",
"and",
"there",
"s",
"no",
"pattern",
"it",
"copies",
"the",
"file",
"to",
"base",
"dst_dir"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/install.py#L133-L140 | train |
BlackEarth/bl | bl/zip.py | ZIP.write | def write(self, fn=None):
"""copy the zip file from its filename to the given filename."""
fn = fn or self.fn
if not os.path.exists(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
f = open(self.fn, 'rb')
b = f.read()
f.close()
f = open(fn, 'wb')... | python | def write(self, fn=None):
"""copy the zip file from its filename to the given filename."""
fn = fn or self.fn
if not os.path.exists(os.path.dirname(fn)):
os.makedirs(os.path.dirname(fn))
f = open(self.fn, 'rb')
b = f.read()
f.close()
f = open(fn, 'wb')... | [
"def",
"write",
"(",
"self",
",",
"fn",
"=",
"None",
")",
":",
"fn",
"=",
"fn",
"or",
"self",
".",
"fn",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fn",
")",
")",
":",
"os",
".",
"makedirs",
... | copy the zip file from its filename to the given filename. | [
"copy",
"the",
"zip",
"file",
"from",
"its",
"filename",
"to",
"the",
"given",
"filename",
"."
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/zip.py#L20-L30 | train |
michaeltcoelho/pagarme.py | pagarme/resources/resource.py | Resource.assign | def assign(self, attrs):
"""Merge new attributes
"""
for k, v in attrs.items():
setattr(self, k, v) | python | def assign(self, attrs):
"""Merge new attributes
"""
for k, v in attrs.items():
setattr(self, k, v) | [
"def",
"assign",
"(",
"self",
",",
"attrs",
")",
":",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")"
] | Merge new attributes | [
"Merge",
"new",
"attributes"
] | 469fdd6e61e7c24a9eaf23d474d25316c3b5450b | https://github.com/michaeltcoelho/pagarme.py/blob/469fdd6e61e7c24a9eaf23d474d25316c3b5450b/pagarme/resources/resource.py#L25-L29 | train |
willkg/socorro-siggen | siggen/rules.py | CSignatureTool.normalize_rust_function | def normalize_rust_function(self, function, line):
"""Normalizes a single rust frame with a function"""
# Drop the prefix and return type if there is any
function = drop_prefix_and_return_type(function)
# Collapse types
function = collapse(
function,
open... | python | def normalize_rust_function(self, function, line):
"""Normalizes a single rust frame with a function"""
# Drop the prefix and return type if there is any
function = drop_prefix_and_return_type(function)
# Collapse types
function = collapse(
function,
open... | [
"def",
"normalize_rust_function",
"(",
"self",
",",
"function",
",",
"line",
")",
":",
"# Drop the prefix and return type if there is any",
"function",
"=",
"drop_prefix_and_return_type",
"(",
"function",
")",
"# Collapse types",
"function",
"=",
"collapse",
"(",
"functio... | Normalizes a single rust frame with a function | [
"Normalizes",
"a",
"single",
"rust",
"frame",
"with",
"a",
"function"
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/rules.py#L121-L156 | train |
willkg/socorro-siggen | siggen/rules.py | CSignatureTool.normalize_cpp_function | def normalize_cpp_function(self, function, line):
"""Normalizes a single cpp frame with a function"""
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len... | python | def normalize_cpp_function(self, function, line):
"""Normalizes a single cpp frame with a function"""
# Drop member function cv/ref qualifiers like const, const&, &, and &&
for ref in ('const', 'const&', '&&', '&'):
if function.endswith(ref):
function = function[:-len... | [
"def",
"normalize_cpp_function",
"(",
"self",
",",
"function",
",",
"line",
")",
":",
"# Drop member function cv/ref qualifiers like const, const&, &, and &&",
"for",
"ref",
"in",
"(",
"'const'",
",",
"'const&'",
",",
"'&&'",
",",
"'&'",
")",
":",
"if",
"function",
... | Normalizes a single cpp frame with a function | [
"Normalizes",
"a",
"single",
"cpp",
"frame",
"with",
"a",
"function"
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/rules.py#L158-L208 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.