repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
soaxelbrooke/join | join/_join_funcs.py | union_join | def union_join(left, right, left_as='left', right_as='right'):
"""
Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog ... | python | def union_join(left, right, left_as='left', right_as='right'):
"""
Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog ... | [
"def",
"union_join",
"(",
"left",
",",
"right",
",",
"left_as",
"=",
"'left'",
",",
"right_as",
"=",
"'right'",
")",
":",
"attrs",
"=",
"{",
"}",
"attrs",
".",
"update",
"(",
"get_object_attrs",
"(",
"right",
")",
")",
"attrs",
".",
"update",
"(",
"g... | Join function truest to the SQL style join. Merges both objects together in a sum-type,
saving references to each parent in ``left`` and ``right`` attributes.
>>> Dog = namedtuple('Dog', ['name', 'woof', 'weight'])
>>> dog = Dog('gatsby', 'Ruff!', 15)
>>> Cat = namedtuple('Cat', ['name', '... | [
"Join",
"function",
"truest",
"to",
"the",
"SQL",
"style",
"join",
".",
"Merges",
"both",
"objects",
"together",
"in",
"a",
"sum",
"-",
"type",
"saving",
"references",
"to",
"each",
"parent",
"in",
"left",
"and",
"right",
"attributes",
"."
] | c84fca68ab6a52b1cee526065dc9f5a691764e69 | https://github.com/soaxelbrooke/join/blob/c84fca68ab6a52b1cee526065dc9f5a691764e69/join/_join_funcs.py#L42-L73 | train | 56,400 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Key/RPiKeyButtons.py | RPiKeyButtons.configKeyButtons | def configKeyButtons( self, enableButtons = [], bounceTime = DEF_BOUNCE_TIME_NORMAL, pullUpDown = GPIO.PUD_UP, event = GPIO.BOTH ):
"""!
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BU... | python | def configKeyButtons( self, enableButtons = [], bounceTime = DEF_BOUNCE_TIME_NORMAL, pullUpDown = GPIO.PUD_UP, event = GPIO.BOTH ):
"""!
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BU... | [
"def",
"configKeyButtons",
"(",
"self",
",",
"enableButtons",
"=",
"[",
"]",
",",
"bounceTime",
"=",
"DEF_BOUNCE_TIME_NORMAL",
",",
"pullUpDown",
"=",
"GPIO",
".",
"PUD_UP",
",",
"event",
"=",
"GPIO",
".",
"BOTH",
")",
":",
"for",
"key",
"in",
"enableButto... | !
\~english
Config multi key buttons IO and event on same time
@param enableButtons: an array of key button configs. eg. <br>
[{ "id":BUTTON_ACT_A, "callback": aCallbackFun }, ... ]
@param bounceTime: Default set to DEF_BOUNCE_TIME_NORMAL
@param pullUpDown: Defau... | [
"!",
"\\",
"~english",
"Config",
"multi",
"key",
"buttons",
"IO",
"and",
"event",
"on",
"same",
"time"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Key/RPiKeyButtons.py#L161-L189 | train | 56,401 |
azraq27/gini | gini/matching.py | best_item_from_list | def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False):
'''Returns just the best item, or ``None``'''
match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess)
if match:
return match[0]
return None | python | def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False):
'''Returns just the best item, or ``None``'''
match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess)
if match:
return match[0]
return None | [
"def",
"best_item_from_list",
"(",
"item",
",",
"options",
",",
"fuzzy",
"=",
"90",
",",
"fname_match",
"=",
"True",
",",
"fuzzy_fragment",
"=",
"None",
",",
"guess",
"=",
"False",
")",
":",
"match",
"=",
"best_match_from_list",
"(",
"item",
",",
"options"... | Returns just the best item, or ``None`` | [
"Returns",
"just",
"the",
"best",
"item",
"or",
"None"
] | 3c2b5265d096d606b303bfe25ac9adb74b8cee14 | https://github.com/azraq27/gini/blob/3c2b5265d096d606b303bfe25ac9adb74b8cee14/gini/matching.py#L63-L68 | train | 56,402 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | create_hlk_sw16_connection | async def create_hlk_sw16_connection(port=None, host=None,
disconnect_callback=None,
reconnect_callback=None, loop=None,
logger=None, timeout=None,
reconnect_interval=None)... | python | async def create_hlk_sw16_connection(port=None, host=None,
disconnect_callback=None,
reconnect_callback=None, loop=None,
logger=None, timeout=None,
reconnect_interval=None)... | [
"async",
"def",
"create_hlk_sw16_connection",
"(",
"port",
"=",
"None",
",",
"host",
"=",
"None",
",",
"disconnect_callback",
"=",
"None",
",",
"reconnect_callback",
"=",
"None",
",",
"loop",
"=",
"None",
",",
"logger",
"=",
"None",
",",
"timeout",
"=",
"N... | Create HLK-SW16 Client class. | [
"Create",
"HLK",
"-",
"SW16",
"Client",
"class",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L292-L305 | train | 56,403 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._reset_timeout | def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | python | def _reset_timeout(self):
"""Reset timeout for date keep alive."""
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | [
"def",
"_reset_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timeout",
":",
"self",
".",
"_timeout",
".",
"cancel",
"(",
")",
"self",
".",
"_timeout",
"=",
"self",
".",
"loop",
".",
"call_later",
"(",
"self",
".",
"client",
".",
"timeout",
",... | Reset timeout for date keep alive. | [
"Reset",
"timeout",
"for",
"date",
"keep",
"alive",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L30-L35 | train | 56,404 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.reset_cmd_timeout | def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | python | def reset_cmd_timeout(self):
"""Reset timeout for command execution."""
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | [
"def",
"reset_cmd_timeout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cmd_timeout",
":",
"self",
".",
"_cmd_timeout",
".",
"cancel",
"(",
")",
"self",
".",
"_cmd_timeout",
"=",
"self",
".",
"loop",
".",
"call_later",
"(",
"self",
".",
"client",
".",
... | Reset timeout for command execution. | [
"Reset",
"timeout",
"for",
"command",
"execution",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L37-L42 | train | 56,405 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._valid_packet | def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18... | python | def _valid_packet(raw_packet):
"""Validate incoming packet."""
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18... | [
"def",
"_valid_packet",
"(",
"raw_packet",
")",
":",
"if",
"raw_packet",
"[",
"0",
":",
"1",
"]",
"!=",
"b'\\xcc'",
":",
"return",
"False",
"if",
"len",
"(",
"raw_packet",
")",
"!=",
"19",
":",
"return",
"False",
"checksum",
"=",
"0",
"for",
"i",
"in... | Validate incoming packet. | [
"Validate",
"incoming",
"packet",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L62-L73 | train | 56,406 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._handle_raw_packet | def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
... | python | def _handle_raw_packet(self, raw_packet):
"""Parse incoming packet."""
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
... | [
"def",
"_handle_raw_packet",
"(",
"self",
",",
"raw_packet",
")",
":",
"if",
"raw_packet",
"[",
"1",
":",
"2",
"]",
"==",
"b'\\x1f'",
":",
"self",
".",
"_reset_timeout",
"(",
")",
"year",
"=",
"raw_packet",
"[",
"2",
"]",
"month",
"=",
"raw_packet",
"[... | Parse incoming packet. | [
"Parse",
"incoming",
"packet",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L75-L125 | train | 56,407 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.send_packet | def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_pack... | python | def send_packet(self):
"""Write next packet in send queue."""
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_pack... | [
"def",
"send_packet",
"(",
"self",
")",
":",
"waiter",
",",
"packet",
"=",
"self",
".",
"client",
".",
"waiters",
".",
"popleft",
"(",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'sending packet: %s'",
",",
"binascii",
".",
"hexlify",
"(",
"packet",
... | Write next packet in send queue. | [
"Write",
"next",
"packet",
"in",
"send",
"queue",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L127-L135 | train | 56,408 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.format_packet | def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim | python | def format_packet(command):
"""Format packet to be sent."""
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim | [
"def",
"format_packet",
"(",
"command",
")",
":",
"frame_header",
"=",
"b\"\\xaa\"",
"verify",
"=",
"b\"\\x0b\"",
"send_delim",
"=",
"b\"\\xbb\"",
"return",
"frame_header",
"+",
"command",
".",
"ljust",
"(",
"17",
",",
"b\"\\x00\"",
")",
"+",
"verify",
"+",
... | Format packet to be sent. | [
"Format",
"packet",
"to",
"be",
"sent",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L138-L143 | train | 56,409 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.setup | async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop,... | python | async def setup(self):
"""Set up the connection with automatic retry."""
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop,... | [
"async",
"def",
"setup",
"(",
"self",
")",
":",
"while",
"True",
":",
"fut",
"=",
"self",
".",
"loop",
".",
"create_connection",
"(",
"lambda",
":",
"SW16Protocol",
"(",
"self",
",",
"disconnect_callback",
"=",
"self",
".",
"handle_disconnect_callback",
",",... | Set up the connection with automatic retry. | [
"Set",
"up",
"the",
"connection",
"with",
"automatic",
"retry",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L188-L211 | train | 56,410 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.stop | def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close() | python | def stop(self):
"""Shut down transport."""
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"reconnect",
"=",
"False",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Shutting down.\"",
")",
"if",
"self",
".",
"transport",
":",
"self",
".",
"transport",
".",
"close",
"(",
")"
] | Shut down transport. | [
"Shut",
"down",
"transport",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L213-L218 | train | 56,411 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.handle_disconnect_callback | async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
aw... | python | async def handle_disconnect_callback(self):
"""Reconnect automatically unless stopping."""
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
aw... | [
"async",
"def",
"handle_disconnect_callback",
"(",
"self",
")",
":",
"self",
".",
"is_connected",
"=",
"False",
"if",
"self",
".",
"disconnect_callback",
":",
"self",
".",
"disconnect_callback",
"(",
")",
"if",
"self",
".",
"reconnect",
":",
"self",
".",
"lo... | Reconnect automatically unless stopping. | [
"Reconnect",
"automatically",
"unless",
"stopping",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L220-L233 | train | 56,412 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.register_status_callback | def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback) | python | def register_status_callback(self, callback, switch):
"""Register a callback which will fire when state changes."""
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback) | [
"def",
"register_status_callback",
"(",
"self",
",",
"callback",
",",
"switch",
")",
":",
"if",
"self",
".",
"status_callbacks",
".",
"get",
"(",
"switch",
",",
"None",
")",
"is",
"None",
":",
"self",
".",
"status_callbacks",
"[",
"switch",
"]",
"=",
"["... | Register a callback which will fire when state changes. | [
"Register",
"a",
"callback",
"which",
"will",
"fire",
"when",
"state",
"changes",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L235-L239 | train | 56,413 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client._send | def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut | python | def _send(self, packet):
"""Add packet to send queue."""
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut | [
"def",
"_send",
"(",
"self",
",",
"packet",
")",
":",
"fut",
"=",
"self",
".",
"loop",
".",
"create_future",
"(",
")",
"self",
".",
"waiters",
".",
"append",
"(",
"(",
"fut",
",",
"packet",
")",
")",
"if",
"self",
".",
"waiters",
"and",
"self",
"... | Add packet to send queue. | [
"Add",
"packet",
"to",
"send",
"queue",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L241-L247 | train | 56,414 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.turn_on | async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
s... | python | async def turn_on(self, switch=None):
"""Turn on relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
s... | [
"async",
"def",
"turn_on",
"(",
"self",
",",
"switch",
"=",
"None",
")",
":",
"if",
"switch",
"is",
"not",
"None",
":",
"switch",
"=",
"codecs",
".",
"decode",
"(",
"switch",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
",",
"'hex'",
")",
"packet",
"... | Turn on relay. | [
"Turn",
"on",
"relay",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L249-L257 | train | 56,415 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.turn_off | async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
... | python | async def turn_off(self, switch=None):
"""Turn off relay."""
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
... | [
"async",
"def",
"turn_off",
"(",
"self",
",",
"switch",
"=",
"None",
")",
":",
"if",
"switch",
"is",
"not",
"None",
":",
"switch",
"=",
"codecs",
".",
"decode",
"(",
"switch",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
",",
"'hex'",
")",
"packet",
... | Turn off relay. | [
"Turn",
"off",
"relay",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L259-L267 | train | 56,416 |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.status | async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = state... | python | async def status(self, switch=None):
"""Get current relay status."""
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = state... | [
"async",
"def",
"status",
"(",
"self",
",",
"switch",
"=",
"None",
")",
":",
"if",
"switch",
"is",
"not",
"None",
":",
"if",
"self",
".",
"waiters",
"or",
"self",
".",
"in_transaction",
":",
"fut",
"=",
"self",
".",
"loop",
".",
"create_future",
"(",... | Get current relay status. | [
"Get",
"current",
"relay",
"status",
"."
] | 4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56 | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L269-L289 | train | 56,417 |
ThomasChiroux/attowiki | src/attowiki/git_tools.py | _delta_dir | def _delta_dir():
"""returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative... | python | def _delta_dir():
"""returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative... | [
"def",
"_delta_dir",
"(",
")",
":",
"repo",
"=",
"Repo",
"(",
")",
"current_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"repo_dir",
"=",
"repo",
".",
"tree",
"(",
")",
".",
"abspath",
"delta_dir",
"=",
"current_dir",
".",
"replace",
"(",
"repo_dir",
",... | returns the relative path of the current directory to the git
repository.
This path will be added the 'filename' path to find the file.
It current_dir is the git root, this function returns an empty string.
Keyword Arguments:
<none>
Returns:
str -- relative path of the current dir ... | [
"returns",
"the",
"relative",
"path",
"of",
"the",
"current",
"directory",
"to",
"the",
"git",
"repository",
".",
"This",
"path",
"will",
"be",
"added",
"the",
"filename",
"path",
"to",
"find",
"the",
"file",
".",
"It",
"current_dir",
"is",
"the",
"git",
... | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L32-L52 | train | 56,418 |
ThomasChiroux/attowiki | src/attowiki/git_tools.py | add_file_to_repo | def add_file_to_repo(filename):
"""Add a file to the git repo
This method does the same than a ::
$ git add filename
Keyword Arguments:
:filename: (str) -- name of the file to commit
Returns:
<nothing>
"""
try:
repo = Repo()
index = repo.index
... | python | def add_file_to_repo(filename):
"""Add a file to the git repo
This method does the same than a ::
$ git add filename
Keyword Arguments:
:filename: (str) -- name of the file to commit
Returns:
<nothing>
"""
try:
repo = Repo()
index = repo.index
... | [
"def",
"add_file_to_repo",
"(",
"filename",
")",
":",
"try",
":",
"repo",
"=",
"Repo",
"(",
")",
"index",
"=",
"repo",
".",
"index",
"index",
".",
"add",
"(",
"[",
"_delta_dir",
"(",
")",
"+",
"filename",
"]",
")",
"except",
"Exception",
"as",
"e",
... | Add a file to the git repo
This method does the same than a ::
$ git add filename
Keyword Arguments:
:filename: (str) -- name of the file to commit
Returns:
<nothing> | [
"Add",
"a",
"file",
"to",
"the",
"git",
"repo"
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L94-L112 | train | 56,419 |
ThomasChiroux/attowiki | src/attowiki/git_tools.py | reset_to_last_commit | def reset_to_last_commit():
"""reset a modified file to his last commit status
This method does the same than a ::
$ git reset --hard
Keyword Arguments:
<none>
Returns:
<nothing>
"""
try:
repo = Repo()
gitcmd = repo.git
gitcmd.reset(hard=True)
... | python | def reset_to_last_commit():
"""reset a modified file to his last commit status
This method does the same than a ::
$ git reset --hard
Keyword Arguments:
<none>
Returns:
<nothing>
"""
try:
repo = Repo()
gitcmd = repo.git
gitcmd.reset(hard=True)
... | [
"def",
"reset_to_last_commit",
"(",
")",
":",
"try",
":",
"repo",
"=",
"Repo",
"(",
")",
"gitcmd",
"=",
"repo",
".",
"git",
"gitcmd",
".",
"reset",
"(",
"hard",
"=",
"True",
")",
"except",
"Exception",
":",
"pass"
] | reset a modified file to his last commit status
This method does the same than a ::
$ git reset --hard
Keyword Arguments:
<none>
Returns:
<nothing> | [
"reset",
"a",
"modified",
"file",
"to",
"his",
"last",
"commit",
"status"
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L115-L133 | train | 56,420 |
ThomasChiroux/attowiki | src/attowiki/git_tools.py | commit_history | def commit_history(filename):
"""Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list
"""
result = []
repo = Repo()... | python | def commit_history(filename):
"""Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list
"""
result = []
repo = Repo()... | [
"def",
"commit_history",
"(",
"filename",
")",
":",
"result",
"=",
"[",
"]",
"repo",
"=",
"Repo",
"(",
")",
"for",
"commit",
"in",
"repo",
".",
"head",
".",
"commit",
".",
"iter_parents",
"(",
"paths",
"=",
"_delta_dir",
"(",
")",
"+",
"filename",
")... | Retrieve the commit history for a given filename.
Keyword Arguments:
:filename: (str) -- full name of the file
Returns:
list of dicts -- list of commit
if the file is not found, returns an empty list | [
"Retrieve",
"the",
"commit",
"history",
"for",
"a",
"given",
"filename",
"."
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L136-L153 | train | 56,421 |
ThomasChiroux/attowiki | src/attowiki/git_tools.py | read_committed_file | def read_committed_file(gitref, filename):
"""Retrieve the content of a file in an old commit and returns it.
Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file
Returns:
str -- content of the file
"""
repo ... | python | def read_committed_file(gitref, filename):
"""Retrieve the content of a file in an old commit and returns it.
Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file
Returns:
str -- content of the file
"""
repo ... | [
"def",
"read_committed_file",
"(",
"gitref",
",",
"filename",
")",
":",
"repo",
"=",
"Repo",
"(",
")",
"commitobj",
"=",
"repo",
".",
"commit",
"(",
"gitref",
")",
"blob",
"=",
"commitobj",
".",
"tree",
"[",
"_delta_dir",
"(",
")",
"+",
"filename",
"]"... | Retrieve the content of a file in an old commit and returns it.
Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file
Returns:
str -- content of the file | [
"Retrieve",
"the",
"content",
"of",
"a",
"file",
"in",
"an",
"old",
"commit",
"and",
"returns",
"it",
"."
] | 6c93c420305490d324fdc95a7b40b2283a222183 | https://github.com/ThomasChiroux/attowiki/blob/6c93c420305490d324fdc95a7b40b2283a222183/src/attowiki/git_tools.py#L156-L170 | train | 56,422 |
stevepeak/dictime | dictime/dictime.py | dictime.get | def get(self, key, _else=None):
"""The method to get an assets value
"""
with self._lock:
self.expired()
# see if everything expired
try:
value = self._dict[key].get()
return value
except KeyError:
re... | python | def get(self, key, _else=None):
"""The method to get an assets value
"""
with self._lock:
self.expired()
# see if everything expired
try:
value = self._dict[key].get()
return value
except KeyError:
re... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"_else",
"=",
"None",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"expired",
"(",
")",
"# see if everything expired",
"try",
":",
"value",
"=",
"self",
".",
"_dict",
"[",
"key",
"]",
".",
"g... | The method to get an assets value | [
"The",
"method",
"to",
"get",
"an",
"assets",
"value"
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L45-L57 | train | 56,423 |
stevepeak/dictime | dictime/dictime.py | dictime.set | def set(self, key, value, expires=None, future=None):
"""Set a value
"""
# assert the values above
with self._lock:
try:
self._dict[key].set(value, expires=expires, future=future)
except KeyError:
self._dict[key] = moment(value, exp... | python | def set(self, key, value, expires=None, future=None):
"""Set a value
"""
# assert the values above
with self._lock:
try:
self._dict[key].set(value, expires=expires, future=future)
except KeyError:
self._dict[key] = moment(value, exp... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
",",
"expires",
"=",
"None",
",",
"future",
"=",
"None",
")",
":",
"# assert the values above",
"with",
"self",
".",
"_lock",
":",
"try",
":",
"self",
".",
"_dict",
"[",
"key",
"]",
".",
"set",
"... | Set a value | [
"Set",
"a",
"value"
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L65-L74 | train | 56,424 |
stevepeak/dictime | dictime/dictime.py | dictime.values | def values(self):
"""Will only return the current values
"""
self.expired()
values = []
for key in self._dict.keys():
try:
value = self._dict[key].get()
values.append(value)
except:
continue
return va... | python | def values(self):
"""Will only return the current values
"""
self.expired()
values = []
for key in self._dict.keys():
try:
value = self._dict[key].get()
values.append(value)
except:
continue
return va... | [
"def",
"values",
"(",
"self",
")",
":",
"self",
".",
"expired",
"(",
")",
"values",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"_dict",
".",
"keys",
"(",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"_dict",
"[",
"key",
"]",
".",
"ge... | Will only return the current values | [
"Will",
"only",
"return",
"the",
"current",
"values"
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L110-L121 | train | 56,425 |
stevepeak/dictime | dictime/dictime.py | dictime.has_key | def has_key(self, key):
"""Does the key exist?
This method will check to see if it has expired too.
"""
if key in self._dict:
try:
self[key]
return True
except ValueError:
return False
except KeyError:
... | python | def has_key(self, key):
"""Does the key exist?
This method will check to see if it has expired too.
"""
if key in self._dict:
try:
self[key]
return True
except ValueError:
return False
except KeyError:
... | [
"def",
"has_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"_dict",
":",
"try",
":",
"self",
"[",
"key",
"]",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False",
"except",
"KeyError",
":",
"return",
"False",
"r... | Does the key exist?
This method will check to see if it has expired too. | [
"Does",
"the",
"key",
"exist?",
"This",
"method",
"will",
"check",
"to",
"see",
"if",
"it",
"has",
"expired",
"too",
"."
] | 6d8724bed5a7844e47a9c16a233f8db494c98c61 | https://github.com/stevepeak/dictime/blob/6d8724bed5a7844e47a9c16a233f8db494c98c61/dictime/dictime.py#L123-L135 | train | 56,426 |
LREN-CHUV/data-tracking | data_tracking/dicom_import.py | dicom2db | def dicom2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False,
visit_in_path=False, rep_in_path=False):
"""Extract some meta-data from a DICOM file and store in a DB.
Arguments:
:param file_path: File path.
:param file_type: File type (should be 'DICO... | python | def dicom2db(file_path, file_type, is_copy, step_id, db_conn, sid_by_patient=False, pid_in_vid=False,
visit_in_path=False, rep_in_path=False):
"""Extract some meta-data from a DICOM file and store in a DB.
Arguments:
:param file_path: File path.
:param file_type: File type (should be 'DICO... | [
"def",
"dicom2db",
"(",
"file_path",
",",
"file_type",
",",
"is_copy",
",",
"step_id",
",",
"db_conn",
",",
"sid_by_patient",
"=",
"False",
",",
"pid_in_vid",
"=",
"False",
",",
"visit_in_path",
"=",
"False",
",",
"rep_in_path",
"=",
"False",
")",
":",
"gl... | Extract some meta-data from a DICOM file and store in a DB.
Arguments:
:param file_path: File path.
:param file_type: File type (should be 'DICOM').
:param is_copy: Indicate if this file is a copy.
:param step_id: Step ID
:param db_conn: Database connection.
:param sid_by_patient: Rarely, a... | [
"Extract",
"some",
"meta",
"-",
"data",
"from",
"a",
"DICOM",
"file",
"and",
"store",
"in",
"a",
"DB",
"."
] | f645a0d6426e6019c92d5aaf4be225cff2864417 | https://github.com/LREN-CHUV/data-tracking/blob/f645a0d6426e6019c92d5aaf4be225cff2864417/data_tracking/dicom_import.py#L25-L77 | train | 56,427 |
mixer/beam-interactive-python | beam_interactive/proto/rw.py | _Decoder.remaining_bytes | def remaining_bytes(self, meta=True):
"""
Returns the remaining, unread bytes from the buffer.
"""
pos, self._pos = self._pos, len(self.buffer)
return self.buffer[pos:] | python | def remaining_bytes(self, meta=True):
"""
Returns the remaining, unread bytes from the buffer.
"""
pos, self._pos = self._pos, len(self.buffer)
return self.buffer[pos:] | [
"def",
"remaining_bytes",
"(",
"self",
",",
"meta",
"=",
"True",
")",
":",
"pos",
",",
"self",
".",
"_pos",
"=",
"self",
".",
"_pos",
",",
"len",
"(",
"self",
".",
"buffer",
")",
"return",
"self",
".",
"buffer",
"[",
"pos",
":",
"]"
] | Returns the remaining, unread bytes from the buffer. | [
"Returns",
"the",
"remaining",
"unread",
"bytes",
"from",
"the",
"buffer",
"."
] | e035bc45515dea9315b77648a24b5ae8685aa5cf | https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/proto/rw.py#L28-L33 | train | 56,428 |
mixer/beam-interactive-python | beam_interactive/proto/rw.py | _Decoder.decode | def decode(self, bytes):
"""
Decodes the packet off the byte string.
"""
self.buffer = bytes
self._pos = 0
Packet = identifier.get_packet_from_id(self._read_variunt())
# unknown packets will be None from the identifier
if Packet is None:
ret... | python | def decode(self, bytes):
"""
Decodes the packet off the byte string.
"""
self.buffer = bytes
self._pos = 0
Packet = identifier.get_packet_from_id(self._read_variunt())
# unknown packets will be None from the identifier
if Packet is None:
ret... | [
"def",
"decode",
"(",
"self",
",",
"bytes",
")",
":",
"self",
".",
"buffer",
"=",
"bytes",
"self",
".",
"_pos",
"=",
"0",
"Packet",
"=",
"identifier",
".",
"get_packet_from_id",
"(",
"self",
".",
"_read_variunt",
"(",
")",
")",
"# unknown packets will be N... | Decodes the packet off the byte string. | [
"Decodes",
"the",
"packet",
"off",
"the",
"byte",
"string",
"."
] | e035bc45515dea9315b77648a24b5ae8685aa5cf | https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/proto/rw.py#L35-L51 | train | 56,429 |
mixer/beam-interactive-python | beam_interactive/proto/rw.py | _Encoder.encode | def encode(self, packet):
"""
Pushes a packet to the writer, encoding it on the internal
buffer.
"""
id = identifier.get_packet_id(packet)
if id is None:
raise EncoderException('unknown packet')
self._write_variunt(id)
self._write(packet.Seri... | python | def encode(self, packet):
"""
Pushes a packet to the writer, encoding it on the internal
buffer.
"""
id = identifier.get_packet_id(packet)
if id is None:
raise EncoderException('unknown packet')
self._write_variunt(id)
self._write(packet.Seri... | [
"def",
"encode",
"(",
"self",
",",
"packet",
")",
":",
"id",
"=",
"identifier",
".",
"get_packet_id",
"(",
"packet",
")",
"if",
"id",
"is",
"None",
":",
"raise",
"EncoderException",
"(",
"'unknown packet'",
")",
"self",
".",
"_write_variunt",
"(",
"id",
... | Pushes a packet to the writer, encoding it on the internal
buffer. | [
"Pushes",
"a",
"packet",
"to",
"the",
"writer",
"encoding",
"it",
"on",
"the",
"internal",
"buffer",
"."
] | e035bc45515dea9315b77648a24b5ae8685aa5cf | https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/proto/rw.py#L71-L84 | train | 56,430 |
wuher/devil | devil/fields/factory.py | Factory.create | def create(self, data):
""" Create object from the given data.
The given data may or may not have been validated prior to calling
this function. This function will try its best in creating the object.
If the resulting object cannot be produced, raises ``ValidationError``.
The s... | python | def create(self, data):
""" Create object from the given data.
The given data may or may not have been validated prior to calling
this function. This function will try its best in creating the object.
If the resulting object cannot be produced, raises ``ValidationError``.
The s... | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"# todo: copy-paste code from representation.validate -> refactor",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"prototype",
"=",
"{",
"}",
"errors",
"=",
"{",
"}",
"# create and populate the prototype",
"f... | Create object from the given data.
The given data may or may not have been validated prior to calling
this function. This function will try its best in creating the object.
If the resulting object cannot be produced, raises ``ValidationError``.
The spec can affect how individual fields... | [
"Create",
"object",
"from",
"the",
"given",
"data",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L74-L132 | train | 56,431 |
wuher/devil | devil/fields/factory.py | Factory.serialize | def serialize(self, entity, request=None):
""" Serialize entity into dictionary.
The spec can affect how individual fields will be serialized by
implementing ``serialize()`` for the fields needing customization.
:returns: dictionary
"""
def should_we_insert(value, fiel... | python | def serialize(self, entity, request=None):
""" Serialize entity into dictionary.
The spec can affect how individual fields will be serialized by
implementing ``serialize()`` for the fields needing customization.
:returns: dictionary
"""
def should_we_insert(value, fiel... | [
"def",
"serialize",
"(",
"self",
",",
"entity",
",",
"request",
"=",
"None",
")",
":",
"def",
"should_we_insert",
"(",
"value",
",",
"field_spec",
")",
":",
"return",
"value",
"not",
"in",
"self",
".",
"missing",
"or",
"field_spec",
".",
"required",
"err... | Serialize entity into dictionary.
The spec can affect how individual fields will be serialized by
implementing ``serialize()`` for the fields needing customization.
:returns: dictionary | [
"Serialize",
"entity",
"into",
"dictionary",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L134-L169 | train | 56,432 |
wuher/devil | devil/fields/factory.py | Factory._create_value | def _create_value(self, data, name, spec):
""" Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity.
"""
field = getattr(self, 'create_' + name, None)
... | python | def _create_value(self, data, name, spec):
""" Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity.
"""
field = getattr(self, 'create_' + name, None)
... | [
"def",
"_create_value",
"(",
"self",
",",
"data",
",",
"name",
",",
"spec",
")",
":",
"field",
"=",
"getattr",
"(",
"self",
",",
"'create_'",
"+",
"name",
",",
"None",
")",
"if",
"field",
":",
"# this factory has a special creator function for this field",
"re... | Create the value for a field.
:param data: the whole data for the entity (all fields).
:param name: name of the initialized field.
:param spec: spec for the whole entity. | [
"Create",
"the",
"value",
"for",
"a",
"field",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L171-L184 | train | 56,433 |
wuher/devil | devil/fields/factory.py | Factory._get_serialize_func | def _get_serialize_func(self, name, spec):
""" Return the function that is used for serialization. """
func = getattr(self, 'serialize_' + name, None)
if func:
# this factory has a special serializer function for this field
return func
func = getattr(spec.fields[n... | python | def _get_serialize_func(self, name, spec):
""" Return the function that is used for serialization. """
func = getattr(self, 'serialize_' + name, None)
if func:
# this factory has a special serializer function for this field
return func
func = getattr(spec.fields[n... | [
"def",
"_get_serialize_func",
"(",
"self",
",",
"name",
",",
"spec",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
",",
"'serialize_'",
"+",
"name",
",",
"None",
")",
"if",
"func",
":",
"# this factory has a special serializer function for this field",
"return",
... | Return the function that is used for serialization. | [
"Return",
"the",
"function",
"that",
"is",
"used",
"for",
"serialization",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L186-L195 | train | 56,434 |
wuher/devil | devil/fields/factory.py | Factory._create_mappings | def _create_mappings(self, spec):
""" Create property name map based on aliases. """
ret = dict(zip(set(spec.fields), set(spec.fields)))
ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias]))
return ret | python | def _create_mappings(self, spec):
""" Create property name map based on aliases. """
ret = dict(zip(set(spec.fields), set(spec.fields)))
ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias]))
return ret | [
"def",
"_create_mappings",
"(",
"self",
",",
"spec",
")",
":",
"ret",
"=",
"dict",
"(",
"zip",
"(",
"set",
"(",
"spec",
".",
"fields",
")",
",",
"set",
"(",
"spec",
".",
"fields",
")",
")",
")",
"ret",
".",
"update",
"(",
"dict",
"(",
"[",
"(",... | Create property name map based on aliases. | [
"Create",
"property",
"name",
"map",
"based",
"on",
"aliases",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/factory.py#L202-L206 | train | 56,435 |
CodyKochmann/generators | generators/all_substrings.py | all_substrings | def all_substrings(s):
''' yields all substrings of a string '''
join = ''.join
for i in range(1, len(s) + 1):
for sub in window(s, i):
yield join(sub) | python | def all_substrings(s):
''' yields all substrings of a string '''
join = ''.join
for i in range(1, len(s) + 1):
for sub in window(s, i):
yield join(sub) | [
"def",
"all_substrings",
"(",
"s",
")",
":",
"join",
"=",
"''",
".",
"join",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"s",
")",
"+",
"1",
")",
":",
"for",
"sub",
"in",
"window",
"(",
"s",
",",
"i",
")",
":",
"yield",
"join",
"(... | yields all substrings of a string | [
"yields",
"all",
"substrings",
"of",
"a",
"string"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/all_substrings.py#L12-L17 | train | 56,436 |
mozilla/rna | rna/models.py | Release.equivalent_release_for_product | def equivalent_release_for_product(self, product):
"""
Returns the release for a specified product with the same
channel and major version with the highest minor version,
or None if no such releases exist
"""
releases = self._default_manager.filter(
version__s... | python | def equivalent_release_for_product(self, product):
"""
Returns the release for a specified product with the same
channel and major version with the highest minor version,
or None if no such releases exist
"""
releases = self._default_manager.filter(
version__s... | [
"def",
"equivalent_release_for_product",
"(",
"self",
",",
"product",
")",
":",
"releases",
"=",
"self",
".",
"_default_manager",
".",
"filter",
"(",
"version__startswith",
"=",
"self",
".",
"major_version",
"(",
")",
"+",
"'.'",
",",
"channel",
"=",
"self",
... | Returns the release for a specified product with the same
channel and major version with the highest minor version,
or None if no such releases exist | [
"Returns",
"the",
"release",
"for",
"a",
"specified",
"product",
"with",
"the",
"same",
"channel",
"and",
"major",
"version",
"with",
"the",
"highest",
"minor",
"version",
"or",
"None",
"if",
"no",
"such",
"releases",
"exist"
] | c1d3931f577dc9c54997f876d36bc0b44dc225ea | https://github.com/mozilla/rna/blob/c1d3931f577dc9c54997f876d36bc0b44dc225ea/rna/models.py#L94-L109 | train | 56,437 |
mozilla/rna | rna/models.py | Release.notes | def notes(self, public_only=False):
"""
Retrieve a list of Note instances that should be shown for this
release, grouped as either new features or known issues, and sorted
first by sort_num highest to lowest and then by created date,
which is applied to both groups,
and t... | python | def notes(self, public_only=False):
"""
Retrieve a list of Note instances that should be shown for this
release, grouped as either new features or known issues, and sorted
first by sort_num highest to lowest and then by created date,
which is applied to both groups,
and t... | [
"def",
"notes",
"(",
"self",
",",
"public_only",
"=",
"False",
")",
":",
"tag_index",
"=",
"dict",
"(",
"(",
"tag",
",",
"i",
")",
"for",
"i",
",",
"tag",
"in",
"enumerate",
"(",
"Note",
".",
"TAGS",
")",
")",
"notes",
"=",
"self",
".",
"note_set... | Retrieve a list of Note instances that should be shown for this
release, grouped as either new features or known issues, and sorted
first by sort_num highest to lowest and then by created date,
which is applied to both groups,
and then for new features we also sort by tag in the order sp... | [
"Retrieve",
"a",
"list",
"of",
"Note",
"instances",
"that",
"should",
"be",
"shown",
"for",
"this",
"release",
"grouped",
"as",
"either",
"new",
"features",
"or",
"known",
"issues",
"and",
"sorted",
"first",
"by",
"sort_num",
"highest",
"to",
"lowest",
"and"... | c1d3931f577dc9c54997f876d36bc0b44dc225ea | https://github.com/mozilla/rna/blob/c1d3931f577dc9c54997f876d36bc0b44dc225ea/rna/models.py#L119-L142 | train | 56,438 |
mozilla/rna | rna/models.py | Release.to_dict | def to_dict(self):
"""Return a dict all all data about the release"""
data = model_to_dict(self, exclude=['id'])
data['title'] = unicode(self)
data['slug'] = self.slug
data['release_date'] = self.release_date.date().isoformat()
data['created'] = self.created.isoformat()
... | python | def to_dict(self):
"""Return a dict all all data about the release"""
data = model_to_dict(self, exclude=['id'])
data['title'] = unicode(self)
data['slug'] = self.slug
data['release_date'] = self.release_date.date().isoformat()
data['created'] = self.created.isoformat()
... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"model_to_dict",
"(",
"self",
",",
"exclude",
"=",
"[",
"'id'",
"]",
")",
"data",
"[",
"'title'",
"]",
"=",
"unicode",
"(",
"self",
")",
"data",
"[",
"'slug'",
"]",
"=",
"self",
".",
"slug",
"... | Return a dict all all data about the release | [
"Return",
"a",
"dict",
"all",
"all",
"data",
"about",
"the",
"release"
] | c1d3931f577dc9c54997f876d36bc0b44dc225ea | https://github.com/mozilla/rna/blob/c1d3931f577dc9c54997f876d36bc0b44dc225ea/rna/models.py#L144-L156 | train | 56,439 |
mozilla/rna | rna/models.py | Release.to_simple_dict | def to_simple_dict(self):
"""Return a dict of only the basic data about the release"""
return {
'version': self.version,
'product': self.product,
'channel': self.channel,
'is_public': self.is_public,
'slug': self.slug,
'title': unic... | python | def to_simple_dict(self):
"""Return a dict of only the basic data about the release"""
return {
'version': self.version,
'product': self.product,
'channel': self.channel,
'is_public': self.is_public,
'slug': self.slug,
'title': unic... | [
"def",
"to_simple_dict",
"(",
"self",
")",
":",
"return",
"{",
"'version'",
":",
"self",
".",
"version",
",",
"'product'",
":",
"self",
".",
"product",
",",
"'channel'",
":",
"self",
".",
"channel",
",",
"'is_public'",
":",
"self",
".",
"is_public",
",",... | Return a dict of only the basic data about the release | [
"Return",
"a",
"dict",
"of",
"only",
"the",
"basic",
"data",
"about",
"the",
"release"
] | c1d3931f577dc9c54997f876d36bc0b44dc225ea | https://github.com/mozilla/rna/blob/c1d3931f577dc9c54997f876d36bc0b44dc225ea/rna/models.py#L158-L167 | train | 56,440 |
mobinrg/rpi_spark_drives | JMRPiSpark/Drives/Audio/RPiTone.py | RPiTonePlayer.playToneList | def playToneList(self, playList = None):
"""!
\~english
Play tone from a tone list
@param playList a array of tones
\~chinese
播放音调列表
@param playList: 音调数组
\~english @note <b>playList</b> format:\n
\~chinese @note <b>playList</b> 格... | python | def playToneList(self, playList = None):
"""!
\~english
Play tone from a tone list
@param playList a array of tones
\~chinese
播放音调列表
@param playList: 音调数组
\~english @note <b>playList</b> format:\n
\~chinese @note <b>playList</b> 格... | [
"def",
"playToneList",
"(",
"self",
",",
"playList",
"=",
"None",
")",
":",
"if",
"playList",
"==",
"None",
":",
"return",
"False",
"for",
"t",
"in",
"playList",
":",
"self",
".",
"playTone",
"(",
"t",
"[",
"\"freq\"",
"]",
",",
"t",
"[",
"\"reps\"",... | !
\~english
Play tone from a tone list
@param playList a array of tones
\~chinese
播放音调列表
@param playList: 音调数组
\~english @note <b>playList</b> format:\n
\~chinese @note <b>playList</b> 格式:\n
\~
<pre>
[
... | [
"!",
"\\",
"~english",
"Play",
"tone",
"from",
"a",
"tone",
"list"
] | e1602d8268a5ef48e9e0a8b37de89e0233f946ea | https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Audio/RPiTone.py#L197-L229 | train | 56,441 |
objectrocket/python-client | objectrocket/acls.py | Acls.all | def all(self, instance):
"""Get all ACLs associated with the instance specified by name.
:param str instance: The name of the instance from which to fetch ACLs.
:returns: A list of :py:class:`Acl` objects associated with the specified instance.
:rtype: list
"""
url = sel... | python | def all(self, instance):
"""Get all ACLs associated with the instance specified by name.
:param str instance: The name of the instance from which to fetch ACLs.
:returns: A list of :py:class:`Acl` objects associated with the specified instance.
:rtype: list
"""
url = sel... | [
"def",
"all",
"(",
"self",
",",
"instance",
")",
":",
"url",
"=",
"self",
".",
"_url",
".",
"format",
"(",
"instance",
"=",
"instance",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"*",
"*",
"self",
".",
"_default_request_kwargs",
"... | Get all ACLs associated with the instance specified by name.
:param str instance: The name of the instance from which to fetch ACLs.
:returns: A list of :py:class:`Acl` objects associated with the specified instance.
:rtype: list | [
"Get",
"all",
"ACLs",
"associated",
"with",
"the",
"instance",
"specified",
"by",
"name",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L28-L38 | train | 56,442 |
objectrocket/python-client | objectrocket/acls.py | Acls.create | def create(self, instance, cidr_mask, description, **kwargs):
"""Create an ACL entry for the specified instance.
:param str instance: The name of the instance to associate the new ACL entry with.
:param str cidr_mask: The IPv4 CIDR mask for the new ACL entry.
:param str description: A s... | python | def create(self, instance, cidr_mask, description, **kwargs):
"""Create an ACL entry for the specified instance.
:param str instance: The name of the instance to associate the new ACL entry with.
:param str cidr_mask: The IPv4 CIDR mask for the new ACL entry.
:param str description: A s... | [
"def",
"create",
"(",
"self",
",",
"instance",
",",
"cidr_mask",
",",
"description",
",",
"*",
"*",
"kwargs",
")",
":",
"# Build up request data.",
"url",
"=",
"self",
".",
"_url",
".",
"format",
"(",
"instance",
"=",
"instance",
")",
"request_data",
"=",
... | Create an ACL entry for the specified instance.
:param str instance: The name of the instance to associate the new ACL entry with.
:param str cidr_mask: The IPv4 CIDR mask for the new ACL entry.
:param str description: A short description for the new ACL entry.
:param collector kwargs: ... | [
"Create",
"an",
"ACL",
"entry",
"for",
"the",
"specified",
"instance",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L41-L75 | train | 56,443 |
objectrocket/python-client | objectrocket/acls.py | Acls.get | def get(self, instance, acl):
"""Get an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance from which to fetch the ACL.
:param str acl: The ID of the ACL to fetch.
:returns: An :py:class:`Acl` object, or None if ACL does not exist.
... | python | def get(self, instance, acl):
"""Get an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance from which to fetch the ACL.
:param str acl: The ID of the ACL to fetch.
:returns: An :py:class:`Acl` object, or None if ACL does not exist.
... | [
"def",
"get",
"(",
"self",
",",
"instance",
",",
"acl",
")",
":",
"base_url",
"=",
"self",
".",
"_url",
".",
"format",
"(",
"instance",
"=",
"instance",
")",
"url",
"=",
"'{base}{aclid}/'",
".",
"format",
"(",
"base",
"=",
"base_url",
",",
"aclid",
"... | Get an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance from which to fetch the ACL.
:param str acl: The ID of the ACL to fetch.
:returns: An :py:class:`Acl` object, or None if ACL does not exist.
:rtype: :py:class:`Acl` | [
"Get",
"an",
"ACL",
"by",
"ID",
"belonging",
"to",
"the",
"instance",
"specified",
"by",
"name",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L78-L90 | train | 56,444 |
objectrocket/python-client | objectrocket/acls.py | Acls.delete | def delete(self, instance, acl):
"""Delete an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance on which the ACL exists.
:param str acll: The ID of the ACL to delete.
"""
base_url = self._url.format(instance=instance)
ur... | python | def delete(self, instance, acl):
"""Delete an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance on which the ACL exists.
:param str acll: The ID of the ACL to delete.
"""
base_url = self._url.format(instance=instance)
ur... | [
"def",
"delete",
"(",
"self",
",",
"instance",
",",
"acl",
")",
":",
"base_url",
"=",
"self",
".",
"_url",
".",
"format",
"(",
"instance",
"=",
"instance",
")",
"url",
"=",
"'{base}{aclid}/'",
".",
"format",
"(",
"base",
"=",
"base_url",
",",
"aclid",
... | Delete an ACL by ID belonging to the instance specified by name.
:param str instance: The name of the instance on which the ACL exists.
:param str acll: The ID of the ACL to delete. | [
"Delete",
"an",
"ACL",
"by",
"ID",
"belonging",
"to",
"the",
"instance",
"specified",
"by",
"name",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L93-L108 | train | 56,445 |
objectrocket/python-client | objectrocket/acls.py | Acls._concrete_acl | def _concrete_acl(self, acl_doc):
"""Concretize an ACL document.
:param dict acl_doc: A document describing an ACL entry. Should come from the API.
:returns: An :py:class:`Acl`, or None.
:rtype: :py:class:`bases.BaseInstance`
"""
if not isinstance(acl_doc, dict):
... | python | def _concrete_acl(self, acl_doc):
"""Concretize an ACL document.
:param dict acl_doc: A document describing an ACL entry. Should come from the API.
:returns: An :py:class:`Acl`, or None.
:rtype: :py:class:`bases.BaseInstance`
"""
if not isinstance(acl_doc, dict):
... | [
"def",
"_concrete_acl",
"(",
"self",
",",
"acl_doc",
")",
":",
"if",
"not",
"isinstance",
"(",
"acl_doc",
",",
"dict",
")",
":",
"return",
"None",
"# Attempt to instantiate an Acl object with the given dict.",
"try",
":",
"return",
"Acl",
"(",
"document",
"=",
"... | Concretize an ACL document.
:param dict acl_doc: A document describing an ACL entry. Should come from the API.
:returns: An :py:class:`Acl`, or None.
:rtype: :py:class:`bases.BaseInstance` | [
"Concretize",
"an",
"ACL",
"document",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L113-L133 | train | 56,446 |
objectrocket/python-client | objectrocket/acls.py | Acls._concrete_acl_list | def _concrete_acl_list(self, acl_docs):
"""Concretize a list of ACL documents.
:param list acl_docs: A list of ACL documents. Should come from the API.
:returns: A list of :py:class:`ACL` objects.
:rtype: list
"""
if not acl_docs:
return []
return li... | python | def _concrete_acl_list(self, acl_docs):
"""Concretize a list of ACL documents.
:param list acl_docs: A list of ACL documents. Should come from the API.
:returns: A list of :py:class:`ACL` objects.
:rtype: list
"""
if not acl_docs:
return []
return li... | [
"def",
"_concrete_acl_list",
"(",
"self",
",",
"acl_docs",
")",
":",
"if",
"not",
"acl_docs",
":",
"return",
"[",
"]",
"return",
"list",
"(",
"filter",
"(",
"None",
",",
"[",
"self",
".",
"_concrete_acl",
"(",
"acl_doc",
"=",
"doc",
")",
"for",
"doc",
... | Concretize a list of ACL documents.
:param list acl_docs: A list of ACL documents. Should come from the API.
:returns: A list of :py:class:`ACL` objects.
:rtype: list | [
"Concretize",
"a",
"list",
"of",
"ACL",
"documents",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L135-L145 | train | 56,447 |
objectrocket/python-client | objectrocket/acls.py | Acls._default_request_kwargs | def _default_request_kwargs(self):
"""The default request keyword arguments to be passed to the requests library."""
defaults = copy.deepcopy(super(Acls, self)._default_request_kwargs)
defaults.setdefault('headers', {}).update({
'X-Auth-Token': self._client.auth._token
})
... | python | def _default_request_kwargs(self):
"""The default request keyword arguments to be passed to the requests library."""
defaults = copy.deepcopy(super(Acls, self)._default_request_kwargs)
defaults.setdefault('headers', {}).update({
'X-Auth-Token': self._client.auth._token
})
... | [
"def",
"_default_request_kwargs",
"(",
"self",
")",
":",
"defaults",
"=",
"copy",
".",
"deepcopy",
"(",
"super",
"(",
"Acls",
",",
"self",
")",
".",
"_default_request_kwargs",
")",
"defaults",
".",
"setdefault",
"(",
"'headers'",
",",
"{",
"}",
")",
".",
... | The default request keyword arguments to be passed to the requests library. | [
"The",
"default",
"request",
"keyword",
"arguments",
"to",
"be",
"passed",
"to",
"the",
"requests",
"library",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L148-L154 | train | 56,448 |
objectrocket/python-client | objectrocket/acls.py | Acl._url | def _url(self):
"""The URL of this ACL object."""
base_url = self._client._url.rstrip('/')
return '{}/instances/{}/acls/{}/'.format(base_url, self.instance_name, self.id) | python | def _url(self):
"""The URL of this ACL object."""
base_url = self._client._url.rstrip('/')
return '{}/instances/{}/acls/{}/'.format(base_url, self.instance_name, self.id) | [
"def",
"_url",
"(",
"self",
")",
":",
"base_url",
"=",
"self",
".",
"_client",
".",
"_url",
".",
"rstrip",
"(",
"'/'",
")",
"return",
"'{}/instances/{}/acls/{}/'",
".",
"format",
"(",
"base_url",
",",
"self",
".",
"instance_name",
",",
"self",
".",
"id",... | The URL of this ACL object. | [
"The",
"URL",
"of",
"this",
"ACL",
"object",
"."
] | a65868c7511ff49a5fbe304e53bf592b7fc6d5ef | https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/acls.py#L273-L276 | train | 56,449 |
thespacedoctor/fundamentals | fundamentals/mysql/insert_list_of_dictionaries_into_database_tables.py | insert_list_of_dictionaries_into_database_tables | def insert_list_of_dictionaries_into_database_tables(
dbConn,
log,
dictList,
dbTableName,
uniqueKeyList=[],
dateModified=False,
dateCreated=True,
batchSize=2500,
replace=False,
dbSettings=False):
"""insert list of dictionaries into data... | python | def insert_list_of_dictionaries_into_database_tables(
dbConn,
log,
dictList,
dbTableName,
uniqueKeyList=[],
dateModified=False,
dateCreated=True,
batchSize=2500,
replace=False,
dbSettings=False):
"""insert list of dictionaries into data... | [
"def",
"insert_list_of_dictionaries_into_database_tables",
"(",
"dbConn",
",",
"log",
",",
"dictList",
",",
"dbTableName",
",",
"uniqueKeyList",
"=",
"[",
"]",
",",
"dateModified",
"=",
"False",
",",
"dateCreated",
"=",
"True",
",",
"batchSize",
"=",
"2500",
","... | insert list of dictionaries into database tables
**Key Arguments:**
- ``dbConn`` -- mysql database connection
- ``log`` -- logger
- ``dictList`` -- list of python dictionaries to add to the database table
- ``dbTableName`` -- name of the database table
- ``uniqueKeyList`` --... | [
"insert",
"list",
"of",
"dictionaries",
"into",
"database",
"tables"
] | 1d2c007ac74442ec2eabde771cfcacdb9c1ab382 | https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/mysql/insert_list_of_dictionaries_into_database_tables.py#L33-L158 | train | 56,450 |
klen/starter | starter/core.py | FS.make_directory | def make_directory(path):
""" Create directory if that not exists. """
try:
makedirs(path)
logging.debug('Directory created: {0}'.format(path))
except OSError as e:
if e.errno != errno.EEXIST:
raise | python | def make_directory(path):
""" Create directory if that not exists. """
try:
makedirs(path)
logging.debug('Directory created: {0}'.format(path))
except OSError as e:
if e.errno != errno.EEXIST:
raise | [
"def",
"make_directory",
"(",
"path",
")",
":",
"try",
":",
"makedirs",
"(",
"path",
")",
"logging",
".",
"debug",
"(",
"'Directory created: {0}'",
".",
"format",
"(",
"path",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!="... | Create directory if that not exists. | [
"Create",
"directory",
"if",
"that",
"not",
"exists",
"."
] | 24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L42-L50 | train | 56,451 |
klen/starter | starter/core.py | FS.copy_file | def copy_file(self, from_path, to_path):
""" Copy file. """
if not op.exists(op.dirname(to_path)):
self.make_directory(op.dirname(to_path))
shutil.copy(from_path, to_path)
logging.debug('File copied: {0}'.format(to_path)) | python | def copy_file(self, from_path, to_path):
""" Copy file. """
if not op.exists(op.dirname(to_path)):
self.make_directory(op.dirname(to_path))
shutil.copy(from_path, to_path)
logging.debug('File copied: {0}'.format(to_path)) | [
"def",
"copy_file",
"(",
"self",
",",
"from_path",
",",
"to_path",
")",
":",
"if",
"not",
"op",
".",
"exists",
"(",
"op",
".",
"dirname",
"(",
"to_path",
")",
")",
":",
"self",
".",
"make_directory",
"(",
"op",
".",
"dirname",
"(",
"to_path",
")",
... | Copy file. | [
"Copy",
"file",
"."
] | 24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L52-L58 | train | 56,452 |
klen/starter | starter/core.py | Template.params | def params(self):
""" Read self params from configuration. """
parser = JinjaInterpolationNamespace()
parser.read(self.configuration)
return dict(parser['params'] or {}) | python | def params(self):
""" Read self params from configuration. """
parser = JinjaInterpolationNamespace()
parser.read(self.configuration)
return dict(parser['params'] or {}) | [
"def",
"params",
"(",
"self",
")",
":",
"parser",
"=",
"JinjaInterpolationNamespace",
"(",
")",
"parser",
".",
"read",
"(",
"self",
".",
"configuration",
")",
"return",
"dict",
"(",
"parser",
"[",
"'params'",
"]",
"or",
"{",
"}",
")"
] | Read self params from configuration. | [
"Read",
"self",
"params",
"from",
"configuration",
"."
] | 24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L105-L109 | train | 56,453 |
klen/starter | starter/core.py | Template.scan | def scan(cls, path):
""" Scan directory for templates. """
result = []
try:
for _p in listdir(path):
try:
result.append(Template(_p, op.join(path, _p)))
except ValueError:
continue
except OSError:
... | python | def scan(cls, path):
""" Scan directory for templates. """
result = []
try:
for _p in listdir(path):
try:
result.append(Template(_p, op.join(path, _p)))
except ValueError:
continue
except OSError:
... | [
"def",
"scan",
"(",
"cls",
",",
"path",
")",
":",
"result",
"=",
"[",
"]",
"try",
":",
"for",
"_p",
"in",
"listdir",
"(",
"path",
")",
":",
"try",
":",
"result",
".",
"append",
"(",
"Template",
"(",
"_p",
",",
"op",
".",
"join",
"(",
"path",
... | Scan directory for templates. | [
"Scan",
"directory",
"for",
"templates",
"."
] | 24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L134-L146 | train | 56,454 |
klen/starter | starter/core.py | Starter.copy | def copy(self):
""" Prepare and paste self templates. """
templates = self.prepare_templates()
if self.params.interactive:
keys = list(self.parser.default)
for key in keys:
if key.startswith('_'):
continue
prompt = "{0} ... | python | def copy(self):
""" Prepare and paste self templates. """
templates = self.prepare_templates()
if self.params.interactive:
keys = list(self.parser.default)
for key in keys:
if key.startswith('_'):
continue
prompt = "{0} ... | [
"def",
"copy",
"(",
"self",
")",
":",
"templates",
"=",
"self",
".",
"prepare_templates",
"(",
")",
"if",
"self",
".",
"params",
".",
"interactive",
":",
"keys",
"=",
"list",
"(",
"self",
".",
"parser",
".",
"default",
")",
"for",
"key",
"in",
"keys"... | Prepare and paste self templates. | [
"Prepare",
"and",
"paste",
"self",
"templates",
"."
] | 24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L180-L211 | train | 56,455 |
klen/starter | starter/core.py | Starter.iterate_templates | def iterate_templates(self):
""" Iterate self starter templates.
:returns: A templates generator
"""
return [t for dd in self.dirs for t in Template.scan(dd)] | python | def iterate_templates(self):
""" Iterate self starter templates.
:returns: A templates generator
"""
return [t for dd in self.dirs for t in Template.scan(dd)] | [
"def",
"iterate_templates",
"(",
"self",
")",
":",
"return",
"[",
"t",
"for",
"dd",
"in",
"self",
".",
"dirs",
"for",
"t",
"in",
"Template",
".",
"scan",
"(",
"dd",
")",
"]"
] | Iterate self starter templates.
:returns: A templates generator | [
"Iterate",
"self",
"starter",
"templates",
"."
] | 24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/core.py#L239-L245 | train | 56,456 |
sci-bots/dmf-device-ui | dmf_device_ui/view.py | DmfDeviceViewBase.on_canvas_slave__electrode_pair_selected | def on_canvas_slave__electrode_pair_selected(self, slave, data):
'''
Process pair of selected electrodes.
For now, this consists of finding the shortest path between the two
electrodes and appending it to the list of droplet routes for the
current step.
Note that the dr... | python | def on_canvas_slave__electrode_pair_selected(self, slave, data):
'''
Process pair of selected electrodes.
For now, this consists of finding the shortest path between the two
electrodes and appending it to the list of droplet routes for the
current step.
Note that the dr... | [
"def",
"on_canvas_slave__electrode_pair_selected",
"(",
"self",
",",
"slave",
",",
"data",
")",
":",
"import",
"networkx",
"as",
"nx",
"source_id",
"=",
"data",
"[",
"'source_id'",
"]",
"target_id",
"=",
"data",
"[",
"'target_id'",
"]",
"if",
"self",
".",
"c... | Process pair of selected electrodes.
For now, this consists of finding the shortest path between the two
electrodes and appending it to the list of droplet routes for the
current step.
Note that the droplet routes for a step are stored in a frame/table in
the `DmfDeviceControll... | [
"Process",
"pair",
"of",
"selected",
"electrodes",
"."
] | 05b480683c9fa43f91ce5a58de2fa90cdf363fc8 | https://github.com/sci-bots/dmf-device-ui/blob/05b480683c9fa43f91ce5a58de2fa90cdf363fc8/dmf_device_ui/view.py#L241-L281 | train | 56,457 |
sci-bots/dmf-device-ui | dmf_device_ui/view.py | DmfDeviceViewBase.ping_hub | def ping_hub(self):
'''
Attempt to ping the ZeroMQ plugin hub to verify connection is alive.
If ping is successful, record timestamp.
If ping is unsuccessful, call `on_heartbeat_error` method.
'''
if self.plugin is not None:
try:
self.plugin.e... | python | def ping_hub(self):
'''
Attempt to ping the ZeroMQ plugin hub to verify connection is alive.
If ping is successful, record timestamp.
If ping is unsuccessful, call `on_heartbeat_error` method.
'''
if self.plugin is not None:
try:
self.plugin.e... | [
"def",
"ping_hub",
"(",
"self",
")",
":",
"if",
"self",
".",
"plugin",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"plugin",
".",
"execute",
"(",
"self",
".",
"plugin",
".",
"hub_name",
",",
"'ping'",
",",
"timeout_s",
"=",
"1",
",",
"silent... | Attempt to ping the ZeroMQ plugin hub to verify connection is alive.
If ping is successful, record timestamp.
If ping is unsuccessful, call `on_heartbeat_error` method. | [
"Attempt",
"to",
"ping",
"the",
"ZeroMQ",
"plugin",
"hub",
"to",
"verify",
"connection",
"is",
"alive",
"."
] | 05b480683c9fa43f91ce5a58de2fa90cdf363fc8 | https://github.com/sci-bots/dmf-device-ui/blob/05b480683c9fa43f91ce5a58de2fa90cdf363fc8/dmf_device_ui/view.py#L330-L347 | train | 56,458 |
lambdalisue/app_version | src/app_version/core.py | get_string_version | def get_string_version(name,
default=DEFAULT_STRING_NOT_FOUND,
allow_ambiguous=True):
"""
Get string version from installed package information.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-----------
... | python | def get_string_version(name,
default=DEFAULT_STRING_NOT_FOUND,
allow_ambiguous=True):
"""
Get string version from installed package information.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-----------
... | [
"def",
"get_string_version",
"(",
"name",
",",
"default",
"=",
"DEFAULT_STRING_NOT_FOUND",
",",
"allow_ambiguous",
"=",
"True",
")",
":",
"# get filename of callar",
"callar",
"=",
"inspect",
".",
"getouterframes",
"(",
"inspect",
".",
"currentframe",
"(",
")",
")... | Get string version from installed package information.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-----------
name : string
An application name used to install via setuptools.
default : string
A default returning value used when the... | [
"Get",
"string",
"version",
"from",
"installed",
"package",
"information",
"."
] | 4b9f0acf44b5ed4230cb510edc15625151246611 | https://github.com/lambdalisue/app_version/blob/4b9f0acf44b5ed4230cb510edc15625151246611/src/app_version/core.py#L27-L77 | train | 56,459 |
lambdalisue/app_version | src/app_version/core.py | get_tuple_version | def get_tuple_version(name,
default=DEFAULT_TUPLE_NOT_FOUND,
allow_ambiguous=True):
"""
Get tuple version from installed package information for easy handling.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-... | python | def get_tuple_version(name,
default=DEFAULT_TUPLE_NOT_FOUND,
allow_ambiguous=True):
"""
Get tuple version from installed package information for easy handling.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-... | [
"def",
"get_tuple_version",
"(",
"name",
",",
"default",
"=",
"DEFAULT_TUPLE_NOT_FOUND",
",",
"allow_ambiguous",
"=",
"True",
")",
":",
"def",
"_prefer_int",
"(",
"x",
")",
":",
"try",
":",
"return",
"int",
"(",
"x",
")",
"except",
"ValueError",
":",
"retu... | Get tuple version from installed package information for easy handling.
It will return :attr:`default` value when the named package is not
installed.
Parameters
-----------
name : string
An application name used to install via setuptools.
default : tuple
A default returning val... | [
"Get",
"tuple",
"version",
"from",
"installed",
"package",
"information",
"for",
"easy",
"handling",
"."
] | 4b9f0acf44b5ed4230cb510edc15625151246611 | https://github.com/lambdalisue/app_version/blob/4b9f0acf44b5ed4230cb510edc15625151246611/src/app_version/core.py#L80-L130 | train | 56,460 |
lambdalisue/app_version | src/app_version/core.py | get_versions | def get_versions(name,
default_string=DEFAULT_STRING_NOT_FOUND,
default_tuple=DEFAULT_TUPLE_NOT_FOUND,
allow_ambiguous=True):
"""
Get string and tuple versions from installed package information
It will return :attr:`default_string` and :attr:`default_tupl... | python | def get_versions(name,
default_string=DEFAULT_STRING_NOT_FOUND,
default_tuple=DEFAULT_TUPLE_NOT_FOUND,
allow_ambiguous=True):
"""
Get string and tuple versions from installed package information
It will return :attr:`default_string` and :attr:`default_tupl... | [
"def",
"get_versions",
"(",
"name",
",",
"default_string",
"=",
"DEFAULT_STRING_NOT_FOUND",
",",
"default_tuple",
"=",
"DEFAULT_TUPLE_NOT_FOUND",
",",
"allow_ambiguous",
"=",
"True",
")",
":",
"version_string",
"=",
"get_string_version",
"(",
"name",
",",
"default_str... | Get string and tuple versions from installed package information
It will return :attr:`default_string` and :attr:`default_tuple` values when
the named package is not installed.
Parameters
-----------
name : string
An application name used to install via setuptools.
default : string
... | [
"Get",
"string",
"and",
"tuple",
"versions",
"from",
"installed",
"package",
"information"
] | 4b9f0acf44b5ed4230cb510edc15625151246611 | https://github.com/lambdalisue/app_version/blob/4b9f0acf44b5ed4230cb510edc15625151246611/src/app_version/core.py#L133-L174 | train | 56,461 |
stxnext/mappet | mappet/helpers.py | no_empty_value | def no_empty_value(func):
"""Raises an exception if function argument is empty."""
@wraps(func)
def wrapper(value):
if not value:
raise Exception("Empty value not allowed")
return func(value)
return wrapper | python | def no_empty_value(func):
"""Raises an exception if function argument is empty."""
@wraps(func)
def wrapper(value):
if not value:
raise Exception("Empty value not allowed")
return func(value)
return wrapper | [
"def",
"no_empty_value",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"raise",
"Exception",
"(",
"\"Empty value not allowed\"",
")",
"return",
"func",
"(",
"value",
")",
"retu... | Raises an exception if function argument is empty. | [
"Raises",
"an",
"exception",
"if",
"function",
"argument",
"is",
"empty",
"."
] | ac7468ac28ed82e45065b1e348cf865c8f73f0db | https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L38-L45 | train | 56,462 |
stxnext/mappet | mappet/helpers.py | to_bool | def to_bool(value):
"""Converts human boolean-like values to Python boolean.
Falls back to :class:`bool` when ``value`` is not recognized.
:param value: the value to convert
:returns: ``True`` if value is truthy, ``False`` otherwise
:rtype: bool
"""
cases = {
'0': False,
'f... | python | def to_bool(value):
"""Converts human boolean-like values to Python boolean.
Falls back to :class:`bool` when ``value`` is not recognized.
:param value: the value to convert
:returns: ``True`` if value is truthy, ``False`` otherwise
:rtype: bool
"""
cases = {
'0': False,
'f... | [
"def",
"to_bool",
"(",
"value",
")",
":",
"cases",
"=",
"{",
"'0'",
":",
"False",
",",
"'false'",
":",
"False",
",",
"'no'",
":",
"False",
",",
"'1'",
":",
"True",
",",
"'true'",
":",
"True",
",",
"'yes'",
":",
"True",
",",
"}",
"value",
"=",
"... | Converts human boolean-like values to Python boolean.
Falls back to :class:`bool` when ``value`` is not recognized.
:param value: the value to convert
:returns: ``True`` if value is truthy, ``False`` otherwise
:rtype: bool | [
"Converts",
"human",
"boolean",
"-",
"like",
"values",
"to",
"Python",
"boolean",
"."
] | ac7468ac28ed82e45065b1e348cf865c8f73f0db | https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L48-L67 | train | 56,463 |
stxnext/mappet | mappet/helpers.py | etree_to_dict | def etree_to_dict(t, trim=True, **kw):
u"""Converts an lxml.etree object to Python dict.
>>> etree_to_dict(etree.Element('root'))
{'root': None}
:param etree.Element t: lxml tree to convert
:returns d: a dict representing the lxml tree ``t``
:rtype: dict
"""
d = {t.tag: {} if t.attrib ... | python | def etree_to_dict(t, trim=True, **kw):
u"""Converts an lxml.etree object to Python dict.
>>> etree_to_dict(etree.Element('root'))
{'root': None}
:param etree.Element t: lxml tree to convert
:returns d: a dict representing the lxml tree ``t``
:rtype: dict
"""
d = {t.tag: {} if t.attrib ... | [
"def",
"etree_to_dict",
"(",
"t",
",",
"trim",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"d",
"=",
"{",
"t",
".",
"tag",
":",
"{",
"}",
"if",
"t",
".",
"attrib",
"else",
"None",
"}",
"children",
"=",
"list",
"(",
"t",
")",
"etree_to_dict_w_ar... | u"""Converts an lxml.etree object to Python dict.
>>> etree_to_dict(etree.Element('root'))
{'root': None}
:param etree.Element t: lxml tree to convert
:returns d: a dict representing the lxml tree ``t``
:rtype: dict | [
"u",
"Converts",
"an",
"lxml",
".",
"etree",
"object",
"to",
"Python",
"dict",
"."
] | ac7468ac28ed82e45065b1e348cf865c8f73f0db | https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L174-L212 | train | 56,464 |
stxnext/mappet | mappet/helpers.py | dict_to_etree | def dict_to_etree(d, root):
u"""Converts a dict to lxml.etree object.
>>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS
<Element root at 0x...>
:param dict d: dict representing the XML tree
:param etree.Element root: XML node which will... | python | def dict_to_etree(d, root):
u"""Converts a dict to lxml.etree object.
>>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS
<Element root at 0x...>
:param dict d: dict representing the XML tree
:param etree.Element root: XML node which will... | [
"def",
"dict_to_etree",
"(",
"d",
",",
"root",
")",
":",
"def",
"_to_etree",
"(",
"d",
",",
"node",
")",
":",
"if",
"d",
"is",
"None",
"or",
"len",
"(",
"d",
")",
"==",
"0",
":",
"return",
"elif",
"isinstance",
"(",
"d",
",",
"basestring",
")",
... | u"""Converts a dict to lxml.etree object.
>>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) # doctest: +ELLIPSIS
<Element root at 0x...>
:param dict d: dict representing the XML tree
:param etree.Element root: XML node which will be assigned the resulting tree
... | [
"u",
"Converts",
"a",
"dict",
"to",
"lxml",
".",
"etree",
"object",
"."
] | ac7468ac28ed82e45065b1e348cf865c8f73f0db | https://github.com/stxnext/mappet/blob/ac7468ac28ed82e45065b1e348cf865c8f73f0db/mappet/helpers.py#L215-L275 | train | 56,465 |
nuSTORM/gnomon | gnomon/JsonToROOT.py | JsonToROOTConverter.objwalk | def objwalk(self, obj, path=(), memo=None):
"""Traverse a dictionary recursively and save path
Taken from:
http://code.activestate.com/recipes/577982-recursively-walk-python-objects/
"""
# dual python 2/3 compatability, inspired by the "six" library
string_types = (str, unicode) if s... | python | def objwalk(self, obj, path=(), memo=None):
"""Traverse a dictionary recursively and save path
Taken from:
http://code.activestate.com/recipes/577982-recursively-walk-python-objects/
"""
# dual python 2/3 compatability, inspired by the "six" library
string_types = (str, unicode) if s... | [
"def",
"objwalk",
"(",
"self",
",",
"obj",
",",
"path",
"=",
"(",
")",
",",
"memo",
"=",
"None",
")",
":",
"# dual python 2/3 compatability, inspired by the \"six\" library",
"string_types",
"=",
"(",
"str",
",",
"unicode",
")",
"if",
"str",
"is",
"bytes",
"... | Traverse a dictionary recursively and save path
Taken from:
http://code.activestate.com/recipes/577982-recursively-walk-python-objects/ | [
"Traverse",
"a",
"dictionary",
"recursively",
"and",
"save",
"path"
] | 7616486ecd6e26b76f677c380e62db1c0ade558a | https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/JsonToROOT.py#L149-L175 | train | 56,466 |
hackedd/gw2api | gw2api/__init__.py | set_cache_dir | def set_cache_dir(directory):
"""Set the directory to cache JSON responses from most API endpoints.
"""
global cache_dir
if directory is None:
cache_dir = None
return
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.isdir(directory):
raise... | python | def set_cache_dir(directory):
"""Set the directory to cache JSON responses from most API endpoints.
"""
global cache_dir
if directory is None:
cache_dir = None
return
if not os.path.exists(directory):
os.makedirs(directory)
if not os.path.isdir(directory):
raise... | [
"def",
"set_cache_dir",
"(",
"directory",
")",
":",
"global",
"cache_dir",
"if",
"directory",
"is",
"None",
":",
"cache_dir",
"=",
"None",
"return",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"os",
".",
"makedirs",
"(",
... | Set the directory to cache JSON responses from most API endpoints. | [
"Set",
"the",
"directory",
"to",
"cache",
"JSON",
"responses",
"from",
"most",
"API",
"endpoints",
"."
] | 5543a78e6e3ed0573b7e84c142c44004b4779eac | https://github.com/hackedd/gw2api/blob/5543a78e6e3ed0573b7e84c142c44004b4779eac/gw2api/__init__.py#L38-L51 | train | 56,467 |
consbio/parserutils | parserutils/elements.py | element_is_empty | def element_is_empty(elem_to_parse, element_path=None):
"""
Returns true if the element is None, or has no text, tail, children or attributes.
Whitespace in the element is stripped from text and tail before making the determination.
"""
element = get_element(elem_to_parse, element_path)
if ele... | python | def element_is_empty(elem_to_parse, element_path=None):
"""
Returns true if the element is None, or has no text, tail, children or attributes.
Whitespace in the element is stripped from text and tail before making the determination.
"""
element = get_element(elem_to_parse, element_path)
if ele... | [
"def",
"element_is_empty",
"(",
"elem_to_parse",
",",
"element_path",
"=",
"None",
")",
":",
"element",
"=",
"get_element",
"(",
"elem_to_parse",
",",
"element_path",
")",
"if",
"element",
"is",
"None",
":",
"return",
"True",
"is_empty",
"=",
"(",
"(",
"elem... | Returns true if the element is None, or has no text, tail, children or attributes.
Whitespace in the element is stripped from text and tail before making the determination. | [
"Returns",
"true",
"if",
"the",
"element",
"is",
"None",
"or",
"has",
"no",
"text",
"tail",
"children",
"or",
"attributes",
".",
"Whitespace",
"in",
"the",
"element",
"is",
"stripped",
"from",
"text",
"and",
"tail",
"before",
"making",
"the",
"determination"... | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L250-L268 | train | 56,468 |
consbio/parserutils | parserutils/elements.py | insert_element | def insert_element(elem_to_parse, elem_idx, elem_path, elem_txt=u'', **attrib_kwargs):
"""
Creates an element named after elem_path, containing elem_txt, with kwargs
as attributes, inserts it into elem_to_parse at elem_idx and returns it.
If elem_path is an XPATH pointing to a non-existent element, ele... | python | def insert_element(elem_to_parse, elem_idx, elem_path, elem_txt=u'', **attrib_kwargs):
"""
Creates an element named after elem_path, containing elem_txt, with kwargs
as attributes, inserts it into elem_to_parse at elem_idx and returns it.
If elem_path is an XPATH pointing to a non-existent element, ele... | [
"def",
"insert_element",
"(",
"elem_to_parse",
",",
"elem_idx",
",",
"elem_path",
",",
"elem_txt",
"=",
"u''",
",",
"*",
"*",
"attrib_kwargs",
")",
":",
"element",
"=",
"get_element",
"(",
"elem_to_parse",
")",
"if",
"element",
"is",
"None",
"or",
"not",
"... | Creates an element named after elem_path, containing elem_txt, with kwargs
as attributes, inserts it into elem_to_parse at elem_idx and returns it.
If elem_path is an XPATH pointing to a non-existent element, elements not
in the path are inserted and the text and index are applied to the last one.
If ... | [
"Creates",
"an",
"element",
"named",
"after",
"elem_path",
"containing",
"elem_txt",
"with",
"kwargs",
"as",
"attributes",
"inserts",
"it",
"into",
"elem_to_parse",
"at",
"elem_idx",
"and",
"returns",
"it",
"."
] | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L271-L328 | train | 56,469 |
consbio/parserutils | parserutils/elements.py | remove_empty_element | def remove_empty_element(parent_to_parse, element_path, target_element=None):
"""
Searches for all empty sub-elements named after element_name in the parsed element,
and if it exists, removes them all and returns them as a list.
"""
element = get_element(parent_to_parse)
removed = []
if el... | python | def remove_empty_element(parent_to_parse, element_path, target_element=None):
"""
Searches for all empty sub-elements named after element_name in the parsed element,
and if it exists, removes them all and returns them as a list.
"""
element = get_element(parent_to_parse)
removed = []
if el... | [
"def",
"remove_empty_element",
"(",
"parent_to_parse",
",",
"element_path",
",",
"target_element",
"=",
"None",
")",
":",
"element",
"=",
"get_element",
"(",
"parent_to_parse",
")",
"removed",
"=",
"[",
"]",
"if",
"element",
"is",
"None",
"or",
"not",
"element... | Searches for all empty sub-elements named after element_name in the parsed element,
and if it exists, removes them all and returns them as a list. | [
"Searches",
"for",
"all",
"empty",
"sub",
"-",
"elements",
"named",
"after",
"element_name",
"in",
"the",
"parsed",
"element",
"and",
"if",
"it",
"exists",
"removes",
"them",
"all",
"and",
"returns",
"them",
"as",
"a",
"list",
"."
] | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L390-L439 | train | 56,470 |
consbio/parserutils | parserutils/elements.py | remove_element_attributes | def remove_element_attributes(elem_to_parse, *args):
"""
Removes the specified keys from the element's attributes, and
returns a dict containing the attributes that have been removed.
"""
element = get_element(elem_to_parse)
if element is None:
return element
if len(args):
... | python | def remove_element_attributes(elem_to_parse, *args):
"""
Removes the specified keys from the element's attributes, and
returns a dict containing the attributes that have been removed.
"""
element = get_element(elem_to_parse)
if element is None:
return element
if len(args):
... | [
"def",
"remove_element_attributes",
"(",
"elem_to_parse",
",",
"*",
"args",
")",
":",
"element",
"=",
"get_element",
"(",
"elem_to_parse",
")",
"if",
"element",
"is",
"None",
":",
"return",
"element",
"if",
"len",
"(",
"args",
")",
":",
"attribs",
"=",
"el... | Removes the specified keys from the element's attributes, and
returns a dict containing the attributes that have been removed. | [
"Removes",
"the",
"specified",
"keys",
"from",
"the",
"element",
"s",
"attributes",
"and",
"returns",
"a",
"dict",
"containing",
"the",
"attributes",
"that",
"have",
"been",
"removed",
"."
] | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L500-L515 | train | 56,471 |
consbio/parserutils | parserutils/elements.py | _get_elements_property | def _get_elements_property(parent_to_parse, element_path, prop_name):
""" A helper to construct a list of values from """
parent_element = get_element(parent_to_parse)
if parent_element is None:
return []
if element_path and not element_exists(parent_element, element_path):
return []
... | python | def _get_elements_property(parent_to_parse, element_path, prop_name):
""" A helper to construct a list of values from """
parent_element = get_element(parent_to_parse)
if parent_element is None:
return []
if element_path and not element_exists(parent_element, element_path):
return []
... | [
"def",
"_get_elements_property",
"(",
"parent_to_parse",
",",
"element_path",
",",
"prop_name",
")",
":",
"parent_element",
"=",
"get_element",
"(",
"parent_to_parse",
")",
"if",
"parent_element",
"is",
"None",
":",
"return",
"[",
"]",
"if",
"element_path",
"and",... | A helper to construct a list of values from | [
"A",
"helper",
"to",
"construct",
"a",
"list",
"of",
"values",
"from"
] | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L595-L616 | train | 56,472 |
consbio/parserutils | parserutils/elements.py | _set_element_property | def _set_element_property(parent_to_parse, element_path, prop_name, value):
""" Assigns the value to the parsed parent element and then returns it """
element = get_element(parent_to_parse)
if element is None:
return None
if element_path and not element_exists(element, element_path):
... | python | def _set_element_property(parent_to_parse, element_path, prop_name, value):
""" Assigns the value to the parsed parent element and then returns it """
element = get_element(parent_to_parse)
if element is None:
return None
if element_path and not element_exists(element, element_path):
... | [
"def",
"_set_element_property",
"(",
"parent_to_parse",
",",
"element_path",
",",
"prop_name",
",",
"value",
")",
":",
"element",
"=",
"get_element",
"(",
"parent_to_parse",
")",
"if",
"element",
"is",
"None",
":",
"return",
"None",
"if",
"element_path",
"and",
... | Assigns the value to the parsed parent element and then returns it | [
"Assigns",
"the",
"value",
"to",
"the",
"parsed",
"parent",
"element",
"and",
"then",
"returns",
"it"
] | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L639-L655 | train | 56,473 |
consbio/parserutils | parserutils/elements.py | set_elements_tail | def set_elements_tail(parent_to_parse, element_path=None, tail_values=None):
"""
Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; b... | python | def set_elements_tail(parent_to_parse, element_path=None, tail_values=None):
"""
Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; b... | [
"def",
"set_elements_tail",
"(",
"parent_to_parse",
",",
"element_path",
"=",
"None",
",",
"tail_values",
"=",
"None",
")",
":",
"if",
"tail_values",
"is",
"None",
":",
"tail_values",
"=",
"[",
"]",
"return",
"_set_elements_property",
"(",
"parent_to_parse",
","... | Assigns an array of tail values to each of the elements parsed from the parent. The
tail values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining tail ... | [
"Assigns",
"an",
"array",
"of",
"tail",
"values",
"to",
"each",
"of",
"the",
"elements",
"parsed",
"from",
"the",
"parent",
".",
"The",
"tail",
"values",
"are",
"assigned",
"in",
"the",
"same",
"order",
"they",
"are",
"provided",
".",
"If",
"there",
"are... | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L658-L669 | train | 56,474 |
consbio/parserutils | parserutils/elements.py | set_elements_text | def set_elements_text(parent_to_parse, element_path=None, text_values=None):
"""
Assigns an array of text values to each of the elements parsed from the parent. The
text values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; b... | python | def set_elements_text(parent_to_parse, element_path=None, text_values=None):
"""
Assigns an array of text values to each of the elements parsed from the parent. The
text values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; b... | [
"def",
"set_elements_text",
"(",
"parent_to_parse",
",",
"element_path",
"=",
"None",
",",
"text_values",
"=",
"None",
")",
":",
"if",
"text_values",
"is",
"None",
":",
"text_values",
"=",
"[",
"]",
"return",
"_set_elements_property",
"(",
"parent_to_parse",
","... | Assigns an array of text values to each of the elements parsed from the parent. The
text values are assigned in the same order they are provided.
If there are less values then elements, the remaining elements are skipped; but if
there are more, new elements will be inserted for each with the remaining text ... | [
"Assigns",
"an",
"array",
"of",
"text",
"values",
"to",
"each",
"of",
"the",
"elements",
"parsed",
"from",
"the",
"parent",
".",
"The",
"text",
"values",
"are",
"assigned",
"in",
"the",
"same",
"order",
"they",
"are",
"provided",
".",
"If",
"there",
"are... | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L672-L683 | train | 56,475 |
consbio/parserutils | parserutils/elements.py | strip_namespaces | def strip_namespaces(file_or_xml):
"""
Removes all namespaces from the XML file or string passed in.
If file_or_xml is not a file or string, it is returned as is.
"""
xml_content = _xml_content_to_string(file_or_xml)
if not isinstance(xml_content, string_types):
return xml_content
... | python | def strip_namespaces(file_or_xml):
"""
Removes all namespaces from the XML file or string passed in.
If file_or_xml is not a file or string, it is returned as is.
"""
xml_content = _xml_content_to_string(file_or_xml)
if not isinstance(xml_content, string_types):
return xml_content
... | [
"def",
"strip_namespaces",
"(",
"file_or_xml",
")",
":",
"xml_content",
"=",
"_xml_content_to_string",
"(",
"file_or_xml",
")",
"if",
"not",
"isinstance",
"(",
"xml_content",
",",
"string_types",
")",
":",
"return",
"xml_content",
"# This pattern can have overlapping ma... | Removes all namespaces from the XML file or string passed in.
If file_or_xml is not a file or string, it is returned as is. | [
"Removes",
"all",
"namespaces",
"from",
"the",
"XML",
"file",
"or",
"string",
"passed",
"in",
".",
"If",
"file_or_xml",
"is",
"not",
"a",
"file",
"or",
"string",
"it",
"is",
"returned",
"as",
"is",
"."
] | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L958-L978 | train | 56,476 |
consbio/parserutils | parserutils/elements.py | strip_xml_declaration | def strip_xml_declaration(file_or_xml):
"""
Removes XML declaration line from file or string passed in.
If file_or_xml is not a file or string, it is returned as is.
"""
xml_content = _xml_content_to_string(file_or_xml)
if not isinstance(xml_content, string_types):
return xml_content
... | python | def strip_xml_declaration(file_or_xml):
"""
Removes XML declaration line from file or string passed in.
If file_or_xml is not a file or string, it is returned as is.
"""
xml_content = _xml_content_to_string(file_or_xml)
if not isinstance(xml_content, string_types):
return xml_content
... | [
"def",
"strip_xml_declaration",
"(",
"file_or_xml",
")",
":",
"xml_content",
"=",
"_xml_content_to_string",
"(",
"file_or_xml",
")",
"if",
"not",
"isinstance",
"(",
"xml_content",
",",
"string_types",
")",
":",
"return",
"xml_content",
"# For Python 2 compliance: replac... | Removes XML declaration line from file or string passed in.
If file_or_xml is not a file or string, it is returned as is. | [
"Removes",
"XML",
"declaration",
"line",
"from",
"file",
"or",
"string",
"passed",
"in",
".",
"If",
"file_or_xml",
"is",
"not",
"a",
"file",
"or",
"string",
"it",
"is",
"returned",
"as",
"is",
"."
] | f13f80db99ed43479336b116e38512e3566e4623 | https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L981-L992 | train | 56,477 |
hayalasalah/adhan.py | adhan/adhan.py | floating_point_to_datetime | def floating_point_to_datetime(day, fp_time):
"""Convert a floating point time to a datetime."""
result = datetime(year=day.year, month=day.month, day=day.day)
result += timedelta(minutes=math.ceil(60 * fp_time))
return result | python | def floating_point_to_datetime(day, fp_time):
"""Convert a floating point time to a datetime."""
result = datetime(year=day.year, month=day.month, day=day.day)
result += timedelta(minutes=math.ceil(60 * fp_time))
return result | [
"def",
"floating_point_to_datetime",
"(",
"day",
",",
"fp_time",
")",
":",
"result",
"=",
"datetime",
"(",
"year",
"=",
"day",
".",
"year",
",",
"month",
"=",
"day",
".",
"month",
",",
"day",
"=",
"day",
".",
"day",
")",
"result",
"+=",
"timedelta",
... | Convert a floating point time to a datetime. | [
"Convert",
"a",
"floating",
"point",
"time",
"to",
"a",
"datetime",
"."
] | a7c080ba48f70be9801f048451d2c91a7d579602 | https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/adhan.py#L39-L43 | train | 56,478 |
hayalasalah/adhan.py | adhan/adhan.py | adhan | def adhan(day, location, parameters, timezone_offset=0):
"""Calculate adhan times given the parameters.
This function will compute the adhan times for a certain location on
certain day. The method for calculating the prayers as well as the time for
Asr can also be specified. The timezone offset naively... | python | def adhan(day, location, parameters, timezone_offset=0):
"""Calculate adhan times given the parameters.
This function will compute the adhan times for a certain location on
certain day. The method for calculating the prayers as well as the time for
Asr can also be specified. The timezone offset naively... | [
"def",
"adhan",
"(",
"day",
",",
"location",
",",
"parameters",
",",
"timezone_offset",
"=",
"0",
")",
":",
"latitude",
",",
"longitude",
"=",
"location",
"#",
"# To reduce a little repetitiveness, using a partial function that has the",
"# day and latitude already set",
... | Calculate adhan times given the parameters.
This function will compute the adhan times for a certain location on
certain day. The method for calculating the prayers as well as the time for
Asr can also be specified. The timezone offset naively adds the specified
number of hours to each time that is ret... | [
"Calculate",
"adhan",
"times",
"given",
"the",
"parameters",
"."
] | a7c080ba48f70be9801f048451d2c91a7d579602 | https://github.com/hayalasalah/adhan.py/blob/a7c080ba48f70be9801f048451d2c91a7d579602/adhan/adhan.py#L46-L112 | train | 56,479 |
trevisanj/a99 | a99/gui/a_WEditor.py | WEditor._make_fn_text | def _make_fn_text(self):
"""Makes filename text"""
if not self._f:
text = "(not loaded)"
elif self._f.filename:
text = os.path.relpath(self._f.filename, ".")
else:
text = "(filename not set)"
return text | python | def _make_fn_text(self):
"""Makes filename text"""
if not self._f:
text = "(not loaded)"
elif self._f.filename:
text = os.path.relpath(self._f.filename, ".")
else:
text = "(filename not set)"
return text | [
"def",
"_make_fn_text",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_f",
":",
"text",
"=",
"\"(not loaded)\"",
"elif",
"self",
".",
"_f",
".",
"filename",
":",
"text",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"self",
".",
"_f",
".",
"file... | Makes filename text | [
"Makes",
"filename",
"text"
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/gui/a_WEditor.py#L91-L99 | train | 56,480 |
trevisanj/a99 | a99/matplotlibaux.py | format_BLB | def format_BLB():
"""Sets some formatting options in Matplotlib."""
rc("figure", facecolor="white")
rc('font', family = 'serif', size=10) #, serif = 'cmr10')
rc('xtick', labelsize=10)
rc('ytick', labelsize=10)
rc('axes', linewidth=1)
rc('xtick.major', size=4, width=1)
rc('xtick.m... | python | def format_BLB():
"""Sets some formatting options in Matplotlib."""
rc("figure", facecolor="white")
rc('font', family = 'serif', size=10) #, serif = 'cmr10')
rc('xtick', labelsize=10)
rc('ytick', labelsize=10)
rc('axes', linewidth=1)
rc('xtick.major', size=4, width=1)
rc('xtick.m... | [
"def",
"format_BLB",
"(",
")",
":",
"rc",
"(",
"\"figure\"",
",",
"facecolor",
"=",
"\"white\"",
")",
"rc",
"(",
"'font'",
",",
"family",
"=",
"'serif'",
",",
"size",
"=",
"10",
")",
"#, serif = 'cmr10')\r",
"rc",
"(",
"'xtick'",
",",
"labelsize",
"=",
... | Sets some formatting options in Matplotlib. | [
"Sets",
"some",
"formatting",
"options",
"in",
"Matplotlib",
"."
] | 193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539 | https://github.com/trevisanj/a99/blob/193e6e3c9b3e4f4a0ba7eb3eece846fe7045c539/a99/matplotlibaux.py#L16-L26 | train | 56,481 |
wuher/devil | devil/fields/representation.py | get_declared_fields | def get_declared_fields(bases, attrs):
""" Find all fields and return them as a dictionary.
note:: this function is copied and modified
from django.forms.get_declared_fields
"""
def is_field(prop):
return isinstance(prop, forms.Field) or \
isinstance(prop, BaseRepresentatio... | python | def get_declared_fields(bases, attrs):
""" Find all fields and return them as a dictionary.
note:: this function is copied and modified
from django.forms.get_declared_fields
"""
def is_field(prop):
return isinstance(prop, forms.Field) or \
isinstance(prop, BaseRepresentatio... | [
"def",
"get_declared_fields",
"(",
"bases",
",",
"attrs",
")",
":",
"def",
"is_field",
"(",
"prop",
")",
":",
"return",
"isinstance",
"(",
"prop",
",",
"forms",
".",
"Field",
")",
"or",
"isinstance",
"(",
"prop",
",",
"BaseRepresentation",
")",
"fields",
... | Find all fields and return them as a dictionary.
note:: this function is copied and modified
from django.forms.get_declared_fields | [
"Find",
"all",
"fields",
"and",
"return",
"them",
"as",
"a",
"dictionary",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/representation.py#L76-L92 | train | 56,482 |
wuher/devil | devil/fields/representation.py | BaseRepresentation.validate | def validate(self, data=None):
""" Validate the data
Check also that no extra properties are present.
:raises: ValidationError if the data is not valid.
"""
errors = {}
data = self._getData(data)
# validate each field, one by one
for name, field in se... | python | def validate(self, data=None):
""" Validate the data
Check also that no extra properties are present.
:raises: ValidationError if the data is not valid.
"""
errors = {}
data = self._getData(data)
# validate each field, one by one
for name, field in se... | [
"def",
"validate",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"data",
"=",
"self",
".",
"_getData",
"(",
"data",
")",
"# validate each field, one by one",
"for",
"name",
",",
"field",
"in",
"self",
".",
"fields",
".",
"it... | Validate the data
Check also that no extra properties are present.
:raises: ValidationError if the data is not valid. | [
"Validate",
"the",
"data"
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/representation.py#L29-L57 | train | 56,483 |
wuher/devil | devil/fields/representation.py | BaseRepresentation._getData | def _getData(self, data):
""" Check that data is acceptable and return it.
Default behavior is that the data has to be of type `dict`. In derived
classes this method could for example allow `None` or empty strings and
just return empty dictionary.
:raises: ``ValidationError`` i... | python | def _getData(self, data):
""" Check that data is acceptable and return it.
Default behavior is that the data has to be of type `dict`. In derived
classes this method could for example allow `None` or empty strings and
just return empty dictionary.
:raises: ``ValidationError`` i... | [
"def",
"_getData",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"raise",
"ValidationError",
"(",
"'data is not a valid dictionary: %s'",
"%",
"(",
"str",
"(",
"type",
"(",
"data",
")",
")",
",",
")",
... | Check that data is acceptable and return it.
Default behavior is that the data has to be of type `dict`. In derived
classes this method could for example allow `None` or empty strings and
just return empty dictionary.
:raises: ``ValidationError`` if data is missing or wrong type
... | [
"Check",
"that",
"data",
"is",
"acceptable",
"and",
"return",
"it",
"."
] | a8834d4f88d915a21754c6b96f99d0ad9123ad4d | https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/representation.py#L59-L73 | train | 56,484 |
wdbm/megaparsex | megaparsex_example_1.py | main | def main():
"""
Loop over a list of input text strings. Parse each string using a list of
parsers, one included in megaparsex and one defined in this script. If a
confirmation is requested, seek confirmation, otherwise display any response
text and engage any triggered functions.
"""
for tex... | python | def main():
"""
Loop over a list of input text strings. Parse each string using a list of
parsers, one included in megaparsex and one defined in this script. If a
confirmation is requested, seek confirmation, otherwise display any response
text and engage any triggered functions.
"""
for tex... | [
"def",
"main",
"(",
")",
":",
"for",
"text",
"in",
"[",
"\"how are you\"",
",",
"\"ip address\"",
",",
"\"restart\"",
",",
"\"run command\"",
",",
"\"rain EGPF\"",
",",
"\"reverse SSH\"",
"]",
":",
"print",
"(",
"\"\\nparse text: \"",
"+",
"text",
"+",
"\"\\nW... | Loop over a list of input text strings. Parse each string using a list of
parsers, one included in megaparsex and one defined in this script. If a
confirmation is requested, seek confirmation, otherwise display any response
text and engage any triggered functions. | [
"Loop",
"over",
"a",
"list",
"of",
"input",
"text",
"strings",
".",
"Parse",
"each",
"string",
"using",
"a",
"list",
"of",
"parsers",
"one",
"included",
"in",
"megaparsex",
"and",
"one",
"defined",
"in",
"this",
"script",
".",
"If",
"a",
"confirmation",
... | 59da05410aa1cf8682dcee2bf0bd0572fa42bd29 | https://github.com/wdbm/megaparsex/blob/59da05410aa1cf8682dcee2bf0bd0572fa42bd29/megaparsex_example_1.py#L44-L92 | train | 56,485 |
mixer/beam-interactive-python | beam_interactive/proto/identifier.py | _Identifier.get_packet_id | def get_packet_id(self, packet):
"""
Returns the ID of a protocol buffer packet. Returns None
if no ID was found.
"""
for p in self._packets:
if isinstance(packet, p['cls']):
return p['id']
return None | python | def get_packet_id(self, packet):
"""
Returns the ID of a protocol buffer packet. Returns None
if no ID was found.
"""
for p in self._packets:
if isinstance(packet, p['cls']):
return p['id']
return None | [
"def",
"get_packet_id",
"(",
"self",
",",
"packet",
")",
":",
"for",
"p",
"in",
"self",
".",
"_packets",
":",
"if",
"isinstance",
"(",
"packet",
",",
"p",
"[",
"'cls'",
"]",
")",
":",
"return",
"p",
"[",
"'id'",
"]",
"return",
"None"
] | Returns the ID of a protocol buffer packet. Returns None
if no ID was found. | [
"Returns",
"the",
"ID",
"of",
"a",
"protocol",
"buffer",
"packet",
".",
"Returns",
"None",
"if",
"no",
"ID",
"was",
"found",
"."
] | e035bc45515dea9315b77648a24b5ae8685aa5cf | https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/proto/identifier.py#L23-L33 | train | 56,486 |
klen/starter | starter/main.py | main | def main(*args):
""" Enter point. """
args = args or sys.argv[1:]
params = PARSER.parse_args(args)
from .log import setup_logging
setup_logging(params.level.upper())
from .core import Starter
starter = Starter(params)
if not starter.params.TEMPLATES or starter.params.list:
set... | python | def main(*args):
""" Enter point. """
args = args or sys.argv[1:]
params = PARSER.parse_args(args)
from .log import setup_logging
setup_logging(params.level.upper())
from .core import Starter
starter = Starter(params)
if not starter.params.TEMPLATES or starter.params.list:
set... | [
"def",
"main",
"(",
"*",
"args",
")",
":",
"args",
"=",
"args",
"or",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"params",
"=",
"PARSER",
".",
"parse_args",
"(",
"args",
")",
"from",
".",
"log",
"import",
"setup_logging",
"setup_logging",
"(",
"params",... | Enter point. | [
"Enter",
"point",
"."
] | 24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f | https://github.com/klen/starter/blob/24a65c10d4ac5a9ca8fc1d8b3d54b3fb13603f5f/starter/main.py#L50-L73 | train | 56,487 |
a2liu/mr-clean | mr_clean/core/tools/summarize.py | summarize | def summarize(df,preview_rows = 8,
display_max_cols = None,display_width = None,
output_path = None, output_safe = True,to_folder = False):
""" Prints information about the DataFrame to a file or to the prompt.
Parameters
----------
df - DataFrame
The DataFrame to summa... | python | def summarize(df,preview_rows = 8,
display_max_cols = None,display_width = None,
output_path = None, output_safe = True,to_folder = False):
""" Prints information about the DataFrame to a file or to the prompt.
Parameters
----------
df - DataFrame
The DataFrame to summa... | [
"def",
"summarize",
"(",
"df",
",",
"preview_rows",
"=",
"8",
",",
"display_max_cols",
"=",
"None",
",",
"display_width",
"=",
"None",
",",
"output_path",
"=",
"None",
",",
"output_safe",
"=",
"True",
",",
"to_folder",
"=",
"False",
")",
":",
"assert",
"... | Prints information about the DataFrame to a file or to the prompt.
Parameters
----------
df - DataFrame
The DataFrame to summarize
preview_rows - int, default 5
Amount of rows to preview from the head and tail of the DataFrame
display_max_cols - int, default None
Maximum amo... | [
"Prints",
"information",
"about",
"the",
"DataFrame",
"to",
"a",
"file",
"or",
"to",
"the",
"prompt",
"."
] | 0ee4ee5639f834dec4b59b94442fa84373f3c176 | https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/core/tools/summarize.py#L13-L103 | train | 56,488 |
CodyKochmann/generators | generators/timed_pipe.py | timed_pipe | def timed_pipe(generator, seconds=3):
''' This is a time limited pipeline. If you have a infinite pipeline and
want it to stop yielding after a certain amount of time, use this! '''
# grab the highest precision timer
# when it started
start = ts()
# when it will stop
end = start + second... | python | def timed_pipe(generator, seconds=3):
''' This is a time limited pipeline. If you have a infinite pipeline and
want it to stop yielding after a certain amount of time, use this! '''
# grab the highest precision timer
# when it started
start = ts()
# when it will stop
end = start + second... | [
"def",
"timed_pipe",
"(",
"generator",
",",
"seconds",
"=",
"3",
")",
":",
"# grab the highest precision timer",
"# when it started",
"start",
"=",
"ts",
"(",
")",
"# when it will stop",
"end",
"=",
"start",
"+",
"seconds",
"# iterate over the pipeline",
"for",
"i",... | This is a time limited pipeline. If you have a infinite pipeline and
want it to stop yielding after a certain amount of time, use this! | [
"This",
"is",
"a",
"time",
"limited",
"pipeline",
".",
"If",
"you",
"have",
"a",
"infinite",
"pipeline",
"and",
"want",
"it",
"to",
"stop",
"yielding",
"after",
"a",
"certain",
"amount",
"of",
"time",
"use",
"this!"
] | e4ca4dd25d5023a94b0349c69d6224070cc2526f | https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/timed_pipe.py#L11-L28 | train | 56,489 |
Titan-C/slaveparticles | slaveparticles/quantum/fermion.py | destruct | def destruct(particles, index):
"""Fermion annihilation operator in matrix representation for a indexed
particle in a bounded N-particles fermion fock space"""
mat = np.zeros((2**particles, 2**particles))
flipper = 2**index
for i in range(2**particles):
ispin = btest(i, index)
i... | python | def destruct(particles, index):
"""Fermion annihilation operator in matrix representation for a indexed
particle in a bounded N-particles fermion fock space"""
mat = np.zeros((2**particles, 2**particles))
flipper = 2**index
for i in range(2**particles):
ispin = btest(i, index)
i... | [
"def",
"destruct",
"(",
"particles",
",",
"index",
")",
":",
"mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"2",
"**",
"particles",
",",
"2",
"**",
"particles",
")",
")",
"flipper",
"=",
"2",
"**",
"index",
"for",
"i",
"in",
"range",
"(",
"2",
"**",
... | Fermion annihilation operator in matrix representation for a indexed
particle in a bounded N-particles fermion fock space | [
"Fermion",
"annihilation",
"operator",
"in",
"matrix",
"representation",
"for",
"a",
"indexed",
"particle",
"in",
"a",
"bounded",
"N",
"-",
"particles",
"fermion",
"fock",
"space"
] | e4c2f5afb1a7b195517ef2f1b5cc758965036aab | https://github.com/Titan-C/slaveparticles/blob/e4c2f5afb1a7b195517ef2f1b5cc758965036aab/slaveparticles/quantum/fermion.py#L23-L34 | train | 56,490 |
inveniosoftware-attic/invenio-utils | invenio_utils/json.py | json_unicode_to_utf8 | def json_unicode_to_utf8(data):
"""Change all strings in a JSON structure to UTF-8."""
if isinstance(data, unicode):
return data.encode('utf-8')
elif isinstance(data, dict):
newdict = {}
for key in data:
newdict[json_unicode_to_utf8(
key)] = json_unicode_t... | python | def json_unicode_to_utf8(data):
"""Change all strings in a JSON structure to UTF-8."""
if isinstance(data, unicode):
return data.encode('utf-8')
elif isinstance(data, dict):
newdict = {}
for key in data:
newdict[json_unicode_to_utf8(
key)] = json_unicode_t... | [
"def",
"json_unicode_to_utf8",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"unicode",
")",
":",
"return",
"data",
".",
"encode",
"(",
"'utf-8'",
")",
"elif",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"newdict",
"=",
"{",
"}",
... | Change all strings in a JSON structure to UTF-8. | [
"Change",
"all",
"strings",
"in",
"a",
"JSON",
"structure",
"to",
"UTF",
"-",
"8",
"."
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/json.py#L32-L45 | train | 56,491 |
inveniosoftware-attic/invenio-utils | invenio_utils/json.py | json_decode_file | def json_decode_file(filename):
"""
Parses a textfile using json to build a python object representation
"""
seq = open(filename).read()
# The JSON standard has no comments syntax. We have to remove them
# before feeding python's JSON parser
seq = json_remove_comments(seq)
# Parse all th... | python | def json_decode_file(filename):
"""
Parses a textfile using json to build a python object representation
"""
seq = open(filename).read()
# The JSON standard has no comments syntax. We have to remove them
# before feeding python's JSON parser
seq = json_remove_comments(seq)
# Parse all th... | [
"def",
"json_decode_file",
"(",
"filename",
")",
":",
"seq",
"=",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
"# The JSON standard has no comments syntax. We have to remove them",
"# before feeding python's JSON parser",
"seq",
"=",
"json_remove_comments",
"(",
"... | Parses a textfile using json to build a python object representation | [
"Parses",
"a",
"textfile",
"using",
"json",
"to",
"build",
"a",
"python",
"object",
"representation"
] | 9a1c6db4e3f1370901f329f510480dd8df188296 | https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/json.py#L48-L57 | train | 56,492 |
cdumay/kser | src/kser/entry.py | Entrypoint._post_init | def _post_init(self):
"""A post init trigger"""
try:
return self.postinit()
except Exception as exc:
return self._onerror(Result.from_exception(exc, uuid=self.uuid)) | python | def _post_init(self):
"""A post init trigger"""
try:
return self.postinit()
except Exception as exc:
return self._onerror(Result.from_exception(exc, uuid=self.uuid)) | [
"def",
"_post_init",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"postinit",
"(",
")",
"except",
"Exception",
"as",
"exc",
":",
"return",
"self",
".",
"_onerror",
"(",
"Result",
".",
"from_exception",
"(",
"exc",
",",
"uuid",
"=",
"self",... | A post init trigger | [
"A",
"post",
"init",
"trigger"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/entry.py#L43-L48 | train | 56,493 |
cdumay/kser | src/kser/entry.py | Entrypoint._postrun | def _postrun(self, result):
""" To execute after exection
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result
"""
logger.debug(
"{}.PostRun: {}[{}]".format(
self.__class__.__name__, self.__cl... | python | def _postrun(self, result):
""" To execute after exection
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result
"""
logger.debug(
"{}.PostRun: {}[{}]".format(
self.__class__.__name__, self.__cl... | [
"def",
"_postrun",
"(",
"self",
",",
"result",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}.PostRun: {}[{}]\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"__class__",
".",
"path",
",",
"self",
".",
"uuid",
")",
",... | To execute after exection
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result | [
"To",
"execute",
"after",
"exection"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/entry.py#L165-L183 | train | 56,494 |
cdumay/kser | src/kser/entry.py | Entrypoint.execute | def execute(self, result=None):
""" Execution 'wrapper' to make sure that it return a result
:return: Execution result
:rtype: kser.result.Result
"""
try:
return self.unsafe_execute(result=result)
except Exception as exc:
return self._onerror(Resu... | python | def execute(self, result=None):
""" Execution 'wrapper' to make sure that it return a result
:return: Execution result
:rtype: kser.result.Result
"""
try:
return self.unsafe_execute(result=result)
except Exception as exc:
return self._onerror(Resu... | [
"def",
"execute",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"unsafe_execute",
"(",
"result",
"=",
"result",
")",
"except",
"Exception",
"as",
"exc",
":",
"return",
"self",
".",
"_onerror",
"(",
"Result",
".",... | Execution 'wrapper' to make sure that it return a result
:return: Execution result
:rtype: kser.result.Result | [
"Execution",
"wrapper",
"to",
"make",
"sure",
"that",
"it",
"return",
"a",
"result"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/entry.py#L238-L247 | train | 56,495 |
cdumay/kser | src/kser/entry.py | Entrypoint.to_Message | def to_Message(self, result=None):
""" Entrypoint -> Message
:param kser.result.Result result: Execution result
:return: Kafka message
:rtype kser.schemas.Message
"""
return Message(
uuid=self.uuid, entrypoint=self.__class__.path, params=self.params,
... | python | def to_Message(self, result=None):
""" Entrypoint -> Message
:param kser.result.Result result: Execution result
:return: Kafka message
:rtype kser.schemas.Message
"""
return Message(
uuid=self.uuid, entrypoint=self.__class__.path, params=self.params,
... | [
"def",
"to_Message",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"return",
"Message",
"(",
"uuid",
"=",
"self",
".",
"uuid",
",",
"entrypoint",
"=",
"self",
".",
"__class__",
".",
"path",
",",
"params",
"=",
"self",
".",
"params",
",",
"result... | Entrypoint -> Message
:param kser.result.Result result: Execution result
:return: Kafka message
:rtype kser.schemas.Message | [
"Entrypoint",
"-",
">",
"Message"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/entry.py#L250-L260 | train | 56,496 |
cdumay/kser | src/kser/entry.py | Entrypoint.from_Message | def from_Message(cls, kmsg):
""" Message -> Entrypoint
:param kser.schemas.Message kmsg: Kafka message
:return: a entrypoint
:rtype kser.entry.Entrypoint
"""
return cls(
uuid=kmsg.uuid, params=kmsg.params, result=kmsg.result,
metadata=kmsg.metadat... | python | def from_Message(cls, kmsg):
""" Message -> Entrypoint
:param kser.schemas.Message kmsg: Kafka message
:return: a entrypoint
:rtype kser.entry.Entrypoint
"""
return cls(
uuid=kmsg.uuid, params=kmsg.params, result=kmsg.result,
metadata=kmsg.metadat... | [
"def",
"from_Message",
"(",
"cls",
",",
"kmsg",
")",
":",
"return",
"cls",
"(",
"uuid",
"=",
"kmsg",
".",
"uuid",
",",
"params",
"=",
"kmsg",
".",
"params",
",",
"result",
"=",
"kmsg",
".",
"result",
",",
"metadata",
"=",
"kmsg",
".",
"metadata",
"... | Message -> Entrypoint
:param kser.schemas.Message kmsg: Kafka message
:return: a entrypoint
:rtype kser.entry.Entrypoint | [
"Message",
"-",
">",
"Entrypoint"
] | fbd6fe9ab34b8b89d9937e5ff727614304af48c1 | https://github.com/cdumay/kser/blob/fbd6fe9ab34b8b89d9937e5ff727614304af48c1/src/kser/entry.py#L264-L274 | train | 56,497 |
trevisanj/f311 | f311/filetypes/datafile.py | DataFile.save_as | def save_as(self, filename=None):
"""
Dumps object contents into file on disk.
Args:
filename (optional): defaults to self.filename. If passed, self.filename
will be updated to filename.
"""
if filename is None:
filename = self.filename
... | python | def save_as(self, filename=None):
"""
Dumps object contents into file on disk.
Args:
filename (optional): defaults to self.filename. If passed, self.filename
will be updated to filename.
"""
if filename is None:
filename = self.filename
... | [
"def",
"save_as",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"default_filename",
"if",
"filename",... | Dumps object contents into file on disk.
Args:
filename (optional): defaults to self.filename. If passed, self.filename
will be updated to filename. | [
"Dumps",
"object",
"contents",
"into",
"file",
"on",
"disk",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/filetypes/datafile.py#L63-L78 | train | 56,498 |
trevisanj/f311 | f311/filetypes/datafile.py | DataFile.load | def load(self, filename=None):
"""Loads file and registers filename as attribute."""
assert not self.__flag_loaded, "File can be loaded only once"
if filename is None:
filename = self.default_filename
assert filename is not None, \
"{0!s} class has no default file... | python | def load(self, filename=None):
"""Loads file and registers filename as attribute."""
assert not self.__flag_loaded, "File can be loaded only once"
if filename is None:
filename = self.default_filename
assert filename is not None, \
"{0!s} class has no default file... | [
"def",
"load",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"__flag_loaded",
",",
"\"File can be loaded only once\"",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"default_filename",
"assert",
"filena... | Loads file and registers filename as attribute. | [
"Loads",
"file",
"and",
"registers",
"filename",
"as",
"attribute",
"."
] | 9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7 | https://github.com/trevisanj/f311/blob/9e502a3d1e1f74d4290a8a0bae9a34ef8d7b29f7/f311/filetypes/datafile.py#L80-L98 | train | 56,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.