partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | AES.decrypt | Decrypt a block of cipher text using the AES block cipher. | pyaes/aes.py | def decrypt(self, ciphertext):
'Decrypt a block of cipher text using the AES block cipher.'
if len(ciphertext) != 16:
raise ValueError('wrong block length')
rounds = len(self._Kd) - 1
(s1, s2, s3) = [3, 2, 1]
a = [0, 0, 0, 0]
# Convert ciphertext to (ints ^... | def decrypt(self, ciphertext):
'Decrypt a block of cipher text using the AES block cipher.'
if len(ciphertext) != 16:
raise ValueError('wrong block length')
rounds = len(self._Kd) - 1
(s1, s2, s3) = [3, 2, 1]
a = [0, 0, 0, 0]
# Convert ciphertext to (ints ^... | [
"Decrypt",
"a",
"block",
"of",
"cipher",
"text",
"using",
"the",
"AES",
"block",
"cipher",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/pyaes/aes.py#L237-L269 | [
"def",
"decrypt",
"(",
"self",
",",
"ciphertext",
")",
":",
"if",
"len",
"(",
"ciphertext",
")",
"!=",
"16",
":",
"raise",
"ValueError",
"(",
"'wrong block length'",
")",
"rounds",
"=",
"len",
"(",
"self",
".",
"_Kd",
")",
"-",
"1",
"(",
"s1",
",",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | Counter.increment | Increment the counter (overflow rolls back to 0). | pyaes/aes.py | def increment(self):
'''Increment the counter (overflow rolls back to 0).'''
for i in xrange(len(self._counter) - 1, -1, -1):
self._counter[i] += 1
if self._counter[i] < 256: break
# Carry the one
self._counter[i] = 0
# Overflow
else:
... | def increment(self):
'''Increment the counter (overflow rolls back to 0).'''
for i in xrange(len(self._counter) - 1, -1, -1):
self._counter[i] += 1
if self._counter[i] < 256: break
# Carry the one
self._counter[i] = 0
# Overflow
else:
... | [
"Increment",
"the",
"counter",
"(",
"overflow",
"rolls",
"back",
"to",
"0",
")",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/pyaes/aes.py#L285-L298 | [
"def",
"increment",
"(",
"self",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"_counter",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"self",
".",
"_counter",
"[",
"i",
"]",
"+=",
"1",
"if",
"self",
".",
"_... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | dump | Dump raw efuse data registers | espefuse.py | def dump(esp, _efuses, args):
""" Dump raw efuse data registers """
for block in range(len(EFUSE_BLOCK_OFFS)):
print("EFUSE block %d:" % block)
offsets = [x + EFUSE_BLOCK_OFFS[block] for x in range(EFUSE_BLOCK_LEN[block])]
print(" ".join(["%08x" % esp.read_efuse(offs) for offs in offsets... | def dump(esp, _efuses, args):
""" Dump raw efuse data registers """
for block in range(len(EFUSE_BLOCK_OFFS)):
print("EFUSE block %d:" % block)
offsets = [x + EFUSE_BLOCK_OFFS[block] for x in range(EFUSE_BLOCK_LEN[block])]
print(" ".join(["%08x" % esp.read_efuse(offs) for offs in offsets... | [
"Dump",
"raw",
"efuse",
"data",
"registers"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espefuse.py#L488-L493 | [
"def",
"dump",
"(",
"esp",
",",
"_efuses",
",",
"args",
")",
":",
"for",
"block",
"in",
"range",
"(",
"len",
"(",
"EFUSE_BLOCK_OFFS",
")",
")",
":",
"print",
"(",
"\"EFUSE block %d:\"",
"%",
"block",
")",
"offsets",
"=",
"[",
"x",
"+",
"EFUSE_BLOCK_OFF... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | summary | Print a human-readable summary of efuse contents | espefuse.py | def summary(esp, efuses, args):
""" Print a human-readable summary of efuse contents """
ROW_FORMAT = "%-22s %-50s%s= %s %s %s"
print(ROW_FORMAT.replace("-50", "-12") % ("EFUSE_NAME", "Description", "", "[Meaningful Value]", "[Readable/Writeable]", "(Hex Value)"))
print("-" * 88)
for category in set... | def summary(esp, efuses, args):
""" Print a human-readable summary of efuse contents """
ROW_FORMAT = "%-22s %-50s%s= %s %s %s"
print(ROW_FORMAT.replace("-50", "-12") % ("EFUSE_NAME", "Description", "", "[Meaningful Value]", "[Readable/Writeable]", "(Hex Value)"))
print("-" * 88)
for category in set... | [
"Print",
"a",
"human",
"-",
"readable",
"summary",
"of",
"efuse",
"contents"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espefuse.py#L496-L536 | [
"def",
"summary",
"(",
"esp",
",",
"efuses",
",",
"args",
")",
":",
"ROW_FORMAT",
"=",
"\"%-22s %-50s%s= %s %s %s\"",
"print",
"(",
"ROW_FORMAT",
".",
"replace",
"(",
"\"-50\"",
",",
"\"-12\"",
")",
"%",
"(",
"\"EFUSE_NAME\"",
",",
"\"Description\"",
",",
"\... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | EspEfuses.write_efuses | Write the values in the efuse write registers to
the efuse hardware, then refresh the efuse read registers. | espefuse.py | def write_efuses(self):
""" Write the values in the efuse write registers to
the efuse hardware, then refresh the efuse read registers.
"""
# Configure clock
apb_freq = self._esp.get_crystal_freq()
clk_sel0, clk_sel1, dac_clk_div = EFUSE_CLK_SETTINGS[apb_freq]
s... | def write_efuses(self):
""" Write the values in the efuse write registers to
the efuse hardware, then refresh the efuse read registers.
"""
# Configure clock
apb_freq = self._esp.get_crystal_freq()
clk_sel0, clk_sel1, dac_clk_div = EFUSE_CLK_SETTINGS[apb_freq]
s... | [
"Write",
"the",
"values",
"in",
"the",
"efuse",
"write",
"registers",
"to",
"the",
"efuse",
"hardware",
"then",
"refresh",
"the",
"efuse",
"read",
"registers",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espefuse.py#L168-L193 | [
"def",
"write_efuses",
"(",
"self",
")",
":",
"# Configure clock",
"apb_freq",
"=",
"self",
".",
"_esp",
".",
"get_crystal_freq",
"(",
")",
"clk_sel0",
",",
"clk_sel1",
",",
"dac_clk_div",
"=",
"EFUSE_CLK_SETTINGS",
"[",
"apb_freq",
"]",
"self",
".",
"update_r... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | EfuseField.get_raw | Return the raw (unformatted) numeric value of the efuse bits
Returns a simple integer or (for some subclasses) a bitstring. | espefuse.py | def get_raw(self):
""" Return the raw (unformatted) numeric value of the efuse bits
Returns a simple integer or (for some subclasses) a bitstring.
"""
value = self.parent.read_efuse(self.data_reg_offs)
return (value & self.mask) >> self.shift | def get_raw(self):
""" Return the raw (unformatted) numeric value of the efuse bits
Returns a simple integer or (for some subclasses) a bitstring.
"""
value = self.parent.read_efuse(self.data_reg_offs)
return (value & self.mask) >> self.shift | [
"Return",
"the",
"raw",
"(",
"unformatted",
")",
"numeric",
"value",
"of",
"the",
"efuse",
"bits"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espefuse.py#L245-L251 | [
"def",
"get_raw",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"parent",
".",
"read_efuse",
"(",
"self",
".",
"data_reg_offs",
")",
"return",
"(",
"value",
"&",
"self",
".",
"mask",
")",
">>",
"self",
".",
"shift"
] | c583756c118039cfcfe256f7a3285618914d16a5 |
train | EfuseField.is_readable | Return true if the efuse is readable by software | espefuse.py | def is_readable(self):
""" Return true if the efuse is readable by software """
if self.read_disable_bit is None:
return True # read cannot be disabled
value = (self.parent.read_efuse(0) >> 16) & 0xF # RD_DIS values
return (value & (1 << self.read_disable_bit)) == 0 | def is_readable(self):
""" Return true if the efuse is readable by software """
if self.read_disable_bit is None:
return True # read cannot be disabled
value = (self.parent.read_efuse(0) >> 16) & 0xF # RD_DIS values
return (value & (1 << self.read_disable_bit)) == 0 | [
"Return",
"true",
"if",
"the",
"efuse",
"is",
"readable",
"by",
"software"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espefuse.py#L257-L262 | [
"def",
"is_readable",
"(",
"self",
")",
":",
"if",
"self",
".",
"read_disable_bit",
"is",
"None",
":",
"return",
"True",
"# read cannot be disabled",
"value",
"=",
"(",
"self",
".",
"parent",
".",
"read_efuse",
"(",
"0",
")",
">>",
"16",
")",
"&",
"0xF",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | EfuseMacField.calc_crc | This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00. | espefuse.py | def calc_crc(raw_mac):
"""
This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00.
"""
result = 0x00
for b in struct.unpack("B" * 6, raw_mac):
result ^= b
for _ in rang... | def calc_crc(raw_mac):
"""
This algorithm is the equivalent of esp_crc8() in ESP32 ROM code
This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00.
"""
result = 0x00
for b in struct.unpack("B" * 6, raw_mac):
result ^= b
for _ in rang... | [
"This",
"algorithm",
"is",
"the",
"equivalent",
"of",
"esp_crc8",
"()",
"in",
"ESP32",
"ROM",
"code"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espefuse.py#L318-L332 | [
"def",
"calc_crc",
"(",
"raw_mac",
")",
":",
"result",
"=",
"0x00",
"for",
"b",
"in",
"struct",
".",
"unpack",
"(",
"\"B\"",
"*",
"6",
",",
"raw_mac",
")",
":",
"result",
"^=",
"b",
"for",
"_",
"in",
"range",
"(",
"8",
")",
":",
"lsb",
"=",
"re... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | EfuseKeyblockField.apply_34_encoding | Takes 24 byte sequence to be represented in 3/4 encoding,
returns 8 words suitable for writing "encoded" to an efuse block | espefuse.py | def apply_34_encoding(self, inbits):
""" Takes 24 byte sequence to be represented in 3/4 encoding,
returns 8 words suitable for writing "encoded" to an efuse block
"""
def popcnt(b):
""" Return number of "1" bits set in 'b' """
return len([x for x in bin(b) if... | def apply_34_encoding(self, inbits):
""" Takes 24 byte sequence to be represented in 3/4 encoding,
returns 8 words suitable for writing "encoded" to an efuse block
"""
def popcnt(b):
""" Return number of "1" bits set in 'b' """
return len([x for x in bin(b) if... | [
"Takes",
"24",
"byte",
"sequence",
"to",
"be",
"represented",
"in",
"3",
"/",
"4",
"encoding",
"returns",
"8",
"words",
"suitable",
"for",
"writing",
"encoded",
"to",
"an",
"efuse",
"block"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espefuse.py#L381-L402 | [
"def",
"apply_34_encoding",
"(",
"self",
",",
"inbits",
")",
":",
"def",
"popcnt",
"(",
"b",
")",
":",
"\"\"\" Return number of \"1\" bits set in 'b' \"\"\"",
"return",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"bin",
"(",
"b",
")",
"if",
"x",
"==",
"\"1\"",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | CurveFp.contains_point | Is the point (x,y) on this curve? | ecdsa/ellipticcurve.py | def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 | def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0 | [
"Is",
"the",
"point",
"(",
"x",
"y",
")",
"on",
"this",
"curve?"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ellipticcurve.py#L57-L59 | [
"def",
"contains_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"(",
"y",
"*",
"y",
"-",
"(",
"x",
"*",
"x",
"*",
"x",
"+",
"self",
".",
"__a",
"*",
"x",
"+",
"self",
".",
"__b",
")",
")",
"%",
"self",
".",
"__p",
"==",
"0"
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | Point.double | Return a new point that is twice the old. | ecdsa/ellipticcurve.py | def double( self ):
"""Return a new point that is twice the old."""
if self == INFINITY:
return INFINITY
# X9.62 B.3:
p = self.__curve.p()
a = self.__curve.a()
l = ( ( 3 * self.__x * self.__x + a ) * \
numbertheory.inverse_mod( 2 * self.__y, p ) ) % p
x3 = ( l * l - 2 * ... | def double( self ):
"""Return a new point that is twice the old."""
if self == INFINITY:
return INFINITY
# X9.62 B.3:
p = self.__curve.p()
a = self.__curve.a()
l = ( ( 3 * self.__x * self.__x + a ) * \
numbertheory.inverse_mod( 2 * self.__y, p ) ) % p
x3 = ( l * l - 2 * ... | [
"Return",
"a",
"new",
"point",
"that",
"is",
"twice",
"the",
"old",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ellipticcurve.py#L149-L166 | [
"def",
"double",
"(",
"self",
")",
":",
"if",
"self",
"==",
"INFINITY",
":",
"return",
"INFINITY",
"# X9.62 B.3:",
"p",
"=",
"self",
".",
"__curve",
".",
"p",
"(",
")",
"a",
"=",
"self",
".",
"__curve",
".",
"a",
"(",
")",
"l",
"=",
"(",
"(",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | timeout_per_mb | Scales timeouts which are size-specific | esptool.py | def timeout_per_mb(seconds_per_mb, size_bytes):
""" Scales timeouts which are size-specific """
result = seconds_per_mb * (size_bytes / 1e6)
if result < DEFAULT_TIMEOUT:
return DEFAULT_TIMEOUT
return result | def timeout_per_mb(seconds_per_mb, size_bytes):
""" Scales timeouts which are size-specific """
result = seconds_per_mb * (size_bytes / 1e6)
if result < DEFAULT_TIMEOUT:
return DEFAULT_TIMEOUT
return result | [
"Scales",
"timeouts",
"which",
"are",
"size",
"-",
"specific"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L79-L84 | [
"def",
"timeout_per_mb",
"(",
"seconds_per_mb",
",",
"size_bytes",
")",
":",
"result",
"=",
"seconds_per_mb",
"*",
"(",
"size_bytes",
"/",
"1e6",
")",
"if",
"result",
"<",
"DEFAULT_TIMEOUT",
":",
"return",
"DEFAULT_TIMEOUT",
"return",
"result"
] | c583756c118039cfcfe256f7a3285618914d16a5 |
train | check_supported_function | Decorator implementation that wraps a check around an ESPLoader
bootloader function to check if it's supported.
This is used to capture the multidimensional differences in
functionality between the ESP8266 & ESP32 ROM loaders, and the
software stub that runs on both. Not possible to do this cleanly
... | esptool.py | def check_supported_function(func, check_func):
"""
Decorator implementation that wraps a check around an ESPLoader
bootloader function to check if it's supported.
This is used to capture the multidimensional differences in
functionality between the ESP8266 & ESP32 ROM loaders, and the
software... | def check_supported_function(func, check_func):
"""
Decorator implementation that wraps a check around an ESPLoader
bootloader function to check if it's supported.
This is used to capture the multidimensional differences in
functionality between the ESP8266 & ESP32 ROM loaders, and the
software... | [
"Decorator",
"implementation",
"that",
"wraps",
"a",
"check",
"around",
"an",
"ESPLoader",
"bootloader",
"function",
"to",
"check",
"if",
"it",
"s",
"supported",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L91-L107 | [
"def",
"check_supported_function",
"(",
"func",
",",
"check_func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"args",
"[",
"0",
"]",
"if",
"check_func",
"(",
"obj",
")",
":",
"return",
"func",
"(",
"*... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | LoadFirmwareImage | Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2). | esptool.py | def LoadFirmwareImage(chip, filename):
""" Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwa... | def LoadFirmwareImage(chip, filename):
""" Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are
original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images.
Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwa... | [
"Load",
"a",
"firmware",
"image",
".",
"Can",
"be",
"for",
"ESP8266",
"or",
"ESP32",
".",
"ESP8266",
"images",
"will",
"be",
"examined",
"to",
"determine",
"if",
"they",
"are",
"original",
"ROM",
"firmware",
"images",
"(",
"ESP8266ROMFirmwareImage",
")",
"or... | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1333-L1350 | [
"def",
"LoadFirmwareImage",
"(",
"chip",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"if",
"chip",
".",
"lower",
"(",
")",
"==",
"'esp32'",
":",
"return",
"ESP32FirmwareImage",
"(",
"f",
")",
"else",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | slip_reader | Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems. | esptool.py | def slip_reader(port, trace_function):
"""Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems.
"""
partial_packet = None
... | def slip_reader(port, trace_function):
"""Generator to read SLIP packets from a serial port.
Yields one full SLIP packet at a time, raises exception on timeout or invalid data.
Designed to avoid too many calls to serial.read(1), which can bog
down on slow systems.
"""
partial_packet = None
... | [
"Generator",
"to",
"read",
"SLIP",
"packets",
"from",
"a",
"serial",
"port",
".",
"Yields",
"one",
"full",
"SLIP",
"packet",
"at",
"a",
"time",
"raises",
"exception",
"on",
"timeout",
"or",
"invalid",
"data",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1978-L2023 | [
"def",
"slip_reader",
"(",
"port",
",",
"trace_function",
")",
":",
"partial_packet",
"=",
"None",
"in_escape",
"=",
"False",
"while",
"True",
":",
"waiting",
"=",
"port",
".",
"inWaiting",
"(",
")",
"read_bytes",
"=",
"port",
".",
"read",
"(",
"1",
"if"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | align_file_position | Align the position in the file to the next block of specified size | esptool.py | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) | def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) | [
"Align",
"the",
"position",
"in",
"the",
"file",
"to",
"the",
"next",
"block",
"of",
"specified",
"size"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L2038-L2041 | [
"def",
"align_file_position",
"(",
"f",
",",
"size",
")",
":",
"align",
"=",
"(",
"size",
"-",
"1",
")",
"-",
"(",
"f",
".",
"tell",
"(",
")",
"%",
"size",
")",
"f",
".",
"seek",
"(",
"align",
",",
"1",
")"
] | c583756c118039cfcfe256f7a3285618914d16a5 |
train | flash_size_bytes | Given a flash size of the type passed in args.flash_size
(ie 512KB or 1MB) then return the size in bytes. | esptool.py | def flash_size_bytes(size):
""" Given a flash size of the type passed in args.flash_size
(ie 512KB or 1MB) then return the size in bytes.
"""
if "MB" in size:
return int(size[:size.index("MB")]) * 1024 * 1024
elif "KB" in size:
return int(size[:size.index("KB")]) * 1024
else:
... | def flash_size_bytes(size):
""" Given a flash size of the type passed in args.flash_size
(ie 512KB or 1MB) then return the size in bytes.
"""
if "MB" in size:
return int(size[:size.index("MB")]) * 1024 * 1024
elif "KB" in size:
return int(size[:size.index("KB")]) * 1024
else:
... | [
"Given",
"a",
"flash",
"size",
"of",
"the",
"type",
"passed",
"in",
"args",
".",
"flash_size",
"(",
"ie",
"512KB",
"or",
"1MB",
")",
"then",
"return",
"the",
"size",
"in",
"bytes",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L2044-L2053 | [
"def",
"flash_size_bytes",
"(",
"size",
")",
":",
"if",
"\"MB\"",
"in",
"size",
":",
"return",
"int",
"(",
"size",
"[",
":",
"size",
".",
"index",
"(",
"\"MB\"",
")",
"]",
")",
"*",
"1024",
"*",
"1024",
"elif",
"\"KB\"",
"in",
"size",
":",
"return"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | pad_to | Pad to the next alignment boundary | esptool.py | def pad_to(data, alignment, pad_character=b'\xFF'):
""" Pad to the next alignment boundary """
pad_mod = len(data) % alignment
if pad_mod != 0:
data += pad_character * (alignment - pad_mod)
return data | def pad_to(data, alignment, pad_character=b'\xFF'):
""" Pad to the next alignment boundary """
pad_mod = len(data) % alignment
if pad_mod != 0:
data += pad_character * (alignment - pad_mod)
return data | [
"Pad",
"to",
"the",
"next",
"alignment",
"boundary"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L2099-L2104 | [
"def",
"pad_to",
"(",
"data",
",",
"alignment",
",",
"pad_character",
"=",
"b'\\xFF'",
")",
":",
"pad_mod",
"=",
"len",
"(",
"data",
")",
"%",
"alignment",
"if",
"pad_mod",
"!=",
"0",
":",
"data",
"+=",
"pad_character",
"*",
"(",
"alignment",
"-",
"pad... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | _update_image_flash_params | Modify the flash mode & size bytes if this looks like an executable bootloader image | esptool.py | def _update_image_flash_params(esp, address, args, image):
""" Modify the flash mode & size bytes if this looks like an executable bootloader image """
if len(image) < 8:
return image # not long enough to be a bootloader image
# unpack the (potential) image header
magic, _, flash_mode, flash_... | def _update_image_flash_params(esp, address, args, image):
""" Modify the flash mode & size bytes if this looks like an executable bootloader image """
if len(image) < 8:
return image # not long enough to be a bootloader image
# unpack the (potential) image header
magic, _, flash_mode, flash_... | [
"Modify",
"the",
"flash",
"mode",
"&",
"size",
"bytes",
"if",
"this",
"looks",
"like",
"an",
"executable",
"bootloader",
"image"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L2199-L2224 | [
"def",
"_update_image_flash_params",
"(",
"esp",
",",
"address",
",",
"args",
",",
"image",
")",
":",
"if",
"len",
"(",
"image",
")",
"<",
"8",
":",
"return",
"image",
"# not long enough to be a bootloader image",
"# unpack the (potential) image header",
"magic",
",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | main | Main function for esptool
custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus
becomes ['-b', '115200']. | esptool.py | def main(custom_commandline=None):
"""
Main function for esptool
custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus
... | def main(custom_commandline=None):
"""
Main function for esptool
custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus
... | [
"Main",
"function",
"for",
"esptool"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L2546-L2892 | [
"def",
"main",
"(",
"custom_commandline",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'esptool.py v%s - ESP8266 ROM Bootloader Utility'",
"%",
"__version__",
",",
"prog",
"=",
"'esptool'",
")",
"parser",
".",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | expand_file_arguments | Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line. | esptool.py | def expand_file_arguments():
""" Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
"""
new_args = []
expanded = False
... | def expand_file_arguments():
""" Any argument starting with "@" gets replaced with all values read from a text file.
Text file arguments can be split by newline or by space.
Values are added "as-is", as if they were specified in this order on the command line.
"""
new_args = []
expanded = False
... | [
"Any",
"argument",
"starting",
"with"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L2895-L2912 | [
"def",
"expand_file_arguments",
"(",
")",
":",
"new_args",
"=",
"[",
"]",
"expanded",
"=",
"False",
"for",
"arg",
"in",
"sys",
".",
"argv",
":",
"if",
"arg",
".",
"startswith",
"(",
"\"@\"",
")",
":",
"expanded",
"=",
"True",
"with",
"open",
"(",
"ar... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.detect_chip | Use serial access to detect the chip type.
We use the UART's datecode register for this, it's mapped at
the same address on ESP8266 & ESP32 so we can use one
memory read and compare to the datecode register for each chip
type.
This routine automatically performs ESPLoader.conne... | esptool.py | def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset', trace_enabled=False):
""" Use serial access to detect the chip type.
We use the UART's datecode register for this, it's mapped at
the same address on ESP8266 & ESP32 so we can use one
memory read and com... | def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset', trace_enabled=False):
""" Use serial access to detect the chip type.
We use the UART's datecode register for this, it's mapped at
the same address on ESP8266 & ESP32 so we can use one
memory read and com... | [
"Use",
"serial",
"access",
"to",
"detect",
"the",
"chip",
"type",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L262-L288 | [
"def",
"detect_chip",
"(",
"port",
"=",
"DEFAULT_PORT",
",",
"baud",
"=",
"ESP_ROM_BAUD",
",",
"connect_mode",
"=",
"'default_reset'",
",",
"trace_enabled",
"=",
"False",
")",
":",
"detect_port",
"=",
"ESPLoader",
"(",
"port",
",",
"baud",
",",
"trace_enabled"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.check_command | Execute a command with 'command', check the result code and throw an appropriate
FatalError if it fails.
Returns the "result" of a successful command. | esptool.py | def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT):
"""
Execute a command with 'command', check the result code and throw an appropriate
FatalError if it fails.
Returns the "result" of a successful command.
"""
val, data = self.com... | def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT):
"""
Execute a command with 'command', check the result code and throw an appropriate
FatalError if it fails.
Returns the "result" of a successful command.
"""
val, data = self.com... | [
"Execute",
"a",
"command",
"with",
"command",
"check",
"the",
"result",
"code",
"and",
"throw",
"an",
"appropriate",
"FatalError",
"if",
"it",
"fails",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L362-L386 | [
"def",
"check_command",
"(",
"self",
",",
"op_description",
",",
"op",
"=",
"None",
",",
"data",
"=",
"b''",
",",
"chk",
"=",
"0",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"val",
",",
"data",
"=",
"self",
".",
"command",
"(",
"op",
",",
"d... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader._connect_attempt | A single connection attempt, with esp32r0 workaround options | esptool.py | def _connect_attempt(self, mode='default_reset', esp32r0_delay=False):
""" A single connection attempt, with esp32r0 workaround options """
# esp32r0_delay is a workaround for bugs with the most common auto reset
# circuit and Windows, if the EN pin on the dev board does not have
# enoug... | def _connect_attempt(self, mode='default_reset', esp32r0_delay=False):
""" A single connection attempt, with esp32r0 workaround options """
# esp32r0_delay is a workaround for bugs with the most common auto reset
# circuit and Windows, if the EN pin on the dev board does not have
# enoug... | [
"A",
"single",
"connection",
"attempt",
"with",
"esp32r0",
"workaround",
"options"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L408-L465 | [
"def",
"_connect_attempt",
"(",
"self",
",",
"mode",
"=",
"'default_reset'",
",",
"esp32r0_delay",
"=",
"False",
")",
":",
"# esp32r0_delay is a workaround for bugs with the most common auto reset",
"# circuit and Windows, if the EN pin on the dev board does not have",
"# enough capa... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.connect | Try connecting repeatedly until successful, or giving up | esptool.py | def connect(self, mode='default_reset'):
""" Try connecting repeatedly until successful, or giving up """
print('Connecting...', end='')
sys.stdout.flush()
last_error = None
try:
for _ in range(7):
last_error = self._connect_attempt(mode=mode, esp32r0... | def connect(self, mode='default_reset'):
""" Try connecting repeatedly until successful, or giving up """
print('Connecting...', end='')
sys.stdout.flush()
last_error = None
try:
for _ in range(7):
last_error = self._connect_attempt(mode=mode, esp32r0... | [
"Try",
"connecting",
"repeatedly",
"until",
"successful",
"or",
"giving",
"up"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L467-L483 | [
"def",
"connect",
"(",
"self",
",",
"mode",
"=",
"'default_reset'",
")",
":",
"print",
"(",
"'Connecting...'",
",",
"end",
"=",
"''",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"last_error",
"=",
"None",
"try",
":",
"for",
"_",
"in",
"range",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.read_reg | Read memory address in target | esptool.py | def read_reg(self, addr):
""" Read memory address in target """
# we don't call check_command here because read_reg() function is called
# when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different
# for different chip types (!)
val, data = self... | def read_reg(self, addr):
""" Read memory address in target """
# we don't call check_command here because read_reg() function is called
# when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different
# for different chip types (!)
val, data = self... | [
"Read",
"memory",
"address",
"in",
"target"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L485-L493 | [
"def",
"read_reg",
"(",
"self",
",",
"addr",
")",
":",
"# we don't call check_command here because read_reg() function is called",
"# when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different",
"# for different chip types (!)",
"val",
",",
"data",
"=",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.write_reg | Write to memory address in target
Note: mask option is not supported by stub loaders, use update_reg() function. | esptool.py | def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0):
""" Write to memory address in target
Note: mask option is not supported by stub loaders, use update_reg() function.
"""
return self.check_command("write target memory", self.ESP_WRITE_REG,
... | def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0):
""" Write to memory address in target
Note: mask option is not supported by stub loaders, use update_reg() function.
"""
return self.check_command("write target memory", self.ESP_WRITE_REG,
... | [
"Write",
"to",
"memory",
"address",
"in",
"target"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L495-L501 | [
"def",
"write_reg",
"(",
"self",
",",
"addr",
",",
"value",
",",
"mask",
"=",
"0xFFFFFFFF",
",",
"delay_us",
"=",
"0",
")",
":",
"return",
"self",
".",
"check_command",
"(",
"\"write target memory\"",
",",
"self",
".",
"ESP_WRITE_REG",
",",
"struct",
".",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.update_reg | Update register at 'addr', replace the bits masked out by 'mask'
with new_val. new_val is shifted left to match the LSB of 'mask'
Returns just-written value of register. | esptool.py | def update_reg(self, addr, mask, new_val):
""" Update register at 'addr', replace the bits masked out by 'mask'
with new_val. new_val is shifted left to match the LSB of 'mask'
Returns just-written value of register.
"""
shift = _mask_to_shift(mask)
val = self.read_reg(a... | def update_reg(self, addr, mask, new_val):
""" Update register at 'addr', replace the bits masked out by 'mask'
with new_val. new_val is shifted left to match the LSB of 'mask'
Returns just-written value of register.
"""
shift = _mask_to_shift(mask)
val = self.read_reg(a... | [
"Update",
"register",
"at",
"addr",
"replace",
"the",
"bits",
"masked",
"out",
"by",
"mask",
"with",
"new_val",
".",
"new_val",
"is",
"shifted",
"left",
"to",
"match",
"the",
"LSB",
"of",
"mask"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L503-L515 | [
"def",
"update_reg",
"(",
"self",
",",
"addr",
",",
"mask",
",",
"new_val",
")",
":",
"shift",
"=",
"_mask_to_shift",
"(",
"mask",
")",
"val",
"=",
"self",
".",
"read_reg",
"(",
"addr",
")",
"val",
"&=",
"~",
"mask",
"val",
"|=",
"(",
"new_val",
"<... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.flash_defl_begin | Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write. | esptool.py | def flash_defl_begin(self, size, compsize, offset):
""" Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
"""
num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
erase_blocks = ... | def flash_defl_begin(self, size, compsize, offset):
""" Start downloading compressed data to Flash (performs an erase)
Returns number of blocks (size self.FLASH_WRITE_SIZE) to write.
"""
num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE
erase_blocks = ... | [
"Start",
"downloading",
"compressed",
"data",
"to",
"Flash",
"(",
"performs",
"an",
"erase",
")"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L644-L666 | [
"def",
"flash_defl_begin",
"(",
"self",
",",
"size",
",",
"compsize",
",",
"offset",
")",
":",
"num_blocks",
"=",
"(",
"compsize",
"+",
"self",
".",
"FLASH_WRITE_SIZE",
"-",
"1",
")",
"//",
"self",
".",
"FLASH_WRITE_SIZE",
"erase_blocks",
"=",
"(",
"size",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.flash_spi_attach | Send SPI attach command to enable the SPI flash pins
ESP8266 ROM does this when you send flash_begin, ESP32 ROM
has it as a SPI command. | esptool.py | def flash_spi_attach(self, hspi_arg):
"""Send SPI attach command to enable the SPI flash pins
ESP8266 ROM does this when you send flash_begin, ESP32 ROM
has it as a SPI command.
"""
# last 3 bytes in ESP_SPI_ATTACH argument are reserved values
arg = struct.pack('<I', hsp... | def flash_spi_attach(self, hspi_arg):
"""Send SPI attach command to enable the SPI flash pins
ESP8266 ROM does this when you send flash_begin, ESP32 ROM
has it as a SPI command.
"""
# last 3 bytes in ESP_SPI_ATTACH argument are reserved values
arg = struct.pack('<I', hsp... | [
"Send",
"SPI",
"attach",
"command",
"to",
"enable",
"the",
"SPI",
"flash",
"pins"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L759-L772 | [
"def",
"flash_spi_attach",
"(",
"self",
",",
"hspi_arg",
")",
":",
"# last 3 bytes in ESP_SPI_ATTACH argument are reserved values",
"arg",
"=",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"hspi_arg",
")",
"if",
"not",
"self",
".",
"IS_STUB",
":",
"# ESP32 ROM loader ta... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.flash_set_parameters | Tell the ESP bootloader the parameters of the chip
Corresponds to the "flashchip" data structure that the ROM
has in RAM.
'size' is in bytes.
All other flash parameters are currently hardcoded (on ESP8266
these are mostly ignored by ROM code, on ESP32 I'm not sure.) | esptool.py | def flash_set_parameters(self, size):
"""Tell the ESP bootloader the parameters of the chip
Corresponds to the "flashchip" data structure that the ROM
has in RAM.
'size' is in bytes.
All other flash parameters are currently hardcoded (on ESP8266
these are mostly ignore... | def flash_set_parameters(self, size):
"""Tell the ESP bootloader the parameters of the chip
Corresponds to the "flashchip" data structure that the ROM
has in RAM.
'size' is in bytes.
All other flash parameters are currently hardcoded (on ESP8266
these are mostly ignore... | [
"Tell",
"the",
"ESP",
"bootloader",
"the",
"parameters",
"of",
"the",
"chip"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L774-L792 | [
"def",
"flash_set_parameters",
"(",
"self",
",",
"size",
")",
":",
"fl_id",
"=",
"0",
"total_size",
"=",
"size",
"block_size",
"=",
"64",
"*",
"1024",
"sector_size",
"=",
"4",
"*",
"1024",
"page_size",
"=",
"256",
"status_mask",
"=",
"0xffff",
"self",
".... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.run_spiflash_command | Run an arbitrary SPI flash command.
This function uses the "USR_COMMAND" functionality in the ESP
SPI hardware, rather than the precanned commands supported by
hardware. So the value of spiflash_command is an actual command
byte, sent over the wire.
After writing command byte, ... | esptool.py | def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0):
"""Run an arbitrary SPI flash command.
This function uses the "USR_COMMAND" functionality in the ESP
SPI hardware, rather than the precanned commands supported by
hardware. So the value of spiflash_command is an ac... | def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0):
"""Run an arbitrary SPI flash command.
This function uses the "USR_COMMAND" functionality in the ESP
SPI hardware, rather than the precanned commands supported by
hardware. So the value of spiflash_command is an ac... | [
"Run",
"an",
"arbitrary",
"SPI",
"flash",
"command",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L794-L886 | [
"def",
"run_spiflash_command",
"(",
"self",
",",
"spiflash_command",
",",
"data",
"=",
"b\"\"",
",",
"read_bits",
"=",
"0",
")",
":",
"# SPI_USR register flags",
"SPI_USR_COMMAND",
"=",
"(",
"1",
"<<",
"31",
")",
"SPI_USR_MISO",
"=",
"(",
"1",
"<<",
"28",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.read_status | Read up to 24 bits (num_bytes) of SPI flash status register contents
via RDSR, RDSR2, RDSR3 commands
Not all SPI flash supports all three commands. The upper 1 or 2
bytes may be 0xFF. | esptool.py | def read_status(self, num_bytes=2):
"""Read up to 24 bits (num_bytes) of SPI flash status register contents
via RDSR, RDSR2, RDSR3 commands
Not all SPI flash supports all three commands. The upper 1 or 2
bytes may be 0xFF.
"""
SPIFLASH_RDSR = 0x05
SPIFLASH_RDSR2... | def read_status(self, num_bytes=2):
"""Read up to 24 bits (num_bytes) of SPI flash status register contents
via RDSR, RDSR2, RDSR3 commands
Not all SPI flash supports all three commands. The upper 1 or 2
bytes may be 0xFF.
"""
SPIFLASH_RDSR = 0x05
SPIFLASH_RDSR2... | [
"Read",
"up",
"to",
"24",
"bits",
"(",
"num_bytes",
")",
"of",
"SPI",
"flash",
"status",
"register",
"contents",
"via",
"RDSR",
"RDSR2",
"RDSR3",
"commands"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L888-L904 | [
"def",
"read_status",
"(",
"self",
",",
"num_bytes",
"=",
"2",
")",
":",
"SPIFLASH_RDSR",
"=",
"0x05",
"SPIFLASH_RDSR2",
"=",
"0x35",
"SPIFLASH_RDSR3",
"=",
"0x15",
"status",
"=",
"0",
"shift",
"=",
"0",
"for",
"cmd",
"in",
"[",
"SPIFLASH_RDSR",
",",
"SP... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESPLoader.write_status | Write up to 24 bits (num_bytes) of new status register
num_bytes can be 1, 2 or 3.
Not all flash supports the additional commands to write the
second and third byte of the status register. When writing 2
bytes, esptool also sends a 16-byte WRSR command (as some
flash types use ... | esptool.py | def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
"""Write up to 24 bits (num_bytes) of new status register
num_bytes can be 1, 2 or 3.
Not all flash supports the additional commands to write the
second and third byte of the status register. When writing 2
... | def write_status(self, new_status, num_bytes=2, set_non_volatile=False):
"""Write up to 24 bits (num_bytes) of new status register
num_bytes can be 1, 2 or 3.
Not all flash supports the additional commands to write the
second and third byte of the status register. When writing 2
... | [
"Write",
"up",
"to",
"24",
"bits",
"(",
"num_bytes",
")",
"of",
"new",
"status",
"register"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L906-L941 | [
"def",
"write_status",
"(",
"self",
",",
"new_status",
",",
"num_bytes",
"=",
"2",
",",
"set_non_volatile",
"=",
"False",
")",
":",
"SPIFLASH_WRSR",
"=",
"0x01",
"SPIFLASH_WRSR2",
"=",
"0x31",
"SPIFLASH_WRSR3",
"=",
"0x11",
"SPIFLASH_WEVSR",
"=",
"0x50",
"SPIF... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP8266ROM.chip_id | Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function | esptool.py | def chip_id(self):
""" Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """
id0 = self.read_reg(self.ESP_OTP_MAC0)
id1 = self.read_reg(self.ESP_OTP_MAC1)
return (id0 >> 24) | ((id1 & MAX_UINT24) << 8) | def chip_id(self):
""" Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """
id0 = self.read_reg(self.ESP_OTP_MAC0)
id1 = self.read_reg(self.ESP_OTP_MAC1)
return (id0 >> 24) | ((id1 & MAX_UINT24) << 8) | [
"Read",
"Chip",
"ID",
"from",
"efuse",
"-",
"the",
"equivalent",
"of",
"the",
"SDK",
"system_get_chip_id",
"()",
"function"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1052-L1056 | [
"def",
"chip_id",
"(",
"self",
")",
":",
"id0",
"=",
"self",
".",
"read_reg",
"(",
"self",
".",
"ESP_OTP_MAC0",
")",
"id1",
"=",
"self",
".",
"read_reg",
"(",
"self",
".",
"ESP_OTP_MAC1",
")",
"return",
"(",
"id0",
">>",
"24",
")",
"|",
"(",
"(",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP8266ROM.read_mac | Read MAC from OTP ROM | esptool.py | def read_mac(self):
""" Read MAC from OTP ROM """
mac0 = self.read_reg(self.ESP_OTP_MAC0)
mac1 = self.read_reg(self.ESP_OTP_MAC1)
mac3 = self.read_reg(self.ESP_OTP_MAC3)
if (mac3 != 0):
oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
elif ((mac1 >... | def read_mac(self):
""" Read MAC from OTP ROM """
mac0 = self.read_reg(self.ESP_OTP_MAC0)
mac1 = self.read_reg(self.ESP_OTP_MAC1)
mac3 = self.read_reg(self.ESP_OTP_MAC3)
if (mac3 != 0):
oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff)
elif ((mac1 >... | [
"Read",
"MAC",
"from",
"OTP",
"ROM"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1058-L1071 | [
"def",
"read_mac",
"(",
"self",
")",
":",
"mac0",
"=",
"self",
".",
"read_reg",
"(",
"self",
".",
"ESP_OTP_MAC0",
")",
"mac1",
"=",
"self",
".",
"read_reg",
"(",
"self",
".",
"ESP_OTP_MAC1",
")",
"mac3",
"=",
"self",
".",
"read_reg",
"(",
"self",
"."... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP8266ROM.get_erase_size | Calculate an erase size given a specific size in bytes.
Provides a workaround for the bootloader erase bug. | esptool.py | def get_erase_size(self, offset, size):
""" Calculate an erase size given a specific size in bytes.
Provides a workaround for the bootloader erase bug."""
sectors_per_block = 16
sector_size = self.FLASH_SECTOR_SIZE
num_sectors = (size + sector_size - 1) // sector_size
s... | def get_erase_size(self, offset, size):
""" Calculate an erase size given a specific size in bytes.
Provides a workaround for the bootloader erase bug."""
sectors_per_block = 16
sector_size = self.FLASH_SECTOR_SIZE
num_sectors = (size + sector_size - 1) // sector_size
s... | [
"Calculate",
"an",
"erase",
"size",
"given",
"a",
"specific",
"size",
"in",
"bytes",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1073-L1090 | [
"def",
"get_erase_size",
"(",
"self",
",",
"offset",
",",
"size",
")",
":",
"sectors_per_block",
"=",
"16",
"sector_size",
"=",
"self",
".",
"FLASH_SECTOR_SIZE",
"num_sectors",
"=",
"(",
"size",
"+",
"sector_size",
"-",
"1",
")",
"//",
"sector_size",
"start_... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP32ROM.is_flash_encryption_key_valid | Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1
this bit is at position 16 in EFUSE_BLK0_RDATA0_REG | esptool.py | def is_flash_encryption_key_valid(self):
""" Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1
this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 16) & 0x1
# reading of BLOCK1 is NOT ALLOWED so we assume valid key is progr... | def is_flash_encryption_key_valid(self):
""" Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1
this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 16) & 0x1
# reading of BLOCK1 is NOT ALLOWED so we assume valid key is progr... | [
"Bit",
"0",
"of",
"efuse_rd_disable",
"[",
"3",
":",
"0",
"]",
"is",
"mapped",
"to",
"BLOCK1",
"this",
"bit",
"is",
"at",
"position",
"16",
"in",
"EFUSE_BLK0_RDATA0_REG"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1155-L1176 | [
"def",
"is_flash_encryption_key_valid",
"(",
"self",
")",
":",
"word0",
"=",
"self",
".",
"read_efuse",
"(",
"0",
")",
"rd_disable",
"=",
"(",
"word0",
">>",
"16",
")",
"&",
"0x1",
"# reading of BLOCK1 is NOT ALLOWED so we assume valid key is programmed",
"if",
"rd_... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP32ROM.get_flash_crypt_config | bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config
this bit is at position 19 in EFUSE_BLK0_RDATA0_REG | esptool.py | def get_flash_crypt_config(self):
""" bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config
this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 19) & 0x1
if rd_disable == 0:
""" we can read the flash_cryp... | def get_flash_crypt_config(self):
""" bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config
this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """
word0 = self.read_efuse(0)
rd_disable = (word0 >> 19) & 0x1
if rd_disable == 0:
""" we can read the flash_cryp... | [
"bit",
"3",
"in",
"efuse_rd_disable",
"[",
"3",
":",
"0",
"]",
"is",
"mapped",
"to",
"flash_crypt_config",
"this",
"bit",
"is",
"at",
"position",
"19",
"in",
"EFUSE_BLK0_RDATA0_REG"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1185-L1199 | [
"def",
"get_flash_crypt_config",
"(",
"self",
")",
":",
"word0",
"=",
"self",
".",
"read_efuse",
"(",
"0",
")",
"rd_disable",
"=",
"(",
"word0",
">>",
"19",
")",
"&",
"0x1",
"if",
"rd_disable",
"==",
"0",
":",
"\"\"\" we can read the flash_crypt_config efuse v... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP32ROM.read_mac | Read MAC from EFUSE region | esptool.py | def read_mac(self):
""" Read MAC from EFUSE region """
words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack(">II", *words)
bitstring = bitstring[2:8] # trim the 2 byte CRC
try:
return tuple(ord(b) for b in bitstring)
except TypeError: # P... | def read_mac(self):
""" Read MAC from EFUSE region """
words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack(">II", *words)
bitstring = bitstring[2:8] # trim the 2 byte CRC
try:
return tuple(ord(b) for b in bitstring)
except TypeError: # P... | [
"Read",
"MAC",
"from",
"EFUSE",
"region"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1271-L1279 | [
"def",
"read_mac",
"(",
"self",
")",
":",
"words",
"=",
"[",
"self",
".",
"read_efuse",
"(",
"2",
")",
",",
"self",
".",
"read_efuse",
"(",
"1",
")",
"]",
"bitstring",
"=",
"struct",
".",
"pack",
"(",
"\">II\"",
",",
"*",
"words",
")",
"bitstring",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ImageSegment.split_image | Return a new ImageSegment which splits "split_len" bytes
from the beginning of the data. Remaining bytes are kept in
this segment object (and the start address is adjusted to match.) | esptool.py | def split_image(self, split_len):
""" Return a new ImageSegment which splits "split_len" bytes
from the beginning of the data. Remaining bytes are kept in
this segment object (and the start address is adjusted to match.) """
result = copy.copy(self)
result.data = self.data[:split... | def split_image(self, split_len):
""" Return a new ImageSegment which splits "split_len" bytes
from the beginning of the data. Remaining bytes are kept in
this segment object (and the start address is adjusted to match.) """
result = copy.copy(self)
result.data = self.data[:split... | [
"Return",
"a",
"new",
"ImageSegment",
"which",
"splits",
"split_len",
"bytes",
"from",
"the",
"beginning",
"of",
"the",
"data",
".",
"Remaining",
"bytes",
"are",
"kept",
"in",
"this",
"segment",
"object",
"(",
"and",
"the",
"start",
"address",
"is",
"adjuste... | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1369-L1379 | [
"def",
"split_image",
"(",
"self",
",",
"split_len",
")",
":",
"result",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"result",
".",
"data",
"=",
"self",
".",
"data",
"[",
":",
"split_len",
"]",
"self",
".",
"data",
"=",
"self",
".",
"data",
"[",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | BaseFirmwareImage.load_segment | Load the next segment from the image file | esptool.py | def load_segment(self, f, is_irom_segment=False):
""" Load the next segment from the image file """
file_offs = f.tell()
(offset, size) = struct.unpack('<II', f.read(8))
self.warn_if_unusual_segment(offset, size, is_irom_segment)
segment_data = f.read(size)
if len(segment... | def load_segment(self, f, is_irom_segment=False):
""" Load the next segment from the image file """
file_offs = f.tell()
(offset, size) = struct.unpack('<II', f.read(8))
self.warn_if_unusual_segment(offset, size, is_irom_segment)
segment_data = f.read(size)
if len(segment... | [
"Load",
"the",
"next",
"segment",
"from",
"the",
"image",
"file"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1424-L1434 | [
"def",
"load_segment",
"(",
"self",
",",
"f",
",",
"is_irom_segment",
"=",
"False",
")",
":",
"file_offs",
"=",
"f",
".",
"tell",
"(",
")",
"(",
"offset",
",",
"size",
")",
"=",
"struct",
".",
"unpack",
"(",
"'<II'",
",",
"f",
".",
"read",
"(",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | BaseFirmwareImage.maybe_patch_segment_data | If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data. | esptool.py | def maybe_patch_segment_data(self, f, segment_data):
"""If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data."""
segment_len = len(segment_data)
file_pos = f.tell() # file_pos is position in the .bin file
if self.elf_sha256_offset >= file_... | def maybe_patch_segment_data(self, f, segment_data):
"""If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data."""
segment_len = len(segment_data)
file_pos = f.tell() # file_pos is position in the .bin file
if self.elf_sha256_offset >= file_... | [
"If",
"SHA256",
"digest",
"of",
"the",
"ELF",
"file",
"needs",
"to",
"be",
"inserted",
"into",
"this",
"segment",
"do",
"so",
".",
"Returns",
"segment",
"data",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1441-L1462 | [
"def",
"maybe_patch_segment_data",
"(",
"self",
",",
"f",
",",
"segment_data",
")",
":",
"segment_len",
"=",
"len",
"(",
"segment_data",
")",
"file_pos",
"=",
"f",
".",
"tell",
"(",
")",
"# file_pos is position in the .bin file",
"if",
"self",
".",
"elf_sha256_o... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | BaseFirmwareImage.save_segment | Save the next segment to the image file, return next checksum value if provided | esptool.py | def save_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
segment_data = self.maybe_patch_segment_data(f, segment.data)
f.write(struct.pack('<II', segment.addr, len(segment_data)))
f.write(segment_data)
... | def save_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
segment_data = self.maybe_patch_segment_data(f, segment.data)
f.write(struct.pack('<II', segment.addr, len(segment_data)))
f.write(segment_data)
... | [
"Save",
"the",
"next",
"segment",
"to",
"the",
"image",
"file",
"return",
"next",
"checksum",
"value",
"if",
"provided"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1464-L1470 | [
"def",
"save_segment",
"(",
"self",
",",
"f",
",",
"segment",
",",
"checksum",
"=",
"None",
")",
":",
"segment_data",
"=",
"self",
".",
"maybe_patch_segment_data",
"(",
"f",
",",
"segment",
".",
"data",
")",
"f",
".",
"write",
"(",
"struct",
".",
"pack... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | BaseFirmwareImage.calculate_checksum | Calculate checksum of loaded image, based on segments in
segment array. | esptool.py | def calculate_checksum(self):
""" Calculate checksum of loaded image, based on segments in
segment array.
"""
checksum = ESPLoader.ESP_CHECKSUM_MAGIC
for seg in self.segments:
if seg.include_in_checksum:
checksum = ESPLoader.checksum(seg.data, checksum... | def calculate_checksum(self):
""" Calculate checksum of loaded image, based on segments in
segment array.
"""
checksum = ESPLoader.ESP_CHECKSUM_MAGIC
for seg in self.segments:
if seg.include_in_checksum:
checksum = ESPLoader.checksum(seg.data, checksum... | [
"Calculate",
"checksum",
"of",
"loaded",
"image",
"based",
"on",
"segments",
"in",
"segment",
"array",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1479-L1487 | [
"def",
"calculate_checksum",
"(",
"self",
")",
":",
"checksum",
"=",
"ESPLoader",
".",
"ESP_CHECKSUM_MAGIC",
"for",
"seg",
"in",
"self",
".",
"segments",
":",
"if",
"seg",
".",
"include_in_checksum",
":",
"checksum",
"=",
"ESPLoader",
".",
"checksum",
"(",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | BaseFirmwareImage.append_checksum | Append ESPLoader checksum to the just-written image | esptool.py | def append_checksum(self, f, checksum):
""" Append ESPLoader checksum to the just-written image """
align_file_position(f, 16)
f.write(struct.pack(b'B', checksum)) | def append_checksum(self, f, checksum):
""" Append ESPLoader checksum to the just-written image """
align_file_position(f, 16)
f.write(struct.pack(b'B', checksum)) | [
"Append",
"ESPLoader",
"checksum",
"to",
"the",
"just",
"-",
"written",
"image"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1489-L1492 | [
"def",
"append_checksum",
"(",
"self",
",",
"f",
",",
"checksum",
")",
":",
"align_file_position",
"(",
"f",
",",
"16",
")",
"f",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"b'B'",
",",
"checksum",
")",
")"
] | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP8266ROMFirmwareImage.save | Save a set of V1 images for flashing. Parameter is a base filename. | esptool.py | def save(self, basename):
""" Save a set of V1 images for flashing. Parameter is a base filename. """
# IROM data goes in its own plain binary file
irom_segment = self.get_irom_segment()
if irom_segment is not None:
with open("%s0x%05x.bin" % (basename, irom_segment.addr - ES... | def save(self, basename):
""" Save a set of V1 images for flashing. Parameter is a base filename. """
# IROM data goes in its own plain binary file
irom_segment = self.get_irom_segment()
if irom_segment is not None:
with open("%s0x%05x.bin" % (basename, irom_segment.addr - ES... | [
"Save",
"a",
"set",
"of",
"V1",
"images",
"for",
"flashing",
".",
"Parameter",
"is",
"a",
"base",
"filename",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1541-L1556 | [
"def",
"save",
"(",
"self",
",",
"basename",
")",
":",
"# IROM data goes in its own plain binary file",
"irom_segment",
"=",
"self",
".",
"get_irom_segment",
"(",
")",
"if",
"irom_segment",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"\"%s0x%05x.bin\"",
"%",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP8266V2FirmwareImage.default_output_name | Derive a default output name from the ELF name. | esptool.py | def default_output_name(self, input_file):
""" Derive a default output name from the ELF name. """
irom_segment = self.get_irom_segment()
if irom_segment is not None:
irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START
else:
irom_offs = 0
return "%s-... | def default_output_name(self, input_file):
""" Derive a default output name from the ELF name. """
irom_segment = self.get_irom_segment()
if irom_segment is not None:
irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START
else:
irom_offs = 0
return "%s-... | [
"Derive",
"a",
"default",
"output",
"name",
"from",
"the",
"ELF",
"name",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1607-L1615 | [
"def",
"default_output_name",
"(",
"self",
",",
"input_file",
")",
":",
"irom_segment",
"=",
"self",
".",
"get_irom_segment",
"(",
")",
"if",
"irom_segment",
"is",
"not",
"None",
":",
"irom_offs",
"=",
"irom_segment",
".",
"addr",
"-",
"ESP8266ROM",
".",
"IR... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | ESP32FirmwareImage.save_flash_segment | Save the next segment to the image file, return next checksum value if provided | esptool.py | def save_flash_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN
segment_len_remainder = segment_end_pos % self.IROM_ALIGN
if segment_len_r... | def save_flash_segment(self, f, segment, checksum=None):
""" Save the next segment to the image file, return next checksum value if provided """
segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN
segment_len_remainder = segment_end_pos % self.IROM_ALIGN
if segment_len_r... | [
"Save",
"the",
"next",
"segment",
"to",
"the",
"image",
"file",
"return",
"next",
"checksum",
"value",
"if",
"provided"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/esptool.py#L1841-L1849 | [
"def",
"save_flash_segment",
"(",
"self",
",",
"f",
",",
"segment",
",",
"checksum",
"=",
"None",
")",
":",
"segment_end_pos",
"=",
"f",
".",
"tell",
"(",
")",
"+",
"len",
"(",
"segment",
".",
"data",
")",
"+",
"self",
".",
"SEG_HEADER_LEN",
"segment_l... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | SigningKey.sign_digest_deterministic | Calculates 'k' from data itself, removing the need for strong
random generator and producing deterministic (reproducible) signatures.
See RFC 6979 for more details. | ecdsa/keys.py | def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string):
"""
Calculates 'k' from data itself, removing the need for strong
random generator and producing deterministic (reproducible) signatures.
See RFC 6979 for more details.
"""
secexp = se... | def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string):
"""
Calculates 'k' from data itself, removing the need for strong
random generator and producing deterministic (reproducible) signatures.
See RFC 6979 for more details.
"""
secexp = se... | [
"Calculates",
"k",
"from",
"data",
"itself",
"removing",
"the",
"need",
"for",
"strong",
"random",
"generator",
"and",
"producing",
"deterministic",
"(",
"reproducible",
")",
"signatures",
".",
"See",
"RFC",
"6979",
"for",
"more",
"details",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/keys.py#L228-L238 | [
"def",
"sign_digest_deterministic",
"(",
"self",
",",
"digest",
",",
"hashfunc",
"=",
"None",
",",
"sigencode",
"=",
"sigencode_string",
")",
":",
"secexp",
"=",
"self",
".",
"privkey",
".",
"secret_multiplier",
"k",
"=",
"rfc6979",
".",
"generate_k",
"(",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | SigningKey.sign | hashfunc= should behave like hashlib.sha1 . The output length of the
hash (in bytes) must not be longer than the length of the curve order
(rounded up to the nearest byte), so using SHA256 with nist256p is
ok, but SHA256 with nist192p is not. (In the 2**-96ish unlikely event
of a hash ou... | ecdsa/keys.py | def sign(self, data, entropy=None, hashfunc=None, sigencode=sigencode_string, k=None):
"""
hashfunc= should behave like hashlib.sha1 . The output length of the
hash (in bytes) must not be longer than the length of the curve order
(rounded up to the nearest byte), so using SHA256 with nis... | def sign(self, data, entropy=None, hashfunc=None, sigencode=sigencode_string, k=None):
"""
hashfunc= should behave like hashlib.sha1 . The output length of the
hash (in bytes) must not be longer than the length of the curve order
(rounded up to the nearest byte), so using SHA256 with nis... | [
"hashfunc",
"=",
"should",
"behave",
"like",
"hashlib",
".",
"sha1",
".",
"The",
"output",
"length",
"of",
"the",
"hash",
"(",
"in",
"bytes",
")",
"must",
"not",
"be",
"longer",
"than",
"the",
"length",
"of",
"the",
"curve",
"order",
"(",
"rounded",
"u... | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/keys.py#L240-L255 | [
"def",
"sign",
"(",
"self",
",",
"data",
",",
"entropy",
"=",
"None",
",",
"hashfunc",
"=",
"None",
",",
"sigencode",
"=",
"sigencode_string",
",",
"k",
"=",
"None",
")",
":",
"hashfunc",
"=",
"hashfunc",
"or",
"self",
".",
"default_hashfunc",
"h",
"="... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | wrap_stub | Wrap an ELF file into a stub 'dict' | flasher_stub/wrap_stub.py | def wrap_stub(elf_file):
""" Wrap an ELF file into a stub 'dict' """
print('Wrapping ELF file %s...' % elf_file)
e = esptool.ELFFile(elf_file)
text_section = e.get_section('.text')
try:
data_section = e.get_section('.data')
except ValueError:
data_section = None
stub = {
... | def wrap_stub(elf_file):
""" Wrap an ELF file into a stub 'dict' """
print('Wrapping ELF file %s...' % elf_file)
e = esptool.ELFFile(elf_file)
text_section = e.get_section('.text')
try:
data_section = e.get_section('.data')
except ValueError:
data_section = None
stub = {
... | [
"Wrap",
"an",
"ELF",
"file",
"into",
"a",
"stub",
"dict"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/flasher_stub/wrap_stub.py#L29-L56 | [
"def",
"wrap_stub",
"(",
"elf_file",
")",
":",
"print",
"(",
"'Wrapping ELF file %s...'",
"%",
"elf_file",
")",
"e",
"=",
"esptool",
".",
"ELFFile",
"(",
"elf_file",
")",
"text_section",
"=",
"e",
".",
"get_section",
"(",
"'.text'",
")",
"try",
":",
"data_... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | generate_k | order - order of the DSA generator used in the signature
secexp - secure exponent (private key) in numeric form
hash_func - reference to the same hash function used for generating hash
data - hash in binary form of the signing data | ecdsa/rfc6979.py | def generate_k(order, secexp, hash_func, data):
'''
order - order of the DSA generator used in the signature
secexp - secure exponent (private key) in numeric form
hash_func - reference to the same hash function used for generating hash
data - hash in binary form of the signing data
... | def generate_k(order, secexp, hash_func, data):
'''
order - order of the DSA generator used in the signature
secexp - secure exponent (private key) in numeric form
hash_func - reference to the same hash function used for generating hash
data - hash in binary form of the signing data
... | [
"order",
"-",
"order",
"of",
"the",
"DSA",
"generator",
"used",
"in",
"the",
"signature",
"secexp",
"-",
"secure",
"exponent",
"(",
"private",
"key",
")",
"in",
"numeric",
"form",
"hash_func",
"-",
"reference",
"to",
"the",
"same",
"hash",
"function",
"use... | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/rfc6979.py#L54-L103 | [
"def",
"generate_k",
"(",
"order",
",",
"secexp",
",",
"hash_func",
",",
"data",
")",
":",
"qlen",
"=",
"bit_length",
"(",
"order",
")",
"holen",
"=",
"hash_func",
"(",
")",
".",
"digest_size",
"rolen",
"=",
"(",
"qlen",
"+",
"7",
")",
"/",
"8",
"b... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | get_chunks | Returns an iterator over 'chunk_len' chunks of 'source' | espsecure.py | def get_chunks(source, chunk_len):
""" Returns an iterator over 'chunk_len' chunks of 'source' """
return (source[i: i + chunk_len] for i in range(0, len(source), chunk_len)) | def get_chunks(source, chunk_len):
""" Returns an iterator over 'chunk_len' chunks of 'source' """
return (source[i: i + chunk_len] for i in range(0, len(source), chunk_len)) | [
"Returns",
"an",
"iterator",
"over",
"chunk_len",
"chunks",
"of",
"source"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L31-L33 | [
"def",
"get_chunks",
"(",
"source",
",",
"chunk_len",
")",
":",
"return",
"(",
"source",
"[",
"i",
":",
"i",
"+",
"chunk_len",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"source",
")",
",",
"chunk_len",
")",
")"
] | c583756c118039cfcfe256f7a3285618914d16a5 |
train | endian_swap_words | Endian-swap each word in 'source' bitstring | espsecure.py | def endian_swap_words(source):
""" Endian-swap each word in 'source' bitstring """
assert len(source) % 4 == 0
words = "I" * (len(source) // 4)
return struct.pack("<" + words, *struct.unpack(">" + words, source)) | def endian_swap_words(source):
""" Endian-swap each word in 'source' bitstring """
assert len(source) % 4 == 0
words = "I" * (len(source) // 4)
return struct.pack("<" + words, *struct.unpack(">" + words, source)) | [
"Endian",
"-",
"swap",
"each",
"word",
"in",
"source",
"bitstring"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L36-L40 | [
"def",
"endian_swap_words",
"(",
"source",
")",
":",
"assert",
"len",
"(",
"source",
")",
"%",
"4",
"==",
"0",
"words",
"=",
"\"I\"",
"*",
"(",
"len",
"(",
"source",
")",
"//",
"4",
")",
"return",
"struct",
".",
"pack",
"(",
"\"<\"",
"+",
"words",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | swap_word_order | Swap the order of the words in 'source' bitstring | espsecure.py | def swap_word_order(source):
""" Swap the order of the words in 'source' bitstring """
assert len(source) % 4 == 0
words = "I" * (len(source) // 4)
return struct.pack(words, *reversed(struct.unpack(words, source))) | def swap_word_order(source):
""" Swap the order of the words in 'source' bitstring """
assert len(source) % 4 == 0
words = "I" * (len(source) // 4)
return struct.pack(words, *reversed(struct.unpack(words, source))) | [
"Swap",
"the",
"order",
"of",
"the",
"words",
"in",
"source",
"bitstring"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L43-L47 | [
"def",
"swap_word_order",
"(",
"source",
")",
":",
"assert",
"len",
"(",
"source",
")",
"%",
"4",
"==",
"0",
"words",
"=",
"\"I\"",
"*",
"(",
"len",
"(",
"source",
")",
"//",
"4",
")",
"return",
"struct",
".",
"pack",
"(",
"words",
",",
"*",
"rev... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | _load_hardware_key | Load a 256-bit key, similar to stored in efuse, from a file
192-bit keys will be extended to 256-bit using the same algorithm used
by hardware if 3/4 Coding Scheme is set. | espsecure.py | def _load_hardware_key(keyfile):
""" Load a 256-bit key, similar to stored in efuse, from a file
192-bit keys will be extended to 256-bit using the same algorithm used
by hardware if 3/4 Coding Scheme is set.
"""
key = keyfile.read()
if len(key) not in [24, 32]:
raise esptool.FatalError... | def _load_hardware_key(keyfile):
""" Load a 256-bit key, similar to stored in efuse, from a file
192-bit keys will be extended to 256-bit using the same algorithm used
by hardware if 3/4 Coding Scheme is set.
"""
key = keyfile.read()
if len(key) not in [24, 32]:
raise esptool.FatalError... | [
"Load",
"a",
"256",
"-",
"bit",
"key",
"similar",
"to",
"stored",
"in",
"efuse",
"from",
"a",
"file"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L50-L66 | [
"def",
"_load_hardware_key",
"(",
"keyfile",
")",
":",
"key",
"=",
"keyfile",
".",
"read",
"(",
")",
"if",
"len",
"(",
"key",
")",
"not",
"in",
"[",
"24",
",",
"32",
"]",
":",
"raise",
"esptool",
".",
"FatalError",
"(",
"\"Key file contains wrong length ... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | digest_secure_bootloader | Calculate the digest of a bootloader image, in the same way the hardware
secure boot engine would do so. Can be used with a pre-loaded key to update a
secure bootloader. | espsecure.py | def digest_secure_bootloader(args):
""" Calculate the digest of a bootloader image, in the same way the hardware
secure boot engine would do so. Can be used with a pre-loaded key to update a
secure bootloader. """
if args.iv is not None:
print("WARNING: --iv argument is for TESTING PURPOSES ONLY... | def digest_secure_bootloader(args):
""" Calculate the digest of a bootloader image, in the same way the hardware
secure boot engine would do so. Can be used with a pre-loaded key to update a
secure bootloader. """
if args.iv is not None:
print("WARNING: --iv argument is for TESTING PURPOSES ONLY... | [
"Calculate",
"the",
"digest",
"of",
"a",
"bootloader",
"image",
"in",
"the",
"same",
"way",
"the",
"hardware",
"secure",
"boot",
"engine",
"would",
"do",
"so",
".",
"Can",
"be",
"used",
"with",
"a",
"pre",
"-",
"loaded",
"key",
"to",
"update",
"a",
"se... | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L69-L126 | [
"def",
"digest_secure_bootloader",
"(",
"args",
")",
":",
"if",
"args",
".",
"iv",
"is",
"not",
"None",
":",
"print",
"(",
"\"WARNING: --iv argument is for TESTING PURPOSES ONLY\"",
")",
"iv",
"=",
"args",
".",
"iv",
".",
"read",
"(",
"128",
")",
"else",
":"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | generate_signing_key | Generate an ECDSA signing key for signing secure boot images (post-bootloader) | espsecure.py | def generate_signing_key(args):
""" Generate an ECDSA signing key for signing secure boot images (post-bootloader) """
if os.path.exists(args.keyfile):
raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile)
sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
with open(args... | def generate_signing_key(args):
""" Generate an ECDSA signing key for signing secure boot images (post-bootloader) """
if os.path.exists(args.keyfile):
raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile)
sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
with open(args... | [
"Generate",
"an",
"ECDSA",
"signing",
"key",
"for",
"signing",
"secure",
"boot",
"images",
"(",
"post",
"-",
"bootloader",
")"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L129-L136 | [
"def",
"generate_signing_key",
"(",
"args",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"args",
".",
"keyfile",
")",
":",
"raise",
"esptool",
".",
"FatalError",
"(",
"\"ERROR: Key file %s already exists\"",
"%",
"args",
".",
"keyfile",
")",
"sk",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | sign_data | Sign a data file with a ECDSA private key, append binary signature to file contents | espsecure.py | def sign_data(args):
""" Sign a data file with a ECDSA private key, append binary signature to file contents """
sk = _load_ecdsa_signing_key(args)
# calculate signature of binary data
binary_content = args.datafile.read()
signature = sk.sign_deterministic(binary_content, hashlib.sha256)
# bac... | def sign_data(args):
""" Sign a data file with a ECDSA private key, append binary signature to file contents """
sk = _load_ecdsa_signing_key(args)
# calculate signature of binary data
binary_content = args.datafile.read()
signature = sk.sign_deterministic(binary_content, hashlib.sha256)
# bac... | [
"Sign",
"a",
"data",
"file",
"with",
"a",
"ECDSA",
"private",
"key",
"append",
"binary",
"signature",
"to",
"file",
"contents"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L146-L167 | [
"def",
"sign_data",
"(",
"args",
")",
":",
"sk",
"=",
"_load_ecdsa_signing_key",
"(",
"args",
")",
"# calculate signature of binary data",
"binary_content",
"=",
"args",
".",
"datafile",
".",
"read",
"(",
")",
"signature",
"=",
"sk",
".",
"sign_deterministic",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | verify_signature | Verify a previously signed binary image, using the ECDSA public key | espsecure.py | def verify_signature(args):
""" Verify a previously signed binary image, using the ECDSA public key """
key_data = args.keyfile.read()
if b"-BEGIN EC PRIVATE KEY" in key_data:
sk = ecdsa.SigningKey.from_pem(key_data)
vk = sk.get_verifying_key()
elif b"-BEGIN PUBLIC KEY" in key_data:
... | def verify_signature(args):
""" Verify a previously signed binary image, using the ECDSA public key """
key_data = args.keyfile.read()
if b"-BEGIN EC PRIVATE KEY" in key_data:
sk = ecdsa.SigningKey.from_pem(key_data)
vk = sk.get_verifying_key()
elif b"-BEGIN PUBLIC KEY" in key_data:
... | [
"Verify",
"a",
"previously",
"signed",
"binary",
"image",
"using",
"the",
"ECDSA",
"public",
"key"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L170-L199 | [
"def",
"verify_signature",
"(",
"args",
")",
":",
"key_data",
"=",
"args",
".",
"keyfile",
".",
"read",
"(",
")",
"if",
"b\"-BEGIN EC PRIVATE KEY\"",
"in",
"key_data",
":",
"sk",
"=",
"ecdsa",
".",
"SigningKey",
".",
"from_pem",
"(",
"key_data",
")",
"vk",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | extract_public_key | Load an ECDSA private key and extract the embedded public key as raw binary data. | espsecure.py | def extract_public_key(args):
""" Load an ECDSA private key and extract the embedded public key as raw binary data. """
sk = _load_ecdsa_signing_key(args)
vk = sk.get_verifying_key()
args.public_keyfile.write(vk.to_string())
print("%s public key extracted to %s" % (args.keyfile.name, args.public_key... | def extract_public_key(args):
""" Load an ECDSA private key and extract the embedded public key as raw binary data. """
sk = _load_ecdsa_signing_key(args)
vk = sk.get_verifying_key()
args.public_keyfile.write(vk.to_string())
print("%s public key extracted to %s" % (args.keyfile.name, args.public_key... | [
"Load",
"an",
"ECDSA",
"private",
"key",
"and",
"extract",
"the",
"embedded",
"public",
"key",
"as",
"raw",
"binary",
"data",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L202-L207 | [
"def",
"extract_public_key",
"(",
"args",
")",
":",
"sk",
"=",
"_load_ecdsa_signing_key",
"(",
"args",
")",
"vk",
"=",
"sk",
".",
"get_verifying_key",
"(",
")",
"args",
".",
"public_keyfile",
".",
"write",
"(",
"vk",
".",
"to_string",
"(",
")",
")",
"pri... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | _flash_encryption_tweak_range | Return a list of the bit indexes that the "key tweak" applies to,
as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value. | espsecure.py | def _flash_encryption_tweak_range(flash_crypt_config=0xF):
""" Return a list of the bit indexes that the "key tweak" applies to,
as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value.
"""
tweak_range = []
if (flash_crypt_config & 1) != 0:
tweak_range += range(67)
if (flash_crypt_conf... | def _flash_encryption_tweak_range(flash_crypt_config=0xF):
""" Return a list of the bit indexes that the "key tweak" applies to,
as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value.
"""
tweak_range = []
if (flash_crypt_config & 1) != 0:
tweak_range += range(67)
if (flash_crypt_conf... | [
"Return",
"a",
"list",
"of",
"the",
"bit",
"indexes",
"that",
"the",
"key",
"tweak",
"applies",
"to",
"as",
"determined",
"by",
"the",
"FLASH_CRYPT_CONFIG",
"4",
"bit",
"efuse",
"value",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L249-L262 | [
"def",
"_flash_encryption_tweak_range",
"(",
"flash_crypt_config",
"=",
"0xF",
")",
":",
"tweak_range",
"=",
"[",
"]",
"if",
"(",
"flash_crypt_config",
"&",
"1",
")",
"!=",
"0",
":",
"tweak_range",
"+=",
"range",
"(",
"67",
")",
"if",
"(",
"flash_crypt_confi... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | _flash_encryption_tweak_key | Apply XOR "tweak" values to the key, derived from flash offset
'offset'. This matches the ESP32 hardware flash encryption.
tweak_range is a list of bit indexes to apply the tweak to, as
generated by _flash_encryption_tweak_range() from the
FLASH_CRYPT_CONFIG efuse value.
Return tweaked key | espsecure.py | def _flash_encryption_tweak_key(key, offset, tweak_range):
"""Apply XOR "tweak" values to the key, derived from flash offset
'offset'. This matches the ESP32 hardware flash encryption.
tweak_range is a list of bit indexes to apply the tweak to, as
generated by _flash_encryption_tweak_range() from the
... | def _flash_encryption_tweak_key(key, offset, tweak_range):
"""Apply XOR "tweak" values to the key, derived from flash offset
'offset'. This matches the ESP32 hardware flash encryption.
tweak_range is a list of bit indexes to apply the tweak to, as
generated by _flash_encryption_tweak_range() from the
... | [
"Apply",
"XOR",
"tweak",
"values",
"to",
"the",
"key",
"derived",
"from",
"flash",
"offset",
"offset",
".",
"This",
"matches",
"the",
"ESP32",
"hardware",
"flash",
"encryption",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/espsecure.py#L265-L292 | [
"def",
"_flash_encryption_tweak_key",
"(",
"key",
",",
"offset",
",",
"tweak_range",
")",
":",
"if",
"esptool",
".",
"PYTHON2",
":",
"key",
"=",
"[",
"ord",
"(",
"k",
")",
"for",
"k",
"in",
"key",
"]",
"else",
":",
"key",
"=",
"list",
"(",
"key",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | int_to_string | Convert integer x into a string of bytes, as per X9.62. | ecdsa/ecdsa.py | def int_to_string( x ):
"""Convert integer x into a string of bytes, as per X9.62."""
assert x >= 0
if x == 0: return b('\0')
result = []
while x:
ordinal = x & 0xFF
result.append(int2byte(ordinal))
x >>= 8
result.reverse()
return b('').join(result) | def int_to_string( x ):
"""Convert integer x into a string of bytes, as per X9.62."""
assert x >= 0
if x == 0: return b('\0')
result = []
while x:
ordinal = x & 0xFF
result.append(int2byte(ordinal))
x >>= 8
result.reverse()
return b('').join(result) | [
"Convert",
"integer",
"x",
"into",
"a",
"string",
"of",
"bytes",
"as",
"per",
"X9",
".",
"62",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L155-L166 | [
"def",
"int_to_string",
"(",
"x",
")",
":",
"assert",
"x",
">=",
"0",
"if",
"x",
"==",
"0",
":",
"return",
"b",
"(",
"'\\0'",
")",
"result",
"=",
"[",
"]",
"while",
"x",
":",
"ordinal",
"=",
"x",
"&",
"0xFF",
"result",
".",
"append",
"(",
"int2... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | string_to_int | Convert a string of bytes into an integer, as per X9.62. | ecdsa/ecdsa.py | def string_to_int( s ):
"""Convert a string of bytes into an integer, as per X9.62."""
result = 0
for c in s:
if not isinstance(c, int): c = ord( c )
result = 256 * result + c
return result | def string_to_int( s ):
"""Convert a string of bytes into an integer, as per X9.62."""
result = 0
for c in s:
if not isinstance(c, int): c = ord( c )
result = 256 * result + c
return result | [
"Convert",
"a",
"string",
"of",
"bytes",
"into",
"an",
"integer",
"as",
"per",
"X9",
".",
"62",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L169-L175 | [
"def",
"string_to_int",
"(",
"s",
")",
":",
"result",
"=",
"0",
"for",
"c",
"in",
"s",
":",
"if",
"not",
"isinstance",
"(",
"c",
",",
"int",
")",
":",
"c",
"=",
"ord",
"(",
"c",
")",
"result",
"=",
"256",
"*",
"result",
"+",
"c",
"return",
"r... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | point_is_valid | Is (x,y) a valid public key based on the specified generator? | ecdsa/ecdsa.py | def point_is_valid( generator, x, y ):
"""Is (x,y) a valid public key based on the specified generator?"""
# These are the tests specified in X9.62.
n = generator.order()
curve = generator.curve()
if x < 0 or n <= x or y < 0 or n <= y:
return False
if not curve.contains_point( x, y ):
return False... | def point_is_valid( generator, x, y ):
"""Is (x,y) a valid public key based on the specified generator?"""
# These are the tests specified in X9.62.
n = generator.order()
curve = generator.curve()
if x < 0 or n <= x or y < 0 or n <= y:
return False
if not curve.contains_point( x, y ):
return False... | [
"Is",
"(",
"x",
"y",
")",
"a",
"valid",
"public",
"key",
"based",
"on",
"the",
"specified",
"generator?"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L190-L204 | [
"def",
"point_is_valid",
"(",
"generator",
",",
"x",
",",
"y",
")",
":",
"# These are the tests specified in X9.62.",
"n",
"=",
"generator",
".",
"order",
"(",
")",
"curve",
"=",
"generator",
".",
"curve",
"(",
")",
"if",
"x",
"<",
"0",
"or",
"n",
"<=",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | Public_key.verifies | Verify that signature is a valid signature of hash.
Return True if the signature is valid. | ecdsa/ecdsa.py | def verifies( self, hash, signature ):
"""Verify that signature is a valid signature of hash.
Return True if the signature is valid.
"""
# From X9.62 J.3.1.
G = self.generator
n = G.order()
r = signature.r
s = signature.s
if r < 1 or r > n-1: return False
if s < 1 or s > n-1: r... | def verifies( self, hash, signature ):
"""Verify that signature is a valid signature of hash.
Return True if the signature is valid.
"""
# From X9.62 J.3.1.
G = self.generator
n = G.order()
r = signature.r
s = signature.s
if r < 1 or r > n-1: return False
if s < 1 or s > n-1: r... | [
"Verify",
"that",
"signature",
"is",
"a",
"valid",
"signature",
"of",
"hash",
".",
"Return",
"True",
"if",
"the",
"signature",
"is",
"valid",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L93-L111 | [
"def",
"verifies",
"(",
"self",
",",
"hash",
",",
"signature",
")",
":",
"# From X9.62 J.3.1.",
"G",
"=",
"self",
".",
"generator",
"n",
"=",
"G",
".",
"order",
"(",
")",
"r",
"=",
"signature",
".",
"r",
"s",
"=",
"signature",
".",
"s",
"if",
"r",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | Private_key.sign | Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compute our private key from a
single signature. Also, if an attacker... | ecdsa/ecdsa.py | def sign( self, hash, random_k ):
"""Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compute our private key from a
... | def sign( self, hash, random_k ):
"""Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compute our private key from a
... | [
"Return",
"a",
"signature",
"for",
"the",
"provided",
"hash",
"using",
"the",
"provided",
"random",
"nonce",
".",
"It",
"is",
"absolutely",
"vital",
"that",
"random_k",
"be",
"an",
"unpredictable",
"number",
"in",
"the",
"range",
"[",
"1",
"self",
".",
"pu... | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/ecdsa.py#L127-L151 | [
"def",
"sign",
"(",
"self",
",",
"hash",
",",
"random_k",
")",
":",
"G",
"=",
"self",
".",
"public_key",
".",
"generator",
"n",
"=",
"G",
".",
"order",
"(",
")",
"k",
"=",
"random_k",
"%",
"n",
"p1",
"=",
"k",
"*",
"G",
"r",
"=",
"p1",
".",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | modular_exp | Raise base to exponent, reducing by modulus | ecdsa/numbertheory.py | def modular_exp( base, exponent, modulus ):
"Raise base to exponent, reducing by modulus"
if exponent < 0:
raise NegativeExponentError( "Negative exponents (%d) not allowed" \
% exponent )
return pow( base, exponent, modulus ) | def modular_exp( base, exponent, modulus ):
"Raise base to exponent, reducing by modulus"
if exponent < 0:
raise NegativeExponentError( "Negative exponents (%d) not allowed" \
% exponent )
return pow( base, exponent, modulus ) | [
"Raise",
"base",
"to",
"exponent",
"reducing",
"by",
"modulus"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L31-L36 | [
"def",
"modular_exp",
"(",
"base",
",",
"exponent",
",",
"modulus",
")",
":",
"if",
"exponent",
"<",
"0",
":",
"raise",
"NegativeExponentError",
"(",
"\"Negative exponents (%d) not allowed\"",
"%",
"exponent",
")",
"return",
"pow",
"(",
"base",
",",
"exponent",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | polynomial_reduce_mod | Reduce poly by polymod, integer arithmetic modulo p.
Polynomials are represented as lists of coefficients
of increasing powers of x. | ecdsa/numbertheory.py | def polynomial_reduce_mod( poly, polymod, p ):
"""Reduce poly by polymod, integer arithmetic modulo p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# This module has been tested only by extensive use
# in calculating modular square roots.
# Just to make this easy, re... | def polynomial_reduce_mod( poly, polymod, p ):
"""Reduce poly by polymod, integer arithmetic modulo p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# This module has been tested only by extensive use
# in calculating modular square roots.
# Just to make this easy, re... | [
"Reduce",
"poly",
"by",
"polymod",
"integer",
"arithmetic",
"modulo",
"p",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L47-L67 | [
"def",
"polynomial_reduce_mod",
"(",
"poly",
",",
"polymod",
",",
"p",
")",
":",
"# This module has been tested only by extensive use",
"# in calculating modular square roots.",
"# Just to make this easy, require a monic polynomial:",
"assert",
"polymod",
"[",
"-",
"1",
"]",
"=... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | polynomial_multiply_mod | Polynomial multiplication modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x. | ecdsa/numbertheory.py | def polynomial_multiply_mod( m1, m2, polymod, p ):
"""Polynomial multiplication modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# This is just a seat-of-the-pants implementation.
# This module has been tested only by extensive use
# ... | def polynomial_multiply_mod( m1, m2, polymod, p ):
"""Polynomial multiplication modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# This is just a seat-of-the-pants implementation.
# This module has been tested only by extensive use
# ... | [
"Polynomial",
"multiplication",
"modulo",
"a",
"polynomial",
"over",
"ints",
"mod",
"p",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L71-L92 | [
"def",
"polynomial_multiply_mod",
"(",
"m1",
",",
"m2",
",",
"polymod",
",",
"p",
")",
":",
"# This is just a seat-of-the-pants implementation.",
"# This module has been tested only by extensive use",
"# in calculating modular square roots.",
"# Initialize the product to zero:",
"pro... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | polynomial_exp_mod | Polynomial exponentiation modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x. | ecdsa/numbertheory.py | def polynomial_exp_mod( base, exponent, polymod, p ):
"""Polynomial exponentiation modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# Based on the Handbook of Applied Cryptography, algorithm 2.227.
# This module has been tested only by ... | def polynomial_exp_mod( base, exponent, polymod, p ):
"""Polynomial exponentiation modulo a polynomial over ints mod p.
Polynomials are represented as lists of coefficients
of increasing powers of x."""
# Based on the Handbook of Applied Cryptography, algorithm 2.227.
# This module has been tested only by ... | [
"Polynomial",
"exponentiation",
"modulo",
"a",
"polynomial",
"over",
"ints",
"mod",
"p",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L95-L120 | [
"def",
"polynomial_exp_mod",
"(",
"base",
",",
"exponent",
",",
"polymod",
",",
"p",
")",
":",
"# Based on the Handbook of Applied Cryptography, algorithm 2.227.",
"# This module has been tested only by extensive use",
"# in calculating modular square roots.",
"assert",
"exponent",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | jacobi | Jacobi symbol | ecdsa/numbertheory.py | def jacobi( a, n ):
"""Jacobi symbol"""
# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.
# This function has been tested by comparison with a small
# table printed in HAC, and by extensive use in calculating
# modular square roots.
assert n >= 3
assert n%2 == 1
a = a % n
if a... | def jacobi( a, n ):
"""Jacobi symbol"""
# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.
# This function has been tested by comparison with a small
# table printed in HAC, and by extensive use in calculating
# modular square roots.
assert n >= 3
assert n%2 == 1
a = a % n
if a... | [
"Jacobi",
"symbol"
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L124-L145 | [
"def",
"jacobi",
"(",
"a",
",",
"n",
")",
":",
"# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.",
"# This function has been tested by comparison with a small",
"# table printed in HAC, and by extensive use in calculating",
"# modular square roots.",
"assert",
"n",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | square_root_mod_prime | Modular square root of a, mod p, p prime. | ecdsa/numbertheory.py | def square_root_mod_prime( a, p ):
"""Modular square root of a, mod p, p prime."""
# Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39.
# This module has been tested for all values in [0,p-1] for
# every prime p from 3 to 1229.
assert 0 <= a < p
assert 1 < p
if a == 0: return 0
... | def square_root_mod_prime( a, p ):
"""Modular square root of a, mod p, p prime."""
# Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39.
# This module has been tested for all values in [0,p-1] for
# every prime p from 3 to 1229.
assert 0 <= a < p
assert 1 < p
if a == 0: return 0
... | [
"Modular",
"square",
"root",
"of",
"a",
"mod",
"p",
"p",
"prime",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L149-L181 | [
"def",
"square_root_mod_prime",
"(",
"a",
",",
"p",
")",
":",
"# Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39.",
"# This module has been tested for all values in [0,p-1] for",
"# every prime p from 3 to 1229.",
"assert",
"0",
"<=",
"a",
"<",
"p",
"assert",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | inverse_mod | Inverse of a mod m. | ecdsa/numbertheory.py | def inverse_mod( a, m ):
"""Inverse of a mod m."""
if a < 0 or m <= a: a = a % m
# From Ferguson and Schneier, roughly:
c, d = a, m
uc, vc, ud, vd = 1, 0, 0, 1
while c != 0:
q, c, d = divmod( d, c ) + ( c, )
uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
# At this point, d is the GCD, and ud*a+... | def inverse_mod( a, m ):
"""Inverse of a mod m."""
if a < 0 or m <= a: a = a % m
# From Ferguson and Schneier, roughly:
c, d = a, m
uc, vc, ud, vd = 1, 0, 0, 1
while c != 0:
q, c, d = divmod( d, c ) + ( c, )
uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
# At this point, d is the GCD, and ud*a+... | [
"Inverse",
"of",
"a",
"mod",
"m",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L185-L203 | [
"def",
"inverse_mod",
"(",
"a",
",",
"m",
")",
":",
"if",
"a",
"<",
"0",
"or",
"m",
"<=",
"a",
":",
"a",
"=",
"a",
"%",
"m",
"# From Ferguson and Schneier, roughly:",
"c",
",",
"d",
"=",
"a",
",",
"m",
"uc",
",",
"vc",
",",
"ud",
",",
"vd",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | gcd2 | Greatest common divisor using Euclid's algorithm. | ecdsa/numbertheory.py | def gcd2(a, b):
"""Greatest common divisor using Euclid's algorithm."""
while a:
a, b = b%a, a
return b | def gcd2(a, b):
"""Greatest common divisor using Euclid's algorithm."""
while a:
a, b = b%a, a
return b | [
"Greatest",
"common",
"divisor",
"using",
"Euclid",
"s",
"algorithm",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L206-L210 | [
"def",
"gcd2",
"(",
"a",
",",
"b",
")",
":",
"while",
"a",
":",
"a",
",",
"b",
"=",
"b",
"%",
"a",
",",
"a",
"return",
"b"
] | c583756c118039cfcfe256f7a3285618914d16a5 |
train | gcd | Greatest common divisor.
Usage: gcd( [ 2, 4, 6 ] )
or: gcd( 2, 4, 6 ) | ecdsa/numbertheory.py | def gcd( *a ):
"""Greatest common divisor.
Usage: gcd( [ 2, 4, 6 ] )
or: gcd( 2, 4, 6 )
"""
if len( a ) > 1: return reduce( gcd2, a )
if hasattr( a[0], "__iter__" ): return reduce( gcd2, a[0] )
return a[0] | def gcd( *a ):
"""Greatest common divisor.
Usage: gcd( [ 2, 4, 6 ] )
or: gcd( 2, 4, 6 )
"""
if len( a ) > 1: return reduce( gcd2, a )
if hasattr( a[0], "__iter__" ): return reduce( gcd2, a[0] )
return a[0] | [
"Greatest",
"common",
"divisor",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L213-L222 | [
"def",
"gcd",
"(",
"*",
"a",
")",
":",
"if",
"len",
"(",
"a",
")",
">",
"1",
":",
"return",
"reduce",
"(",
"gcd2",
",",
"a",
")",
"if",
"hasattr",
"(",
"a",
"[",
"0",
"]",
",",
"\"__iter__\"",
")",
":",
"return",
"reduce",
"(",
"gcd2",
",",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | lcm | Least common multiple.
Usage: lcm( [ 3, 4, 5 ] )
or: lcm( 3, 4, 5 ) | ecdsa/numbertheory.py | def lcm( *a ):
"""Least common multiple.
Usage: lcm( [ 3, 4, 5 ] )
or: lcm( 3, 4, 5 )
"""
if len( a ) > 1: return reduce( lcm2, a )
if hasattr( a[0], "__iter__" ): return reduce( lcm2, a[0] )
return a[0] | def lcm( *a ):
"""Least common multiple.
Usage: lcm( [ 3, 4, 5 ] )
or: lcm( 3, 4, 5 )
"""
if len( a ) > 1: return reduce( lcm2, a )
if hasattr( a[0], "__iter__" ): return reduce( lcm2, a[0] )
return a[0] | [
"Least",
"common",
"multiple",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L231-L240 | [
"def",
"lcm",
"(",
"*",
"a",
")",
":",
"if",
"len",
"(",
"a",
")",
">",
"1",
":",
"return",
"reduce",
"(",
"lcm2",
",",
"a",
")",
"if",
"hasattr",
"(",
"a",
"[",
"0",
"]",
",",
"\"__iter__\"",
")",
":",
"return",
"reduce",
"(",
"lcm2",
",",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | factorization | Decompose n into a list of (prime,exponent) pairs. | ecdsa/numbertheory.py | def factorization( n ):
"""Decompose n into a list of (prime,exponent) pairs."""
assert isinstance( n, integer_types )
if n < 2: return []
result = []
d = 2
# Test the small primes:
for d in smallprimes:
if d > n: break
q, r = divmod( n, d )
if r == 0:
count = 1
while d <= n:
... | def factorization( n ):
"""Decompose n into a list of (prime,exponent) pairs."""
assert isinstance( n, integer_types )
if n < 2: return []
result = []
d = 2
# Test the small primes:
for d in smallprimes:
if d > n: break
q, r = divmod( n, d )
if r == 0:
count = 1
while d <= n:
... | [
"Decompose",
"n",
"into",
"a",
"list",
"of",
"(",
"prime",
"exponent",
")",
"pairs",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L244-L291 | [
"def",
"factorization",
"(",
"n",
")",
":",
"assert",
"isinstance",
"(",
"n",
",",
"integer_types",
")",
"if",
"n",
"<",
"2",
":",
"return",
"[",
"]",
"result",
"=",
"[",
"]",
"d",
"=",
"2",
"# Test the small primes:",
"for",
"d",
"in",
"smallprimes",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | phi | Return the Euler totient function of n. | ecdsa/numbertheory.py | def phi( n ):
"""Return the Euler totient function of n."""
assert isinstance( n, integer_types )
if n < 3: return 1
result = 1
ff = factorization( n )
for f in ff:
e = f[1]
if e > 1:
result = result * f[0] ** (e-1) * ( f[0] - 1 )
else:
result = result * ( f[0] - 1 )
return resu... | def phi( n ):
"""Return the Euler totient function of n."""
assert isinstance( n, integer_types )
if n < 3: return 1
result = 1
ff = factorization( n )
for f in ff:
e = f[1]
if e > 1:
result = result * f[0] ** (e-1) * ( f[0] - 1 )
else:
result = result * ( f[0] - 1 )
return resu... | [
"Return",
"the",
"Euler",
"totient",
"function",
"of",
"n",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L295-L310 | [
"def",
"phi",
"(",
"n",
")",
":",
"assert",
"isinstance",
"(",
"n",
",",
"integer_types",
")",
"if",
"n",
"<",
"3",
":",
"return",
"1",
"result",
"=",
"1",
"ff",
"=",
"factorization",
"(",
"n",
")",
"for",
"f",
"in",
"ff",
":",
"e",
"=",
"f",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | carmichael_of_factorized | Return the Carmichael function of a number that is
represented as a list of (prime,exponent) pairs. | ecdsa/numbertheory.py | def carmichael_of_factorized( f_list ):
"""Return the Carmichael function of a number that is
represented as a list of (prime,exponent) pairs.
"""
if len( f_list ) < 1: return 1
result = carmichael_of_ppower( f_list[0] )
for i in range( 1, len( f_list ) ):
result = lcm( result, carmichael_of_ppower( f... | def carmichael_of_factorized( f_list ):
"""Return the Carmichael function of a number that is
represented as a list of (prime,exponent) pairs.
"""
if len( f_list ) < 1: return 1
result = carmichael_of_ppower( f_list[0] )
for i in range( 1, len( f_list ) ):
result = lcm( result, carmichael_of_ppower( f... | [
"Return",
"the",
"Carmichael",
"function",
"of",
"a",
"number",
"that",
"is",
"represented",
"as",
"a",
"list",
"of",
"(",
"prime",
"exponent",
")",
"pairs",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L323-L334 | [
"def",
"carmichael_of_factorized",
"(",
"f_list",
")",
":",
"if",
"len",
"(",
"f_list",
")",
"<",
"1",
":",
"return",
"1",
"result",
"=",
"carmichael_of_ppower",
"(",
"f_list",
"[",
"0",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | carmichael_of_ppower | Carmichael function of the given power of the given prime. | ecdsa/numbertheory.py | def carmichael_of_ppower( pp ):
"""Carmichael function of the given power of the given prime.
"""
p, a = pp
if p == 2 and a > 2: return 2**(a-2)
else: return (p-1) * p**(a-1) | def carmichael_of_ppower( pp ):
"""Carmichael function of the given power of the given prime.
"""
p, a = pp
if p == 2 and a > 2: return 2**(a-2)
else: return (p-1) * p**(a-1) | [
"Carmichael",
"function",
"of",
"the",
"given",
"power",
"of",
"the",
"given",
"prime",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L336-L342 | [
"def",
"carmichael_of_ppower",
"(",
"pp",
")",
":",
"p",
",",
"a",
"=",
"pp",
"if",
"p",
"==",
"2",
"and",
"a",
">",
"2",
":",
"return",
"2",
"**",
"(",
"a",
"-",
"2",
")",
"else",
":",
"return",
"(",
"p",
"-",
"1",
")",
"*",
"p",
"**",
"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | order_mod | Return the order of x in the multiplicative group mod m. | ecdsa/numbertheory.py | def order_mod( x, m ):
"""Return the order of x in the multiplicative group mod m.
"""
# Warning: this implementation is not very clever, and will
# take a long time if m is very large.
if m <= 1: return 0
assert gcd( x, m ) == 1
z = x
result = 1
while z != 1:
z = ( z * x ) % m
result = re... | def order_mod( x, m ):
"""Return the order of x in the multiplicative group mod m.
"""
# Warning: this implementation is not very clever, and will
# take a long time if m is very large.
if m <= 1: return 0
assert gcd( x, m ) == 1
z = x
result = 1
while z != 1:
z = ( z * x ) % m
result = re... | [
"Return",
"the",
"order",
"of",
"x",
"in",
"the",
"multiplicative",
"group",
"mod",
"m",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L346-L362 | [
"def",
"order_mod",
"(",
"x",
",",
"m",
")",
":",
"# Warning: this implementation is not very clever, and will",
"# take a long time if m is very large.",
"if",
"m",
"<=",
"1",
":",
"return",
"0",
"assert",
"gcd",
"(",
"x",
",",
"m",
")",
"==",
"1",
"z",
"=",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | largest_factor_relatively_prime | Return the largest factor of a relatively prime to b. | ecdsa/numbertheory.py | def largest_factor_relatively_prime( a, b ):
"""Return the largest factor of a relatively prime to b.
"""
while 1:
d = gcd( a, b )
if d <= 1: break
b = d
while 1:
q, r = divmod( a, d )
if r > 0:
break
a = q
return a | def largest_factor_relatively_prime( a, b ):
"""Return the largest factor of a relatively prime to b.
"""
while 1:
d = gcd( a, b )
if d <= 1: break
b = d
while 1:
q, r = divmod( a, d )
if r > 0:
break
a = q
return a | [
"Return",
"the",
"largest",
"factor",
"of",
"a",
"relatively",
"prime",
"to",
"b",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L365-L378 | [
"def",
"largest_factor_relatively_prime",
"(",
"a",
",",
"b",
")",
":",
"while",
"1",
":",
"d",
"=",
"gcd",
"(",
"a",
",",
"b",
")",
"if",
"d",
"<=",
"1",
":",
"break",
"b",
"=",
"d",
"while",
"1",
":",
"q",
",",
"r",
"=",
"divmod",
"(",
"a",... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | is_prime | Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first test,
5 got past the sec... | ecdsa/numbertheory.py | def is_prime( n ):
"""Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first te... | def is_prime( n ):
"""Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first te... | [
"Return",
"True",
"if",
"x",
"is",
"prime",
"False",
"otherwise",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L389-L459 | [
"def",
"is_prime",
"(",
"n",
")",
":",
"# (This is used to study the risk of false positives:)",
"global",
"miller_rabin_test_count",
"miller_rabin_test_count",
"=",
"0",
"if",
"n",
"<=",
"smallprimes",
"[",
"-",
"1",
"]",
":",
"if",
"n",
"in",
"smallprimes",
":",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | next_prime | Return the smallest prime larger than the starting value. | ecdsa/numbertheory.py | def next_prime( starting_value ):
"Return the smallest prime larger than the starting value."
if starting_value < 2: return 2
result = ( starting_value + 1 ) | 1
while not is_prime( result ): result = result + 2
return result | def next_prime( starting_value ):
"Return the smallest prime larger than the starting value."
if starting_value < 2: return 2
result = ( starting_value + 1 ) | 1
while not is_prime( result ): result = result + 2
return result | [
"Return",
"the",
"smallest",
"prime",
"larger",
"than",
"the",
"starting",
"value",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/numbertheory.py#L462-L468 | [
"def",
"next_prime",
"(",
"starting_value",
")",
":",
"if",
"starting_value",
"<",
"2",
":",
"return",
"2",
"result",
"=",
"(",
"starting_value",
"+",
"1",
")",
"|",
"1",
"while",
"not",
"is_prime",
"(",
"result",
")",
":",
"result",
"=",
"result",
"+"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | _feed_stream | Uses feeder to read and convert from in_stream and write to out_stream. | pyaes/blockfeeder.py | def _feed_stream(feeder, in_stream, out_stream, block_size = BLOCK_SIZE):
'Uses feeder to read and convert from in_stream and write to out_stream.'
while True:
chunk = in_stream.read(block_size)
if not chunk:
break
converted = feeder.feed(chunk)
out_stream.write(conv... | def _feed_stream(feeder, in_stream, out_stream, block_size = BLOCK_SIZE):
'Uses feeder to read and convert from in_stream and write to out_stream.'
while True:
chunk = in_stream.read(block_size)
if not chunk:
break
converted = feeder.feed(chunk)
out_stream.write(conv... | [
"Uses",
"feeder",
"to",
"read",
"and",
"convert",
"from",
"in_stream",
"and",
"write",
"to",
"out_stream",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/pyaes/blockfeeder.py#L203-L213 | [
"def",
"_feed_stream",
"(",
"feeder",
",",
"in_stream",
",",
"out_stream",
",",
"block_size",
"=",
"BLOCK_SIZE",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"in_stream",
".",
"read",
"(",
"block_size",
")",
"if",
"not",
"chunk",
":",
"break",
"converted"... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | encrypt_stream | Encrypts a stream of bytes from in_stream to out_stream using mode. | pyaes/blockfeeder.py | def encrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):
'Encrypts a stream of bytes from in_stream to out_stream using mode.'
encrypter = Encrypter(mode, padding = padding)
_feed_stream(encrypter, in_stream, out_stream, block_size) | def encrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):
'Encrypts a stream of bytes from in_stream to out_stream using mode.'
encrypter = Encrypter(mode, padding = padding)
_feed_stream(encrypter, in_stream, out_stream, block_size) | [
"Encrypts",
"a",
"stream",
"of",
"bytes",
"from",
"in_stream",
"to",
"out_stream",
"using",
"mode",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/pyaes/blockfeeder.py#L216-L220 | [
"def",
"encrypt_stream",
"(",
"mode",
",",
"in_stream",
",",
"out_stream",
",",
"block_size",
"=",
"BLOCK_SIZE",
",",
"padding",
"=",
"PADDING_DEFAULT",
")",
":",
"encrypter",
"=",
"Encrypter",
"(",
"mode",
",",
"padding",
"=",
"padding",
")",
"_feed_stream",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | decrypt_stream | Decrypts a stream of bytes from in_stream to out_stream using mode. | pyaes/blockfeeder.py | def decrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):
'Decrypts a stream of bytes from in_stream to out_stream using mode.'
decrypter = Decrypter(mode, padding = padding)
_feed_stream(decrypter, in_stream, out_stream, block_size) | def decrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):
'Decrypts a stream of bytes from in_stream to out_stream using mode.'
decrypter = Decrypter(mode, padding = padding)
_feed_stream(decrypter, in_stream, out_stream, block_size) | [
"Decrypts",
"a",
"stream",
"of",
"bytes",
"from",
"in_stream",
"to",
"out_stream",
"using",
"mode",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/pyaes/blockfeeder.py#L223-L227 | [
"def",
"decrypt_stream",
"(",
"mode",
",",
"in_stream",
",",
"out_stream",
",",
"block_size",
"=",
"BLOCK_SIZE",
",",
"padding",
"=",
"PADDING_DEFAULT",
")",
":",
"decrypter",
"=",
"Decrypter",
"(",
"mode",
",",
"padding",
"=",
"padding",
")",
"_feed_stream",
... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | BlockFeeder.feed | Provide bytes to encrypt (or decrypt), returning any bytes
possible from this or any previous calls to feed.
Call with None or an empty string to flush the mode of
operation and return any final bytes; no further calls to
feed may be made. | pyaes/blockfeeder.py | def feed(self, data = None):
'''Provide bytes to encrypt (or decrypt), returning any bytes
possible from this or any previous calls to feed.
Call with None or an empty string to flush the mode of
operation and return any final bytes; no further calls to
feed may be m... | def feed(self, data = None):
'''Provide bytes to encrypt (or decrypt), returning any bytes
possible from this or any previous calls to feed.
Call with None or an empty string to flush the mode of
operation and return any final bytes; no further calls to
feed may be m... | [
"Provide",
"bytes",
"to",
"encrypt",
"(",
"or",
"decrypt",
")",
"returning",
"any",
"bytes",
"possible",
"from",
"this",
"or",
"any",
"previous",
"calls",
"to",
"feed",
"."
] | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/pyaes/blockfeeder.py#L156-L183 | [
"def",
"feed",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"if",
"self",
".",
"_buffer",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'already finished feeder'",
")",
"# Finalize; process the spare bytes we were keeping",
"if",
"not",
"data",
":",
"resul... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | randrange | Return a random integer k such that 1 <= k < order, uniformly
distributed across that range. For simplicity, this only behaves well if
'order' is fairly close (but below) a power of 256. The try-try-again
algorithm we use takes longer and longer time (on average) to complete as
'order' falls, rising to ... | ecdsa/util.py | def randrange(order, entropy=None):
"""Return a random integer k such that 1 <= k < order, uniformly
distributed across that range. For simplicity, this only behaves well if
'order' is fairly close (but below) a power of 256. The try-try-again
algorithm we use takes longer and longer time (on average) t... | def randrange(order, entropy=None):
"""Return a random integer k such that 1 <= k < order, uniformly
distributed across that range. For simplicity, this only behaves well if
'order' is fairly close (but below) a power of 256. The try-try-again
algorithm we use takes longer and longer time (on average) t... | [
"Return",
"a",
"random",
"integer",
"k",
"such",
"that",
"1",
"<",
"=",
"k",
"<",
"order",
"uniformly",
"distributed",
"across",
"that",
"range",
".",
"For",
"simplicity",
"this",
"only",
"behaves",
"well",
"if",
"order",
"is",
"fairly",
"close",
"(",
"b... | espressif/esptool | python | https://github.com/espressif/esptool/blob/c583756c118039cfcfe256f7a3285618914d16a5/ecdsa/util.py#L19-L57 | [
"def",
"randrange",
"(",
"order",
",",
"entropy",
"=",
"None",
")",
":",
"# we could handle arbitrary orders (even 256**k+1) better if we created",
"# candidates bit-wise instead of byte-wise, which would reduce the",
"# worst-case behavior to avg=2 loops, but that would be more complex. The... | c583756c118039cfcfe256f7a3285618914d16a5 |
train | generate_authors | Create AUTHORS file using git commits. | tools/generate_authors.py | def generate_authors(git_dir):
"""Create AUTHORS file using git commits."""
authors = []
emails = []
git_log_cmd = ['git', 'log', '--format=%aN|%aE']
tmp_authors = _run_shell_command(git_log_cmd, git_dir).split('\n')
for author_str in tmp_authors:
author, email = author_str.split('|')
... | def generate_authors(git_dir):
"""Create AUTHORS file using git commits."""
authors = []
emails = []
git_log_cmd = ['git', 'log', '--format=%aN|%aE']
tmp_authors = _run_shell_command(git_log_cmd, git_dir).split('\n')
for author_str in tmp_authors:
author, email = author_str.split('|')
... | [
"Create",
"AUTHORS",
"file",
"using",
"git",
"commits",
"."
] | Qiskit/qiskit | python | https://github.com/Qiskit/qiskit/blob/f1c3b63b23f912c1026dc886a723b58cf0c3b3df/tools/generate_authors.py#L22-L50 | [
"def",
"generate_authors",
"(",
"git_dir",
")",
":",
"authors",
"=",
"[",
"]",
"emails",
"=",
"[",
"]",
"git_log_cmd",
"=",
"[",
"'git'",
",",
"'log'",
",",
"'--format=%aN|%aE'",
"]",
"tmp_authors",
"=",
"_run_shell_command",
"(",
"git_log_cmd",
",",
"git_di... | f1c3b63b23f912c1026dc886a723b58cf0c3b3df |
train | NoUTurnSampler._initalize_tree | Initalizes root node of the tree, i.e depth = 0 | pgmpy/sampling/NUTS.py | def _initalize_tree(self, position, momentum, slice_var, stepsize):
"""
Initalizes root node of the tree, i.e depth = 0
"""
position_bar, momentum_bar, _ = self.simulate_dynamics(self.model, position, momentum, stepsize,
sel... | def _initalize_tree(self, position, momentum, slice_var, stepsize):
"""
Initalizes root node of the tree, i.e depth = 0
"""
position_bar, momentum_bar, _ = self.simulate_dynamics(self.model, position, momentum, stepsize,
sel... | [
"Initalizes",
"root",
"node",
"of",
"the",
"tree",
"i",
".",
"e",
"depth",
"=",
"0"
] | pgmpy/pgmpy | python | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/NUTS.py#L66-L81 | [
"def",
"_initalize_tree",
"(",
"self",
",",
"position",
",",
"momentum",
",",
"slice_var",
",",
"stepsize",
")",
":",
"position_bar",
",",
"momentum_bar",
",",
"_",
"=",
"self",
".",
"simulate_dynamics",
"(",
"self",
".",
"model",
",",
"position",
",",
"mo... | 9381a66aba3c3871d3ccd00672b148d17d63239e |
train | NoUTurnSampler._build_tree | Recursively builds a tree for proposing new position and momentum | pgmpy/sampling/NUTS.py | def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize):
"""
Recursively builds a tree for proposing new position and momentum
"""
# Parameter names in algorithm (here -> representation in algorithm)
# position -> theta, momentum -> r, slice_var -> u, di... | def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize):
"""
Recursively builds a tree for proposing new position and momentum
"""
# Parameter names in algorithm (here -> representation in algorithm)
# position -> theta, momentum -> r, slice_var -> u, di... | [
"Recursively",
"builds",
"a",
"tree",
"for",
"proposing",
"new",
"position",
"and",
"momentum"
] | pgmpy/pgmpy | python | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/NUTS.py#L97-L139 | [
"def",
"_build_tree",
"(",
"self",
",",
"position",
",",
"momentum",
",",
"slice_var",
",",
"direction",
",",
"depth",
",",
"stepsize",
")",
":",
"# Parameter names in algorithm (here -> representation in algorithm)",
"# position -> theta, momentum -> r, slice_var -> u, directi... | 9381a66aba3c3871d3ccd00672b148d17d63239e |
train | NoUTurnSampler._sample | Returns a sample using a single iteration of NUTS | pgmpy/sampling/NUTS.py | def _sample(self, position, stepsize):
"""
Returns a sample using a single iteration of NUTS
"""
# Re-sampling momentum
momentum = np.random.normal(0, 1, len(position))
# Initializations
depth = 0
position_backward, position_forward = position, position
... | def _sample(self, position, stepsize):
"""
Returns a sample using a single iteration of NUTS
"""
# Re-sampling momentum
momentum = np.random.normal(0, 1, len(position))
# Initializations
depth = 0
position_backward, position_forward = position, position
... | [
"Returns",
"a",
"sample",
"using",
"a",
"single",
"iteration",
"of",
"NUTS"
] | pgmpy/pgmpy | python | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/NUTS.py#L141-L181 | [
"def",
"_sample",
"(",
"self",
",",
"position",
",",
"stepsize",
")",
":",
"# Re-sampling momentum",
"momentum",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"1",
",",
"len",
"(",
"position",
")",
")",
"# Initializations",
"depth",
"=",
"0",
... | 9381a66aba3c3871d3ccd00672b148d17d63239e |
train | NoUTurnSampler.sample | Method to return samples using No U Turn Sampler
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_samples: int
Number of samples to be generated
... | pgmpy/sampling/NUTS.py | def sample(self, initial_pos, num_samples, stepsize=None, return_type='dataframe'):
"""
Method to return samples using No U Turn Sampler
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
... | def sample(self, initial_pos, num_samples, stepsize=None, return_type='dataframe'):
"""
Method to return samples using No U Turn Sampler
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
... | [
"Method",
"to",
"return",
"samples",
"using",
"No",
"U",
"Turn",
"Sampler"
] | pgmpy/pgmpy | python | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/NUTS.py#L183-L250 | [
"def",
"sample",
"(",
"self",
",",
"initial_pos",
",",
"num_samples",
",",
"stepsize",
"=",
"None",
",",
"return_type",
"=",
"'dataframe'",
")",
":",
"initial_pos",
"=",
"_check_1d_array_object",
"(",
"initial_pos",
",",
"'initial_pos'",
")",
"_check_length_equal"... | 9381a66aba3c3871d3ccd00672b148d17d63239e |
train | NoUTurnSampler.generate_sample | Returns a generator type object whose each iteration yields a sample
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_samples: int
Number of samples to... | pgmpy/sampling/NUTS.py | def generate_sample(self, initial_pos, num_samples, stepsize=None):
"""
Returns a generator type object whose each iteration yields a sample
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
... | def generate_sample(self, initial_pos, num_samples, stepsize=None):
"""
Returns a generator type object whose each iteration yields a sample
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
... | [
"Returns",
"a",
"generator",
"type",
"object",
"whose",
"each",
"iteration",
"yields",
"a",
"sample"
] | pgmpy/pgmpy | python | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/NUTS.py#L252-L308 | [
"def",
"generate_sample",
"(",
"self",
",",
"initial_pos",
",",
"num_samples",
",",
"stepsize",
"=",
"None",
")",
":",
"initial_pos",
"=",
"_check_1d_array_object",
"(",
"initial_pos",
",",
"'initial_pos'",
")",
"_check_length_equal",
"(",
"initial_pos",
",",
"sel... | 9381a66aba3c3871d3ccd00672b148d17d63239e |
train | NoUTurnSamplerDA._build_tree | Recursively builds a tree for proposing new position and momentum | pgmpy/sampling/NUTS.py | def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0):
"""
Recursively builds a tree for proposing new position and momentum
"""
if depth == 0:
position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
... | def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0):
"""
Recursively builds a tree for proposing new position and momentum
"""
if depth == 0:
position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
... | [
"Recursively",
"builds",
"a",
"tree",
"for",
"proposing",
"new",
"position",
"and",
"momentum"
] | pgmpy/pgmpy | python | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/NUTS.py#L380-L423 | [
"def",
"_build_tree",
"(",
"self",
",",
"position",
",",
"momentum",
",",
"slice_var",
",",
"direction",
",",
"depth",
",",
"stepsize",
",",
"position0",
",",
"momentum0",
")",
":",
"if",
"depth",
"==",
"0",
":",
"position_bar",
",",
"momentum_bar",
",",
... | 9381a66aba3c3871d3ccd00672b148d17d63239e |
train | NoUTurnSamplerDA.sample | Returns samples using No U Turn Sampler with dual averaging
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_adapt: int
The number of interations to ru... | pgmpy/sampling/NUTS.py | def sample(self, initial_pos, num_adapt, num_samples, stepsize=None, return_type='dataframe'):
"""
Returns samples using No U Turn Sampler with dual averaging
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, ... | def sample(self, initial_pos, num_adapt, num_samples, stepsize=None, return_type='dataframe'):
"""
Returns samples using No U Turn Sampler with dual averaging
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, ... | [
"Returns",
"samples",
"using",
"No",
"U",
"Turn",
"Sampler",
"with",
"dual",
"averaging"
] | pgmpy/pgmpy | python | https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/sampling/NUTS.py#L470-L553 | [
"def",
"sample",
"(",
"self",
",",
"initial_pos",
",",
"num_adapt",
",",
"num_samples",
",",
"stepsize",
"=",
"None",
",",
"return_type",
"=",
"'dataframe'",
")",
":",
"initial_pos",
"=",
"_check_1d_array_object",
"(",
"initial_pos",
",",
"'initial_pos'",
")",
... | 9381a66aba3c3871d3ccd00672b148d17d63239e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.