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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mvn23/pyotgw | pyotgw/protocol.py | protocol._dissect_msg | def _dissect_msg(self, match):
"""
Split messages into bytes and return a tuple of bytes.
"""
recvfrom = match.group(1)
frame = bytes.fromhex(match.group(2))
if recvfrom == 'E':
_LOGGER.warning("Received erroneous message, ignoring: %s", frame)
return (None, None, None, None, None)
msgtype = self._get_msgtype(frame[0])
if msgtype in (READ_ACK, WRITE_ACK, READ_DATA, WRITE_DATA):
# Some info is best read from the READ/WRITE_DATA messages
# as the boiler may not support the data ID.
# Slice syntax is used to prevent implicit cast to int.
data_id = frame[1:2]
data_msb = frame[2:3]
data_lsb = frame[3:4]
return (recvfrom, msgtype, data_id, data_msb, data_lsb)
return (None, None, None, None, None) | python | def _dissect_msg(self, match):
"""
Split messages into bytes and return a tuple of bytes.
"""
recvfrom = match.group(1)
frame = bytes.fromhex(match.group(2))
if recvfrom == 'E':
_LOGGER.warning("Received erroneous message, ignoring: %s", frame)
return (None, None, None, None, None)
msgtype = self._get_msgtype(frame[0])
if msgtype in (READ_ACK, WRITE_ACK, READ_DATA, WRITE_DATA):
# Some info is best read from the READ/WRITE_DATA messages
# as the boiler may not support the data ID.
# Slice syntax is used to prevent implicit cast to int.
data_id = frame[1:2]
data_msb = frame[2:3]
data_lsb = frame[3:4]
return (recvfrom, msgtype, data_id, data_msb, data_lsb)
return (None, None, None, None, None) | [
"def",
"_dissect_msg",
"(",
"self",
",",
"match",
")",
":",
"recvfrom",
"=",
"match",
".",
"group",
"(",
"1",
")",
"frame",
"=",
"bytes",
".",
"fromhex",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"if",
"recvfrom",
"==",
"'E'",
":",
"_LOGGER",... | Split messages into bytes and return a tuple of bytes. | [
"Split",
"messages",
"into",
"bytes",
"and",
"return",
"a",
"tuple",
"of",
"bytes",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/protocol.py#L157-L175 | train | 23,900 |
mvn23/pyotgw | pyotgw/protocol.py | protocol._get_u16 | def _get_u16(self, msb, lsb):
"""
Convert 2 bytes into an unsigned int.
"""
buf = struct.pack('>BB', self._get_u8(msb), self._get_u8(lsb))
return int(struct.unpack('>H', buf)[0]) | python | def _get_u16(self, msb, lsb):
"""
Convert 2 bytes into an unsigned int.
"""
buf = struct.pack('>BB', self._get_u8(msb), self._get_u8(lsb))
return int(struct.unpack('>H', buf)[0]) | [
"def",
"_get_u16",
"(",
"self",
",",
"msb",
",",
"lsb",
")",
":",
"buf",
"=",
"struct",
".",
"pack",
"(",
"'>BB'",
",",
"self",
".",
"_get_u8",
"(",
"msb",
")",
",",
"self",
".",
"_get_u8",
"(",
"lsb",
")",
")",
"return",
"int",
"(",
"struct",
... | Convert 2 bytes into an unsigned int. | [
"Convert",
"2",
"bytes",
"into",
"an",
"unsigned",
"int",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/protocol.py#L445-L450 | train | 23,901 |
mvn23/pyotgw | pyotgw/protocol.py | protocol._get_s16 | def _get_s16(self, msb, lsb):
"""
Convert 2 bytes into a signed int.
"""
buf = struct.pack('>bB', self._get_s8(msb), self._get_u8(lsb))
return int(struct.unpack('>h', buf)[0]) | python | def _get_s16(self, msb, lsb):
"""
Convert 2 bytes into a signed int.
"""
buf = struct.pack('>bB', self._get_s8(msb), self._get_u8(lsb))
return int(struct.unpack('>h', buf)[0]) | [
"def",
"_get_s16",
"(",
"self",
",",
"msb",
",",
"lsb",
")",
":",
"buf",
"=",
"struct",
".",
"pack",
"(",
"'>bB'",
",",
"self",
".",
"_get_s8",
"(",
"msb",
")",
",",
"self",
".",
"_get_u8",
"(",
"lsb",
")",
")",
"return",
"int",
"(",
"struct",
... | Convert 2 bytes into a signed int. | [
"Convert",
"2",
"bytes",
"into",
"a",
"signed",
"int",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/protocol.py#L452-L457 | train | 23,902 |
mvn23/pyotgw | pyotgw/protocol.py | protocol._report | async def _report(self):
"""
Call _update_cb with the status dict as an argument whenever a status
update occurs.
This method is a coroutine
"""
while True:
oldstatus = dict(self.status)
stat = await self._updateq.get()
if self._update_cb is not None and oldstatus != stat:
# Each client gets its own copy of the dict.
self.loop.create_task(self._update_cb(dict(stat))) | python | async def _report(self):
"""
Call _update_cb with the status dict as an argument whenever a status
update occurs.
This method is a coroutine
"""
while True:
oldstatus = dict(self.status)
stat = await self._updateq.get()
if self._update_cb is not None and oldstatus != stat:
# Each client gets its own copy of the dict.
self.loop.create_task(self._update_cb(dict(stat))) | [
"async",
"def",
"_report",
"(",
"self",
")",
":",
"while",
"True",
":",
"oldstatus",
"=",
"dict",
"(",
"self",
".",
"status",
")",
"stat",
"=",
"await",
"self",
".",
"_updateq",
".",
"get",
"(",
")",
"if",
"self",
".",
"_update_cb",
"is",
"not",
"N... | Call _update_cb with the status dict as an argument whenever a status
update occurs.
This method is a coroutine | [
"Call",
"_update_cb",
"with",
"the",
"status",
"dict",
"as",
"an",
"argument",
"whenever",
"a",
"status",
"update",
"occurs",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/protocol.py#L459-L471 | train | 23,903 |
mvn23/pyotgw | pyotgw/protocol.py | protocol.set_update_cb | async def set_update_cb(self, cb):
"""Register the update callback."""
if self._report_task is not None and not self._report_task.cancelled():
self.loop.create_task(self._report_task.cancel())
self._update_cb = cb
if cb is not None:
self._report_task = self.loop.create_task(self._report()) | python | async def set_update_cb(self, cb):
"""Register the update callback."""
if self._report_task is not None and not self._report_task.cancelled():
self.loop.create_task(self._report_task.cancel())
self._update_cb = cb
if cb is not None:
self._report_task = self.loop.create_task(self._report()) | [
"async",
"def",
"set_update_cb",
"(",
"self",
",",
"cb",
")",
":",
"if",
"self",
".",
"_report_task",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"_report_task",
".",
"cancelled",
"(",
")",
":",
"self",
".",
"loop",
".",
"create_task",
"(",
"self",... | Register the update callback. | [
"Register",
"the",
"update",
"callback",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/protocol.py#L473-L479 | train | 23,904 |
mvn23/pyotgw | pyotgw/protocol.py | protocol.issue_cmd | async def issue_cmd(self, cmd, value, retry=3):
"""
Issue a command, then await and return the return value.
This method is a coroutine
"""
async with self._cmd_lock:
if not self.connected:
_LOGGER.debug(
"Serial transport closed, not sending command %s", cmd)
return
while not self._cmdq.empty():
_LOGGER.debug("Clearing leftover message from command queue:"
" %s", await self._cmdq.get())
_LOGGER.debug("Sending command: %s with value %s", cmd, value)
self.transport.write(
'{}={}\r\n'.format(cmd, value).encode('ascii'))
if cmd == OTGW_CMD_REPORT:
expect = r'^{}:\s*([A-Z]{{2}}|{}=[^$]+)$'.format(cmd, value)
else:
expect = r'^{}:\s*([^$]+)$'.format(cmd)
async def send_again(err):
"""Resend the command."""
nonlocal retry
_LOGGER.warning("Command %s failed with %s, retrying...", cmd,
err)
retry -= 1
self.transport.write(
'{}={}\r\n'.format(cmd, value).encode('ascii'))
async def process(msg):
"""Process a possible response."""
_LOGGER.debug("Got possible response for command %s: %s", cmd,
msg)
if msg in OTGW_ERRS:
# Some errors appear by themselves on one line.
if retry == 0:
raise OTGW_ERRS[msg]
await send_again(msg)
return
if cmd == OTGW_CMD_MODE and value == 'R':
# Device was reset, msg contains build info
while not re.match(
r'OpenTherm Gateway \d+\.\d+\.\d+', msg):
msg = await self._cmdq.get()
return True
match = re.match(expect, msg)
if match:
if match.group(1) in OTGW_ERRS:
# Some errors are considered a response.
if retry == 0:
raise OTGW_ERRS[match.group(1)]
await send_again(msg)
return
ret = match.group(1)
if cmd == OTGW_CMD_SUMMARY and ret == '1':
# Expects a second line
part2 = await self._cmdq.get()
ret = [ret, part2]
return ret
if re.match(r'Error 0[1-4]', msg):
_LOGGER.warning("Received %s. If this happens during a "
"reset of the gateway it can be safely "
"ignored.", msg)
return
_LOGGER.warning("Unknown message in command queue: %s", msg)
await send_again(msg)
while True:
msg = await self._cmdq.get()
ret = await process(msg)
if ret is not None:
return ret | python | async def issue_cmd(self, cmd, value, retry=3):
"""
Issue a command, then await and return the return value.
This method is a coroutine
"""
async with self._cmd_lock:
if not self.connected:
_LOGGER.debug(
"Serial transport closed, not sending command %s", cmd)
return
while not self._cmdq.empty():
_LOGGER.debug("Clearing leftover message from command queue:"
" %s", await self._cmdq.get())
_LOGGER.debug("Sending command: %s with value %s", cmd, value)
self.transport.write(
'{}={}\r\n'.format(cmd, value).encode('ascii'))
if cmd == OTGW_CMD_REPORT:
expect = r'^{}:\s*([A-Z]{{2}}|{}=[^$]+)$'.format(cmd, value)
else:
expect = r'^{}:\s*([^$]+)$'.format(cmd)
async def send_again(err):
"""Resend the command."""
nonlocal retry
_LOGGER.warning("Command %s failed with %s, retrying...", cmd,
err)
retry -= 1
self.transport.write(
'{}={}\r\n'.format(cmd, value).encode('ascii'))
async def process(msg):
"""Process a possible response."""
_LOGGER.debug("Got possible response for command %s: %s", cmd,
msg)
if msg in OTGW_ERRS:
# Some errors appear by themselves on one line.
if retry == 0:
raise OTGW_ERRS[msg]
await send_again(msg)
return
if cmd == OTGW_CMD_MODE and value == 'R':
# Device was reset, msg contains build info
while not re.match(
r'OpenTherm Gateway \d+\.\d+\.\d+', msg):
msg = await self._cmdq.get()
return True
match = re.match(expect, msg)
if match:
if match.group(1) in OTGW_ERRS:
# Some errors are considered a response.
if retry == 0:
raise OTGW_ERRS[match.group(1)]
await send_again(msg)
return
ret = match.group(1)
if cmd == OTGW_CMD_SUMMARY and ret == '1':
# Expects a second line
part2 = await self._cmdq.get()
ret = [ret, part2]
return ret
if re.match(r'Error 0[1-4]', msg):
_LOGGER.warning("Received %s. If this happens during a "
"reset of the gateway it can be safely "
"ignored.", msg)
return
_LOGGER.warning("Unknown message in command queue: %s", msg)
await send_again(msg)
while True:
msg = await self._cmdq.get()
ret = await process(msg)
if ret is not None:
return ret | [
"async",
"def",
"issue_cmd",
"(",
"self",
",",
"cmd",
",",
"value",
",",
"retry",
"=",
"3",
")",
":",
"async",
"with",
"self",
".",
"_cmd_lock",
":",
"if",
"not",
"self",
".",
"connected",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Serial transport closed, no... | Issue a command, then await and return the return value.
This method is a coroutine | [
"Issue",
"a",
"command",
"then",
"await",
"and",
"return",
"the",
"return",
"value",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/protocol.py#L481-L554 | train | 23,905 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.get_target_temp | def get_target_temp(self):
"""
Get the target temperature.
"""
if not self._connected:
return
temp_ovrd = self._protocol.status.get(DATA_ROOM_SETPOINT_OVRD)
if temp_ovrd:
return temp_ovrd
return self._protocol.status.get(DATA_ROOM_SETPOINT) | python | def get_target_temp(self):
"""
Get the target temperature.
"""
if not self._connected:
return
temp_ovrd = self._protocol.status.get(DATA_ROOM_SETPOINT_OVRD)
if temp_ovrd:
return temp_ovrd
return self._protocol.status.get(DATA_ROOM_SETPOINT) | [
"def",
"get_target_temp",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_connected",
":",
"return",
"temp_ovrd",
"=",
"self",
".",
"_protocol",
".",
"status",
".",
"get",
"(",
"DATA_ROOM_SETPOINT_OVRD",
")",
"if",
"temp_ovrd",
":",
"return",
"temp_ovrd",... | Get the target temperature. | [
"Get",
"the",
"target",
"temperature",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L113-L122 | train | 23,906 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.get_reports | async def get_reports(self):
"""
Update the pyotgw object with the information from all of the
PR commands and return the updated status dict.
This method is a coroutine
"""
cmd = OTGW_CMD_REPORT
reports = {}
for value in OTGW_REPORTS.keys():
ret = await self._wait_for_cmd(cmd, value)
if ret is None:
reports[value] = None
continue
reports[value] = ret[2:]
status = {
OTGW_ABOUT: reports.get(OTGW_REPORT_ABOUT),
OTGW_BUILD: reports.get(OTGW_REPORT_BUILDDATE),
OTGW_CLOCKMHZ: reports.get(OTGW_REPORT_CLOCKMHZ),
OTGW_MODE: reports.get(OTGW_REPORT_GW_MODE),
OTGW_SMART_PWR: reports.get(OTGW_REPORT_SMART_PWR),
OTGW_THRM_DETECT: reports.get(OTGW_REPORT_THERMOSTAT_DETECT),
OTGW_DHW_OVRD: reports.get(OTGW_REPORT_DHW_SETTING),
}
ovrd_mode = reports.get(OTGW_REPORT_SETPOINT_OVRD)
if ovrd_mode is not None:
ovrd_mode = str.upper(ovrd_mode[0])
status.update({OTGW_SETP_OVRD_MODE: ovrd_mode})
gpio_funcs = reports.get(OTGW_REPORT_GPIO_FUNCS)
if gpio_funcs is not None:
status.update({
OTGW_GPIO_A: int(gpio_funcs[0]),
OTGW_GPIO_B: int(gpio_funcs[1]),
})
led_funcs = reports.get(OTGW_REPORT_LED_FUNCS)
if led_funcs is not None:
status.update({
OTGW_LED_A: led_funcs[0],
OTGW_LED_B: led_funcs[1],
OTGW_LED_C: led_funcs[2],
OTGW_LED_D: led_funcs[3],
OTGW_LED_E: led_funcs[4],
OTGW_LED_F: led_funcs[5],
})
tweaks = reports.get(OTGW_REPORT_TWEAKS)
if tweaks is not None:
status.update({
OTGW_IGNORE_TRANSITIONS: int(tweaks[0]),
OTGW_OVRD_HB: int(tweaks[1]),
})
sb_temp = reports.get(OTGW_REPORT_SETBACK_TEMP)
if sb_temp is not None:
status.update({OTGW_SB_TEMP: float(sb_temp)})
vref = reports.get(OTGW_REPORT_VREF)
if vref is not None:
status.update({OTGW_VREF: int(vref)})
if (ovrd_mode is not None and ovrd_mode != OTGW_SETP_OVRD_DISABLED):
status[DATA_ROOM_SETPOINT_OVRD] = float(
reports[OTGW_REPORT_SETPOINT_OVRD][1:])
self._update_status(status)
return dict(self._protocol.status) | python | async def get_reports(self):
"""
Update the pyotgw object with the information from all of the
PR commands and return the updated status dict.
This method is a coroutine
"""
cmd = OTGW_CMD_REPORT
reports = {}
for value in OTGW_REPORTS.keys():
ret = await self._wait_for_cmd(cmd, value)
if ret is None:
reports[value] = None
continue
reports[value] = ret[2:]
status = {
OTGW_ABOUT: reports.get(OTGW_REPORT_ABOUT),
OTGW_BUILD: reports.get(OTGW_REPORT_BUILDDATE),
OTGW_CLOCKMHZ: reports.get(OTGW_REPORT_CLOCKMHZ),
OTGW_MODE: reports.get(OTGW_REPORT_GW_MODE),
OTGW_SMART_PWR: reports.get(OTGW_REPORT_SMART_PWR),
OTGW_THRM_DETECT: reports.get(OTGW_REPORT_THERMOSTAT_DETECT),
OTGW_DHW_OVRD: reports.get(OTGW_REPORT_DHW_SETTING),
}
ovrd_mode = reports.get(OTGW_REPORT_SETPOINT_OVRD)
if ovrd_mode is not None:
ovrd_mode = str.upper(ovrd_mode[0])
status.update({OTGW_SETP_OVRD_MODE: ovrd_mode})
gpio_funcs = reports.get(OTGW_REPORT_GPIO_FUNCS)
if gpio_funcs is not None:
status.update({
OTGW_GPIO_A: int(gpio_funcs[0]),
OTGW_GPIO_B: int(gpio_funcs[1]),
})
led_funcs = reports.get(OTGW_REPORT_LED_FUNCS)
if led_funcs is not None:
status.update({
OTGW_LED_A: led_funcs[0],
OTGW_LED_B: led_funcs[1],
OTGW_LED_C: led_funcs[2],
OTGW_LED_D: led_funcs[3],
OTGW_LED_E: led_funcs[4],
OTGW_LED_F: led_funcs[5],
})
tweaks = reports.get(OTGW_REPORT_TWEAKS)
if tweaks is not None:
status.update({
OTGW_IGNORE_TRANSITIONS: int(tweaks[0]),
OTGW_OVRD_HB: int(tweaks[1]),
})
sb_temp = reports.get(OTGW_REPORT_SETBACK_TEMP)
if sb_temp is not None:
status.update({OTGW_SB_TEMP: float(sb_temp)})
vref = reports.get(OTGW_REPORT_VREF)
if vref is not None:
status.update({OTGW_VREF: int(vref)})
if (ovrd_mode is not None and ovrd_mode != OTGW_SETP_OVRD_DISABLED):
status[DATA_ROOM_SETPOINT_OVRD] = float(
reports[OTGW_REPORT_SETPOINT_OVRD][1:])
self._update_status(status)
return dict(self._protocol.status) | [
"async",
"def",
"get_reports",
"(",
"self",
")",
":",
"cmd",
"=",
"OTGW_CMD_REPORT",
"reports",
"=",
"{",
"}",
"for",
"value",
"in",
"OTGW_REPORTS",
".",
"keys",
"(",
")",
":",
"ret",
"=",
"await",
"self",
".",
"_wait_for_cmd",
"(",
"cmd",
",",
"value"... | Update the pyotgw object with the information from all of the
PR commands and return the updated status dict.
This method is a coroutine | [
"Update",
"the",
"pyotgw",
"object",
"with",
"the",
"information",
"from",
"all",
"of",
"the",
"PR",
"commands",
"and",
"return",
"the",
"updated",
"status",
"dict",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L218-L278 | train | 23,907 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.add_alternative | async def add_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Add the specified Data-ID to the list of alternative commands
to send to the boiler instead of a Data-ID that is known to be
unsupported by the boiler. Alternative Data-IDs will always be
sent to the boiler in a Read-Data request message with the
data-value set to zero. The table of alternative Data-IDs is
stored in non-volatile memory so it will persist even if the
gateway has been powered off. Data-ID values from 1 to 255 are
allowed.
Return the ID that was added to the list, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_ADD_ALT
alt = int(alt)
if alt < 1 or alt > 255:
return None
ret = await self._wait_for_cmd(cmd, alt, timeout)
if ret is not None:
return int(ret) | python | async def add_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Add the specified Data-ID to the list of alternative commands
to send to the boiler instead of a Data-ID that is known to be
unsupported by the boiler. Alternative Data-IDs will always be
sent to the boiler in a Read-Data request message with the
data-value set to zero. The table of alternative Data-IDs is
stored in non-volatile memory so it will persist even if the
gateway has been powered off. Data-ID values from 1 to 255 are
allowed.
Return the ID that was added to the list, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_ADD_ALT
alt = int(alt)
if alt < 1 or alt > 255:
return None
ret = await self._wait_for_cmd(cmd, alt, timeout)
if ret is not None:
return int(ret) | [
"async",
"def",
"add_alternative",
"(",
"self",
",",
"alt",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_ADD_ALT",
"alt",
"=",
"int",
"(",
"alt",
")",
"if",
"alt",
"<",
"1",
"or",
"alt",
">",
"255",
":",
"return",
"None"... | Add the specified Data-ID to the list of alternative commands
to send to the boiler instead of a Data-ID that is known to be
unsupported by the boiler. Alternative Data-IDs will always be
sent to the boiler in a Read-Data request message with the
data-value set to zero. The table of alternative Data-IDs is
stored in non-volatile memory so it will persist even if the
gateway has been powered off. Data-ID values from 1 to 255 are
allowed.
Return the ID that was added to the list, or None on failure.
This method is a coroutine | [
"Add",
"the",
"specified",
"Data",
"-",
"ID",
"to",
"the",
"list",
"of",
"alternative",
"commands",
"to",
"send",
"to",
"the",
"boiler",
"instead",
"of",
"a",
"Data",
"-",
"ID",
"that",
"is",
"known",
"to",
"be",
"unsupported",
"by",
"the",
"boiler",
"... | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L528-L548 | train | 23,908 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.del_alternative | async def del_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Remove the specified Data-ID from the list of alternative
commands. Only one occurrence is deleted. If the Data-ID
appears multiple times in the list of alternative commands,
this command must be repeated to delete all occurrences. The
table of alternative Data-IDs is stored in non-volatile memory
so it will persist even if the gateway has been powered off.
Data-ID values from 1 to 255 are allowed.
Return the ID that was removed from the list, or None on
failure.
This method is a coroutine
"""
cmd = OTGW_CMD_DEL_ALT
alt = int(alt)
if alt < 1 or alt > 255:
return None
ret = await self._wait_for_cmd(cmd, alt, timeout)
if ret is not None:
return int(ret) | python | async def del_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Remove the specified Data-ID from the list of alternative
commands. Only one occurrence is deleted. If the Data-ID
appears multiple times in the list of alternative commands,
this command must be repeated to delete all occurrences. The
table of alternative Data-IDs is stored in non-volatile memory
so it will persist even if the gateway has been powered off.
Data-ID values from 1 to 255 are allowed.
Return the ID that was removed from the list, or None on
failure.
This method is a coroutine
"""
cmd = OTGW_CMD_DEL_ALT
alt = int(alt)
if alt < 1 or alt > 255:
return None
ret = await self._wait_for_cmd(cmd, alt, timeout)
if ret is not None:
return int(ret) | [
"async",
"def",
"del_alternative",
"(",
"self",
",",
"alt",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_DEL_ALT",
"alt",
"=",
"int",
"(",
"alt",
")",
"if",
"alt",
"<",
"1",
"or",
"alt",
">",
"255",
":",
"return",
"None"... | Remove the specified Data-ID from the list of alternative
commands. Only one occurrence is deleted. If the Data-ID
appears multiple times in the list of alternative commands,
this command must be repeated to delete all occurrences. The
table of alternative Data-IDs is stored in non-volatile memory
so it will persist even if the gateway has been powered off.
Data-ID values from 1 to 255 are allowed.
Return the ID that was removed from the list, or None on
failure.
This method is a coroutine | [
"Remove",
"the",
"specified",
"Data",
"-",
"ID",
"from",
"the",
"list",
"of",
"alternative",
"commands",
".",
"Only",
"one",
"occurrence",
"is",
"deleted",
".",
"If",
"the",
"Data",
"-",
"ID",
"appears",
"multiple",
"times",
"in",
"the",
"list",
"of",
"a... | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L550-L570 | train | 23,909 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.add_unknown_id | async def add_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Inform the gateway that the boiler doesn't support the
specified Data-ID, even if the boiler doesn't indicate that
by returning an Unknown-DataId response. Using this command
allows the gateway to send an alternative Data-ID to the boiler
instead.
Return the added ID, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_UNKNOWN_ID
unknown_id = int(unknown_id)
if unknown_id < 1 or unknown_id > 255:
return None
ret = await self._wait_for_cmd(cmd, unknown_id, timeout)
if ret is not None:
return int(ret) | python | async def add_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Inform the gateway that the boiler doesn't support the
specified Data-ID, even if the boiler doesn't indicate that
by returning an Unknown-DataId response. Using this command
allows the gateway to send an alternative Data-ID to the boiler
instead.
Return the added ID, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_UNKNOWN_ID
unknown_id = int(unknown_id)
if unknown_id < 1 or unknown_id > 255:
return None
ret = await self._wait_for_cmd(cmd, unknown_id, timeout)
if ret is not None:
return int(ret) | [
"async",
"def",
"add_unknown_id",
"(",
"self",
",",
"unknown_id",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_UNKNOWN_ID",
"unknown_id",
"=",
"int",
"(",
"unknown_id",
")",
"if",
"unknown_id",
"<",
"1",
"or",
"unknown_id",
">",... | Inform the gateway that the boiler doesn't support the
specified Data-ID, even if the boiler doesn't indicate that
by returning an Unknown-DataId response. Using this command
allows the gateway to send an alternative Data-ID to the boiler
instead.
Return the added ID, or None on failure.
This method is a coroutine | [
"Inform",
"the",
"gateway",
"that",
"the",
"boiler",
"doesn",
"t",
"support",
"the",
"specified",
"Data",
"-",
"ID",
"even",
"if",
"the",
"boiler",
"doesn",
"t",
"indicate",
"that",
"by",
"returning",
"an",
"Unknown",
"-",
"DataId",
"response",
".",
"Using... | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L572-L589 | train | 23,910 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.del_unknown_id | async def del_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Start forwarding the specified Data-ID to the boiler again.
This command resets the counter used to determine if the
specified Data-ID is supported by the boiler.
Return the ID that was marked as supported, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_KNOWN_ID
unknown_id = int(unknown_id)
if unknown_id < 1 or unknown_id > 255:
return None
ret = await self._wait_for_cmd(cmd, unknown_id, timeout)
if ret is not None:
return int(ret) | python | async def del_unknown_id(self, unknown_id, timeout=OTGW_DEFAULT_TIMEOUT):
"""
Start forwarding the specified Data-ID to the boiler again.
This command resets the counter used to determine if the
specified Data-ID is supported by the boiler.
Return the ID that was marked as supported, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_KNOWN_ID
unknown_id = int(unknown_id)
if unknown_id < 1 or unknown_id > 255:
return None
ret = await self._wait_for_cmd(cmd, unknown_id, timeout)
if ret is not None:
return int(ret) | [
"async",
"def",
"del_unknown_id",
"(",
"self",
",",
"unknown_id",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_KNOWN_ID",
"unknown_id",
"=",
"int",
"(",
"unknown_id",
")",
"if",
"unknown_id",
"<",
"1",
"or",
"unknown_id",
">",
... | Start forwarding the specified Data-ID to the boiler again.
This command resets the counter used to determine if the
specified Data-ID is supported by the boiler.
Return the ID that was marked as supported, or None on failure.
This method is a coroutine | [
"Start",
"forwarding",
"the",
"specified",
"Data",
"-",
"ID",
"to",
"the",
"boiler",
"again",
".",
"This",
"command",
"resets",
"the",
"counter",
"used",
"to",
"determine",
"if",
"the",
"specified",
"Data",
"-",
"ID",
"is",
"supported",
"by",
"the",
"boile... | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L591-L606 | train | 23,911 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.set_max_ch_setpoint | async def set_max_ch_setpoint(self, temperature,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Set the maximum central heating setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_SET_MAX
status = {}
ret = await self._wait_for_cmd(cmd, temperature, timeout)
if ret is None:
return
ret = float(ret)
status[DATA_MAX_CH_SETPOINT] = ret
self._update_status(status)
return ret | python | async def set_max_ch_setpoint(self, temperature,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Set the maximum central heating setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_SET_MAX
status = {}
ret = await self._wait_for_cmd(cmd, temperature, timeout)
if ret is None:
return
ret = float(ret)
status[DATA_MAX_CH_SETPOINT] = ret
self._update_status(status)
return ret | [
"async",
"def",
"set_max_ch_setpoint",
"(",
"self",
",",
"temperature",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_SET_MAX",
"status",
"=",
"{",
"}",
"ret",
"=",
"await",
"self",
".",
"_wait_for_cmd",
"(",
"cmd",
",",
"tempe... | Set the maximum central heating setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
This method is a coroutine | [
"Set",
"the",
"maximum",
"central",
"heating",
"setpoint",
".",
"This",
"command",
"is",
"only",
"available",
"with",
"boilers",
"that",
"support",
"this",
"function",
".",
"Return",
"the",
"newly",
"accepted",
"setpoint",
"or",
"None",
"on",
"failure",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L648-L665 | train | 23,912 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.set_dhw_setpoint | async def set_dhw_setpoint(self, temperature,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Set the domestic hot water setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_SET_WATER
status = {}
ret = await self._wait_for_cmd(cmd, temperature, timeout)
if ret is None:
return
ret = float(ret)
status[DATA_DHW_SETPOINT] = ret
self._update_status(status)
return ret | python | async def set_dhw_setpoint(self, temperature,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Set the domestic hot water setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_SET_WATER
status = {}
ret = await self._wait_for_cmd(cmd, temperature, timeout)
if ret is None:
return
ret = float(ret)
status[DATA_DHW_SETPOINT] = ret
self._update_status(status)
return ret | [
"async",
"def",
"set_dhw_setpoint",
"(",
"self",
",",
"temperature",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_SET_WATER",
"status",
"=",
"{",
"}",
"ret",
"=",
"await",
"self",
".",
"_wait_for_cmd",
"(",
"cmd",
",",
"temper... | Set the domestic hot water setpoint. This command is only
available with boilers that support this function.
Return the newly accepted setpoint, or None on failure.
This method is a coroutine | [
"Set",
"the",
"domestic",
"hot",
"water",
"setpoint",
".",
"This",
"command",
"is",
"only",
"available",
"with",
"boilers",
"that",
"support",
"this",
"function",
".",
"Return",
"the",
"newly",
"accepted",
"setpoint",
"or",
"None",
"on",
"failure",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L667-L684 | train | 23,913 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.set_max_relative_mod | async def set_max_relative_mod(self, max_mod,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Override the maximum relative modulation from the thermostat.
Valid values are 0 through 100. Clear the setting by specifying
a non-numeric value.
Return the newly accepted value, '-' if a previous value was
cleared, or None on failure.
This method is a coroutine
"""
if isinstance(max_mod, int) and not 0 <= max_mod <= 100:
return None
cmd = OTGW_CMD_MAX_MOD
status = {}
ret = await self._wait_for_cmd(cmd, max_mod, timeout)
if ret not in ['-', None]:
ret = int(ret)
if ret == '-':
status[DATA_SLAVE_MAX_RELATIVE_MOD] = None
else:
status[DATA_SLAVE_MAX_RELATIVE_MOD] = ret
self._update_status(status)
return ret | python | async def set_max_relative_mod(self, max_mod,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Override the maximum relative modulation from the thermostat.
Valid values are 0 through 100. Clear the setting by specifying
a non-numeric value.
Return the newly accepted value, '-' if a previous value was
cleared, or None on failure.
This method is a coroutine
"""
if isinstance(max_mod, int) and not 0 <= max_mod <= 100:
return None
cmd = OTGW_CMD_MAX_MOD
status = {}
ret = await self._wait_for_cmd(cmd, max_mod, timeout)
if ret not in ['-', None]:
ret = int(ret)
if ret == '-':
status[DATA_SLAVE_MAX_RELATIVE_MOD] = None
else:
status[DATA_SLAVE_MAX_RELATIVE_MOD] = ret
self._update_status(status)
return ret | [
"async",
"def",
"set_max_relative_mod",
"(",
"self",
",",
"max_mod",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"if",
"isinstance",
"(",
"max_mod",
",",
"int",
")",
"and",
"not",
"0",
"<=",
"max_mod",
"<=",
"100",
":",
"return",
"None",
"cmd",
... | Override the maximum relative modulation from the thermostat.
Valid values are 0 through 100. Clear the setting by specifying
a non-numeric value.
Return the newly accepted value, '-' if a previous value was
cleared, or None on failure.
This method is a coroutine | [
"Override",
"the",
"maximum",
"relative",
"modulation",
"from",
"the",
"thermostat",
".",
"Valid",
"values",
"are",
"0",
"through",
"100",
".",
"Clear",
"the",
"setting",
"by",
"specifying",
"a",
"non",
"-",
"numeric",
"value",
".",
"Return",
"the",
"newly",... | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L686-L709 | train | 23,914 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw.set_control_setpoint | async def set_control_setpoint(self, setpoint,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Manipulate the control setpoint being sent to the boiler. Set
to 0 to pass along the value specified by the thermostat.
Return the newly accepted value, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_CONTROL_SETPOINT
status = {}
ret = await self._wait_for_cmd(cmd, setpoint, timeout)
if ret is None:
return
ret = float(ret)
status[DATA_CONTROL_SETPOINT] = ret
self._update_status(status)
return ret | python | async def set_control_setpoint(self, setpoint,
timeout=OTGW_DEFAULT_TIMEOUT):
"""
Manipulate the control setpoint being sent to the boiler. Set
to 0 to pass along the value specified by the thermostat.
Return the newly accepted value, or None on failure.
This method is a coroutine
"""
cmd = OTGW_CMD_CONTROL_SETPOINT
status = {}
ret = await self._wait_for_cmd(cmd, setpoint, timeout)
if ret is None:
return
ret = float(ret)
status[DATA_CONTROL_SETPOINT] = ret
self._update_status(status)
return ret | [
"async",
"def",
"set_control_setpoint",
"(",
"self",
",",
"setpoint",
",",
"timeout",
"=",
"OTGW_DEFAULT_TIMEOUT",
")",
":",
"cmd",
"=",
"OTGW_CMD_CONTROL_SETPOINT",
"status",
"=",
"{",
"}",
"ret",
"=",
"await",
"self",
".",
"_wait_for_cmd",
"(",
"cmd",
",",
... | Manipulate the control setpoint being sent to the boiler. Set
to 0 to pass along the value specified by the thermostat.
Return the newly accepted value, or None on failure.
This method is a coroutine | [
"Manipulate",
"the",
"control",
"setpoint",
"being",
"sent",
"to",
"the",
"boiler",
".",
"Set",
"to",
"0",
"to",
"pass",
"along",
"the",
"value",
"specified",
"by",
"the",
"thermostat",
".",
"Return",
"the",
"newly",
"accepted",
"value",
"or",
"None",
"on"... | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L711-L728 | train | 23,915 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw._send_report | async def _send_report(self, status):
"""
Call all subscribed coroutines in _notify whenever a status
update occurs.
This method is a coroutine
"""
if len(self._notify) > 0:
# Each client gets its own copy of the dict.
asyncio.gather(*[coro(dict(status)) for coro in self._notify],
loop=self.loop) | python | async def _send_report(self, status):
"""
Call all subscribed coroutines in _notify whenever a status
update occurs.
This method is a coroutine
"""
if len(self._notify) > 0:
# Each client gets its own copy of the dict.
asyncio.gather(*[coro(dict(status)) for coro in self._notify],
loop=self.loop) | [
"async",
"def",
"_send_report",
"(",
"self",
",",
"status",
")",
":",
"if",
"len",
"(",
"self",
".",
"_notify",
")",
">",
"0",
":",
"# Each client gets its own copy of the dict.",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"coro",
"(",
"dict",
"(",
"status",... | Call all subscribed coroutines in _notify whenever a status
update occurs.
This method is a coroutine | [
"Call",
"all",
"subscribed",
"coroutines",
"in",
"_notify",
"whenever",
"a",
"status",
"update",
"occurs",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L800-L810 | train | 23,916 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw._poll_gpio | async def _poll_gpio(self, poll, interval=10):
"""
Start or stop polling GPIO states.
GPIO states aren't being pushed by the gateway, we need to poll
if we want updates.
"""
if poll and self._gpio_task is None:
async def polling_routine(interval):
"""Poll GPIO state every @interval seconds."""
while True:
try:
pios = None
ret = await self._wait_for_cmd(
OTGW_CMD_REPORT, OTGW_REPORT_GPIO_STATES)
if ret:
pios = ret[2:]
status = {
OTGW_GPIO_A_STATE: int(pios[0]),
OTGW_GPIO_B_STATE: int(pios[1]),
}
self._update_status(status)
await asyncio.sleep(interval)
except asyncio.CancelledError:
status = {
OTGW_GPIO_A_STATE: 0,
OTGW_GPIO_B_STATE: 0,
}
self._update_status(status)
self._gpio_task = None
break
self._gpio_task = self.loop.create_task(polling_routine(interval))
elif not poll and self._gpio_task is not None:
self._gpio_task.cancel() | python | async def _poll_gpio(self, poll, interval=10):
"""
Start or stop polling GPIO states.
GPIO states aren't being pushed by the gateway, we need to poll
if we want updates.
"""
if poll and self._gpio_task is None:
async def polling_routine(interval):
"""Poll GPIO state every @interval seconds."""
while True:
try:
pios = None
ret = await self._wait_for_cmd(
OTGW_CMD_REPORT, OTGW_REPORT_GPIO_STATES)
if ret:
pios = ret[2:]
status = {
OTGW_GPIO_A_STATE: int(pios[0]),
OTGW_GPIO_B_STATE: int(pios[1]),
}
self._update_status(status)
await asyncio.sleep(interval)
except asyncio.CancelledError:
status = {
OTGW_GPIO_A_STATE: 0,
OTGW_GPIO_B_STATE: 0,
}
self._update_status(status)
self._gpio_task = None
break
self._gpio_task = self.loop.create_task(polling_routine(interval))
elif not poll and self._gpio_task is not None:
self._gpio_task.cancel() | [
"async",
"def",
"_poll_gpio",
"(",
"self",
",",
"poll",
",",
"interval",
"=",
"10",
")",
":",
"if",
"poll",
"and",
"self",
".",
"_gpio_task",
"is",
"None",
":",
"async",
"def",
"polling_routine",
"(",
"interval",
")",
":",
"\"\"\"Poll GPIO state every @inter... | Start or stop polling GPIO states.
GPIO states aren't being pushed by the gateway, we need to poll
if we want updates. | [
"Start",
"or",
"stop",
"polling",
"GPIO",
"states",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L832-L865 | train | 23,917 |
mvn23/pyotgw | pyotgw/pyotgw.py | pyotgw._update_status | def _update_status(self, update):
"""Update the status dict and push it to subscribers."""
if isinstance(update, dict):
self._protocol.status.update(update)
self._protocol._updateq.put_nowait(self._protocol.status) | python | def _update_status(self, update):
"""Update the status dict and push it to subscribers."""
if isinstance(update, dict):
self._protocol.status.update(update)
self._protocol._updateq.put_nowait(self._protocol.status) | [
"def",
"_update_status",
"(",
"self",
",",
"update",
")",
":",
"if",
"isinstance",
"(",
"update",
",",
"dict",
")",
":",
"self",
".",
"_protocol",
".",
"status",
".",
"update",
"(",
"update",
")",
"self",
".",
"_protocol",
".",
"_updateq",
".",
"put_no... | Update the status dict and push it to subscribers. | [
"Update",
"the",
"status",
"dict",
"and",
"push",
"it",
"to",
"subscribers",
"."
] | 7612378ef4332b250176505af33e7536d6c9da78 | https://github.com/mvn23/pyotgw/blob/7612378ef4332b250176505af33e7536d6c9da78/pyotgw/pyotgw.py#L867-L871 | train | 23,918 |
avirshup/DockerMake | dockermake/builds.py | BuildTarget.write_dockerfile | def write_dockerfile(self, output_dir):
""" Used only to write a Dockerfile that will NOT be built by docker-make
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
lines = []
for istep, step in enumerate(self.steps):
if istep == 0:
lines.extend(step.dockerfile_lines)
else:
lines.extend(step.dockerfile_lines[1:])
path = os.path.join(output_dir, 'Dockerfile.%s' % self.imagename)
with open(path, 'w') as outfile:
outfile.write('\n'.join(lines))
print('Wrote %s' % path) | python | def write_dockerfile(self, output_dir):
""" Used only to write a Dockerfile that will NOT be built by docker-make
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
lines = []
for istep, step in enumerate(self.steps):
if istep == 0:
lines.extend(step.dockerfile_lines)
else:
lines.extend(step.dockerfile_lines[1:])
path = os.path.join(output_dir, 'Dockerfile.%s' % self.imagename)
with open(path, 'w') as outfile:
outfile.write('\n'.join(lines))
print('Wrote %s' % path) | [
"def",
"write_dockerfile",
"(",
"self",
",",
"output_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"output_dir",
")",
"lines",
"=",
"[",
"]",
"for",
"istep",
",",
"step",
"in",... | Used only to write a Dockerfile that will NOT be built by docker-make | [
"Used",
"only",
"to",
"write",
"a",
"Dockerfile",
"that",
"will",
"NOT",
"be",
"built",
"by",
"docker",
"-",
"make"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/builds.py#L47-L62 | train | 23,919 |
avirshup/DockerMake | dockermake/builds.py | BuildTarget.build | def build(self, client,
nobuild=False,
usecache=True,
pull=False):
"""
Drives the build of the final image - get the list of steps and execute them.
Args:
client (docker.Client): docker client object that will build the image
nobuild (bool): just create dockerfiles, don't actually build the image
usecache (bool): use docker cache, or rebuild everything from scratch?
pull (bool): try to pull new versions of repository images?
"""
if not nobuild:
self.update_source_images(client,
usecache=usecache,
pull=pull)
width = utils.get_console_width()
cprint('\n' + '='*width,
color='white', attrs=['bold'])
line = 'STARTING BUILD for "%s" (image definition "%s" from %s)\n' % (
self.targetname, self.imagename, self.steps[-1].sourcefile)
cprint(_centered(line, width), color='blue', attrs=['bold'])
for istep, step in enumerate(self.steps):
print(colored('* Step','blue'),
colored('%d/%d' % (istep+1, len(self.steps)), 'blue', attrs=['bold']),
colored('for image', color='blue'),
colored(self.imagename, color='blue', attrs=['bold']))
if not nobuild:
if step.bust_cache:
stackkey = self._get_stack_key(istep)
if stackkey in _rebuilt:
step.bust_cache = False
step.build(client, usecache=usecache)
print(colored("* Created intermediate image", 'green'),
colored(step.buildname, 'green', attrs=['bold']),
end='\n\n')
if step.bust_cache:
_rebuilt.add(stackkey)
finalimage = step.buildname
if not nobuild:
self.finalizenames(client, finalimage)
line = 'FINISHED BUILDING "%s" (image definition "%s" from %s)'%(
self.targetname, self.imagename, self.steps[-1].sourcefile)
cprint(_centered(line, width),
color='green', attrs=['bold'])
cprint('=' * width, color='white', attrs=['bold'], end='\n\n') | python | def build(self, client,
nobuild=False,
usecache=True,
pull=False):
"""
Drives the build of the final image - get the list of steps and execute them.
Args:
client (docker.Client): docker client object that will build the image
nobuild (bool): just create dockerfiles, don't actually build the image
usecache (bool): use docker cache, or rebuild everything from scratch?
pull (bool): try to pull new versions of repository images?
"""
if not nobuild:
self.update_source_images(client,
usecache=usecache,
pull=pull)
width = utils.get_console_width()
cprint('\n' + '='*width,
color='white', attrs=['bold'])
line = 'STARTING BUILD for "%s" (image definition "%s" from %s)\n' % (
self.targetname, self.imagename, self.steps[-1].sourcefile)
cprint(_centered(line, width), color='blue', attrs=['bold'])
for istep, step in enumerate(self.steps):
print(colored('* Step','blue'),
colored('%d/%d' % (istep+1, len(self.steps)), 'blue', attrs=['bold']),
colored('for image', color='blue'),
colored(self.imagename, color='blue', attrs=['bold']))
if not nobuild:
if step.bust_cache:
stackkey = self._get_stack_key(istep)
if stackkey in _rebuilt:
step.bust_cache = False
step.build(client, usecache=usecache)
print(colored("* Created intermediate image", 'green'),
colored(step.buildname, 'green', attrs=['bold']),
end='\n\n')
if step.bust_cache:
_rebuilt.add(stackkey)
finalimage = step.buildname
if not nobuild:
self.finalizenames(client, finalimage)
line = 'FINISHED BUILDING "%s" (image definition "%s" from %s)'%(
self.targetname, self.imagename, self.steps[-1].sourcefile)
cprint(_centered(line, width),
color='green', attrs=['bold'])
cprint('=' * width, color='white', attrs=['bold'], end='\n\n') | [
"def",
"build",
"(",
"self",
",",
"client",
",",
"nobuild",
"=",
"False",
",",
"usecache",
"=",
"True",
",",
"pull",
"=",
"False",
")",
":",
"if",
"not",
"nobuild",
":",
"self",
".",
"update_source_images",
"(",
"client",
",",
"usecache",
"=",
"usecach... | Drives the build of the final image - get the list of steps and execute them.
Args:
client (docker.Client): docker client object that will build the image
nobuild (bool): just create dockerfiles, don't actually build the image
usecache (bool): use docker cache, or rebuild everything from scratch?
pull (bool): try to pull new versions of repository images? | [
"Drives",
"the",
"build",
"of",
"the",
"final",
"image",
"-",
"get",
"the",
"list",
"of",
"steps",
"and",
"execute",
"them",
"."
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/builds.py#L64-L119 | train | 23,920 |
avirshup/DockerMake | dockermake/builds.py | BuildTarget.finalizenames | def finalizenames(self, client, finalimage):
""" Tag the built image with its final name and untag intermediate containers
"""
client.api.tag(finalimage, *self.targetname.split(':'))
cprint('Tagged final image as "%s"' % self.targetname,
'green')
if not self.keepbuildtags:
print('Untagging intermediate containers:', end='')
for step in self.steps:
client.api.remove_image(step.buildname, force=True)
print(step.buildname, end=',')
print() | python | def finalizenames(self, client, finalimage):
""" Tag the built image with its final name and untag intermediate containers
"""
client.api.tag(finalimage, *self.targetname.split(':'))
cprint('Tagged final image as "%s"' % self.targetname,
'green')
if not self.keepbuildtags:
print('Untagging intermediate containers:', end='')
for step in self.steps:
client.api.remove_image(step.buildname, force=True)
print(step.buildname, end=',')
print() | [
"def",
"finalizenames",
"(",
"self",
",",
"client",
",",
"finalimage",
")",
":",
"client",
".",
"api",
".",
"tag",
"(",
"finalimage",
",",
"*",
"self",
".",
"targetname",
".",
"split",
"(",
"':'",
")",
")",
"cprint",
"(",
"'Tagged final image as \"%s\"'",
... | Tag the built image with its final name and untag intermediate containers | [
"Tag",
"the",
"built",
"image",
"with",
"its",
"final",
"name",
"and",
"untag",
"intermediate",
"containers"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/builds.py#L142-L153 | train | 23,921 |
avirshup/DockerMake | dockermake/step.py | BuildStep._resolve_squash_cache | def _resolve_squash_cache(self, client):
"""
Currently doing a "squash" basically negates the cache for any subsequent layers.
But we can work around this by A) checking if the cache was successful for the _unsquashed_
version of the image, and B) if so, re-using an older squashed version of the image.
Three ways to do this:
1. get the shas of the before/after images from `image.history` comments
OR the output stream (or both). Both are extremely brittle, but also easy to access
2. Build the image without squash first. If the unsquashed image sha matches
a cached one, substitute the unsuqashed image for the squashed one.
If no match, re-run the steps with squash=True and store the resulting pair
Less brittle than 1., but harder and defs not elegant
3. Use docker-squash as a dependency - this is by far the most preferable solution,
except that they don't yet support the newest docker sdk version.
Currently option 1 is implemented - we parse the comment string in the image history
to figure out which layers the image was squashed from
"""
from .staging import BUILD_CACHEDIR
history = client.api.history(self.buildname)
comment = history[0].get('Comment', '').split()
if len(comment) != 4 or comment[0] != 'merge' or comment[2] != 'to':
print('WARNING: failed to parse this image\'s pre-squash history. '
'The build will continue, but all subsequent layers will be rebuilt.')
return
squashed_sha = history[0]['Id']
start_squash_sha = comment[1]
end_squash_sha = comment[3]
cprint(' Layers %s to %s were squashed.' % (start_squash_sha, end_squash_sha), 'yellow')
# check cache
squashcache = os.path.join(BUILD_CACHEDIR, 'squashes')
if not os.path.exists(squashcache):
os.makedirs(squashcache)
cachepath = os.path.join(BUILD_CACHEDIR,
'squashes', '%s-%s' % (start_squash_sha, end_squash_sha))
# on hit, tag the squashedsha as the result of this build step
if os.path.exists(cachepath):
self._get_squashed_layer_cache(client, squashed_sha, cachepath)
else:
self._cache_squashed_layer(squashed_sha, cachepath) | python | def _resolve_squash_cache(self, client):
"""
Currently doing a "squash" basically negates the cache for any subsequent layers.
But we can work around this by A) checking if the cache was successful for the _unsquashed_
version of the image, and B) if so, re-using an older squashed version of the image.
Three ways to do this:
1. get the shas of the before/after images from `image.history` comments
OR the output stream (or both). Both are extremely brittle, but also easy to access
2. Build the image without squash first. If the unsquashed image sha matches
a cached one, substitute the unsuqashed image for the squashed one.
If no match, re-run the steps with squash=True and store the resulting pair
Less brittle than 1., but harder and defs not elegant
3. Use docker-squash as a dependency - this is by far the most preferable solution,
except that they don't yet support the newest docker sdk version.
Currently option 1 is implemented - we parse the comment string in the image history
to figure out which layers the image was squashed from
"""
from .staging import BUILD_CACHEDIR
history = client.api.history(self.buildname)
comment = history[0].get('Comment', '').split()
if len(comment) != 4 or comment[0] != 'merge' or comment[2] != 'to':
print('WARNING: failed to parse this image\'s pre-squash history. '
'The build will continue, but all subsequent layers will be rebuilt.')
return
squashed_sha = history[0]['Id']
start_squash_sha = comment[1]
end_squash_sha = comment[3]
cprint(' Layers %s to %s were squashed.' % (start_squash_sha, end_squash_sha), 'yellow')
# check cache
squashcache = os.path.join(BUILD_CACHEDIR, 'squashes')
if not os.path.exists(squashcache):
os.makedirs(squashcache)
cachepath = os.path.join(BUILD_CACHEDIR,
'squashes', '%s-%s' % (start_squash_sha, end_squash_sha))
# on hit, tag the squashedsha as the result of this build step
if os.path.exists(cachepath):
self._get_squashed_layer_cache(client, squashed_sha, cachepath)
else:
self._cache_squashed_layer(squashed_sha, cachepath) | [
"def",
"_resolve_squash_cache",
"(",
"self",
",",
"client",
")",
":",
"from",
".",
"staging",
"import",
"BUILD_CACHEDIR",
"history",
"=",
"client",
".",
"api",
".",
"history",
"(",
"self",
".",
"buildname",
")",
"comment",
"=",
"history",
"[",
"0",
"]",
... | Currently doing a "squash" basically negates the cache for any subsequent layers.
But we can work around this by A) checking if the cache was successful for the _unsquashed_
version of the image, and B) if so, re-using an older squashed version of the image.
Three ways to do this:
1. get the shas of the before/after images from `image.history` comments
OR the output stream (or both). Both are extremely brittle, but also easy to access
2. Build the image without squash first. If the unsquashed image sha matches
a cached one, substitute the unsuqashed image for the squashed one.
If no match, re-run the steps with squash=True and store the resulting pair
Less brittle than 1., but harder and defs not elegant
3. Use docker-squash as a dependency - this is by far the most preferable solution,
except that they don't yet support the newest docker sdk version.
Currently option 1 is implemented - we parse the comment string in the image history
to figure out which layers the image was squashed from | [
"Currently",
"doing",
"a",
"squash",
"basically",
"negates",
"the",
"cache",
"for",
"any",
"subsequent",
"layers",
".",
"But",
"we",
"can",
"work",
"around",
"this",
"by",
"A",
")",
"checking",
"if",
"the",
"cache",
"was",
"successful",
"for",
"the",
"_uns... | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/step.py#L183-L227 | train | 23,922 |
avirshup/DockerMake | dockermake/step.py | FileCopyStep.dockerfile_lines | def dockerfile_lines(self):
"""
Used only when printing dockerfiles, not for building
"""
w1 = colored(
'WARNING: this build includes files that are built in other images!!! The generated'
'\n Dockerfile must be built in a directory that contains'
' the file/directory:',
'red', attrs=['bold'])
w2 = colored(' ' + self.sourcepath, 'red')
w3 = (colored(' from image ', 'red')
+ colored(self.sourcepath, 'blue', attrs=['bold']))
print('\n'.join((w1, w2, w3)))
return ["",
"# Warning: the file \"%s\" from the image \"%s\""
" must be present in this build context!!" %
(self.sourcepath, self.sourceimage),
"ADD %s %s" % (os.path.basename(self.sourcepath), self.destpath),
''] | python | def dockerfile_lines(self):
"""
Used only when printing dockerfiles, not for building
"""
w1 = colored(
'WARNING: this build includes files that are built in other images!!! The generated'
'\n Dockerfile must be built in a directory that contains'
' the file/directory:',
'red', attrs=['bold'])
w2 = colored(' ' + self.sourcepath, 'red')
w3 = (colored(' from image ', 'red')
+ colored(self.sourcepath, 'blue', attrs=['bold']))
print('\n'.join((w1, w2, w3)))
return ["",
"# Warning: the file \"%s\" from the image \"%s\""
" must be present in this build context!!" %
(self.sourcepath, self.sourceimage),
"ADD %s %s" % (os.path.basename(self.sourcepath), self.destpath),
''] | [
"def",
"dockerfile_lines",
"(",
"self",
")",
":",
"w1",
"=",
"colored",
"(",
"'WARNING: this build includes files that are built in other images!!! The generated'",
"'\\n Dockerfile must be built in a directory that contains'",
"' the file/directory:'",
",",
"'red'",
",",
"at... | Used only when printing dockerfiles, not for building | [
"Used",
"only",
"when",
"printing",
"dockerfiles",
"not",
"for",
"building"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/step.py#L335-L353 | train | 23,923 |
avirshup/DockerMake | dockermake/imagedefs.py | ImageDefs._check_yaml_and_paths | def _check_yaml_and_paths(ymlfilepath, yamldefs):
""" Checks YAML for errors and resolves all paths
"""
relpath = os.path.relpath(ymlfilepath)
if '/' not in relpath:
relpath = './%s' % relpath
pathroot = os.path.abspath(os.path.dirname(ymlfilepath))
for imagename, defn in iteritems(yamldefs):
if imagename == '_SOURCES_':
yamldefs['_SOURCES_'] = [os.path.relpath(_get_abspath(pathroot, p))
for p in yamldefs['_SOURCES_']]
continue
elif imagename in SPECIAL_FIELDS:
continue
for key in ('build_directory', 'FROM_DOCKERFILE', 'ignorefile'):
if key in defn:
defn[key] = _get_abspath(pathroot, defn[key])
if 'copy_from' in defn:
if not isinstance(defn['copy_from'], dict):
raise errors.ParsingFailure((
'Syntax error in file "%s": \n' +
'The "copy_from" field in image definition "%s" is not \n'
'a key:value list.') % (ymlfilepath, imagename))
for otherimg, value in defn.get('copy_from', {}).items():
if not isinstance(value, dict):
raise errors.ParsingFailure((
'Syntax error in field:\n'
' %s . copy_from . %s\nin file "%s". \n'
'All entries must be of the form "sourcepath: destpath"')%
(imagename, otherimg, ymlfilepath))
# save the file path for logging
defn['_sourcefile'] = relpath
if 'ignore' in defn and 'ignorefile' in defn:
raise errors.MultipleIgnoreError(
'Image "%s" has both "ignore" AND "ignorefile" fields.' % imagename +
' At most ONE of these should be defined')
if 'secret_files' in defn and not defn.get('squash', True):
raise errors.ParsingFailure(
"Step '%s' defines secret_files, so 'squash' cannot be set to 'false'"
% imagename)
if defn.get('secret_files', None) and defn.get('copy_from', False):
raise errors.ParsingFailure(
'`secret_files` currently is not implmemented to handle `copy_from`'
' (step %s)' % imagename)
for key in defn:
if key not in RECOGNIZED_KEYS:
raise errors.UnrecognizedKeyError(
'Field "%s" in image "%s" in file "%s" not recognized' %
(key, imagename, relpath)) | python | def _check_yaml_and_paths(ymlfilepath, yamldefs):
""" Checks YAML for errors and resolves all paths
"""
relpath = os.path.relpath(ymlfilepath)
if '/' not in relpath:
relpath = './%s' % relpath
pathroot = os.path.abspath(os.path.dirname(ymlfilepath))
for imagename, defn in iteritems(yamldefs):
if imagename == '_SOURCES_':
yamldefs['_SOURCES_'] = [os.path.relpath(_get_abspath(pathroot, p))
for p in yamldefs['_SOURCES_']]
continue
elif imagename in SPECIAL_FIELDS:
continue
for key in ('build_directory', 'FROM_DOCKERFILE', 'ignorefile'):
if key in defn:
defn[key] = _get_abspath(pathroot, defn[key])
if 'copy_from' in defn:
if not isinstance(defn['copy_from'], dict):
raise errors.ParsingFailure((
'Syntax error in file "%s": \n' +
'The "copy_from" field in image definition "%s" is not \n'
'a key:value list.') % (ymlfilepath, imagename))
for otherimg, value in defn.get('copy_from', {}).items():
if not isinstance(value, dict):
raise errors.ParsingFailure((
'Syntax error in field:\n'
' %s . copy_from . %s\nin file "%s". \n'
'All entries must be of the form "sourcepath: destpath"')%
(imagename, otherimg, ymlfilepath))
# save the file path for logging
defn['_sourcefile'] = relpath
if 'ignore' in defn and 'ignorefile' in defn:
raise errors.MultipleIgnoreError(
'Image "%s" has both "ignore" AND "ignorefile" fields.' % imagename +
' At most ONE of these should be defined')
if 'secret_files' in defn and not defn.get('squash', True):
raise errors.ParsingFailure(
"Step '%s' defines secret_files, so 'squash' cannot be set to 'false'"
% imagename)
if defn.get('secret_files', None) and defn.get('copy_from', False):
raise errors.ParsingFailure(
'`secret_files` currently is not implmemented to handle `copy_from`'
' (step %s)' % imagename)
for key in defn:
if key not in RECOGNIZED_KEYS:
raise errors.UnrecognizedKeyError(
'Field "%s" in image "%s" in file "%s" not recognized' %
(key, imagename, relpath)) | [
"def",
"_check_yaml_and_paths",
"(",
"ymlfilepath",
",",
"yamldefs",
")",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"ymlfilepath",
")",
"if",
"'/'",
"not",
"in",
"relpath",
":",
"relpath",
"=",
"'./%s'",
"%",
"relpath",
"pathroot",
"=",
... | Checks YAML for errors and resolves all paths | [
"Checks",
"YAML",
"for",
"errors",
"and",
"resolves",
"all",
"paths"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/imagedefs.py#L82-L138 | train | 23,924 |
avirshup/DockerMake | dockermake/imagedefs.py | ImageDefs.generate_build | def generate_build(self, image, targetname, rebuilds=None, cache_repo='', cache_tag='',
buildargs=None, **kwargs):
"""
Separate the build into a series of one or more intermediate steps.
Each specified build directory gets its own step
Args:
image (str): name of the image as defined in the dockermake.py file
targetname (str): name to tag the final built image with
rebuilds (List[str]): list of image layers to rebuild (i.e., without docker's cache)
cache_repo (str): repository to get images for caches in builds
cache_tag (str): tags to use from repository for caches in builds
buildargs (dict): build-time dockerfile arugments
**kwargs (dict): extra keyword arguments for the BuildTarget object
"""
from_image = self.get_external_base_image(image)
if cache_repo or cache_tag:
cache_from = utils.generate_name(image, cache_repo, cache_tag)
else:
cache_from = None
if from_image is None:
raise errors.NoBaseError("No base image found in %s's dependencies" % image)
if isinstance(from_image, ExternalDockerfile):
build_first = from_image
base_image = from_image.tag
else:
base_image = from_image
build_first = None
build_steps = []
istep = 0
sourceimages = set()
if rebuilds is None:
rebuilds = []
else:
rebuilds = set(rebuilds)
for base_name in self.sort_dependencies(image):
istep += 1
buildname = 'dmkbuild_%s_%d' % (image, istep)
secret_files = self.ymldefs[base_name].get('secret_files', None)
squash = self.ymldefs[base_name].get('squash', bool(secret_files))
build_steps.append(
dockermake.step.BuildStep(
base_name,
base_image,
self.ymldefs[base_name],
buildname,
bust_cache=base_name in rebuilds,
build_first=build_first, cache_from=cache_from,
buildargs=buildargs,
squash=squash,
secret_files=secret_files))
base_image = buildname
build_first = None
for sourceimage, files in iteritems(self.ymldefs[base_name].get('copy_from', {})):
sourceimages.add(sourceimage)
for sourcepath, destpath in iteritems(files):
istep += 1
buildname = 'dmkbuild_%s_%d' % (image, istep)
build_steps.append(
dockermake.step.FileCopyStep(
sourceimage, sourcepath, destpath,
base_name, base_image, self.ymldefs[base_name],
buildname, bust_cache=base_name in rebuilds,
build_first=build_first, cache_from=cache_from))
base_image = buildname
sourcebuilds = [self.generate_build(img,
img,
cache_repo=cache_repo,
cache_tag=cache_tag,
**kwargs)
for img in sourceimages]
return builds.BuildTarget(imagename=image,
targetname=targetname,
steps=build_steps,
sourcebuilds=sourcebuilds,
from_image=from_image,
**kwargs) | python | def generate_build(self, image, targetname, rebuilds=None, cache_repo='', cache_tag='',
buildargs=None, **kwargs):
"""
Separate the build into a series of one or more intermediate steps.
Each specified build directory gets its own step
Args:
image (str): name of the image as defined in the dockermake.py file
targetname (str): name to tag the final built image with
rebuilds (List[str]): list of image layers to rebuild (i.e., without docker's cache)
cache_repo (str): repository to get images for caches in builds
cache_tag (str): tags to use from repository for caches in builds
buildargs (dict): build-time dockerfile arugments
**kwargs (dict): extra keyword arguments for the BuildTarget object
"""
from_image = self.get_external_base_image(image)
if cache_repo or cache_tag:
cache_from = utils.generate_name(image, cache_repo, cache_tag)
else:
cache_from = None
if from_image is None:
raise errors.NoBaseError("No base image found in %s's dependencies" % image)
if isinstance(from_image, ExternalDockerfile):
build_first = from_image
base_image = from_image.tag
else:
base_image = from_image
build_first = None
build_steps = []
istep = 0
sourceimages = set()
if rebuilds is None:
rebuilds = []
else:
rebuilds = set(rebuilds)
for base_name in self.sort_dependencies(image):
istep += 1
buildname = 'dmkbuild_%s_%d' % (image, istep)
secret_files = self.ymldefs[base_name].get('secret_files', None)
squash = self.ymldefs[base_name].get('squash', bool(secret_files))
build_steps.append(
dockermake.step.BuildStep(
base_name,
base_image,
self.ymldefs[base_name],
buildname,
bust_cache=base_name in rebuilds,
build_first=build_first, cache_from=cache_from,
buildargs=buildargs,
squash=squash,
secret_files=secret_files))
base_image = buildname
build_first = None
for sourceimage, files in iteritems(self.ymldefs[base_name].get('copy_from', {})):
sourceimages.add(sourceimage)
for sourcepath, destpath in iteritems(files):
istep += 1
buildname = 'dmkbuild_%s_%d' % (image, istep)
build_steps.append(
dockermake.step.FileCopyStep(
sourceimage, sourcepath, destpath,
base_name, base_image, self.ymldefs[base_name],
buildname, bust_cache=base_name in rebuilds,
build_first=build_first, cache_from=cache_from))
base_image = buildname
sourcebuilds = [self.generate_build(img,
img,
cache_repo=cache_repo,
cache_tag=cache_tag,
**kwargs)
for img in sourceimages]
return builds.BuildTarget(imagename=image,
targetname=targetname,
steps=build_steps,
sourcebuilds=sourcebuilds,
from_image=from_image,
**kwargs) | [
"def",
"generate_build",
"(",
"self",
",",
"image",
",",
"targetname",
",",
"rebuilds",
"=",
"None",
",",
"cache_repo",
"=",
"''",
",",
"cache_tag",
"=",
"''",
",",
"buildargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from_image",
"=",
"self",... | Separate the build into a series of one or more intermediate steps.
Each specified build directory gets its own step
Args:
image (str): name of the image as defined in the dockermake.py file
targetname (str): name to tag the final built image with
rebuilds (List[str]): list of image layers to rebuild (i.e., without docker's cache)
cache_repo (str): repository to get images for caches in builds
cache_tag (str): tags to use from repository for caches in builds
buildargs (dict): build-time dockerfile arugments
**kwargs (dict): extra keyword arguments for the BuildTarget object | [
"Separate",
"the",
"build",
"into",
"a",
"series",
"of",
"one",
"or",
"more",
"intermediate",
"steps",
".",
"Each",
"specified",
"build",
"directory",
"gets",
"its",
"own",
"step"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/imagedefs.py#L140-L221 | train | 23,925 |
avirshup/DockerMake | dockermake/imagedefs.py | ImageDefs.sort_dependencies | def sort_dependencies(self, image, dependencies=None):
"""
Topologically sort the docker commands by their requirements
Note:
Circular "requires" dependencies are assumed to have already been checked in
get_external_base_image, they are not checked here
Args:
image (str): process this docker image's dependencies
dependencies (OrderedDict): running cache of sorted dependencies (ordered dict)
Returns:
List[str]: list of dependencies a topologically-sorted build order
"""
if dependencies is None:
dependencies = OrderedDict() # using this as an ordered set - not storing any values
if image in dependencies:
return
requires = self.ymldefs[image].get('requires', [])
for dep in requires:
self.sort_dependencies(dep, dependencies)
dependencies[image] = None
return dependencies.keys() | python | def sort_dependencies(self, image, dependencies=None):
"""
Topologically sort the docker commands by their requirements
Note:
Circular "requires" dependencies are assumed to have already been checked in
get_external_base_image, they are not checked here
Args:
image (str): process this docker image's dependencies
dependencies (OrderedDict): running cache of sorted dependencies (ordered dict)
Returns:
List[str]: list of dependencies a topologically-sorted build order
"""
if dependencies is None:
dependencies = OrderedDict() # using this as an ordered set - not storing any values
if image in dependencies:
return
requires = self.ymldefs[image].get('requires', [])
for dep in requires:
self.sort_dependencies(dep, dependencies)
dependencies[image] = None
return dependencies.keys() | [
"def",
"sort_dependencies",
"(",
"self",
",",
"image",
",",
"dependencies",
"=",
"None",
")",
":",
"if",
"dependencies",
"is",
"None",
":",
"dependencies",
"=",
"OrderedDict",
"(",
")",
"# using this as an ordered set - not storing any values",
"if",
"image",
"in",
... | Topologically sort the docker commands by their requirements
Note:
Circular "requires" dependencies are assumed to have already been checked in
get_external_base_image, they are not checked here
Args:
image (str): process this docker image's dependencies
dependencies (OrderedDict): running cache of sorted dependencies (ordered dict)
Returns:
List[str]: list of dependencies a topologically-sorted build order | [
"Topologically",
"sort",
"the",
"docker",
"commands",
"by",
"their",
"requirements"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/imagedefs.py#L223-L250 | train | 23,926 |
avirshup/DockerMake | dockermake/imagedefs.py | ImageDefs.get_external_base_image | def get_external_base_image(self, image, stack=None):
""" Makes sure that this image has exactly one unique external base image
"""
if stack is None:
stack = list()
mydef = self.ymldefs[image]
if image in stack:
stack.append(image)
raise errors.CircularDependencyError('Circular dependency found:\n' + '->'.join(stack))
stack.append(image)
# Deal with FROM and FROM_DOCKERFILE fields
if 'FROM' in mydef and 'FROM_DOCKERFILE' in mydef:
raise errors.MultipleBaseError(
'ERROR: Image "%s" has both a "FROM" and a "FROM_DOCKERFILE" field.' % image +
' It should have at most ONE of these fields.')
if 'FROM' in mydef:
externalbase = mydef['FROM']
elif 'FROM_DOCKERFILE' in mydef:
path = mydef['FROM_DOCKERFILE']
if path not in self._external_dockerfiles:
self._external_dockerfiles[path] = ExternalDockerfile(path)
externalbase = self._external_dockerfiles[path]
else:
externalbase = None
requires = mydef.get('requires', [])
if not isinstance(requires, list):
raise errors.InvalidRequiresList('Requirements for image "%s" are not a list' % image)
for base in requires:
try:
otherexternal = self.get_external_base_image(base, stack)
except ValueError:
continue
if externalbase is None:
externalbase = otherexternal
elif otherexternal is None:
continue
elif externalbase != otherexternal:
raise errors.ConflictingBaseError(
'Multiple external dependencies: definition "%s" depends on:\n' % image +
' %s (FROM: %s), and\n' % (image, externalbase) +
' %s (FROM: %s).' % (base, otherexternal))
assert stack.pop() == image
return externalbase | python | def get_external_base_image(self, image, stack=None):
""" Makes sure that this image has exactly one unique external base image
"""
if stack is None:
stack = list()
mydef = self.ymldefs[image]
if image in stack:
stack.append(image)
raise errors.CircularDependencyError('Circular dependency found:\n' + '->'.join(stack))
stack.append(image)
# Deal with FROM and FROM_DOCKERFILE fields
if 'FROM' in mydef and 'FROM_DOCKERFILE' in mydef:
raise errors.MultipleBaseError(
'ERROR: Image "%s" has both a "FROM" and a "FROM_DOCKERFILE" field.' % image +
' It should have at most ONE of these fields.')
if 'FROM' in mydef:
externalbase = mydef['FROM']
elif 'FROM_DOCKERFILE' in mydef:
path = mydef['FROM_DOCKERFILE']
if path not in self._external_dockerfiles:
self._external_dockerfiles[path] = ExternalDockerfile(path)
externalbase = self._external_dockerfiles[path]
else:
externalbase = None
requires = mydef.get('requires', [])
if not isinstance(requires, list):
raise errors.InvalidRequiresList('Requirements for image "%s" are not a list' % image)
for base in requires:
try:
otherexternal = self.get_external_base_image(base, stack)
except ValueError:
continue
if externalbase is None:
externalbase = otherexternal
elif otherexternal is None:
continue
elif externalbase != otherexternal:
raise errors.ConflictingBaseError(
'Multiple external dependencies: definition "%s" depends on:\n' % image +
' %s (FROM: %s), and\n' % (image, externalbase) +
' %s (FROM: %s).' % (base, otherexternal))
assert stack.pop() == image
return externalbase | [
"def",
"get_external_base_image",
"(",
"self",
",",
"image",
",",
"stack",
"=",
"None",
")",
":",
"if",
"stack",
"is",
"None",
":",
"stack",
"=",
"list",
"(",
")",
"mydef",
"=",
"self",
".",
"ymldefs",
"[",
"image",
"]",
"if",
"image",
"in",
"stack",... | Makes sure that this image has exactly one unique external base image | [
"Makes",
"sure",
"that",
"this",
"image",
"has",
"exactly",
"one",
"unique",
"external",
"base",
"image"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/imagedefs.py#L252-L301 | train | 23,927 |
avirshup/DockerMake | dockermake/staging.py | StagedFile.stage | def stage(self, startimage, newimage):
""" Copies the file from source to target
Args:
startimage (str): name of the image to stage these files into
newimage (str): name of the created image
"""
client = utils.get_client()
cprint(' Copying file from "%s:/%s" \n to "%s://%s/"'
% (self.sourceimage, self.sourcepath, startimage, self.destpath),
'blue')
# copy build artifacts from the container if necessary
cachedir = self._setcache(client)
cacherelpath = os.path.relpath(cachedir, TMPDIR)
# if cached file doesn't exist (presumably purged by OS), trigger it to be recreated
if os.path.exists(cachedir) and not os.path.exists(os.path.join(cachedir, 'content.tar')):
shutil.rmtree(cachedir)
if not os.path.exists(cachedir):
print(' * Creating cache at %s' % cacherelpath)
container = client.containers.create(self.sourceimage)
try:
tarfile_stream, tarfile_stats = container.get_archive(self.sourcepath)
except docker.errors.NotFound:
raise errors.MissingFileError(
'Cannot copy file "%s" from image "%s" - it does not exist!' %
(self.sourcepath, self.sourceimage))
# write files to disk (would be nice to stream them, haven't gotten it to work)
tempdir = tempfile.mkdtemp(dir=BUILD_TEMPDIR)
with open(os.path.join(tempdir, 'content.tar'), 'wb') as localfile:
for chunk in tarfile_stream:
localfile.write(chunk)
os.mkdir(cachedir)
os.rename(tempdir, cachedir)
else:
print(' Using cached files from %s' % cacherelpath)
# write Dockerfile for the new image and then build it
dockerfile = 'FROM %s\nADD content.tar %s' % (startimage, self.destpath)
with open(os.path.join(cachedir, 'Dockerfile'), 'w') as df:
df.write(dockerfile)
buildargs = dict(path=cachedir,
tag=newimage,
decode=True)
utils.set_build_cachefrom(self.cache_from, buildargs, client)
# Build and show logs
stream = client.api.build(**buildargs)
try:
utils.stream_docker_logs(stream, newimage)
except ValueError as e:
raise errors.BuildError(dockerfile, e.args[0], build_args=buildargs) | python | def stage(self, startimage, newimage):
""" Copies the file from source to target
Args:
startimage (str): name of the image to stage these files into
newimage (str): name of the created image
"""
client = utils.get_client()
cprint(' Copying file from "%s:/%s" \n to "%s://%s/"'
% (self.sourceimage, self.sourcepath, startimage, self.destpath),
'blue')
# copy build artifacts from the container if necessary
cachedir = self._setcache(client)
cacherelpath = os.path.relpath(cachedir, TMPDIR)
# if cached file doesn't exist (presumably purged by OS), trigger it to be recreated
if os.path.exists(cachedir) and not os.path.exists(os.path.join(cachedir, 'content.tar')):
shutil.rmtree(cachedir)
if not os.path.exists(cachedir):
print(' * Creating cache at %s' % cacherelpath)
container = client.containers.create(self.sourceimage)
try:
tarfile_stream, tarfile_stats = container.get_archive(self.sourcepath)
except docker.errors.NotFound:
raise errors.MissingFileError(
'Cannot copy file "%s" from image "%s" - it does not exist!' %
(self.sourcepath, self.sourceimage))
# write files to disk (would be nice to stream them, haven't gotten it to work)
tempdir = tempfile.mkdtemp(dir=BUILD_TEMPDIR)
with open(os.path.join(tempdir, 'content.tar'), 'wb') as localfile:
for chunk in tarfile_stream:
localfile.write(chunk)
os.mkdir(cachedir)
os.rename(tempdir, cachedir)
else:
print(' Using cached files from %s' % cacherelpath)
# write Dockerfile for the new image and then build it
dockerfile = 'FROM %s\nADD content.tar %s' % (startimage, self.destpath)
with open(os.path.join(cachedir, 'Dockerfile'), 'w') as df:
df.write(dockerfile)
buildargs = dict(path=cachedir,
tag=newimage,
decode=True)
utils.set_build_cachefrom(self.cache_from, buildargs, client)
# Build and show logs
stream = client.api.build(**buildargs)
try:
utils.stream_docker_logs(stream, newimage)
except ValueError as e:
raise errors.BuildError(dockerfile, e.args[0], build_args=buildargs) | [
"def",
"stage",
"(",
"self",
",",
"startimage",
",",
"newimage",
")",
":",
"client",
"=",
"utils",
".",
"get_client",
"(",
")",
"cprint",
"(",
"' Copying file from \"%s:/%s\" \\n to \"%s://%s/\"'",
"%",
"(",
"self",
".",
"sourceimage",
",",
"self"... | Copies the file from source to target
Args:
startimage (str): name of the image to stage these files into
newimage (str): name of the created image | [
"Copies",
"the",
"file",
"from",
"source",
"to",
"target"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/staging.py#L60-L115 | train | 23,928 |
avirshup/DockerMake | dockermake/__main__.py | _runargs | def _runargs(argstring):
""" Entrypoint for debugging
"""
import shlex
parser = cli.make_arg_parser()
args = parser.parse_args(shlex.split(argstring))
run(args) | python | def _runargs(argstring):
""" Entrypoint for debugging
"""
import shlex
parser = cli.make_arg_parser()
args = parser.parse_args(shlex.split(argstring))
run(args) | [
"def",
"_runargs",
"(",
"argstring",
")",
":",
"import",
"shlex",
"parser",
"=",
"cli",
".",
"make_arg_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"shlex",
".",
"split",
"(",
"argstring",
")",
")",
"run",
"(",
"args",
")"
] | Entrypoint for debugging | [
"Entrypoint",
"for",
"debugging"
] | 2173199904f086353ef539ea578788b99f6fea0a | https://github.com/avirshup/DockerMake/blob/2173199904f086353ef539ea578788b99f6fea0a/dockermake/__main__.py#L44-L50 | train | 23,929 |
Cue/scales | src/greplin/scales/util.py | lookup | def lookup(source, keys, fallback = None):
"""Traverses the source, looking up each key. Returns None if can't find anything instead of raising an exception."""
try:
for key in keys:
source = source[key]
return source
except (KeyError, AttributeError, TypeError):
return fallback | python | def lookup(source, keys, fallback = None):
"""Traverses the source, looking up each key. Returns None if can't find anything instead of raising an exception."""
try:
for key in keys:
source = source[key]
return source
except (KeyError, AttributeError, TypeError):
return fallback | [
"def",
"lookup",
"(",
"source",
",",
"keys",
",",
"fallback",
"=",
"None",
")",
":",
"try",
":",
"for",
"key",
"in",
"keys",
":",
"source",
"=",
"source",
"[",
"key",
"]",
"return",
"source",
"except",
"(",
"KeyError",
",",
"AttributeError",
",",
"Ty... | Traverses the source, looking up each key. Returns None if can't find anything instead of raising an exception. | [
"Traverses",
"the",
"source",
"looking",
"up",
"each",
"key",
".",
"Returns",
"None",
"if",
"can",
"t",
"find",
"anything",
"instead",
"of",
"raising",
"an",
"exception",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L30-L37 | train | 23,930 |
Cue/scales | src/greplin/scales/util.py | GraphiteReporter.run | def run(self):
"""Run the thread."""
while True:
try:
try:
name, value, valueType, stamp = self.queue.get()
except TypeError:
break
self.log(name, value, valueType, stamp)
finally:
self.queue.task_done() | python | def run(self):
"""Run the thread."""
while True:
try:
try:
name, value, valueType, stamp = self.queue.get()
except TypeError:
break
self.log(name, value, valueType, stamp)
finally:
self.queue.task_done() | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"try",
":",
"name",
",",
"value",
",",
"valueType",
",",
"stamp",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"except",
"TypeError",
":",
"break",
"self",
".",
"log",
"("... | Run the thread. | [
"Run",
"the",
"thread",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L55-L65 | train | 23,931 |
Cue/scales | src/greplin/scales/util.py | GraphiteReporter.connect | def connect(self):
"""Connects to the Graphite server if not already connected."""
if self.sock is not None:
return
backoff = 0.01
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect((self.host, self.port))
self.sock = sock
return
except socket.error:
time.sleep(random.uniform(0, 2.0*backoff))
backoff = min(backoff*2.0, 5.0) | python | def connect(self):
"""Connects to the Graphite server if not already connected."""
if self.sock is not None:
return
backoff = 0.01
while True:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect((self.host, self.port))
self.sock = sock
return
except socket.error:
time.sleep(random.uniform(0, 2.0*backoff))
backoff = min(backoff*2.0, 5.0) | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"sock",
"is",
"not",
"None",
":",
"return",
"backoff",
"=",
"0.01",
"while",
"True",
":",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".... | Connects to the Graphite server if not already connected. | [
"Connects",
"to",
"the",
"Graphite",
"server",
"if",
"not",
"already",
"connected",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L68-L82 | train | 23,932 |
Cue/scales | src/greplin/scales/util.py | GraphiteReporter.disconnect | def disconnect(self):
"""Disconnect from the Graphite server if connected."""
if self.sock is not None:
try:
self.sock.close()
except socket.error:
pass
finally:
self.sock = None | python | def disconnect(self):
"""Disconnect from the Graphite server if connected."""
if self.sock is not None:
try:
self.sock.close()
except socket.error:
pass
finally:
self.sock = None | [
"def",
"disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"sock",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"sock",
".",
"close",
"(",
")",
"except",
"socket",
".",
"error",
":",
"pass",
"finally",
":",
"self",
".",
"sock",
"=",
"No... | Disconnect from the Graphite server if connected. | [
"Disconnect",
"from",
"the",
"Graphite",
"server",
"if",
"connected",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L85-L93 | train | 23,933 |
Cue/scales | src/greplin/scales/util.py | GraphiteReporter._sendMsg | def _sendMsg(self, msg):
"""Send a line to graphite. Retry with exponential backoff."""
if not self.sock:
self.connect()
if not isinstance(msg, binary_type):
msg = msg.encode("UTF-8")
backoff = 0.001
while True:
try:
self.sock.sendall(msg)
break
except socket.error:
log.warning('Graphite connection error', exc_info = True)
self.disconnect()
time.sleep(random.uniform(0, 2.0*backoff))
backoff = min(backoff*2.0, 5.0)
self.connect() | python | def _sendMsg(self, msg):
"""Send a line to graphite. Retry with exponential backoff."""
if not self.sock:
self.connect()
if not isinstance(msg, binary_type):
msg = msg.encode("UTF-8")
backoff = 0.001
while True:
try:
self.sock.sendall(msg)
break
except socket.error:
log.warning('Graphite connection error', exc_info = True)
self.disconnect()
time.sleep(random.uniform(0, 2.0*backoff))
backoff = min(backoff*2.0, 5.0)
self.connect() | [
"def",
"_sendMsg",
"(",
"self",
",",
"msg",
")",
":",
"if",
"not",
"self",
".",
"sock",
":",
"self",
".",
"connect",
"(",
")",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"binary_type",
")",
":",
"msg",
"=",
"msg",
".",
"encode",
"(",
"\"UTF-8\"",
... | Send a line to graphite. Retry with exponential backoff. | [
"Send",
"a",
"line",
"to",
"graphite",
".",
"Retry",
"with",
"exponential",
"backoff",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L96-L113 | train | 23,934 |
Cue/scales | src/greplin/scales/util.py | GraphiteReporter.log | def log(self, name, value, valueType=None, stamp=None):
"""Log a named numeric value. The value type may be 'value',
'count', or None."""
if type(value) == float:
form = "%s%s %2.2f %d\n"
else:
form = "%s%s %s %d\n"
if valueType is not None and len(valueType) > 0 and valueType[0] != '.':
valueType = '.' + valueType
if not stamp:
stamp = time.time()
self._sendMsg(form % (self._sanitizeName(name), valueType or '', value, stamp)) | python | def log(self, name, value, valueType=None, stamp=None):
"""Log a named numeric value. The value type may be 'value',
'count', or None."""
if type(value) == float:
form = "%s%s %2.2f %d\n"
else:
form = "%s%s %s %d\n"
if valueType is not None and len(valueType) > 0 and valueType[0] != '.':
valueType = '.' + valueType
if not stamp:
stamp = time.time()
self._sendMsg(form % (self._sanitizeName(name), valueType or '', value, stamp)) | [
"def",
"log",
"(",
"self",
",",
"name",
",",
"value",
",",
"valueType",
"=",
"None",
",",
"stamp",
"=",
"None",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"float",
":",
"form",
"=",
"\"%s%s %2.2f %d\\n\"",
"else",
":",
"form",
"=",
"\"%s%s %s %... | Log a named numeric value. The value type may be 'value',
'count', or None. | [
"Log",
"a",
"named",
"numeric",
"value",
".",
"The",
"value",
"type",
"may",
"be",
"value",
"count",
"or",
"None",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L121-L135 | train | 23,935 |
Cue/scales | src/greplin/scales/util.py | GraphiteReporter.enqueue | def enqueue(self, name, value, valueType=None, stamp=None):
"""Enqueue a call to log."""
# If queue is too large, refuse to log.
if self.maxQueueSize and self.queue.qsize() > self.maxQueueSize:
return
# Stick arguments into the queue
self.queue.put((name, value, valueType, stamp)) | python | def enqueue(self, name, value, valueType=None, stamp=None):
"""Enqueue a call to log."""
# If queue is too large, refuse to log.
if self.maxQueueSize and self.queue.qsize() > self.maxQueueSize:
return
# Stick arguments into the queue
self.queue.put((name, value, valueType, stamp)) | [
"def",
"enqueue",
"(",
"self",
",",
"name",
",",
"value",
",",
"valueType",
"=",
"None",
",",
"stamp",
"=",
"None",
")",
":",
"# If queue is too large, refuse to log.",
"if",
"self",
".",
"maxQueueSize",
"and",
"self",
".",
"queue",
".",
"qsize",
"(",
")",... | Enqueue a call to log. | [
"Enqueue",
"a",
"call",
"to",
"log",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L138-L144 | train | 23,936 |
Cue/scales | src/greplin/scales/util.py | AtomicValue.update | def update(self, function):
"""Atomically apply function to the value, and return the old and new values."""
with self.lock:
oldValue = self.value
self.value = function(oldValue)
return oldValue, self.value | python | def update(self, function):
"""Atomically apply function to the value, and return the old and new values."""
with self.lock:
oldValue = self.value
self.value = function(oldValue)
return oldValue, self.value | [
"def",
"update",
"(",
"self",
",",
"function",
")",
":",
"with",
"self",
".",
"lock",
":",
"oldValue",
"=",
"self",
".",
"value",
"self",
".",
"value",
"=",
"function",
"(",
"oldValue",
")",
"return",
"oldValue",
",",
"self",
".",
"value"
] | Atomically apply function to the value, and return the old and new values. | [
"Atomically",
"apply",
"function",
"to",
"the",
"value",
"and",
"return",
"the",
"old",
"and",
"new",
"values",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L167-L172 | train | 23,937 |
Cue/scales | src/greplin/scales/util.py | EWMA.tick | def tick(self):
"""Updates rates and decays"""
count = self._uncounted.getAndSet(0)
instantRate = float(count) / self.interval
if self._initialized:
self.rate += (self.alpha * (instantRate - self.rate))
else:
self.rate = instantRate
self._initialized = True | python | def tick(self):
"""Updates rates and decays"""
count = self._uncounted.getAndSet(0)
instantRate = float(count) / self.interval
if self._initialized:
self.rate += (self.alpha * (instantRate - self.rate))
else:
self.rate = instantRate
self._initialized = True | [
"def",
"tick",
"(",
"self",
")",
":",
"count",
"=",
"self",
".",
"_uncounted",
".",
"getAndSet",
"(",
"0",
")",
"instantRate",
"=",
"float",
"(",
"count",
")",
"/",
"self",
".",
"interval",
"if",
"self",
".",
"_initialized",
":",
"self",
".",
"rate",... | Updates rates and decays | [
"Updates",
"rates",
"and",
"decays"
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L231-L240 | train | 23,938 |
Cue/scales | src/greplin/scales/__init__.py | statsId | def statsId(obj):
"""Gets a unique ID for each object."""
if hasattr(obj, ID_KEY):
return getattr(obj, ID_KEY)
newId = next(NEXT_ID)
setattr(obj, ID_KEY, newId)
return newId | python | def statsId(obj):
"""Gets a unique ID for each object."""
if hasattr(obj, ID_KEY):
return getattr(obj, ID_KEY)
newId = next(NEXT_ID)
setattr(obj, ID_KEY, newId)
return newId | [
"def",
"statsId",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"ID_KEY",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"ID_KEY",
")",
"newId",
"=",
"next",
"(",
"NEXT_ID",
")",
"setattr",
"(",
"obj",
",",
"ID_KEY",
",",
"newId",
")",
... | Gets a unique ID for each object. | [
"Gets",
"a",
"unique",
"ID",
"for",
"each",
"object",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L39-L45 | train | 23,939 |
Cue/scales | src/greplin/scales/__init__.py | filterCollapsedItems | def filterCollapsedItems(data):
"""Return a filtered iteration over a list of items."""
return ((key, value)\
for key, value in six.iteritems(data) \
if not (isinstance(value, StatContainer) and value.isCollapsed())) | python | def filterCollapsedItems(data):
"""Return a filtered iteration over a list of items."""
return ((key, value)\
for key, value in six.iteritems(data) \
if not (isinstance(value, StatContainer) and value.isCollapsed())) | [
"def",
"filterCollapsedItems",
"(",
"data",
")",
":",
"return",
"(",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
"if",
"not",
"(",
"isinstance",
"(",
"value",
",",
"StatContainer",
")",
... | Return a filtered iteration over a list of items. | [
"Return",
"a",
"filtered",
"iteration",
"over",
"a",
"list",
"of",
"items",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L669-L673 | train | 23,940 |
Cue/scales | src/greplin/scales/__init__.py | dumpStatsTo | def dumpStatsTo(filename):
"""Writes the stats dict to filanem"""
with open(filename, 'w') as f:
latest = getStats()
latest['last-updated'] = time.time()
json.dump(getStats(), f, cls=StatContainerEncoder) | python | def dumpStatsTo(filename):
"""Writes the stats dict to filanem"""
with open(filename, 'w') as f:
latest = getStats()
latest['last-updated'] = time.time()
json.dump(getStats(), f, cls=StatContainerEncoder) | [
"def",
"dumpStatsTo",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"latest",
"=",
"getStats",
"(",
")",
"latest",
"[",
"'last-updated'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"json",
".",
"dump",
"... | Writes the stats dict to filanem | [
"Writes",
"the",
"stats",
"dict",
"to",
"filanem"
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L692-L697 | train | 23,941 |
Cue/scales | src/greplin/scales/__init__.py | collection | def collection(path, *stats):
"""Creates a named stats collection object."""
def initMethod(self):
"""Init method for the underlying stat object's class."""
init(self, path)
attributes = {'__init__': initMethod}
for stat in stats:
attributes[stat.getName()] = stat
newClass = type('Stats:%s' % path, (object,), attributes)
instance = newClass()
for stat in stats:
default = stat._getInit() # Consider this method package-protected. # pylint: disable=W0212
if default:
setattr(instance, stat.getName(), default)
return instance | python | def collection(path, *stats):
"""Creates a named stats collection object."""
def initMethod(self):
"""Init method for the underlying stat object's class."""
init(self, path)
attributes = {'__init__': initMethod}
for stat in stats:
attributes[stat.getName()] = stat
newClass = type('Stats:%s' % path, (object,), attributes)
instance = newClass()
for stat in stats:
default = stat._getInit() # Consider this method package-protected. # pylint: disable=W0212
if default:
setattr(instance, stat.getName(), default)
return instance | [
"def",
"collection",
"(",
"path",
",",
"*",
"stats",
")",
":",
"def",
"initMethod",
"(",
"self",
")",
":",
"\"\"\"Init method for the underlying stat object's class.\"\"\"",
"init",
"(",
"self",
",",
"path",
")",
"attributes",
"=",
"{",
"'__init__'",
":",
"initM... | Creates a named stats collection object. | [
"Creates",
"a",
"named",
"stats",
"collection",
"object",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L701-L717 | train | 23,942 |
Cue/scales | src/greplin/scales/__init__.py | _Stats.reset | def reset(cls):
"""Resets the static state. Should only be called by tests."""
cls.stats = StatContainer()
cls.parentMap = {}
cls.containerMap = {}
cls.subId = 0
for stat in gc.get_objects():
if isinstance(stat, Stat):
stat._aggregators = {} | python | def reset(cls):
"""Resets the static state. Should only be called by tests."""
cls.stats = StatContainer()
cls.parentMap = {}
cls.containerMap = {}
cls.subId = 0
for stat in gc.get_objects():
if isinstance(stat, Stat):
stat._aggregators = {} | [
"def",
"reset",
"(",
"cls",
")",
":",
"cls",
".",
"stats",
"=",
"StatContainer",
"(",
")",
"cls",
".",
"parentMap",
"=",
"{",
"}",
"cls",
".",
"containerMap",
"=",
"{",
"}",
"cls",
".",
"subId",
"=",
"0",
"for",
"stat",
"in",
"gc",
".",
"get_obje... | Resets the static state. Should only be called by tests. | [
"Resets",
"the",
"static",
"state",
".",
"Should",
"only",
"be",
"called",
"by",
"tests",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L111-L119 | train | 23,943 |
Cue/scales | src/greplin/scales/__init__.py | _Stats.init | def init(cls, obj, context):
"""Implementation of init."""
addr = statsId(obj)
if addr not in cls.containerMap:
cls.containerMap[addr] = cls.__getStatContainer(context)
return cls.containerMap[addr] | python | def init(cls, obj, context):
"""Implementation of init."""
addr = statsId(obj)
if addr not in cls.containerMap:
cls.containerMap[addr] = cls.__getStatContainer(context)
return cls.containerMap[addr] | [
"def",
"init",
"(",
"cls",
",",
"obj",
",",
"context",
")",
":",
"addr",
"=",
"statsId",
"(",
"obj",
")",
"if",
"addr",
"not",
"in",
"cls",
".",
"containerMap",
":",
"cls",
".",
"containerMap",
"[",
"addr",
"]",
"=",
"cls",
".",
"__getStatContainer",... | Implementation of init. | [
"Implementation",
"of",
"init",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L123-L128 | train | 23,944 |
Cue/scales | src/greplin/scales/__init__.py | _Stats.initChild | def initChild(cls, obj, name, subContext, parent = None):
"""Implementation of initChild."""
addr = statsId(obj)
if addr not in cls.containerMap:
if not parent:
# Find out the parent of the calling object by going back through the call stack until a self != this.
f = inspect.currentframe()
while not cls.__getSelf(f):
f = f.f_back
this = cls.__getSelf(f)
f = f.f_back
while cls.__getSelf(f) == this or not cls.__getSelf(f):
f = f.f_back
parent = cls.__getSelf(f)
# Default subcontext to an autoincrementing ID.
if subContext is None:
cls.subId += 1
subContext = cls.subId
if subContext is not '':
path = '%s/%s' % (name, subContext)
else:
path = name
# Now that we have the name, create an entry for this object.
cls.parentMap[addr] = parent
container = cls.getContainerForObject(statsId(parent))
if not container and isinstance(parent, unittest.TestCase):
cls.init(parent, '/test-case')
cls.containerMap[addr] = cls.__getStatContainer(path, cls.getContainerForObject(statsId(parent)))
return cls.containerMap[addr] | python | def initChild(cls, obj, name, subContext, parent = None):
"""Implementation of initChild."""
addr = statsId(obj)
if addr not in cls.containerMap:
if not parent:
# Find out the parent of the calling object by going back through the call stack until a self != this.
f = inspect.currentframe()
while not cls.__getSelf(f):
f = f.f_back
this = cls.__getSelf(f)
f = f.f_back
while cls.__getSelf(f) == this or not cls.__getSelf(f):
f = f.f_back
parent = cls.__getSelf(f)
# Default subcontext to an autoincrementing ID.
if subContext is None:
cls.subId += 1
subContext = cls.subId
if subContext is not '':
path = '%s/%s' % (name, subContext)
else:
path = name
# Now that we have the name, create an entry for this object.
cls.parentMap[addr] = parent
container = cls.getContainerForObject(statsId(parent))
if not container and isinstance(parent, unittest.TestCase):
cls.init(parent, '/test-case')
cls.containerMap[addr] = cls.__getStatContainer(path, cls.getContainerForObject(statsId(parent)))
return cls.containerMap[addr] | [
"def",
"initChild",
"(",
"cls",
",",
"obj",
",",
"name",
",",
"subContext",
",",
"parent",
"=",
"None",
")",
":",
"addr",
"=",
"statsId",
"(",
"obj",
")",
"if",
"addr",
"not",
"in",
"cls",
".",
"containerMap",
":",
"if",
"not",
"parent",
":",
"# Fi... | Implementation of initChild. | [
"Implementation",
"of",
"initChild",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L138-L169 | train | 23,945 |
Cue/scales | src/greplin/scales/__init__.py | _Stats.__getStatContainer | def __getStatContainer(cls, context, parent=None):
"""Get the stat container for the given context under the given parent."""
container = parent
if container is None:
container = cls.stats
if context is not None:
context = str(context).lstrip('/')
for key in context.split('/'):
container.setdefault(key, StatContainer())
container = container[key]
return container | python | def __getStatContainer(cls, context, parent=None):
"""Get the stat container for the given context under the given parent."""
container = parent
if container is None:
container = cls.stats
if context is not None:
context = str(context).lstrip('/')
for key in context.split('/'):
container.setdefault(key, StatContainer())
container = container[key]
return container | [
"def",
"__getStatContainer",
"(",
"cls",
",",
"context",
",",
"parent",
"=",
"None",
")",
":",
"container",
"=",
"parent",
"if",
"container",
"is",
"None",
":",
"container",
"=",
"cls",
".",
"stats",
"if",
"context",
"is",
"not",
"None",
":",
"context",
... | Get the stat container for the given context under the given parent. | [
"Get",
"the",
"stat",
"container",
"for",
"the",
"given",
"context",
"under",
"the",
"given",
"parent",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L173-L183 | train | 23,946 |
Cue/scales | src/greplin/scales/__init__.py | _Stats.getStat | def getStat(cls, obj, name):
"""Gets the stat for the given object with the given name, or None if no such stat exists."""
objClass = type(obj)
for theClass in objClass.__mro__:
if theClass == object:
break
for value in theClass.__dict__.values():
if isinstance(value, Stat) and value.getName() == name:
return value | python | def getStat(cls, obj, name):
"""Gets the stat for the given object with the given name, or None if no such stat exists."""
objClass = type(obj)
for theClass in objClass.__mro__:
if theClass == object:
break
for value in theClass.__dict__.values():
if isinstance(value, Stat) and value.getName() == name:
return value | [
"def",
"getStat",
"(",
"cls",
",",
"obj",
",",
"name",
")",
":",
"objClass",
"=",
"type",
"(",
"obj",
")",
"for",
"theClass",
"in",
"objClass",
".",
"__mro__",
":",
"if",
"theClass",
"==",
"object",
":",
"break",
"for",
"value",
"in",
"theClass",
"."... | Gets the stat for the given object with the given name, or None if no such stat exists. | [
"Gets",
"the",
"stat",
"for",
"the",
"given",
"object",
"with",
"the",
"given",
"name",
"or",
"None",
"if",
"no",
"such",
"stat",
"exists",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L193-L201 | train | 23,947 |
Cue/scales | src/greplin/scales/__init__.py | _Stats.getAggregator | def getAggregator(cls, instanceId, name):
"""Gets the aggregate stat for the given stat."""
parent = cls.parentMap.get(instanceId)
while parent:
stat = cls.getStat(parent, name)
if stat:
return stat, parent
parent = cls.parentMap.get(statsId(parent)) | python | def getAggregator(cls, instanceId, name):
"""Gets the aggregate stat for the given stat."""
parent = cls.parentMap.get(instanceId)
while parent:
stat = cls.getStat(parent, name)
if stat:
return stat, parent
parent = cls.parentMap.get(statsId(parent)) | [
"def",
"getAggregator",
"(",
"cls",
",",
"instanceId",
",",
"name",
")",
":",
"parent",
"=",
"cls",
".",
"parentMap",
".",
"get",
"(",
"instanceId",
")",
"while",
"parent",
":",
"stat",
"=",
"cls",
".",
"getStat",
"(",
"parent",
",",
"name",
")",
"if... | Gets the aggregate stat for the given stat. | [
"Gets",
"the",
"aggregate",
"stat",
"for",
"the",
"given",
"stat",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L205-L212 | train | 23,948 |
Cue/scales | src/greplin/scales/__init__.py | Stat._aggregate | def _aggregate(self, instanceId, container, value, subKey = None):
"""Performs stat aggregation."""
# Get the aggregator.
if instanceId not in self._aggregators:
self._aggregators[instanceId] = _Stats.getAggregator(instanceId, self.__name)
aggregator = self._aggregators[instanceId]
# If we are aggregating, get the old value.
if aggregator:
oldValue = container.get(self.__name)
if subKey:
oldValue = oldValue[subKey]
aggregator[0].update(aggregator[1], oldValue, value, subKey)
else:
aggregator[0].update(aggregator[1], oldValue, value) | python | def _aggregate(self, instanceId, container, value, subKey = None):
"""Performs stat aggregation."""
# Get the aggregator.
if instanceId not in self._aggregators:
self._aggregators[instanceId] = _Stats.getAggregator(instanceId, self.__name)
aggregator = self._aggregators[instanceId]
# If we are aggregating, get the old value.
if aggregator:
oldValue = container.get(self.__name)
if subKey:
oldValue = oldValue[subKey]
aggregator[0].update(aggregator[1], oldValue, value, subKey)
else:
aggregator[0].update(aggregator[1], oldValue, value) | [
"def",
"_aggregate",
"(",
"self",
",",
"instanceId",
",",
"container",
",",
"value",
",",
"subKey",
"=",
"None",
")",
":",
"# Get the aggregator.",
"if",
"instanceId",
"not",
"in",
"self",
".",
"_aggregators",
":",
"self",
".",
"_aggregators",
"[",
"instance... | Performs stat aggregation. | [
"Performs",
"stat",
"aggregation",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L254-L269 | train | 23,949 |
Cue/scales | src/greplin/scales/__init__.py | Stat.updateItem | def updateItem(self, instance, subKey, value):
"""Updates a child value. Must be called before the update has actually occurred."""
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) | python | def updateItem(self, instance, subKey, value):
"""Updates a child value. Must be called before the update has actually occurred."""
instanceId = statsId(instance)
container = _Stats.getContainerForObject(instanceId)
self._aggregate(instanceId, container, value, subKey) | [
"def",
"updateItem",
"(",
"self",
",",
"instance",
",",
"subKey",
",",
"value",
")",
":",
"instanceId",
"=",
"statsId",
"(",
"instance",
")",
"container",
"=",
"_Stats",
".",
"getContainerForObject",
"(",
"instanceId",
")",
"self",
".",
"_aggregate",
"(",
... | Updates a child value. Must be called before the update has actually occurred. | [
"Updates",
"a",
"child",
"value",
".",
"Must",
"be",
"called",
"before",
"the",
"update",
"has",
"actually",
"occurred",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L283-L288 | train | 23,950 |
Cue/scales | src/greplin/scales/__init__.py | StateTimeStatDict.incr | def incr(self, item, value):
"""Increment a key by the given amount."""
if item in self:
old = UserDict.__getitem__(self, item)
else:
old = 0.0
self[item] = old + value | python | def incr(self, item, value):
"""Increment a key by the given amount."""
if item in self:
old = UserDict.__getitem__(self, item)
else:
old = 0.0
self[item] = old + value | [
"def",
"incr",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"if",
"item",
"in",
"self",
":",
"old",
"=",
"UserDict",
".",
"__getitem__",
"(",
"self",
",",
"item",
")",
"else",
":",
"old",
"=",
"0.0",
"self",
"[",
"item",
"]",
"=",
"old",
"... | Increment a key by the given amount. | [
"Increment",
"a",
"key",
"by",
"the",
"given",
"amount",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L617-L623 | train | 23,951 |
Cue/scales | src/greplin/scales/aggregation.py | Aggregation.addSource | def addSource(self, source, data):
"""Adds the given source's stats."""
self._aggregate(source, self._aggregators, data, self._result) | python | def addSource(self, source, data):
"""Adds the given source's stats."""
self._aggregate(source, self._aggregators, data, self._result) | [
"def",
"addSource",
"(",
"self",
",",
"source",
",",
"data",
")",
":",
"self",
".",
"_aggregate",
"(",
"source",
",",
"self",
".",
"_aggregators",
",",
"data",
",",
"self",
".",
"_result",
")"
] | Adds the given source's stats. | [
"Adds",
"the",
"given",
"source",
"s",
"stats",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/aggregation.py#L332-L334 | train | 23,952 |
Cue/scales | src/greplin/scales/aggregation.py | Aggregation.addJsonDirectory | def addJsonDirectory(self, directory, test=None):
"""Adds data from json files in the given directory."""
for filename in os.listdir(directory):
try:
fullPath = os.path.join(directory, filename)
if not test or test(filename, fullPath):
with open(fullPath) as f:
jsonData = json.load(f)
name, _ = os.path.splitext(filename)
self.addSource(name, jsonData)
except ValueError:
continue | python | def addJsonDirectory(self, directory, test=None):
"""Adds data from json files in the given directory."""
for filename in os.listdir(directory):
try:
fullPath = os.path.join(directory, filename)
if not test or test(filename, fullPath):
with open(fullPath) as f:
jsonData = json.load(f)
name, _ = os.path.splitext(filename)
self.addSource(name, jsonData)
except ValueError:
continue | [
"def",
"addJsonDirectory",
"(",
"self",
",",
"directory",
",",
"test",
"=",
"None",
")",
":",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"try",
":",
"fullPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",... | Adds data from json files in the given directory. | [
"Adds",
"data",
"from",
"json",
"files",
"in",
"the",
"given",
"directory",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/aggregation.py#L337-L350 | train | 23,953 |
Cue/scales | src/greplin/scales/samplestats.py | Sampler.mean | def mean(self):
"""Return the sample mean."""
if len(self) == 0:
return float('NaN')
arr = self.samples()
return sum(arr) / float(len(arr)) | python | def mean(self):
"""Return the sample mean."""
if len(self) == 0:
return float('NaN')
arr = self.samples()
return sum(arr) / float(len(arr)) | [
"def",
"mean",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"float",
"(",
"'NaN'",
")",
"arr",
"=",
"self",
".",
"samples",
"(",
")",
"return",
"sum",
"(",
"arr",
")",
"/",
"float",
"(",
"len",
"(",
"arr",
"... | Return the sample mean. | [
"Return",
"the",
"sample",
"mean",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L46-L51 | train | 23,954 |
Cue/scales | src/greplin/scales/samplestats.py | Sampler.stddev | def stddev(self):
"""Return the sample standard deviation."""
if len(self) < 2:
return float('NaN')
# The stupidest algorithm, but it works fine.
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqrt(bigsum / (len(arr) - 1))
except ZeroDivisionError:
return float('NaN') | python | def stddev(self):
"""Return the sample standard deviation."""
if len(self) < 2:
return float('NaN')
# The stupidest algorithm, but it works fine.
try:
arr = self.samples()
mean = sum(arr) / len(arr)
bigsum = 0.0
for x in arr:
bigsum += (x - mean)**2
return sqrt(bigsum / (len(arr) - 1))
except ZeroDivisionError:
return float('NaN') | [
"def",
"stddev",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"<",
"2",
":",
"return",
"float",
"(",
"'NaN'",
")",
"# The stupidest algorithm, but it works fine.",
"try",
":",
"arr",
"=",
"self",
".",
"samples",
"(",
")",
"mean",
"=",
"sum",
"... | Return the sample standard deviation. | [
"Return",
"the",
"sample",
"standard",
"deviation",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L55-L68 | train | 23,955 |
Cue/scales | src/greplin/scales/samplestats.py | ExponentiallyDecayingReservoir.clear | def clear(self):
""" Clear the samples. """
self.__init__(size=self.size, alpha=self.alpha, clock=self.clock) | python | def clear(self):
""" Clear the samples. """
self.__init__(size=self.size, alpha=self.alpha, clock=self.clock) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"__init__",
"(",
"size",
"=",
"self",
".",
"size",
",",
"alpha",
"=",
"self",
".",
"alpha",
",",
"clock",
"=",
"self",
".",
"clock",
")"
] | Clear the samples. | [
"Clear",
"the",
"samples",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L140-L142 | train | 23,956 |
Cue/scales | src/greplin/scales/samplestats.py | ExponentiallyDecayingReservoir.update | def update(self, value):
"""
Adds an old value with a fixed timestamp to the reservoir.
@param value the value to be added
"""
super(ExponentiallyDecayingReservoir, self).update(value)
timestamp = self.clock.time()
self.__rescaleIfNeeded()
priority = self.__weight(timestamp - self.startTime) / random.random()
self.count += 1
if (self.count <= self.size):
self.values[priority] = value
else:
first = min(self.values)
if first < priority and priority not in self.values:
self.values[priority] = value
while first not in self.values:
first = min(self.values)
del self.values[first] | python | def update(self, value):
"""
Adds an old value with a fixed timestamp to the reservoir.
@param value the value to be added
"""
super(ExponentiallyDecayingReservoir, self).update(value)
timestamp = self.clock.time()
self.__rescaleIfNeeded()
priority = self.__weight(timestamp - self.startTime) / random.random()
self.count += 1
if (self.count <= self.size):
self.values[priority] = value
else:
first = min(self.values)
if first < priority and priority not in self.values:
self.values[priority] = value
while first not in self.values:
first = min(self.values)
del self.values[first] | [
"def",
"update",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"ExponentiallyDecayingReservoir",
",",
"self",
")",
".",
"update",
"(",
"value",
")",
"timestamp",
"=",
"self",
".",
"clock",
".",
"time",
"(",
")",
"self",
".",
"__rescaleIfNeeded",
"("... | Adds an old value with a fixed timestamp to the reservoir.
@param value the value to be added | [
"Adds",
"an",
"old",
"value",
"with",
"a",
"fixed",
"timestamp",
"to",
"the",
"reservoir",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L144-L167 | train | 23,957 |
Cue/scales | src/greplin/scales/samplestats.py | UniformSample.clear | def clear(self):
"""Clear the sample."""
for i in range(len(self.sample)):
self.sample[i] = 0.0
self.count = 0 | python | def clear(self):
"""Clear the sample."""
for i in range(len(self.sample)):
self.sample[i] = 0.0
self.count = 0 | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"sample",
")",
")",
":",
"self",
".",
"sample",
"[",
"i",
"]",
"=",
"0.0",
"self",
".",
"count",
"=",
"0"
] | Clear the sample. | [
"Clear",
"the",
"sample",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L212-L216 | train | 23,958 |
Cue/scales | src/greplin/scales/samplestats.py | UniformSample.update | def update(self, value):
"""Add a value to the sample."""
super(UniformSample, self).update(value)
self.count += 1
c = self.count
if c < len(self.sample):
self.sample[c-1] = value
else:
r = random.randint(0, c)
if r < len(self.sample):
self.sample[r] = value | python | def update(self, value):
"""Add a value to the sample."""
super(UniformSample, self).update(value)
self.count += 1
c = self.count
if c < len(self.sample):
self.sample[c-1] = value
else:
r = random.randint(0, c)
if r < len(self.sample):
self.sample[r] = value | [
"def",
"update",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
"UniformSample",
",",
"self",
")",
".",
"update",
"(",
"value",
")",
"self",
".",
"count",
"+=",
"1",
"c",
"=",
"self",
".",
"count",
"if",
"c",
"<",
"len",
"(",
"self",
".",
"... | Add a value to the sample. | [
"Add",
"a",
"value",
"to",
"the",
"sample",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/samplestats.py#L222-L233 | train | 23,959 |
Cue/scales | src/greplin/scales/graphite.py | GraphitePusher._forbidden | def _forbidden(self, path, value):
"""Is a stat forbidden? Goes through the rules to find one that
applies. Chronologically newer rules are higher-precedence than
older ones. If no rule applies, the stat is forbidden by default."""
if path[0] == '/':
path = path[1:]
for rule in reversed(self.rules):
if isinstance(rule[1], six.string_types):
if fnmatch(path, rule[1]):
return not rule[0]
elif rule[1](path, value):
return not rule[0]
return True | python | def _forbidden(self, path, value):
"""Is a stat forbidden? Goes through the rules to find one that
applies. Chronologically newer rules are higher-precedence than
older ones. If no rule applies, the stat is forbidden by default."""
if path[0] == '/':
path = path[1:]
for rule in reversed(self.rules):
if isinstance(rule[1], six.string_types):
if fnmatch(path, rule[1]):
return not rule[0]
elif rule[1](path, value):
return not rule[0]
return True | [
"def",
"_forbidden",
"(",
"self",
",",
"path",
",",
"value",
")",
":",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"for",
"rule",
"in",
"reversed",
"(",
"self",
".",
"rules",
")",
":",
"if",
"isinstan... | Is a stat forbidden? Goes through the rules to find one that
applies. Chronologically newer rules are higher-precedence than
older ones. If no rule applies, the stat is forbidden by default. | [
"Is",
"a",
"stat",
"forbidden?",
"Goes",
"through",
"the",
"rules",
"to",
"find",
"one",
"that",
"applies",
".",
"Chronologically",
"newer",
"rules",
"are",
"higher",
"-",
"precedence",
"than",
"older",
"ones",
".",
"If",
"no",
"rule",
"applies",
"the",
"s... | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L55-L67 | train | 23,960 |
Cue/scales | src/greplin/scales/graphite.py | GraphitePusher._pruned | def _pruned(self, path):
"""Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default."""
if path[0] == '/':
path = path[1:]
for rule in reversed(self.pruneRules):
if isinstance(rule, six.string_types):
if fnmatch(path, rule):
return True
elif rule(path):
return True
return False | python | def _pruned(self, path):
"""Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default."""
if path[0] == '/':
path = path[1:]
for rule in reversed(self.pruneRules):
if isinstance(rule, six.string_types):
if fnmatch(path, rule):
return True
elif rule(path):
return True
return False | [
"def",
"_pruned",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"path",
"=",
"path",
"[",
"1",
":",
"]",
"for",
"rule",
"in",
"reversed",
"(",
"self",
".",
"pruneRules",
")",
":",
"if",
"isinstance",
"(",
"r... | Is a stat tree node pruned? Goes through the list of prune rules
to find one that applies. Chronologically newer rules are
higher-precedence than older ones. If no rule applies, the stat is
not pruned by default. | [
"Is",
"a",
"stat",
"tree",
"node",
"pruned?",
"Goes",
"through",
"the",
"list",
"of",
"prune",
"rules",
"to",
"find",
"one",
"that",
"applies",
".",
"Chronologically",
"newer",
"rules",
"are",
"higher",
"-",
"precedence",
"than",
"older",
"ones",
".",
"If"... | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L70-L83 | train | 23,961 |
Cue/scales | src/greplin/scales/graphite.py | GraphitePusher.push | def push(self, statsDict=None, prefix=None, path=None):
"""Push stat values out to Graphite."""
if statsDict is None:
statsDict = scales.getStats()
prefix = prefix or self.prefix
path = path or '/'
for name, value in list(statsDict.items()):
name = str(name)
subpath = os.path.join(path, name)
if self._pruned(subpath):
continue
if hasattr(value, '__call__'):
try:
value = value()
except: # pylint: disable=W0702
value = None
log.exception('Error when calling stat function for graphite push')
if hasattr(value, 'items'):
self.push(value, '%s%s.' % (prefix, self._sanitize(name)), subpath)
elif self._forbidden(subpath, value):
continue
if six.PY3:
type_values = (int, float)
else:
type_values = (int, long, float)
if type(value) in type_values and len(name) < 500:
self.graphite.log(prefix + self._sanitize(name), value) | python | def push(self, statsDict=None, prefix=None, path=None):
"""Push stat values out to Graphite."""
if statsDict is None:
statsDict = scales.getStats()
prefix = prefix or self.prefix
path = path or '/'
for name, value in list(statsDict.items()):
name = str(name)
subpath = os.path.join(path, name)
if self._pruned(subpath):
continue
if hasattr(value, '__call__'):
try:
value = value()
except: # pylint: disable=W0702
value = None
log.exception('Error when calling stat function for graphite push')
if hasattr(value, 'items'):
self.push(value, '%s%s.' % (prefix, self._sanitize(name)), subpath)
elif self._forbidden(subpath, value):
continue
if six.PY3:
type_values = (int, float)
else:
type_values = (int, long, float)
if type(value) in type_values and len(name) < 500:
self.graphite.log(prefix + self._sanitize(name), value) | [
"def",
"push",
"(",
"self",
",",
"statsDict",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"if",
"statsDict",
"is",
"None",
":",
"statsDict",
"=",
"scales",
".",
"getStats",
"(",
")",
"prefix",
"=",
"prefix",
"or",
"... | Push stat values out to Graphite. | [
"Push",
"stat",
"values",
"out",
"to",
"Graphite",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L86-L118 | train | 23,962 |
Cue/scales | src/greplin/scales/graphite.py | GraphitePeriodicPusher.run | def run(self):
"""Loop forever, pushing out stats."""
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done pushing stats to Graphite')
except:
log.exception('Exception while pushing stats to Graphite')
raise | python | def run(self):
"""Loop forever, pushing out stats."""
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done pushing stats to Graphite')
except:
log.exception('Exception while pushing stats to Graphite')
raise | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"graphite",
".",
"start",
"(",
")",
"while",
"True",
":",
"log",
".",
"debug",
"(",
"'Graphite pusher is sleeping for %d seconds'",
",",
"self",
".",
"period",
")",
"time",
".",
"sleep",
"(",
"self",
".",... | Loop forever, pushing out stats. | [
"Loop",
"forever",
"pushing",
"out",
"stats",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/graphite.py#L163-L175 | train | 23,963 |
Cue/scales | src/greplin/scales/loop.py | installStatsLoop | def installStatsLoop(statsFile, statsDelay):
"""Installs an interval loop that dumps stats to a file."""
def dumpStats():
"""Actual stats dump function."""
scales.dumpStatsTo(statsFile)
reactor.callLater(statsDelay, dumpStats)
def startStats():
"""Starts the stats dump in "statsDelay" seconds."""
reactor.callLater(statsDelay, dumpStats)
reactor.callWhenRunning(startStats) | python | def installStatsLoop(statsFile, statsDelay):
"""Installs an interval loop that dumps stats to a file."""
def dumpStats():
"""Actual stats dump function."""
scales.dumpStatsTo(statsFile)
reactor.callLater(statsDelay, dumpStats)
def startStats():
"""Starts the stats dump in "statsDelay" seconds."""
reactor.callLater(statsDelay, dumpStats)
reactor.callWhenRunning(startStats) | [
"def",
"installStatsLoop",
"(",
"statsFile",
",",
"statsDelay",
")",
":",
"def",
"dumpStats",
"(",
")",
":",
"\"\"\"Actual stats dump function.\"\"\"",
"scales",
".",
"dumpStatsTo",
"(",
"statsFile",
")",
"reactor",
".",
"callLater",
"(",
"statsDelay",
",",
"dumpS... | Installs an interval loop that dumps stats to a file. | [
"Installs",
"an",
"interval",
"loop",
"that",
"dumps",
"stats",
"to",
"a",
"file",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/loop.py#L22-L34 | train | 23,964 |
Cue/scales | src/greplin/scales/formats.py | runQuery | def runQuery(statDict, query):
"""Filters for the given query."""
parts = [x.strip() for x in OPERATOR.split(query)]
assert len(parts) in (1, 3)
queryKey = parts[0]
result = {}
for key, value in six.iteritems(statDict):
if key == queryKey:
if len(parts) == 3:
op = OPERATORS[parts[1]]
try:
queryValue = type(value)(parts[2]) if value else parts[2]
except (TypeError, ValueError):
continue
if not op(value, queryValue):
continue
result[key] = value
elif isinstance(value, scales.StatContainer) or isinstance(value, dict):
child = runQuery(value, query)
if child:
result[key] = child
return result | python | def runQuery(statDict, query):
"""Filters for the given query."""
parts = [x.strip() for x in OPERATOR.split(query)]
assert len(parts) in (1, 3)
queryKey = parts[0]
result = {}
for key, value in six.iteritems(statDict):
if key == queryKey:
if len(parts) == 3:
op = OPERATORS[parts[1]]
try:
queryValue = type(value)(parts[2]) if value else parts[2]
except (TypeError, ValueError):
continue
if not op(value, queryValue):
continue
result[key] = value
elif isinstance(value, scales.StatContainer) or isinstance(value, dict):
child = runQuery(value, query)
if child:
result[key] = child
return result | [
"def",
"runQuery",
"(",
"statDict",
",",
"query",
")",
":",
"parts",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"OPERATOR",
".",
"split",
"(",
"query",
")",
"]",
"assert",
"len",
"(",
"parts",
")",
"in",
"(",
"1",
",",
"3",
")",
... | Filters for the given query. | [
"Filters",
"for",
"the",
"given",
"query",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L38-L60 | train | 23,965 |
Cue/scales | src/greplin/scales/formats.py | htmlHeader | def htmlHeader(output, path, serverName, query = None):
"""Writes an HTML header."""
if path and path != '/':
output.write('<title>%s - Status: %s</title>' % (serverName, path))
else:
output.write('<title>%s - Status</title>' % serverName)
output.write('''
<style>
body,td { font-family: monospace }
.level div {
padding-bottom: 4px;
}
.level .level {
margin-left: 2em;
padding: 1px 0;
}
span { color: #090; vertical-align: top }
.key { color: black; font-weight: bold }
.int, .float { color: #00c }
</style>
''')
output.write('<h1 style="margin: 0">Stats</h1>')
output.write('<h3 style="margin: 3px 0 18px">%s</h3>' % serverName)
output.write(
'<p><form action="#" method="GET">Filter: <input type="text" name="query" size="20" value="%s"></form></p>' %
(query or '')) | python | def htmlHeader(output, path, serverName, query = None):
"""Writes an HTML header."""
if path and path != '/':
output.write('<title>%s - Status: %s</title>' % (serverName, path))
else:
output.write('<title>%s - Status</title>' % serverName)
output.write('''
<style>
body,td { font-family: monospace }
.level div {
padding-bottom: 4px;
}
.level .level {
margin-left: 2em;
padding: 1px 0;
}
span { color: #090; vertical-align: top }
.key { color: black; font-weight: bold }
.int, .float { color: #00c }
</style>
''')
output.write('<h1 style="margin: 0">Stats</h1>')
output.write('<h3 style="margin: 3px 0 18px">%s</h3>' % serverName)
output.write(
'<p><form action="#" method="GET">Filter: <input type="text" name="query" size="20" value="%s"></form></p>' %
(query or '')) | [
"def",
"htmlHeader",
"(",
"output",
",",
"path",
",",
"serverName",
",",
"query",
"=",
"None",
")",
":",
"if",
"path",
"and",
"path",
"!=",
"'/'",
":",
"output",
".",
"write",
"(",
"'<title>%s - Status: %s</title>'",
"%",
"(",
"serverName",
",",
"path",
... | Writes an HTML header. | [
"Writes",
"an",
"HTML",
"header",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L63-L88 | train | 23,966 |
Cue/scales | src/greplin/scales/formats.py | htmlFormat | def htmlFormat(output, pathParts = (), statDict = None, query = None):
"""Formats as HTML, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
_htmlRenderDict(pathParts, statDict, output) | python | def htmlFormat(output, pathParts = (), statDict = None, query = None):
"""Formats as HTML, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
_htmlRenderDict(pathParts, statDict, output) | [
"def",
"htmlFormat",
"(",
"output",
",",
"pathParts",
"=",
"(",
")",
",",
"statDict",
"=",
"None",
",",
"query",
"=",
"None",
")",
":",
"statDict",
"=",
"statDict",
"or",
"scales",
".",
"getStats",
"(",
")",
"if",
"query",
":",
"statDict",
"=",
"runQ... | Formats as HTML, writing to the given object. | [
"Formats",
"as",
"HTML",
"writing",
"to",
"the",
"given",
"object",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L91-L96 | train | 23,967 |
Cue/scales | src/greplin/scales/formats.py | _htmlRenderDict | def _htmlRenderDict(pathParts, statDict, output):
"""Render a dictionary as a table - recursing as necessary."""
keys = list(statDict.keys())
keys.sort()
links = []
output.write('<div class="level">')
for key in keys:
keyStr = cgi.escape(_utf8str(key))
value = statDict[key]
if hasattr(value, '__call__'):
value = value()
if hasattr(value, 'keys'):
valuePath = pathParts + (keyStr,)
if isinstance(value, scales.StatContainer) and value.isCollapsed():
link = '/status/' + '/'.join(valuePath)
links.append('<div class="key"><a href="%s">%s</a></div>' % (link, keyStr))
else:
output.write('<div class="key">%s</div>' % keyStr)
_htmlRenderDict(valuePath, value, output)
else:
output.write('<div><span class="key">%s</span> <span class="%s">%s</span></div>' %
(keyStr, type(value).__name__, cgi.escape(_utf8str(value)).replace('\n', '<br/>')))
if links:
for link in links:
output.write(link)
output.write('</div>') | python | def _htmlRenderDict(pathParts, statDict, output):
"""Render a dictionary as a table - recursing as necessary."""
keys = list(statDict.keys())
keys.sort()
links = []
output.write('<div class="level">')
for key in keys:
keyStr = cgi.escape(_utf8str(key))
value = statDict[key]
if hasattr(value, '__call__'):
value = value()
if hasattr(value, 'keys'):
valuePath = pathParts + (keyStr,)
if isinstance(value, scales.StatContainer) and value.isCollapsed():
link = '/status/' + '/'.join(valuePath)
links.append('<div class="key"><a href="%s">%s</a></div>' % (link, keyStr))
else:
output.write('<div class="key">%s</div>' % keyStr)
_htmlRenderDict(valuePath, value, output)
else:
output.write('<div><span class="key">%s</span> <span class="%s">%s</span></div>' %
(keyStr, type(value).__name__, cgi.escape(_utf8str(value)).replace('\n', '<br/>')))
if links:
for link in links:
output.write(link)
output.write('</div>') | [
"def",
"_htmlRenderDict",
"(",
"pathParts",
",",
"statDict",
",",
"output",
")",
":",
"keys",
"=",
"list",
"(",
"statDict",
".",
"keys",
"(",
")",
")",
"keys",
".",
"sort",
"(",
")",
"links",
"=",
"[",
"]",
"output",
".",
"write",
"(",
"'<div class=\... | Render a dictionary as a table - recursing as necessary. | [
"Render",
"a",
"dictionary",
"as",
"a",
"table",
"-",
"recursing",
"as",
"necessary",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L99-L128 | train | 23,968 |
Cue/scales | src/greplin/scales/formats.py | jsonFormat | def jsonFormat(output, statDict = None, query = None, pretty = False):
"""Formats as JSON, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
indent = 2 if pretty else None
# At first, assume that strings are in UTF-8. If this fails -- if, for example, we have
# crazy binary data -- then in order to get *something* out, we assume ISO-8859-1,
# which maps each byte to a unicode code point.
try:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent)
except UnicodeDecodeError:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent, encoding='iso-8859-1')
output.write(serialized)
output.write('\n') | python | def jsonFormat(output, statDict = None, query = None, pretty = False):
"""Formats as JSON, writing to the given object."""
statDict = statDict or scales.getStats()
if query:
statDict = runQuery(statDict, query)
indent = 2 if pretty else None
# At first, assume that strings are in UTF-8. If this fails -- if, for example, we have
# crazy binary data -- then in order to get *something* out, we assume ISO-8859-1,
# which maps each byte to a unicode code point.
try:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent)
except UnicodeDecodeError:
serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent, encoding='iso-8859-1')
output.write(serialized)
output.write('\n') | [
"def",
"jsonFormat",
"(",
"output",
",",
"statDict",
"=",
"None",
",",
"query",
"=",
"None",
",",
"pretty",
"=",
"False",
")",
":",
"statDict",
"=",
"statDict",
"or",
"scales",
".",
"getStats",
"(",
")",
"if",
"query",
":",
"statDict",
"=",
"runQuery",... | Formats as JSON, writing to the given object. | [
"Formats",
"as",
"JSON",
"writing",
"to",
"the",
"given",
"object",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L143-L158 | train | 23,969 |
Cue/scales | src/greplin/scales/timer.py | RepeatTimer | def RepeatTimer(interval, function, iterations=0, *args, **kwargs):
"""Repeating timer. Returns a thread id."""
def __repeat_timer(interval, function, iterations, args, kwargs):
"""Inner function, run in background thread."""
count = 0
while iterations <= 0 or count < iterations:
sleep(interval)
function(*args, **kwargs)
count += 1
return start_new_thread(__repeat_timer, (interval, function, iterations, args, kwargs)) | python | def RepeatTimer(interval, function, iterations=0, *args, **kwargs):
"""Repeating timer. Returns a thread id."""
def __repeat_timer(interval, function, iterations, args, kwargs):
"""Inner function, run in background thread."""
count = 0
while iterations <= 0 or count < iterations:
sleep(interval)
function(*args, **kwargs)
count += 1
return start_new_thread(__repeat_timer, (interval, function, iterations, args, kwargs)) | [
"def",
"RepeatTimer",
"(",
"interval",
",",
"function",
",",
"iterations",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"__repeat_timer",
"(",
"interval",
",",
"function",
",",
"iterations",
",",
"args",
",",
"kwargs",
")",
":"... | Repeating timer. Returns a thread id. | [
"Repeating",
"timer",
".",
"Returns",
"a",
"thread",
"id",
"."
] | 0aced26eb050ceb98ee9d5d6cdca8db448666986 | https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/timer.py#L39-L50 | train | 23,970 |
arthurk/django-disqus | disqus/templatetags/disqus_tags.py | get_config | def get_config(context):
"""
Return the formatted javascript for any disqus config variables.
"""
conf_vars = ['disqus_developer',
'disqus_identifier',
'disqus_url',
'disqus_title',
'disqus_category_id'
]
js = '\tvar {} = "{}";'
output = [js.format(item, context[item]) for item in conf_vars \
if item in context]
return '\n'.join(output) | python | def get_config(context):
"""
Return the formatted javascript for any disqus config variables.
"""
conf_vars = ['disqus_developer',
'disqus_identifier',
'disqus_url',
'disqus_title',
'disqus_category_id'
]
js = '\tvar {} = "{}";'
output = [js.format(item, context[item]) for item in conf_vars \
if item in context]
return '\n'.join(output) | [
"def",
"get_config",
"(",
"context",
")",
":",
"conf_vars",
"=",
"[",
"'disqus_developer'",
",",
"'disqus_identifier'",
",",
"'disqus_url'",
",",
"'disqus_title'",
",",
"'disqus_category_id'",
"]",
"js",
"=",
"'\\tvar {} = \"{}\";'",
"output",
"=",
"[",
"js",
".",... | Return the formatted javascript for any disqus config variables. | [
"Return",
"the",
"formatted",
"javascript",
"for",
"any",
"disqus",
"config",
"variables",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/templatetags/disqus_tags.py#L45-L62 | train | 23,971 |
arthurk/django-disqus | disqus/templatetags/disqus_tags.py | disqus_show_comments | def disqus_show_comments(context, shortname=''):
"""
Return the HTML code to display DISQUS comments.
"""
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'config': get_config(context),
} | python | def disqus_show_comments(context, shortname=''):
"""
Return the HTML code to display DISQUS comments.
"""
shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname)
return {
'shortname': shortname,
'config': get_config(context),
} | [
"def",
"disqus_show_comments",
"(",
"context",
",",
"shortname",
"=",
"''",
")",
":",
"shortname",
"=",
"getattr",
"(",
"settings",
",",
"'DISQUS_WEBSITE_SHORTNAME'",
",",
"shortname",
")",
"return",
"{",
"'shortname'",
":",
"shortname",
",",
"'config'",
":",
... | Return the HTML code to display DISQUS comments. | [
"Return",
"the",
"HTML",
"code",
"to",
"display",
"DISQUS",
"comments",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/templatetags/disqus_tags.py#L158-L167 | train | 23,972 |
arthurk/django-disqus | disqus/wxr_feed.py | WxrFeedType.add_item | def add_item(self, title, link, description, author_email=None,
author_name=None, author_link=None, pubdate=None, comments=None,
unique_id=None, enclosure=None, categories=(), item_copyright=None,
ttl=None, **kwargs):
"""
Adds an item to the feed. All args are expected to be Python Unicode
objects except pubdate, which is a datetime.datetime object, and
enclosure, which is an instance of the Enclosure class.
"""
to_unicode = lambda s: force_text(s, strings_only=True)
if categories:
categories = [to_unicode(c) for c in categories]
if ttl is not None:
# Force ints to unicode
ttl = force_text(ttl)
item = {
'title': to_unicode(title),
'link': iri_to_uri(link),
'description': to_unicode(description),
'author_email': to_unicode(author_email),
'author_name': to_unicode(author_name),
'author_link': iri_to_uri(author_link),
'pubdate': pubdate,
'comments': comments,
'unique_id': to_unicode(unique_id),
'enclosure': enclosure,
'categories': categories or (),
'item_copyright': to_unicode(item_copyright),
'ttl': ttl,
}
item.update(kwargs)
self.items.append(item) | python | def add_item(self, title, link, description, author_email=None,
author_name=None, author_link=None, pubdate=None, comments=None,
unique_id=None, enclosure=None, categories=(), item_copyright=None,
ttl=None, **kwargs):
"""
Adds an item to the feed. All args are expected to be Python Unicode
objects except pubdate, which is a datetime.datetime object, and
enclosure, which is an instance of the Enclosure class.
"""
to_unicode = lambda s: force_text(s, strings_only=True)
if categories:
categories = [to_unicode(c) for c in categories]
if ttl is not None:
# Force ints to unicode
ttl = force_text(ttl)
item = {
'title': to_unicode(title),
'link': iri_to_uri(link),
'description': to_unicode(description),
'author_email': to_unicode(author_email),
'author_name': to_unicode(author_name),
'author_link': iri_to_uri(author_link),
'pubdate': pubdate,
'comments': comments,
'unique_id': to_unicode(unique_id),
'enclosure': enclosure,
'categories': categories or (),
'item_copyright': to_unicode(item_copyright),
'ttl': ttl,
}
item.update(kwargs)
self.items.append(item) | [
"def",
"add_item",
"(",
"self",
",",
"title",
",",
"link",
",",
"description",
",",
"author_email",
"=",
"None",
",",
"author_name",
"=",
"None",
",",
"author_link",
"=",
"None",
",",
"pubdate",
"=",
"None",
",",
"comments",
"=",
"None",
",",
"unique_id"... | Adds an item to the feed. All args are expected to be Python Unicode
objects except pubdate, which is a datetime.datetime object, and
enclosure, which is an instance of the Enclosure class. | [
"Adds",
"an",
"item",
"to",
"the",
"feed",
".",
"All",
"args",
"are",
"expected",
"to",
"be",
"Python",
"Unicode",
"objects",
"except",
"pubdate",
"which",
"is",
"a",
"datetime",
".",
"datetime",
"object",
"and",
"enclosure",
"which",
"is",
"an",
"instance... | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/wxr_feed.py#L31-L62 | train | 23,973 |
arthurk/django-disqus | disqus/__init__.py | call | def call(method, data, post=False):
"""
Calls `method` from the DISQUS API with data either in POST or GET.
Returns deserialized JSON response.
"""
url = "%s%s" % ('http://disqus.com/api/', method)
if post:
# POST request
url += "/"
data = urlencode(data)
else:
# GET request
url += "?%s" % urlencode(data)
data = ''
res = json.load(urlopen(url, data))
if not res['succeeded']:
raise CommandError("'%s' failed: %s\nData: %s" % (method, res['code'], data))
return res['message'] | python | def call(method, data, post=False):
"""
Calls `method` from the DISQUS API with data either in POST or GET.
Returns deserialized JSON response.
"""
url = "%s%s" % ('http://disqus.com/api/', method)
if post:
# POST request
url += "/"
data = urlencode(data)
else:
# GET request
url += "?%s" % urlencode(data)
data = ''
res = json.load(urlopen(url, data))
if not res['succeeded']:
raise CommandError("'%s' failed: %s\nData: %s" % (method, res['code'], data))
return res['message'] | [
"def",
"call",
"(",
"method",
",",
"data",
",",
"post",
"=",
"False",
")",
":",
"url",
"=",
"\"%s%s\"",
"%",
"(",
"'http://disqus.com/api/'",
",",
"method",
")",
"if",
"post",
":",
"# POST request",
"url",
"+=",
"\"/\"",
"data",
"=",
"urlencode",
"(",
... | Calls `method` from the DISQUS API with data either in POST or GET.
Returns deserialized JSON response. | [
"Calls",
"method",
"from",
"the",
"DISQUS",
"API",
"with",
"data",
"either",
"in",
"POST",
"or",
"GET",
".",
"Returns",
"deserialized",
"JSON",
"response",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/__init__.py#L8-L25 | train | 23,974 |
arthurk/django-disqus | disqus/management/commands/disqus_export.py | Command._get_comments_to_export | def _get_comments_to_export(self, last_export_id=None):
"""Return comments which should be exported."""
qs = comments.get_model().objects.order_by('pk')\
.filter(is_public=True, is_removed=False)
if last_export_id is not None:
print("Resuming after comment %s" % str(last_export_id))
qs = qs.filter(id__gt=last_export_id)
return qs | python | def _get_comments_to_export(self, last_export_id=None):
"""Return comments which should be exported."""
qs = comments.get_model().objects.order_by('pk')\
.filter(is_public=True, is_removed=False)
if last_export_id is not None:
print("Resuming after comment %s" % str(last_export_id))
qs = qs.filter(id__gt=last_export_id)
return qs | [
"def",
"_get_comments_to_export",
"(",
"self",
",",
"last_export_id",
"=",
"None",
")",
":",
"qs",
"=",
"comments",
".",
"get_model",
"(",
")",
".",
"objects",
".",
"order_by",
"(",
"'pk'",
")",
".",
"filter",
"(",
"is_public",
"=",
"True",
",",
"is_remo... | Return comments which should be exported. | [
"Return",
"comments",
"which",
"should",
"be",
"exported",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/management/commands/disqus_export.py#L32-L39 | train | 23,975 |
arthurk/django-disqus | disqus/management/commands/disqus_export.py | Command._get_last_state | def _get_last_state(self, state_file):
"""Checks the given path for the last exported comment's id"""
state = None
fp = open(state_file)
try:
state = int(fp.read())
print("Found previous state: %d" % (state,))
finally:
fp.close()
return state | python | def _get_last_state(self, state_file):
"""Checks the given path for the last exported comment's id"""
state = None
fp = open(state_file)
try:
state = int(fp.read())
print("Found previous state: %d" % (state,))
finally:
fp.close()
return state | [
"def",
"_get_last_state",
"(",
"self",
",",
"state_file",
")",
":",
"state",
"=",
"None",
"fp",
"=",
"open",
"(",
"state_file",
")",
"try",
":",
"state",
"=",
"int",
"(",
"fp",
".",
"read",
"(",
")",
")",
"print",
"(",
"\"Found previous state: %d\"",
"... | Checks the given path for the last exported comment's id | [
"Checks",
"the",
"given",
"path",
"for",
"the",
"last",
"exported",
"comment",
"s",
"id"
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/management/commands/disqus_export.py#L41-L50 | train | 23,976 |
arthurk/django-disqus | disqus/management/commands/disqus_export.py | Command._save_state | def _save_state(self, state_file, last_pk):
"""Saves the last_pk into the given state_file"""
fp = open(state_file, 'w+')
try:
fp.write(str(last_pk))
finally:
fp.close() | python | def _save_state(self, state_file, last_pk):
"""Saves the last_pk into the given state_file"""
fp = open(state_file, 'w+')
try:
fp.write(str(last_pk))
finally:
fp.close() | [
"def",
"_save_state",
"(",
"self",
",",
"state_file",
",",
"last_pk",
")",
":",
"fp",
"=",
"open",
"(",
"state_file",
",",
"'w+'",
")",
"try",
":",
"fp",
".",
"write",
"(",
"str",
"(",
"last_pk",
")",
")",
"finally",
":",
"fp",
".",
"close",
"(",
... | Saves the last_pk into the given state_file | [
"Saves",
"the",
"last_pk",
"into",
"the",
"given",
"state_file"
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/management/commands/disqus_export.py#L52-L58 | train | 23,977 |
arthurk/django-disqus | disqus/api.py | DisqusClient._get_request | def _get_request(self, request_url, request_method, **params):
"""
Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object.
"""
if request_method == 'GET':
if params:
request_url += '&%s' % urlencode(params)
request = Request(request_url)
elif request_method == 'POST':
request = Request(request_url, urlencode(params, doseq=1))
return request | python | def _get_request(self, request_url, request_method, **params):
"""
Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object.
"""
if request_method == 'GET':
if params:
request_url += '&%s' % urlencode(params)
request = Request(request_url)
elif request_method == 'POST':
request = Request(request_url, urlencode(params, doseq=1))
return request | [
"def",
"_get_request",
"(",
"self",
",",
"request_url",
",",
"request_method",
",",
"*",
"*",
"params",
")",
":",
"if",
"request_method",
"==",
"'GET'",
":",
"if",
"params",
":",
"request_url",
"+=",
"'&%s'",
"%",
"urlencode",
"(",
"params",
")",
"request"... | Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object. | [
"Return",
"a",
"Request",
"object",
"that",
"has",
"the",
"GET",
"parameters",
"attached",
"to",
"the",
"url",
"or",
"the",
"POST",
"data",
"attached",
"to",
"the",
"object",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/api.py#L65-L76 | train | 23,978 |
arthurk/django-disqus | disqus/api.py | DisqusClient.call | def call(self, method, **params):
"""
Call the DISQUS API and return the json response.
URLError is raised when the request failed.
DisqusException is raised when the query didn't succeed.
"""
url = self.api_url % method
request = self._get_request(url, self.METHODS[method], **params)
try:
response = urlopen(request)
except URLError:
raise
else:
response_json = json.loads(response.read())
if not response_json['succeeded']:
raise DisqusException(response_json['message'])
return response_json['message'] | python | def call(self, method, **params):
"""
Call the DISQUS API and return the json response.
URLError is raised when the request failed.
DisqusException is raised when the query didn't succeed.
"""
url = self.api_url % method
request = self._get_request(url, self.METHODS[method], **params)
try:
response = urlopen(request)
except URLError:
raise
else:
response_json = json.loads(response.read())
if not response_json['succeeded']:
raise DisqusException(response_json['message'])
return response_json['message'] | [
"def",
"call",
"(",
"self",
",",
"method",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"self",
".",
"api_url",
"%",
"method",
"request",
"=",
"self",
".",
"_get_request",
"(",
"url",
",",
"self",
".",
"METHODS",
"[",
"method",
"]",
",",
"*",
"... | Call the DISQUS API and return the json response.
URLError is raised when the request failed.
DisqusException is raised when the query didn't succeed. | [
"Call",
"the",
"DISQUS",
"API",
"and",
"return",
"the",
"json",
"response",
".",
"URLError",
"is",
"raised",
"when",
"the",
"request",
"failed",
".",
"DisqusException",
"is",
"raised",
"when",
"the",
"query",
"didn",
"t",
"succeed",
"."
] | 0db52c240906c6663189c0a7aca9979a0db004d1 | https://github.com/arthurk/django-disqus/blob/0db52c240906c6663189c0a7aca9979a0db004d1/disqus/api.py#L78-L94 | train | 23,979 |
lavr/flask-emails | flask_emails/message.py | init_app | def init_app(app):
"""
'Initialize' flask application.
It creates EmailsConfig object and saves it in app.extensions.
You don't have to call this method directly.
:param app: Flask application object
:return: Just created :meth:`~EmailsConfig` object
"""
config = EmailsConfig(app)
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['emails'] = config
return config | python | def init_app(app):
"""
'Initialize' flask application.
It creates EmailsConfig object and saves it in app.extensions.
You don't have to call this method directly.
:param app: Flask application object
:return: Just created :meth:`~EmailsConfig` object
"""
config = EmailsConfig(app)
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['emails'] = config
return config | [
"def",
"init_app",
"(",
"app",
")",
":",
"config",
"=",
"EmailsConfig",
"(",
"app",
")",
"# register extension with app",
"app",
".",
"extensions",
"=",
"getattr",
"(",
"app",
",",
"'extensions'",
",",
"{",
"}",
")",
"app",
".",
"extensions",
"[",
"'emails... | 'Initialize' flask application.
It creates EmailsConfig object and saves it in app.extensions.
You don't have to call this method directly.
:param app: Flask application object
:return: Just created :meth:`~EmailsConfig` object | [
"Initialize",
"flask",
"application",
".",
"It",
"creates",
"EmailsConfig",
"object",
"and",
"saves",
"it",
"in",
"app",
".",
"extensions",
"."
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/message.py#L9-L23 | train | 23,980 |
lavr/flask-emails | flask_emails/message.py | Message.send | def send(self, smtp=None, **kw):
"""
Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response objects from emails backend.
For default `emails.backend.smtp.STMPBackend` returns an `emails.backend.smtp.SMTPResponse` object.
"""
smtp_options = {}
smtp_options.update(self.config.smtp_options)
if smtp:
smtp_options.update(smtp)
return super(Message, self).send(smtp=smtp_options, **kw) | python | def send(self, smtp=None, **kw):
"""
Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response objects from emails backend.
For default `emails.backend.smtp.STMPBackend` returns an `emails.backend.smtp.SMTPResponse` object.
"""
smtp_options = {}
smtp_options.update(self.config.smtp_options)
if smtp:
smtp_options.update(smtp)
return super(Message, self).send(smtp=smtp_options, **kw) | [
"def",
"send",
"(",
"self",
",",
"smtp",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"smtp_options",
"=",
"{",
"}",
"smtp_options",
".",
"update",
"(",
"self",
".",
"config",
".",
"smtp_options",
")",
"if",
"smtp",
":",
"smtp_options",
".",
"update",... | Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response objects from emails backend.
For default `emails.backend.smtp.STMPBackend` returns an `emails.backend.smtp.SMTPResponse` object. | [
"Sends",
"message",
"."
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/message.py#L47-L63 | train | 23,981 |
lavr/flask-emails | flask_emails/config.py | EmailsConfig.options | def options(self):
"""
Reads all EMAIL_ options and set default values.
"""
config = self._config
o = {}
o.update(self._default_smtp_options)
o.update(self._default_message_options)
o.update(self._default_backend_options)
o.update(get_namespace(config, 'EMAIL_', valid_keys=o.keys()))
o['port'] = int(o['port'])
o['timeout'] = float(o['timeout'])
return o | python | def options(self):
"""
Reads all EMAIL_ options and set default values.
"""
config = self._config
o = {}
o.update(self._default_smtp_options)
o.update(self._default_message_options)
o.update(self._default_backend_options)
o.update(get_namespace(config, 'EMAIL_', valid_keys=o.keys()))
o['port'] = int(o['port'])
o['timeout'] = float(o['timeout'])
return o | [
"def",
"options",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_config",
"o",
"=",
"{",
"}",
"o",
".",
"update",
"(",
"self",
".",
"_default_smtp_options",
")",
"o",
".",
"update",
"(",
"self",
".",
"_default_message_options",
")",
"o",
".",
"... | Reads all EMAIL_ options and set default values. | [
"Reads",
"all",
"EMAIL_",
"options",
"and",
"set",
"default",
"values",
"."
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/config.py#L109-L121 | train | 23,982 |
lavr/flask-emails | flask_emails/config.py | EmailsConfig.smtp_options | def smtp_options(self):
"""
Convert config namespace to emails.backend.SMTPBackend namespace
Returns dict for SMTPFactory
"""
o = {}
options = self.options
for key in self._default_smtp_options:
if key in options:
o[key] = options[key]
o['user'] = o.pop('host_user', None)
o['password'] = o.pop('host_password', None)
o['tls'] = o.pop('use_tls', False)
o['ssl'] = o.pop('use_ssl', False)
o['debug'] = o.pop('smtp_debug', 0)
for k in ('certfile', 'keyfile'):
v = o.pop('ssl_'+k, None)
if v:
o[k] = v
return o | python | def smtp_options(self):
"""
Convert config namespace to emails.backend.SMTPBackend namespace
Returns dict for SMTPFactory
"""
o = {}
options = self.options
for key in self._default_smtp_options:
if key in options:
o[key] = options[key]
o['user'] = o.pop('host_user', None)
o['password'] = o.pop('host_password', None)
o['tls'] = o.pop('use_tls', False)
o['ssl'] = o.pop('use_ssl', False)
o['debug'] = o.pop('smtp_debug', 0)
for k in ('certfile', 'keyfile'):
v = o.pop('ssl_'+k, None)
if v:
o[k] = v
return o | [
"def",
"smtp_options",
"(",
"self",
")",
":",
"o",
"=",
"{",
"}",
"options",
"=",
"self",
".",
"options",
"for",
"key",
"in",
"self",
".",
"_default_smtp_options",
":",
"if",
"key",
"in",
"options",
":",
"o",
"[",
"key",
"]",
"=",
"options",
"[",
"... | Convert config namespace to emails.backend.SMTPBackend namespace
Returns dict for SMTPFactory | [
"Convert",
"config",
"namespace",
"to",
"emails",
".",
"backend",
".",
"SMTPBackend",
"namespace",
"Returns",
"dict",
"for",
"SMTPFactory"
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/config.py#L124-L144 | train | 23,983 |
lavr/flask-emails | flask_emails/config.py | EmailsConfig.message_options | def message_options(self):
"""
Convert config namespace to emails.Message namespace
"""
o = {}
options = self.options
for key in self._default_message_options:
if key in options:
o[key] = options[key]
return o | python | def message_options(self):
"""
Convert config namespace to emails.Message namespace
"""
o = {}
options = self.options
for key in self._default_message_options:
if key in options:
o[key] = options[key]
return o | [
"def",
"message_options",
"(",
"self",
")",
":",
"o",
"=",
"{",
"}",
"options",
"=",
"self",
".",
"options",
"for",
"key",
"in",
"self",
".",
"_default_message_options",
":",
"if",
"key",
"in",
"options",
":",
"o",
"[",
"key",
"]",
"=",
"options",
"[... | Convert config namespace to emails.Message namespace | [
"Convert",
"config",
"namespace",
"to",
"emails",
".",
"Message",
"namespace"
] | a1a47108ce7d109fe6c32b6f967445e62f7e5ef6 | https://github.com/lavr/flask-emails/blob/a1a47108ce7d109fe6c32b6f967445e62f7e5ef6/flask_emails/config.py#L147-L156 | train | 23,984 |
acroz/pylivy | livy/session.py | LivySession.start | def start(self) -> None:
"""Create the remote Spark session and wait for it to be ready."""
session = self.client.create_session(
self.kind,
self.proxy_user,
self.jars,
self.py_files,
self.files,
self.driver_memory,
self.driver_cores,
self.executor_memory,
self.executor_cores,
self.num_executors,
self.archives,
self.queue,
self.name,
self.spark_conf,
)
self.session_id = session.session_id
not_ready = {SessionState.NOT_STARTED, SessionState.STARTING}
intervals = polling_intervals([0.1, 0.2, 0.3, 0.5], 1.0)
while self.state in not_ready:
time.sleep(next(intervals)) | python | def start(self) -> None:
"""Create the remote Spark session and wait for it to be ready."""
session = self.client.create_session(
self.kind,
self.proxy_user,
self.jars,
self.py_files,
self.files,
self.driver_memory,
self.driver_cores,
self.executor_memory,
self.executor_cores,
self.num_executors,
self.archives,
self.queue,
self.name,
self.spark_conf,
)
self.session_id = session.session_id
not_ready = {SessionState.NOT_STARTED, SessionState.STARTING}
intervals = polling_intervals([0.1, 0.2, 0.3, 0.5], 1.0)
while self.state in not_ready:
time.sleep(next(intervals)) | [
"def",
"start",
"(",
"self",
")",
"->",
"None",
":",
"session",
"=",
"self",
".",
"client",
".",
"create_session",
"(",
"self",
".",
"kind",
",",
"self",
".",
"proxy_user",
",",
"self",
".",
"jars",
",",
"self",
".",
"py_files",
",",
"self",
".",
"... | Create the remote Spark session and wait for it to be ready. | [
"Create",
"the",
"remote",
"Spark",
"session",
"and",
"wait",
"for",
"it",
"to",
"be",
"ready",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L165-L190 | train | 23,985 |
acroz/pylivy | livy/session.py | LivySession.state | def state(self) -> SessionState:
"""The state of the managed Spark session."""
if self.session_id is None:
raise ValueError("session not yet started")
session = self.client.get_session(self.session_id)
if session is None:
raise ValueError("session not found - it may have been shut down")
return session.state | python | def state(self) -> SessionState:
"""The state of the managed Spark session."""
if self.session_id is None:
raise ValueError("session not yet started")
session = self.client.get_session(self.session_id)
if session is None:
raise ValueError("session not found - it may have been shut down")
return session.state | [
"def",
"state",
"(",
"self",
")",
"->",
"SessionState",
":",
"if",
"self",
".",
"session_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"session not yet started\"",
")",
"session",
"=",
"self",
".",
"client",
".",
"get_session",
"(",
"self",
".",
"s... | The state of the managed Spark session. | [
"The",
"state",
"of",
"the",
"managed",
"Spark",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L193-L200 | train | 23,986 |
acroz/pylivy | livy/session.py | LivySession.close | def close(self) -> None:
"""Kill the managed Spark session."""
if self.session_id is not None:
self.client.delete_session(self.session_id)
self.client.close() | python | def close(self) -> None:
"""Kill the managed Spark session."""
if self.session_id is not None:
self.client.delete_session(self.session_id)
self.client.close() | [
"def",
"close",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"session_id",
"is",
"not",
"None",
":",
"self",
".",
"client",
".",
"delete_session",
"(",
"self",
".",
"session_id",
")",
"self",
".",
"client",
".",
"close",
"(",
")"
] | Kill the managed Spark session. | [
"Kill",
"the",
"managed",
"Spark",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L202-L206 | train | 23,987 |
acroz/pylivy | livy/session.py | LivySession.run | def run(self, code: str) -> Output:
"""Run some code in the managed Spark session.
:param code: The code to run.
"""
output = self._execute(code)
if self.echo and output.text:
print(output.text)
if self.check:
output.raise_for_status()
return output | python | def run(self, code: str) -> Output:
"""Run some code in the managed Spark session.
:param code: The code to run.
"""
output = self._execute(code)
if self.echo and output.text:
print(output.text)
if self.check:
output.raise_for_status()
return output | [
"def",
"run",
"(",
"self",
",",
"code",
":",
"str",
")",
"->",
"Output",
":",
"output",
"=",
"self",
".",
"_execute",
"(",
"code",
")",
"if",
"self",
".",
"echo",
"and",
"output",
".",
"text",
":",
"print",
"(",
"output",
".",
"text",
")",
"if",
... | Run some code in the managed Spark session.
:param code: The code to run. | [
"Run",
"some",
"code",
"in",
"the",
"managed",
"Spark",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L208-L218 | train | 23,988 |
acroz/pylivy | livy/session.py | LivySession.read | def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
"""
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)
output.raise_for_status()
if output.text is None:
raise RuntimeError("statement had no text output")
return deserialise_dataframe(output.text) | python | def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
"""
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)
output.raise_for_status()
if output.text is None:
raise RuntimeError("statement had no text output")
return deserialise_dataframe(output.text) | [
"def",
"read",
"(",
"self",
",",
"dataframe_name",
":",
"str",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"code",
"=",
"serialise_dataframe_code",
"(",
"dataframe_name",
",",
"self",
".",
"kind",
")",
"output",
"=",
"self",
".",
"_execute",
"(",
"code",
... | Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read. | [
"Evaluate",
"and",
"retrieve",
"a",
"Spark",
"dataframe",
"in",
"the",
"managed",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L220-L230 | train | 23,989 |
acroz/pylivy | livy/session.py | LivySession.read_sql | def read_sql(self, code: str) -> pandas.DataFrame:
"""Evaluate a Spark SQL satatement and retrieve the result.
:param code: The Spark SQL statement to evaluate.
"""
if self.kind != SessionKind.SQL:
raise ValueError("not a SQL session")
output = self._execute(code)
output.raise_for_status()
if output.json is None:
raise RuntimeError("statement had no JSON output")
return dataframe_from_json_output(output.json) | python | def read_sql(self, code: str) -> pandas.DataFrame:
"""Evaluate a Spark SQL satatement and retrieve the result.
:param code: The Spark SQL statement to evaluate.
"""
if self.kind != SessionKind.SQL:
raise ValueError("not a SQL session")
output = self._execute(code)
output.raise_for_status()
if output.json is None:
raise RuntimeError("statement had no JSON output")
return dataframe_from_json_output(output.json) | [
"def",
"read_sql",
"(",
"self",
",",
"code",
":",
"str",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"if",
"self",
".",
"kind",
"!=",
"SessionKind",
".",
"SQL",
":",
"raise",
"ValueError",
"(",
"\"not a SQL session\"",
")",
"output",
"=",
"self",
".",
... | Evaluate a Spark SQL satatement and retrieve the result.
:param code: The Spark SQL statement to evaluate. | [
"Evaluate",
"a",
"Spark",
"SQL",
"satatement",
"and",
"retrieve",
"the",
"result",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/session.py#L232-L243 | train | 23,990 |
acroz/pylivy | livy/client.py | LivyClient.server_version | def server_version(self) -> Version:
"""Get the version of Livy running on the server."""
if self._server_version_cache is None:
data = self._client.get("/version")
self._server_version_cache = Version(data["version"])
return self._server_version_cache | python | def server_version(self) -> Version:
"""Get the version of Livy running on the server."""
if self._server_version_cache is None:
data = self._client.get("/version")
self._server_version_cache = Version(data["version"])
return self._server_version_cache | [
"def",
"server_version",
"(",
"self",
")",
"->",
"Version",
":",
"if",
"self",
".",
"_server_version_cache",
"is",
"None",
":",
"data",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"/version\"",
")",
"self",
".",
"_server_version_cache",
"=",
"Version",
... | Get the version of Livy running on the server. | [
"Get",
"the",
"version",
"of",
"Livy",
"running",
"on",
"the",
"server",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L78-L83 | train | 23,991 |
acroz/pylivy | livy/client.py | LivyClient.list_sessions | def list_sessions(self) -> List[Session]:
"""List all the active sessions in Livy."""
data = self._client.get("/sessions")
return [Session.from_json(item) for item in data["sessions"]] | python | def list_sessions(self) -> List[Session]:
"""List all the active sessions in Livy."""
data = self._client.get("/sessions")
return [Session.from_json(item) for item in data["sessions"]] | [
"def",
"list_sessions",
"(",
"self",
")",
"->",
"List",
"[",
"Session",
"]",
":",
"data",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"\"/sessions\"",
")",
"return",
"[",
"Session",
".",
"from_json",
"(",
"item",
")",
"for",
"item",
"in",
"data",
"... | List all the active sessions in Livy. | [
"List",
"all",
"the",
"active",
"sessions",
"in",
"Livy",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L94-L97 | train | 23,992 |
acroz/pylivy | livy/client.py | LivyClient.create_session | def create_session(
self,
kind: SessionKind,
proxy_user: str = None,
jars: List[str] = None,
py_files: List[str] = None,
files: List[str] = None,
driver_memory: str = None,
driver_cores: int = None,
executor_memory: str = None,
executor_cores: int = None,
num_executors: int = None,
archives: List[str] = None,
queue: str = None,
name: str = None,
spark_conf: Dict[str, Any] = None,
) -> Session:
"""Create a new session in Livy.
The py_files, files, jars and archives arguments are lists of URLs,
e.g. ["s3://bucket/object", "hdfs://path/to/file", ...] and must be
reachable by the Spark driver process. If the provided URL has no
scheme, it's considered to be relative to the default file system
configured in the Livy server.
URLs in the py_files argument are copied to a temporary staging area
and inserted into Python's sys.path ahead of the standard library
paths. This allows you to import .py, .zip and .egg files in Python.
URLs for jars, py_files, files and archives arguments are all copied
to the same working directory on the Spark cluster.
The driver_memory and executor_memory arguments have the same format
as JVM memory strings with a size unit suffix ("k", "m", "g" or "t")
(e.g. 512m, 2g).
See https://spark.apache.org/docs/latest/configuration.html for more
information on Spark configuration properties.
:param kind: The kind of session to create.
:param proxy_user: User to impersonate when starting the session.
:param jars: URLs of jars to be used in this session.
:param py_files: URLs of Python files to be used in this session.
:param files: URLs of files to be used in this session.
:param driver_memory: Amount of memory to use for the driver process
(e.g. '512m').
:param driver_cores: Number of cores to use for the driver process.
:param executor_memory: Amount of memory to use per executor process
(e.g. '512m').
:param executor_cores: Number of cores to use for each executor.
:param num_executors: Number of executors to launch for this session.
:param archives: URLs of archives to be used in this session.
:param queue: The name of the YARN queue to which submitted.
:param name: The name of this session.
:param spark_conf: Spark configuration properties.
"""
if self.legacy_server():
valid_kinds = VALID_LEGACY_SESSION_KINDS
else:
valid_kinds = VALID_SESSION_KINDS
if kind not in valid_kinds:
raise ValueError(
f"{kind} is not a valid session kind for a Livy server of "
f"this version (should be one of {valid_kinds})"
)
body = {"kind": kind.value}
if proxy_user is not None:
body["proxyUser"] = proxy_user
if jars is not None:
body["jars"] = jars
if py_files is not None:
body["pyFiles"] = py_files
if files is not None:
body["files"] = files
if driver_memory is not None:
body["driverMemory"] = driver_memory
if driver_cores is not None:
body["driverCores"] = driver_cores
if executor_memory is not None:
body["executorMemory"] = executor_memory
if executor_cores is not None:
body["executorCores"] = executor_cores
if num_executors is not None:
body["numExecutors"] = num_executors
if archives is not None:
body["archives"] = archives
if queue is not None:
body["queue"] = queue
if name is not None:
body["name"] = name
if spark_conf is not None:
body["conf"] = spark_conf
data = self._client.post("/sessions", data=body)
return Session.from_json(data) | python | def create_session(
self,
kind: SessionKind,
proxy_user: str = None,
jars: List[str] = None,
py_files: List[str] = None,
files: List[str] = None,
driver_memory: str = None,
driver_cores: int = None,
executor_memory: str = None,
executor_cores: int = None,
num_executors: int = None,
archives: List[str] = None,
queue: str = None,
name: str = None,
spark_conf: Dict[str, Any] = None,
) -> Session:
"""Create a new session in Livy.
The py_files, files, jars and archives arguments are lists of URLs,
e.g. ["s3://bucket/object", "hdfs://path/to/file", ...] and must be
reachable by the Spark driver process. If the provided URL has no
scheme, it's considered to be relative to the default file system
configured in the Livy server.
URLs in the py_files argument are copied to a temporary staging area
and inserted into Python's sys.path ahead of the standard library
paths. This allows you to import .py, .zip and .egg files in Python.
URLs for jars, py_files, files and archives arguments are all copied
to the same working directory on the Spark cluster.
The driver_memory and executor_memory arguments have the same format
as JVM memory strings with a size unit suffix ("k", "m", "g" or "t")
(e.g. 512m, 2g).
See https://spark.apache.org/docs/latest/configuration.html for more
information on Spark configuration properties.
:param kind: The kind of session to create.
:param proxy_user: User to impersonate when starting the session.
:param jars: URLs of jars to be used in this session.
:param py_files: URLs of Python files to be used in this session.
:param files: URLs of files to be used in this session.
:param driver_memory: Amount of memory to use for the driver process
(e.g. '512m').
:param driver_cores: Number of cores to use for the driver process.
:param executor_memory: Amount of memory to use per executor process
(e.g. '512m').
:param executor_cores: Number of cores to use for each executor.
:param num_executors: Number of executors to launch for this session.
:param archives: URLs of archives to be used in this session.
:param queue: The name of the YARN queue to which submitted.
:param name: The name of this session.
:param spark_conf: Spark configuration properties.
"""
if self.legacy_server():
valid_kinds = VALID_LEGACY_SESSION_KINDS
else:
valid_kinds = VALID_SESSION_KINDS
if kind not in valid_kinds:
raise ValueError(
f"{kind} is not a valid session kind for a Livy server of "
f"this version (should be one of {valid_kinds})"
)
body = {"kind": kind.value}
if proxy_user is not None:
body["proxyUser"] = proxy_user
if jars is not None:
body["jars"] = jars
if py_files is not None:
body["pyFiles"] = py_files
if files is not None:
body["files"] = files
if driver_memory is not None:
body["driverMemory"] = driver_memory
if driver_cores is not None:
body["driverCores"] = driver_cores
if executor_memory is not None:
body["executorMemory"] = executor_memory
if executor_cores is not None:
body["executorCores"] = executor_cores
if num_executors is not None:
body["numExecutors"] = num_executors
if archives is not None:
body["archives"] = archives
if queue is not None:
body["queue"] = queue
if name is not None:
body["name"] = name
if spark_conf is not None:
body["conf"] = spark_conf
data = self._client.post("/sessions", data=body)
return Session.from_json(data) | [
"def",
"create_session",
"(",
"self",
",",
"kind",
":",
"SessionKind",
",",
"proxy_user",
":",
"str",
"=",
"None",
",",
"jars",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"py_files",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"files",
":"... | Create a new session in Livy.
The py_files, files, jars and archives arguments are lists of URLs,
e.g. ["s3://bucket/object", "hdfs://path/to/file", ...] and must be
reachable by the Spark driver process. If the provided URL has no
scheme, it's considered to be relative to the default file system
configured in the Livy server.
URLs in the py_files argument are copied to a temporary staging area
and inserted into Python's sys.path ahead of the standard library
paths. This allows you to import .py, .zip and .egg files in Python.
URLs for jars, py_files, files and archives arguments are all copied
to the same working directory on the Spark cluster.
The driver_memory and executor_memory arguments have the same format
as JVM memory strings with a size unit suffix ("k", "m", "g" or "t")
(e.g. 512m, 2g).
See https://spark.apache.org/docs/latest/configuration.html for more
information on Spark configuration properties.
:param kind: The kind of session to create.
:param proxy_user: User to impersonate when starting the session.
:param jars: URLs of jars to be used in this session.
:param py_files: URLs of Python files to be used in this session.
:param files: URLs of files to be used in this session.
:param driver_memory: Amount of memory to use for the driver process
(e.g. '512m').
:param driver_cores: Number of cores to use for the driver process.
:param executor_memory: Amount of memory to use per executor process
(e.g. '512m').
:param executor_cores: Number of cores to use for each executor.
:param num_executors: Number of executors to launch for this session.
:param archives: URLs of archives to be used in this session.
:param queue: The name of the YARN queue to which submitted.
:param name: The name of this session.
:param spark_conf: Spark configuration properties. | [
"Create",
"a",
"new",
"session",
"in",
"Livy",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L99-L195 | train | 23,993 |
acroz/pylivy | livy/client.py | LivyClient.list_statements | def list_statements(self, session_id: int) -> List[Statement]:
"""Get all the statements in a session.
:param session_id: The ID of the session.
"""
response = self._client.get(f"/sessions/{session_id}/statements")
return [
Statement.from_json(session_id, data)
for data in response["statements"]
] | python | def list_statements(self, session_id: int) -> List[Statement]:
"""Get all the statements in a session.
:param session_id: The ID of the session.
"""
response = self._client.get(f"/sessions/{session_id}/statements")
return [
Statement.from_json(session_id, data)
for data in response["statements"]
] | [
"def",
"list_statements",
"(",
"self",
",",
"session_id",
":",
"int",
")",
"->",
"List",
"[",
"Statement",
"]",
":",
"response",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"f\"/sessions/{session_id}/statements\"",
")",
"return",
"[",
"Statement",
".",
"fr... | Get all the statements in a session.
:param session_id: The ID of the session. | [
"Get",
"all",
"the",
"statements",
"in",
"a",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L218-L227 | train | 23,994 |
acroz/pylivy | livy/client.py | LivyClient.create_statement | def create_statement(
self, session_id: int, code: str, kind: StatementKind = None
) -> Statement:
"""Run a statement in a session.
:param session_id: The ID of the session.
:param code: The code to execute.
:param kind: The kind of code to execute.
"""
data = {"code": code}
if kind is not None:
if self.legacy_server():
LOGGER.warning("statement kind ignored on Livy<0.5.0")
data["kind"] = kind.value
response = self._client.post(
f"/sessions/{session_id}/statements", data=data
)
return Statement.from_json(session_id, response) | python | def create_statement(
self, session_id: int, code: str, kind: StatementKind = None
) -> Statement:
"""Run a statement in a session.
:param session_id: The ID of the session.
:param code: The code to execute.
:param kind: The kind of code to execute.
"""
data = {"code": code}
if kind is not None:
if self.legacy_server():
LOGGER.warning("statement kind ignored on Livy<0.5.0")
data["kind"] = kind.value
response = self._client.post(
f"/sessions/{session_id}/statements", data=data
)
return Statement.from_json(session_id, response) | [
"def",
"create_statement",
"(",
"self",
",",
"session_id",
":",
"int",
",",
"code",
":",
"str",
",",
"kind",
":",
"StatementKind",
"=",
"None",
")",
"->",
"Statement",
":",
"data",
"=",
"{",
"\"code\"",
":",
"code",
"}",
"if",
"kind",
"is",
"not",
"N... | Run a statement in a session.
:param session_id: The ID of the session.
:param code: The code to execute.
:param kind: The kind of code to execute. | [
"Run",
"a",
"statement",
"in",
"a",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L229-L249 | train | 23,995 |
acroz/pylivy | livy/client.py | LivyClient.get_statement | def get_statement(self, session_id: int, statement_id: int) -> Statement:
"""Get information about a statement in a session.
:param session_id: The ID of the session.
:param statement_id: The ID of the statement.
"""
response = self._client.get(
f"/sessions/{session_id}/statements/{statement_id}"
)
return Statement.from_json(session_id, response) | python | def get_statement(self, session_id: int, statement_id: int) -> Statement:
"""Get information about a statement in a session.
:param session_id: The ID of the session.
:param statement_id: The ID of the statement.
"""
response = self._client.get(
f"/sessions/{session_id}/statements/{statement_id}"
)
return Statement.from_json(session_id, response) | [
"def",
"get_statement",
"(",
"self",
",",
"session_id",
":",
"int",
",",
"statement_id",
":",
"int",
")",
"->",
"Statement",
":",
"response",
"=",
"self",
".",
"_client",
".",
"get",
"(",
"f\"/sessions/{session_id}/statements/{statement_id}\"",
")",
"return",
"S... | Get information about a statement in a session.
:param session_id: The ID of the session.
:param statement_id: The ID of the statement. | [
"Get",
"information",
"about",
"a",
"statement",
"in",
"a",
"session",
"."
] | 14fc65e19434c51ec959c92acb0925b87a6e3569 | https://github.com/acroz/pylivy/blob/14fc65e19434c51ec959c92acb0925b87a6e3569/livy/client.py#L251-L260 | train | 23,996 |
xflr6/concepts | concepts/visualize.py | lattice | def lattice(lattice, filename, directory, render, view, **kwargs):
"""Return graphviz source for visualizing the lattice graph."""
dot = graphviz.Digraph(
name=lattice.__class__.__name__,
comment=repr(lattice),
filename=filename,
directory=directory,
node_attr=dict(shape='circle', width='.25', style='filled', label=''),
edge_attr=dict(dir='none', labeldistance='1.5', minlen='2'),
**kwargs
)
sortkey = SORTKEYS[0]
node_name = NAME_GETTERS[0]
for concept in lattice._concepts:
name = node_name(concept)
dot.node(name)
if concept.objects:
dot.edge(name, name,
headlabel=' '.join(concept.objects),
labelangle='270', color='transparent')
if concept.properties:
dot.edge(name, name,
taillabel=' '.join(concept.properties),
labelangle='90', color='transparent')
dot.edges((name, node_name(c))
for c in sorted(concept.lower_neighbors, key=sortkey))
if render or view:
dot.render(view=view) # pragma: no cover
return dot | python | def lattice(lattice, filename, directory, render, view, **kwargs):
"""Return graphviz source for visualizing the lattice graph."""
dot = graphviz.Digraph(
name=lattice.__class__.__name__,
comment=repr(lattice),
filename=filename,
directory=directory,
node_attr=dict(shape='circle', width='.25', style='filled', label=''),
edge_attr=dict(dir='none', labeldistance='1.5', minlen='2'),
**kwargs
)
sortkey = SORTKEYS[0]
node_name = NAME_GETTERS[0]
for concept in lattice._concepts:
name = node_name(concept)
dot.node(name)
if concept.objects:
dot.edge(name, name,
headlabel=' '.join(concept.objects),
labelangle='270', color='transparent')
if concept.properties:
dot.edge(name, name,
taillabel=' '.join(concept.properties),
labelangle='90', color='transparent')
dot.edges((name, node_name(c))
for c in sorted(concept.lower_neighbors, key=sortkey))
if render or view:
dot.render(view=view) # pragma: no cover
return dot | [
"def",
"lattice",
"(",
"lattice",
",",
"filename",
",",
"directory",
",",
"render",
",",
"view",
",",
"*",
"*",
"kwargs",
")",
":",
"dot",
"=",
"graphviz",
".",
"Digraph",
"(",
"name",
"=",
"lattice",
".",
"__class__",
".",
"__name__",
",",
"comment",
... | Return graphviz source for visualizing the lattice graph. | [
"Return",
"graphviz",
"source",
"for",
"visualizing",
"the",
"lattice",
"graph",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/visualize.py#L15-L50 | train | 23,997 |
xflr6/concepts | concepts/formats.py | Format.load | def load(cls, filename, encoding):
"""Load and parse serialized objects, properties, bools from file."""
if encoding is None:
encoding = cls.encoding
with io.open(filename, 'r', encoding=encoding) as fd:
source = fd.read()
if cls.normalize_newlines:
source = source.replace('\r\n', '\n').replace('\r', '\n')
return cls.loads(source) | python | def load(cls, filename, encoding):
"""Load and parse serialized objects, properties, bools from file."""
if encoding is None:
encoding = cls.encoding
with io.open(filename, 'r', encoding=encoding) as fd:
source = fd.read()
if cls.normalize_newlines:
source = source.replace('\r\n', '\n').replace('\r', '\n')
return cls.loads(source) | [
"def",
"load",
"(",
"cls",
",",
"filename",
",",
"encoding",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"cls",
".",
"encoding",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"encoding",
")",
"as",
... | Load and parse serialized objects, properties, bools from file. | [
"Load",
"and",
"parse",
"serialized",
"objects",
"properties",
"bools",
"from",
"file",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/formats.py#L67-L77 | train | 23,998 |
xflr6/concepts | concepts/formats.py | Format.dump | def dump(cls, filename, objects, properties, bools, encoding):
"""Write serialized objects, properties, bools to file."""
if encoding is None:
encoding = cls.encoding
source = cls.dumps(objects, properties, bools)
if PY2:
source = unicode(source)
with io.open(filename, 'w', encoding=encoding) as fd:
fd.write(source) | python | def dump(cls, filename, objects, properties, bools, encoding):
"""Write serialized objects, properties, bools to file."""
if encoding is None:
encoding = cls.encoding
source = cls.dumps(objects, properties, bools)
if PY2:
source = unicode(source)
with io.open(filename, 'w', encoding=encoding) as fd:
fd.write(source) | [
"def",
"dump",
"(",
"cls",
",",
"filename",
",",
"objects",
",",
"properties",
",",
"bools",
",",
"encoding",
")",
":",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"cls",
".",
"encoding",
"source",
"=",
"cls",
".",
"dumps",
"(",
"objects",
... | Write serialized objects, properties, bools to file. | [
"Write",
"serialized",
"objects",
"properties",
"bools",
"to",
"file",
"."
] | 2801b27b05fa02cccee7d549451810ffcbf5c942 | https://github.com/xflr6/concepts/blob/2801b27b05fa02cccee7d549451810ffcbf5c942/concepts/formats.py#L80-L90 | train | 23,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.