id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
3,300 | gccxml/pygccxml | release_utils/utils.py | find_version | def find_version(file_path):
"""
Find the version of pygccxml.
Used by setup.py and the sphinx's conf.py.
Inspired by https://packaging.python.org/single_source_version/
Args:
file_path (str): path to the file containing the version.
"""
with io.open(
os.path.join(
os.path.dirname(__file__),
os.path.normpath(file_path)),
encoding="utf8") as fp:
content = fp.read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
content, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.") | python | def find_version(file_path):
"""
Find the version of pygccxml.
Used by setup.py and the sphinx's conf.py.
Inspired by https://packaging.python.org/single_source_version/
Args:
file_path (str): path to the file containing the version.
"""
with io.open(
os.path.join(
os.path.dirname(__file__),
os.path.normpath(file_path)),
encoding="utf8") as fp:
content = fp.read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
content, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.") | [
"def",
"find_version",
"(",
"file_path",
")",
":",
"with",
"io",
".",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"os",
".",
"path",
".",
"normpath",
"(",
"file_path",
")",
")",
",",
"encoding",
"=",
"\"utf8\"",
")",
"as",
"fp",
":",
"content",
"=",
"fp",
".",
"read",
"(",
")",
"version_match",
"=",
"re",
".",
"search",
"(",
"r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"",
",",
"content",
",",
"re",
".",
"M",
")",
"if",
"version_match",
":",
"return",
"version_match",
".",
"group",
"(",
"1",
")",
"raise",
"RuntimeError",
"(",
"\"Unable to find version string.\"",
")"
] | Find the version of pygccxml.
Used by setup.py and the sphinx's conf.py.
Inspired by https://packaging.python.org/single_source_version/
Args:
file_path (str): path to the file containing the version. | [
"Find",
"the",
"version",
"of",
"pygccxml",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/release_utils/utils.py#L12-L34 |
3,301 | gccxml/pygccxml | pygccxml/parser/scanner.py | scanner_t.__read_byte_size | def __read_byte_size(decl, attrs):
"""Using duck typing to set the size instead of in constructor"""
size = attrs.get(XML_AN_SIZE, 0)
# Make sure the size is in bytes instead of bits
decl.byte_size = int(size) / 8 | python | def __read_byte_size(decl, attrs):
"""Using duck typing to set the size instead of in constructor"""
size = attrs.get(XML_AN_SIZE, 0)
# Make sure the size is in bytes instead of bits
decl.byte_size = int(size) / 8 | [
"def",
"__read_byte_size",
"(",
"decl",
",",
"attrs",
")",
":",
"size",
"=",
"attrs",
".",
"get",
"(",
"XML_AN_SIZE",
",",
"0",
")",
"# Make sure the size is in bytes instead of bits",
"decl",
".",
"byte_size",
"=",
"int",
"(",
"size",
")",
"/",
"8"
] | Using duck typing to set the size instead of in constructor | [
"Using",
"duck",
"typing",
"to",
"set",
"the",
"size",
"instead",
"of",
"in",
"constructor"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/scanner.py#L338-L342 |
3,302 | gccxml/pygccxml | pygccxml/parser/scanner.py | scanner_t.__read_byte_offset | def __read_byte_offset(decl, attrs):
"""Using duck typing to set the offset instead of in constructor"""
offset = attrs.get(XML_AN_OFFSET, 0)
# Make sure the size is in bytes instead of bits
decl.byte_offset = int(offset) / 8 | python | def __read_byte_offset(decl, attrs):
"""Using duck typing to set the offset instead of in constructor"""
offset = attrs.get(XML_AN_OFFSET, 0)
# Make sure the size is in bytes instead of bits
decl.byte_offset = int(offset) / 8 | [
"def",
"__read_byte_offset",
"(",
"decl",
",",
"attrs",
")",
":",
"offset",
"=",
"attrs",
".",
"get",
"(",
"XML_AN_OFFSET",
",",
"0",
")",
"# Make sure the size is in bytes instead of bits",
"decl",
".",
"byte_offset",
"=",
"int",
"(",
"offset",
")",
"/",
"8"
] | Using duck typing to set the offset instead of in constructor | [
"Using",
"duck",
"typing",
"to",
"set",
"the",
"offset",
"instead",
"of",
"in",
"constructor"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/scanner.py#L345-L349 |
3,303 | gccxml/pygccxml | pygccxml/parser/scanner.py | scanner_t.__read_byte_align | def __read_byte_align(decl, attrs):
"""Using duck typing to set the alignment"""
align = attrs.get(XML_AN_ALIGN, 0)
# Make sure the size is in bytes instead of bits
decl.byte_align = int(align) / 8 | python | def __read_byte_align(decl, attrs):
"""Using duck typing to set the alignment"""
align = attrs.get(XML_AN_ALIGN, 0)
# Make sure the size is in bytes instead of bits
decl.byte_align = int(align) / 8 | [
"def",
"__read_byte_align",
"(",
"decl",
",",
"attrs",
")",
":",
"align",
"=",
"attrs",
".",
"get",
"(",
"XML_AN_ALIGN",
",",
"0",
")",
"# Make sure the size is in bytes instead of bits",
"decl",
".",
"byte_align",
"=",
"int",
"(",
"align",
")",
"/",
"8"
] | Using duck typing to set the alignment | [
"Using",
"duck",
"typing",
"to",
"set",
"the",
"alignment"
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/scanner.py#L352-L356 |
3,304 | gccxml/pygccxml | pygccxml/parser/declarations_joiner.py | bind_aliases | def bind_aliases(decls):
"""
This function binds between class and it's typedefs.
:param decls: list of all declarations
:rtype: None
"""
visited = set()
typedefs = [
decl for decl in decls if isinstance(decl, declarations.typedef_t)]
for decl in typedefs:
type_ = declarations.remove_alias(decl.decl_type)
if not isinstance(type_, declarations.declarated_t):
continue
cls_inst = type_.declaration
if not isinstance(cls_inst, declarations.class_types):
continue
if id(cls_inst) not in visited:
visited.add(id(cls_inst))
del cls_inst.aliases[:]
cls_inst.aliases.append(decl) | python | def bind_aliases(decls):
"""
This function binds between class and it's typedefs.
:param decls: list of all declarations
:rtype: None
"""
visited = set()
typedefs = [
decl for decl in decls if isinstance(decl, declarations.typedef_t)]
for decl in typedefs:
type_ = declarations.remove_alias(decl.decl_type)
if not isinstance(type_, declarations.declarated_t):
continue
cls_inst = type_.declaration
if not isinstance(cls_inst, declarations.class_types):
continue
if id(cls_inst) not in visited:
visited.add(id(cls_inst))
del cls_inst.aliases[:]
cls_inst.aliases.append(decl) | [
"def",
"bind_aliases",
"(",
"decls",
")",
":",
"visited",
"=",
"set",
"(",
")",
"typedefs",
"=",
"[",
"decl",
"for",
"decl",
"in",
"decls",
"if",
"isinstance",
"(",
"decl",
",",
"declarations",
".",
"typedef_t",
")",
"]",
"for",
"decl",
"in",
"typedefs",
":",
"type_",
"=",
"declarations",
".",
"remove_alias",
"(",
"decl",
".",
"decl_type",
")",
"if",
"not",
"isinstance",
"(",
"type_",
",",
"declarations",
".",
"declarated_t",
")",
":",
"continue",
"cls_inst",
"=",
"type_",
".",
"declaration",
"if",
"not",
"isinstance",
"(",
"cls_inst",
",",
"declarations",
".",
"class_types",
")",
":",
"continue",
"if",
"id",
"(",
"cls_inst",
")",
"not",
"in",
"visited",
":",
"visited",
".",
"add",
"(",
"id",
"(",
"cls_inst",
")",
")",
"del",
"cls_inst",
".",
"aliases",
"[",
":",
"]",
"cls_inst",
".",
"aliases",
".",
"append",
"(",
"decl",
")"
] | This function binds between class and it's typedefs.
:param decls: list of all declarations
:rtype: None | [
"This",
"function",
"binds",
"between",
"class",
"and",
"it",
"s",
"typedefs",
"."
] | 2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/declarations_joiner.py#L9-L32 |
3,305 | d11wtq/dockerpty | features/environment.py | after_scenario | def after_scenario(ctx, scenario):
"""
Cleans up docker containers used as test fixtures after test completes.
"""
if hasattr(ctx, 'container') and hasattr(ctx, 'client'):
try:
ctx.client.remove_container(ctx.container, force=True)
except:
pass | python | def after_scenario(ctx, scenario):
"""
Cleans up docker containers used as test fixtures after test completes.
"""
if hasattr(ctx, 'container') and hasattr(ctx, 'client'):
try:
ctx.client.remove_container(ctx.container, force=True)
except:
pass | [
"def",
"after_scenario",
"(",
"ctx",
",",
"scenario",
")",
":",
"if",
"hasattr",
"(",
"ctx",
",",
"'container'",
")",
"and",
"hasattr",
"(",
"ctx",
",",
"'client'",
")",
":",
"try",
":",
"ctx",
".",
"client",
".",
"remove_container",
"(",
"ctx",
".",
"container",
",",
"force",
"=",
"True",
")",
"except",
":",
"pass"
] | Cleans up docker containers used as test fixtures after test completes. | [
"Cleans",
"up",
"docker",
"containers",
"used",
"as",
"test",
"fixtures",
"after",
"test",
"completes",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/features/environment.py#L37-L46 |
3,306 | d11wtq/dockerpty | dockerpty/io.py | set_blocking | def set_blocking(fd, blocking=True):
"""
Set the given file-descriptor blocking or non-blocking.
Returns the original blocking status.
"""
old_flag = fcntl.fcntl(fd, fcntl.F_GETFL)
if blocking:
new_flag = old_flag & ~ os.O_NONBLOCK
else:
new_flag = old_flag | os.O_NONBLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, new_flag)
return not bool(old_flag & os.O_NONBLOCK) | python | def set_blocking(fd, blocking=True):
"""
Set the given file-descriptor blocking or non-blocking.
Returns the original blocking status.
"""
old_flag = fcntl.fcntl(fd, fcntl.F_GETFL)
if blocking:
new_flag = old_flag & ~ os.O_NONBLOCK
else:
new_flag = old_flag | os.O_NONBLOCK
fcntl.fcntl(fd, fcntl.F_SETFL, new_flag)
return not bool(old_flag & os.O_NONBLOCK) | [
"def",
"set_blocking",
"(",
"fd",
",",
"blocking",
"=",
"True",
")",
":",
"old_flag",
"=",
"fcntl",
".",
"fcntl",
"(",
"fd",
",",
"fcntl",
".",
"F_GETFL",
")",
"if",
"blocking",
":",
"new_flag",
"=",
"old_flag",
"&",
"~",
"os",
".",
"O_NONBLOCK",
"else",
":",
"new_flag",
"=",
"old_flag",
"|",
"os",
".",
"O_NONBLOCK",
"fcntl",
".",
"fcntl",
"(",
"fd",
",",
"fcntl",
".",
"F_SETFL",
",",
"new_flag",
")",
"return",
"not",
"bool",
"(",
"old_flag",
"&",
"os",
".",
"O_NONBLOCK",
")"
] | Set the given file-descriptor blocking or non-blocking.
Returns the original blocking status. | [
"Set",
"the",
"given",
"file",
"-",
"descriptor",
"blocking",
"or",
"non",
"-",
"blocking",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L25-L41 |
3,307 | d11wtq/dockerpty | dockerpty/io.py | select | def select(read_streams, write_streams, timeout=0):
"""
Select the streams from `read_streams` that are ready for reading, and
streams from `write_streams` ready for writing.
Uses `select.select()` internally but only returns two lists of ready streams.
"""
exception_streams = []
try:
return builtin_select.select(
read_streams,
write_streams,
exception_streams,
timeout,
)[0:2]
except builtin_select.error as e:
# POSIX signals interrupt select()
no = e.errno if six.PY3 else e[0]
if no == errno.EINTR:
return ([], [])
else:
raise e | python | def select(read_streams, write_streams, timeout=0):
"""
Select the streams from `read_streams` that are ready for reading, and
streams from `write_streams` ready for writing.
Uses `select.select()` internally but only returns two lists of ready streams.
"""
exception_streams = []
try:
return builtin_select.select(
read_streams,
write_streams,
exception_streams,
timeout,
)[0:2]
except builtin_select.error as e:
# POSIX signals interrupt select()
no = e.errno if six.PY3 else e[0]
if no == errno.EINTR:
return ([], [])
else:
raise e | [
"def",
"select",
"(",
"read_streams",
",",
"write_streams",
",",
"timeout",
"=",
"0",
")",
":",
"exception_streams",
"=",
"[",
"]",
"try",
":",
"return",
"builtin_select",
".",
"select",
"(",
"read_streams",
",",
"write_streams",
",",
"exception_streams",
",",
"timeout",
",",
")",
"[",
"0",
":",
"2",
"]",
"except",
"builtin_select",
".",
"error",
"as",
"e",
":",
"# POSIX signals interrupt select()",
"no",
"=",
"e",
".",
"errno",
"if",
"six",
".",
"PY3",
"else",
"e",
"[",
"0",
"]",
"if",
"no",
"==",
"errno",
".",
"EINTR",
":",
"return",
"(",
"[",
"]",
",",
"[",
"]",
")",
"else",
":",
"raise",
"e"
] | Select the streams from `read_streams` that are ready for reading, and
streams from `write_streams` ready for writing.
Uses `select.select()` internally but only returns two lists of ready streams. | [
"Select",
"the",
"streams",
"from",
"read_streams",
"that",
"are",
"ready",
"for",
"reading",
"and",
"streams",
"from",
"write_streams",
"ready",
"for",
"writing",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L44-L67 |
3,308 | d11wtq/dockerpty | dockerpty/io.py | Stream.read | def read(self, n=4096):
"""
Return `n` bytes of data from the Stream, or None at end of stream.
"""
while True:
try:
if hasattr(self.fd, 'recv'):
return self.fd.recv(n)
return os.read(self.fd.fileno(), n)
except EnvironmentError as e:
if e.errno not in Stream.ERRNO_RECOVERABLE:
raise e | python | def read(self, n=4096):
"""
Return `n` bytes of data from the Stream, or None at end of stream.
"""
while True:
try:
if hasattr(self.fd, 'recv'):
return self.fd.recv(n)
return os.read(self.fd.fileno(), n)
except EnvironmentError as e:
if e.errno not in Stream.ERRNO_RECOVERABLE:
raise e | [
"def",
"read",
"(",
"self",
",",
"n",
"=",
"4096",
")",
":",
"while",
"True",
":",
"try",
":",
"if",
"hasattr",
"(",
"self",
".",
"fd",
",",
"'recv'",
")",
":",
"return",
"self",
".",
"fd",
".",
"recv",
"(",
"n",
")",
"return",
"os",
".",
"read",
"(",
"self",
".",
"fd",
".",
"fileno",
"(",
")",
",",
"n",
")",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"Stream",
".",
"ERRNO_RECOVERABLE",
":",
"raise",
"e"
] | Return `n` bytes of data from the Stream, or None at end of stream. | [
"Return",
"n",
"bytes",
"of",
"data",
"from",
"the",
"Stream",
"or",
"None",
"at",
"end",
"of",
"stream",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L112-L124 |
3,309 | d11wtq/dockerpty | dockerpty/io.py | Stream.do_write | def do_write(self):
"""
Flushes as much pending data from the internal write buffer as possible.
"""
while True:
try:
written = 0
if hasattr(self.fd, 'send'):
written = self.fd.send(self.buffer)
else:
written = os.write(self.fd.fileno(), self.buffer)
self.buffer = self.buffer[written:]
# try to close after writes if a close was requested
if self.close_requested and len(self.buffer) == 0:
self.close()
return written
except EnvironmentError as e:
if e.errno not in Stream.ERRNO_RECOVERABLE:
raise e | python | def do_write(self):
"""
Flushes as much pending data from the internal write buffer as possible.
"""
while True:
try:
written = 0
if hasattr(self.fd, 'send'):
written = self.fd.send(self.buffer)
else:
written = os.write(self.fd.fileno(), self.buffer)
self.buffer = self.buffer[written:]
# try to close after writes if a close was requested
if self.close_requested and len(self.buffer) == 0:
self.close()
return written
except EnvironmentError as e:
if e.errno not in Stream.ERRNO_RECOVERABLE:
raise e | [
"def",
"do_write",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"written",
"=",
"0",
"if",
"hasattr",
"(",
"self",
".",
"fd",
",",
"'send'",
")",
":",
"written",
"=",
"self",
".",
"fd",
".",
"send",
"(",
"self",
".",
"buffer",
")",
"else",
":",
"written",
"=",
"os",
".",
"write",
"(",
"self",
".",
"fd",
".",
"fileno",
"(",
")",
",",
"self",
".",
"buffer",
")",
"self",
".",
"buffer",
"=",
"self",
".",
"buffer",
"[",
"written",
":",
"]",
"# try to close after writes if a close was requested",
"if",
"self",
".",
"close_requested",
"and",
"len",
"(",
"self",
".",
"buffer",
")",
"==",
"0",
":",
"self",
".",
"close",
"(",
")",
"return",
"written",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"not",
"in",
"Stream",
".",
"ERRNO_RECOVERABLE",
":",
"raise",
"e"
] | Flushes as much pending data from the internal write buffer as possible. | [
"Flushes",
"as",
"much",
"pending",
"data",
"from",
"the",
"internal",
"write",
"buffer",
"as",
"possible",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L142-L164 |
3,310 | d11wtq/dockerpty | dockerpty/io.py | Demuxer.read | def read(self, n=4096):
"""
Read up to `n` bytes of data from the Stream, after demuxing.
Less than `n` bytes of data may be returned depending on the available
payload, but the number of bytes returned will never exceed `n`.
Because demuxing involves scanning 8-byte headers, the actual amount of
data read from the underlying stream may be greater than `n`.
"""
size = self._next_packet_size(n)
if size <= 0:
return
else:
data = six.binary_type()
while len(data) < size:
nxt = self.stream.read(size - len(data))
if not nxt:
# the stream has closed, return what data we got
return data
data = data + nxt
return data | python | def read(self, n=4096):
"""
Read up to `n` bytes of data from the Stream, after demuxing.
Less than `n` bytes of data may be returned depending on the available
payload, but the number of bytes returned will never exceed `n`.
Because demuxing involves scanning 8-byte headers, the actual amount of
data read from the underlying stream may be greater than `n`.
"""
size = self._next_packet_size(n)
if size <= 0:
return
else:
data = six.binary_type()
while len(data) < size:
nxt = self.stream.read(size - len(data))
if not nxt:
# the stream has closed, return what data we got
return data
data = data + nxt
return data | [
"def",
"read",
"(",
"self",
",",
"n",
"=",
"4096",
")",
":",
"size",
"=",
"self",
".",
"_next_packet_size",
"(",
"n",
")",
"if",
"size",
"<=",
"0",
":",
"return",
"else",
":",
"data",
"=",
"six",
".",
"binary_type",
"(",
")",
"while",
"len",
"(",
"data",
")",
"<",
"size",
":",
"nxt",
"=",
"self",
".",
"stream",
".",
"read",
"(",
"size",
"-",
"len",
"(",
"data",
")",
")",
"if",
"not",
"nxt",
":",
"# the stream has closed, return what data we got",
"return",
"data",
"data",
"=",
"data",
"+",
"nxt",
"return",
"data"
] | Read up to `n` bytes of data from the Stream, after demuxing.
Less than `n` bytes of data may be returned depending on the available
payload, but the number of bytes returned will never exceed `n`.
Because demuxing involves scanning 8-byte headers, the actual amount of
data read from the underlying stream may be greater than `n`. | [
"Read",
"up",
"to",
"n",
"bytes",
"of",
"data",
"from",
"the",
"Stream",
"after",
"demuxing",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L224-L247 |
3,311 | d11wtq/dockerpty | dockerpty/io.py | Pump.flush | def flush(self, n=4096):
"""
Flush `n` bytes of data from the reader Stream to the writer Stream.
Returns the number of bytes that were actually flushed. A return value
of zero is not an error.
If EOF has been reached, `None` is returned.
"""
try:
read = self.from_stream.read(n)
if read is None or len(read) == 0:
self.eof = True
if self.propagate_close:
self.to_stream.close()
return None
return self.to_stream.write(read)
except OSError as e:
if e.errno != errno.EPIPE:
raise e | python | def flush(self, n=4096):
"""
Flush `n` bytes of data from the reader Stream to the writer Stream.
Returns the number of bytes that were actually flushed. A return value
of zero is not an error.
If EOF has been reached, `None` is returned.
"""
try:
read = self.from_stream.read(n)
if read is None or len(read) == 0:
self.eof = True
if self.propagate_close:
self.to_stream.close()
return None
return self.to_stream.write(read)
except OSError as e:
if e.errno != errno.EPIPE:
raise e | [
"def",
"flush",
"(",
"self",
",",
"n",
"=",
"4096",
")",
":",
"try",
":",
"read",
"=",
"self",
".",
"from_stream",
".",
"read",
"(",
"n",
")",
"if",
"read",
"is",
"None",
"or",
"len",
"(",
"read",
")",
"==",
"0",
":",
"self",
".",
"eof",
"=",
"True",
"if",
"self",
".",
"propagate_close",
":",
"self",
".",
"to_stream",
".",
"close",
"(",
")",
"return",
"None",
"return",
"self",
".",
"to_stream",
".",
"write",
"(",
"read",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EPIPE",
":",
"raise",
"e"
] | Flush `n` bytes of data from the reader Stream to the writer Stream.
Returns the number of bytes that were actually flushed. A return value
of zero is not an error.
If EOF has been reached, `None` is returned. | [
"Flush",
"n",
"bytes",
"of",
"data",
"from",
"the",
"reader",
"Stream",
"to",
"the",
"writer",
"Stream",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L356-L378 |
3,312 | d11wtq/dockerpty | dockerpty/__init__.py | exec_command | def exec_command(
client, container, command, interactive=True, stdout=None, stderr=None, stdin=None):
"""
Run provided command via exec API in provided container.
This is just a wrapper for PseudoTerminal(client, container).exec_command()
"""
exec_id = exec_create(client, container, command, interactive=interactive)
operation = ExecOperation(client, exec_id,
interactive=interactive, stdout=stdout, stderr=stderr, stdin=stdin)
PseudoTerminal(client, operation).start() | python | def exec_command(
client, container, command, interactive=True, stdout=None, stderr=None, stdin=None):
"""
Run provided command via exec API in provided container.
This is just a wrapper for PseudoTerminal(client, container).exec_command()
"""
exec_id = exec_create(client, container, command, interactive=interactive)
operation = ExecOperation(client, exec_id,
interactive=interactive, stdout=stdout, stderr=stderr, stdin=stdin)
PseudoTerminal(client, operation).start() | [
"def",
"exec_command",
"(",
"client",
",",
"container",
",",
"command",
",",
"interactive",
"=",
"True",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"stdin",
"=",
"None",
")",
":",
"exec_id",
"=",
"exec_create",
"(",
"client",
",",
"container",
",",
"command",
",",
"interactive",
"=",
"interactive",
")",
"operation",
"=",
"ExecOperation",
"(",
"client",
",",
"exec_id",
",",
"interactive",
"=",
"interactive",
",",
"stdout",
"=",
"stdout",
",",
"stderr",
"=",
"stderr",
",",
"stdin",
"=",
"stdin",
")",
"PseudoTerminal",
"(",
"client",
",",
"operation",
")",
".",
"start",
"(",
")"
] | Run provided command via exec API in provided container.
This is just a wrapper for PseudoTerminal(client, container).exec_command() | [
"Run",
"provided",
"command",
"via",
"exec",
"API",
"in",
"provided",
"container",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/__init__.py#L33-L44 |
3,313 | d11wtq/dockerpty | dockerpty/tty.py | Terminal.start | def start(self):
"""
Saves the current terminal attributes and makes the tty raw.
This method returns None immediately.
"""
if os.isatty(self.fd.fileno()) and self.israw():
self.original_attributes = termios.tcgetattr(self.fd)
tty.setraw(self.fd) | python | def start(self):
"""
Saves the current terminal attributes and makes the tty raw.
This method returns None immediately.
"""
if os.isatty(self.fd.fileno()) and self.israw():
self.original_attributes = termios.tcgetattr(self.fd)
tty.setraw(self.fd) | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"os",
".",
"isatty",
"(",
"self",
".",
"fd",
".",
"fileno",
"(",
")",
")",
"and",
"self",
".",
"israw",
"(",
")",
":",
"self",
".",
"original_attributes",
"=",
"termios",
".",
"tcgetattr",
"(",
"self",
".",
"fd",
")",
"tty",
".",
"setraw",
"(",
"self",
".",
"fd",
")"
] | Saves the current terminal attributes and makes the tty raw.
This method returns None immediately. | [
"Saves",
"the",
"current",
"terminal",
"attributes",
"and",
"makes",
"the",
"tty",
"raw",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/tty.py#L100-L109 |
3,314 | d11wtq/dockerpty | dockerpty/tty.py | Terminal.stop | def stop(self):
"""
Restores the terminal attributes back to before setting raw mode.
If the raw terminal was not started, does nothing.
"""
if self.original_attributes is not None:
termios.tcsetattr(
self.fd,
termios.TCSADRAIN,
self.original_attributes,
) | python | def stop(self):
"""
Restores the terminal attributes back to before setting raw mode.
If the raw terminal was not started, does nothing.
"""
if self.original_attributes is not None:
termios.tcsetattr(
self.fd,
termios.TCSADRAIN,
self.original_attributes,
) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"original_attributes",
"is",
"not",
"None",
":",
"termios",
".",
"tcsetattr",
"(",
"self",
".",
"fd",
",",
"termios",
".",
"TCSADRAIN",
",",
"self",
".",
"original_attributes",
",",
")"
] | Restores the terminal attributes back to before setting raw mode.
If the raw terminal was not started, does nothing. | [
"Restores",
"the",
"terminal",
"attributes",
"back",
"to",
"before",
"setting",
"raw",
"mode",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/tty.py#L112-L124 |
3,315 | d11wtq/dockerpty | dockerpty/pty.py | WINCHHandler.start | def start(self):
"""
Start trapping WINCH signals and resizing the PTY.
This method saves the previous WINCH handler so it can be restored on
`stop()`.
"""
def handle(signum, frame):
if signum == signal.SIGWINCH:
self.pty.resize()
self.original_handler = signal.signal(signal.SIGWINCH, handle) | python | def start(self):
"""
Start trapping WINCH signals and resizing the PTY.
This method saves the previous WINCH handler so it can be restored on
`stop()`.
"""
def handle(signum, frame):
if signum == signal.SIGWINCH:
self.pty.resize()
self.original_handler = signal.signal(signal.SIGWINCH, handle) | [
"def",
"start",
"(",
"self",
")",
":",
"def",
"handle",
"(",
"signum",
",",
"frame",
")",
":",
"if",
"signum",
"==",
"signal",
".",
"SIGWINCH",
":",
"self",
".",
"pty",
".",
"resize",
"(",
")",
"self",
".",
"original_handler",
"=",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGWINCH",
",",
"handle",
")"
] | Start trapping WINCH signals and resizing the PTY.
This method saves the previous WINCH handler so it can be restored on
`stop()`. | [
"Start",
"trapping",
"WINCH",
"signals",
"and",
"resizing",
"the",
"PTY",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L57-L69 |
3,316 | d11wtq/dockerpty | dockerpty/pty.py | WINCHHandler.stop | def stop(self):
"""
Stop trapping WINCH signals and restore the previous WINCH handler.
"""
if self.original_handler is not None:
signal.signal(signal.SIGWINCH, self.original_handler) | python | def stop(self):
"""
Stop trapping WINCH signals and restore the previous WINCH handler.
"""
if self.original_handler is not None:
signal.signal(signal.SIGWINCH, self.original_handler) | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"original_handler",
"is",
"not",
"None",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGWINCH",
",",
"self",
".",
"original_handler",
")"
] | Stop trapping WINCH signals and restore the previous WINCH handler. | [
"Stop",
"trapping",
"WINCH",
"signals",
"and",
"restore",
"the",
"previous",
"WINCH",
"handler",
"."
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L71-L77 |
3,317 | d11wtq/dockerpty | dockerpty/pty.py | RunOperation.resize | def resize(self, height, width, **kwargs):
"""
resize pty within container
"""
self.client.resize(self.container, height=height, width=width) | python | def resize(self, height, width, **kwargs):
"""
resize pty within container
"""
self.client.resize(self.container, height=height, width=width) | [
"def",
"resize",
"(",
"self",
",",
"height",
",",
"width",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
".",
"resize",
"(",
"self",
".",
"container",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
")"
] | resize pty within container | [
"resize",
"pty",
"within",
"container"
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L193-L197 |
3,318 | d11wtq/dockerpty | dockerpty/pty.py | ExecOperation.resize | def resize(self, height, width, **kwargs):
"""
resize pty of an execed process
"""
self.client.exec_resize(self.exec_id, height=height, width=width) | python | def resize(self, height, width, **kwargs):
"""
resize pty of an execed process
"""
self.client.exec_resize(self.exec_id, height=height, width=width) | [
"def",
"resize",
"(",
"self",
",",
"height",
",",
"width",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
".",
"exec_resize",
"(",
"self",
".",
"exec_id",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
")"
] | resize pty of an execed process | [
"resize",
"pty",
"of",
"an",
"execed",
"process"
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L267-L271 |
3,319 | d11wtq/dockerpty | dockerpty/pty.py | ExecOperation._exec_info | def _exec_info(self):
"""
Caching wrapper around client.exec_inspect
"""
if self._info is None:
self._info = self.client.exec_inspect(self.exec_id)
return self._info | python | def _exec_info(self):
"""
Caching wrapper around client.exec_inspect
"""
if self._info is None:
self._info = self.client.exec_inspect(self.exec_id)
return self._info | [
"def",
"_exec_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"_info",
"is",
"None",
":",
"self",
".",
"_info",
"=",
"self",
".",
"client",
".",
"exec_inspect",
"(",
"self",
".",
"exec_id",
")",
"return",
"self",
".",
"_info"
] | Caching wrapper around client.exec_inspect | [
"Caching",
"wrapper",
"around",
"client",
".",
"exec_inspect"
] | f8d17d893c6758b7cc25825e99f6b02202632a97 | https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L279-L285 |
3,320 | mhe/pynrrd | nrrd/formatters.py | format_number | def format_number(x):
"""Format number to string
Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print
the entire floating point number. Any padding zeros will be removed at the end of the number.
See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format.
.. note::
IEEE754-1985 standard says that 17 significant decimal digits are required to adequately represent a
64-bit floating point number. Not all fractional numbers can be exactly represented in floating point. An
example is 0.1 which will be approximated as 0.10000000000000001.
Parameters
----------
x : :class:`int` or :class:`float`
Number to convert to string
Returns
-------
vector : :class:`str`
String of number :obj:`x`
"""
if isinstance(x, float):
# Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision.
# However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a
# floating point number.
# The g option is used rather than f because g precision uses significant digits while f is just the number of
# digits after the decimal. (NRRD C implementation uses g).
value = '{:.17g}'.format(x)
else:
value = str(x)
return value | python | def format_number(x):
"""Format number to string
Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print
the entire floating point number. Any padding zeros will be removed at the end of the number.
See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format.
.. note::
IEEE754-1985 standard says that 17 significant decimal digits are required to adequately represent a
64-bit floating point number. Not all fractional numbers can be exactly represented in floating point. An
example is 0.1 which will be approximated as 0.10000000000000001.
Parameters
----------
x : :class:`int` or :class:`float`
Number to convert to string
Returns
-------
vector : :class:`str`
String of number :obj:`x`
"""
if isinstance(x, float):
# Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision.
# However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a
# floating point number.
# The g option is used rather than f because g precision uses significant digits while f is just the number of
# digits after the decimal. (NRRD C implementation uses g).
value = '{:.17g}'.format(x)
else:
value = str(x)
return value | [
"def",
"format_number",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"float",
")",
":",
"# Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision.",
"# However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a",
"# floating point number.",
"# The g option is used rather than f because g precision uses significant digits while f is just the number of",
"# digits after the decimal. (NRRD C implementation uses g).",
"value",
"=",
"'{:.17g}'",
".",
"format",
"(",
"x",
")",
"else",
":",
"value",
"=",
"str",
"(",
"x",
")",
"return",
"value"
] | Format number to string
Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print
the entire floating point number. Any padding zeros will be removed at the end of the number.
See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format.
.. note::
IEEE754-1985 standard says that 17 significant decimal digits are required to adequately represent a
64-bit floating point number. Not all fractional numbers can be exactly represented in floating point. An
example is 0.1 which will be approximated as 0.10000000000000001.
Parameters
----------
x : :class:`int` or :class:`float`
Number to convert to string
Returns
-------
vector : :class:`str`
String of number :obj:`x` | [
"Format",
"number",
"to",
"string"
] | 96dd875b302031ea27e2d3aaa611dc6f2dfc7979 | https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/formatters.py#L4-L38 |
3,321 | mhe/pynrrd | nrrd/parsers.py | parse_number_auto_dtype | def parse_number_auto_dtype(x):
"""Parse number from string with automatic type detection.
Parses input string and converts to a number using automatic type detection. If the number contains any
fractional parts, then the number will be converted to float, otherwise the number will be converted to an int.
See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format.
Parameters
----------
x : :class:`str`
String representation of number
Returns
-------
result : :class:`int` or :class:`float`
Number parsed from :obj:`x` string
"""
value = float(x)
if value.is_integer():
value = int(value)
return value | python | def parse_number_auto_dtype(x):
"""Parse number from string with automatic type detection.
Parses input string and converts to a number using automatic type detection. If the number contains any
fractional parts, then the number will be converted to float, otherwise the number will be converted to an int.
See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format.
Parameters
----------
x : :class:`str`
String representation of number
Returns
-------
result : :class:`int` or :class:`float`
Number parsed from :obj:`x` string
"""
value = float(x)
if value.is_integer():
value = int(value)
return value | [
"def",
"parse_number_auto_dtype",
"(",
"x",
")",
":",
"value",
"=",
"float",
"(",
"x",
")",
"if",
"value",
".",
"is_integer",
"(",
")",
":",
"value",
"=",
"int",
"(",
"value",
")",
"return",
"value"
] | Parse number from string with automatic type detection.
Parses input string and converts to a number using automatic type detection. If the number contains any
fractional parts, then the number will be converted to float, otherwise the number will be converted to an int.
See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format.
Parameters
----------
x : :class:`str`
String representation of number
Returns
-------
result : :class:`int` or :class:`float`
Number parsed from :obj:`x` string | [
"Parse",
"number",
"from",
"string",
"with",
"automatic",
"type",
"detection",
"."
] | 96dd875b302031ea27e2d3aaa611dc6f2dfc7979 | https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/parsers.py#L207-L231 |
3,322 | mhe/pynrrd | nrrd/reader.py | _determine_datatype | def _determine_datatype(fields):
"""Determine the numpy dtype of the data."""
# Convert the NRRD type string identifier into a NumPy string identifier using a map
np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']]
# This is only added if the datatype has more than one byte and is not using ASCII encoding
# Note: Endian is not required for ASCII encoding
if np.dtype(np_typestring).itemsize > 1 and fields['encoding'] not in ['ASCII', 'ascii', 'text', 'txt']:
if 'endian' not in fields:
raise NRRDError('Header is missing required field: "endian".')
elif fields['endian'] == 'big':
np_typestring = '>' + np_typestring
elif fields['endian'] == 'little':
np_typestring = '<' + np_typestring
else:
raise NRRDError('Invalid endian value in header: "%s"' % fields['endian'])
return np.dtype(np_typestring) | python | def _determine_datatype(fields):
"""Determine the numpy dtype of the data."""
# Convert the NRRD type string identifier into a NumPy string identifier using a map
np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']]
# This is only added if the datatype has more than one byte and is not using ASCII encoding
# Note: Endian is not required for ASCII encoding
if np.dtype(np_typestring).itemsize > 1 and fields['encoding'] not in ['ASCII', 'ascii', 'text', 'txt']:
if 'endian' not in fields:
raise NRRDError('Header is missing required field: "endian".')
elif fields['endian'] == 'big':
np_typestring = '>' + np_typestring
elif fields['endian'] == 'little':
np_typestring = '<' + np_typestring
else:
raise NRRDError('Invalid endian value in header: "%s"' % fields['endian'])
return np.dtype(np_typestring) | [
"def",
"_determine_datatype",
"(",
"fields",
")",
":",
"# Convert the NRRD type string identifier into a NumPy string identifier using a map",
"np_typestring",
"=",
"_TYPEMAP_NRRD2NUMPY",
"[",
"fields",
"[",
"'type'",
"]",
"]",
"# This is only added if the datatype has more than one byte and is not using ASCII encoding",
"# Note: Endian is not required for ASCII encoding",
"if",
"np",
".",
"dtype",
"(",
"np_typestring",
")",
".",
"itemsize",
">",
"1",
"and",
"fields",
"[",
"'encoding'",
"]",
"not",
"in",
"[",
"'ASCII'",
",",
"'ascii'",
",",
"'text'",
",",
"'txt'",
"]",
":",
"if",
"'endian'",
"not",
"in",
"fields",
":",
"raise",
"NRRDError",
"(",
"'Header is missing required field: \"endian\".'",
")",
"elif",
"fields",
"[",
"'endian'",
"]",
"==",
"'big'",
":",
"np_typestring",
"=",
"'>'",
"+",
"np_typestring",
"elif",
"fields",
"[",
"'endian'",
"]",
"==",
"'little'",
":",
"np_typestring",
"=",
"'<'",
"+",
"np_typestring",
"else",
":",
"raise",
"NRRDError",
"(",
"'Invalid endian value in header: \"%s\"'",
"%",
"fields",
"[",
"'endian'",
"]",
")",
"return",
"np",
".",
"dtype",
"(",
"np_typestring",
")"
] | Determine the numpy dtype of the data. | [
"Determine",
"the",
"numpy",
"dtype",
"of",
"the",
"data",
"."
] | 96dd875b302031ea27e2d3aaa611dc6f2dfc7979 | https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/reader.py#L145-L163 |
3,323 | mhe/pynrrd | nrrd/reader.py | _validate_magic_line | def _validate_magic_line(line):
"""For NRRD files, the first four characters are always "NRRD", and
remaining characters give information about the file format version
>>> _validate_magic_line('NRRD0005')
8
>>> _validate_magic_line('NRRD0006')
Traceback (most recent call last):
...
NrrdError: NRRD file version too new for this library.
>>> _validate_magic_line('NRRD')
Traceback (most recent call last):
...
NrrdError: Invalid NRRD magic line: NRRD
"""
if not line.startswith('NRRD'):
raise NRRDError('Invalid NRRD magic line. Is this an NRRD file?')
try:
version = int(line[4:])
if version > 5:
raise NRRDError('Unsupported NRRD file version (version: %i). This library only supports v%i and below.'
% (version, 5))
except ValueError:
raise NRRDError('Invalid NRRD magic line: %s' % line)
return len(line) | python | def _validate_magic_line(line):
"""For NRRD files, the first four characters are always "NRRD", and
remaining characters give information about the file format version
>>> _validate_magic_line('NRRD0005')
8
>>> _validate_magic_line('NRRD0006')
Traceback (most recent call last):
...
NrrdError: NRRD file version too new for this library.
>>> _validate_magic_line('NRRD')
Traceback (most recent call last):
...
NrrdError: Invalid NRRD magic line: NRRD
"""
if not line.startswith('NRRD'):
raise NRRDError('Invalid NRRD magic line. Is this an NRRD file?')
try:
version = int(line[4:])
if version > 5:
raise NRRDError('Unsupported NRRD file version (version: %i). This library only supports v%i and below.'
% (version, 5))
except ValueError:
raise NRRDError('Invalid NRRD magic line: %s' % line)
return len(line) | [
"def",
"_validate_magic_line",
"(",
"line",
")",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"'NRRD'",
")",
":",
"raise",
"NRRDError",
"(",
"'Invalid NRRD magic line. Is this an NRRD file?'",
")",
"try",
":",
"version",
"=",
"int",
"(",
"line",
"[",
"4",
":",
"]",
")",
"if",
"version",
">",
"5",
":",
"raise",
"NRRDError",
"(",
"'Unsupported NRRD file version (version: %i). This library only supports v%i and below.'",
"%",
"(",
"version",
",",
"5",
")",
")",
"except",
"ValueError",
":",
"raise",
"NRRDError",
"(",
"'Invalid NRRD magic line: %s'",
"%",
"line",
")",
"return",
"len",
"(",
"line",
")"
] | For NRRD files, the first four characters are always "NRRD", and
remaining characters give information about the file format version
>>> _validate_magic_line('NRRD0005')
8
>>> _validate_magic_line('NRRD0006')
Traceback (most recent call last):
...
NrrdError: NRRD file version too new for this library.
>>> _validate_magic_line('NRRD')
Traceback (most recent call last):
...
NrrdError: Invalid NRRD magic line: NRRD | [
"For",
"NRRD",
"files",
"the",
"first",
"four",
"characters",
"are",
"always",
"NRRD",
"and",
"remaining",
"characters",
"give",
"information",
"about",
"the",
"file",
"format",
"version"
] | 96dd875b302031ea27e2d3aaa611dc6f2dfc7979 | https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/reader.py#L166-L193 |
3,324 | mhe/pynrrd | nrrd/reader.py | read | def read(filename, custom_field_map=None, index_order='F'):
"""Read a NRRD file and return the header and data
See :ref:`user-guide:Reading NRRD files` for more information on reading NRRD files.
.. note::
Users should be aware that the `index_order` argument needs to be consistent between `nrrd.read` and `nrrd.write`. I.e., reading an array with `index_order='F'` will result in a transposed version of the original data and hence the writer needs to be aware of this.
Parameters
----------
filename : :class:`str`
Filename of the NRRD file
custom_field_map : :class:`dict` (:class:`str`, :class:`str`), optional
Dictionary used for parsing custom field types where the key is the custom field name and the value is a
string identifying datatype for the custom field.
index_order : {'C', 'F'}, optional
Specifies the index order of the resulting data array. Either 'C' (C-order) where the dimensions are ordered from
slowest-varying to fastest-varying (e.g. (z, y, x)), or 'F' (Fortran-order) where the dimensions are ordered
from fastest-varying to slowest-varying (e.g. (x, y, z)).
Returns
-------
data : :class:`numpy.ndarray`
Data read from NRRD file
header : :class:`dict` (:class:`str`, :obj:`Object`)
Dictionary containing the header fields and their corresponding parsed value
See Also
--------
:meth:`write`, :meth:`read_header`, :meth:`read_data`
"""
"""Read a NRRD file and return a tuple (data, header)."""
with open(filename, 'rb') as fh:
header = read_header(fh, custom_field_map)
data = read_data(header, fh, filename, index_order)
return data, header | python | def read(filename, custom_field_map=None, index_order='F'):
"""Read a NRRD file and return the header and data
See :ref:`user-guide:Reading NRRD files` for more information on reading NRRD files.
.. note::
Users should be aware that the `index_order` argument needs to be consistent between `nrrd.read` and `nrrd.write`. I.e., reading an array with `index_order='F'` will result in a transposed version of the original data and hence the writer needs to be aware of this.
Parameters
----------
filename : :class:`str`
Filename of the NRRD file
custom_field_map : :class:`dict` (:class:`str`, :class:`str`), optional
Dictionary used for parsing custom field types where the key is the custom field name and the value is a
string identifying datatype for the custom field.
index_order : {'C', 'F'}, optional
Specifies the index order of the resulting data array. Either 'C' (C-order) where the dimensions are ordered from
slowest-varying to fastest-varying (e.g. (z, y, x)), or 'F' (Fortran-order) where the dimensions are ordered
from fastest-varying to slowest-varying (e.g. (x, y, z)).
Returns
-------
data : :class:`numpy.ndarray`
Data read from NRRD file
header : :class:`dict` (:class:`str`, :obj:`Object`)
Dictionary containing the header fields and their corresponding parsed value
See Also
--------
:meth:`write`, :meth:`read_header`, :meth:`read_data`
"""
"""Read a NRRD file and return a tuple (data, header)."""
with open(filename, 'rb') as fh:
header = read_header(fh, custom_field_map)
data = read_data(header, fh, filename, index_order)
return data, header | [
"def",
"read",
"(",
"filename",
",",
"custom_field_map",
"=",
"None",
",",
"index_order",
"=",
"'F'",
")",
":",
"\"\"\"Read a NRRD file and return a tuple (data, header).\"\"\"",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fh",
":",
"header",
"=",
"read_header",
"(",
"fh",
",",
"custom_field_map",
")",
"data",
"=",
"read_data",
"(",
"header",
",",
"fh",
",",
"filename",
",",
"index_order",
")",
"return",
"data",
",",
"header"
] | Read a NRRD file and return the header and data
See :ref:`user-guide:Reading NRRD files` for more information on reading NRRD files.
.. note::
Users should be aware that the `index_order` argument needs to be consistent between `nrrd.read` and `nrrd.write`. I.e., reading an array with `index_order='F'` will result in a transposed version of the original data and hence the writer needs to be aware of this.
Parameters
----------
filename : :class:`str`
Filename of the NRRD file
custom_field_map : :class:`dict` (:class:`str`, :class:`str`), optional
Dictionary used for parsing custom field types where the key is the custom field name and the value is a
string identifying datatype for the custom field.
index_order : {'C', 'F'}, optional
Specifies the index order of the resulting data array. Either 'C' (C-order) where the dimensions are ordered from
slowest-varying to fastest-varying (e.g. (z, y, x)), or 'F' (Fortran-order) where the dimensions are ordered
from fastest-varying to slowest-varying (e.g. (x, y, z)).
Returns
-------
data : :class:`numpy.ndarray`
Data read from NRRD file
header : :class:`dict` (:class:`str`, :obj:`Object`)
Dictionary containing the header fields and their corresponding parsed value
See Also
--------
:meth:`write`, :meth:`read_header`, :meth:`read_data` | [
"Read",
"a",
"NRRD",
"file",
"and",
"return",
"the",
"header",
"and",
"data"
] | 96dd875b302031ea27e2d3aaa611dc6f2dfc7979 | https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/reader.py#L469-L506 |
3,325 | bspaans/python-mingus | mingus/containers/track.py | Track.add_notes | def add_notes(self, note, duration=None):
"""Add a Note, note as string or NoteContainer to the last Bar.
If the Bar is full, a new one will automatically be created.
If the Bar is not full but the note can't fit in, this method will
return False. True otherwise.
An InstrumentRangeError exception will be raised if an Instrument is
attached to the Track, but the note turns out not to be within the
range of the Instrument.
"""
if self.instrument != None:
if not self.instrument.can_play_notes(note):
raise InstrumentRangeError, \
"Note '%s' is not in range of the instrument (%s)" % (note,
self.instrument)
if duration == None:
duration = 4
# Check whether the last bar is full, if so create a new bar and add the
# note there
if len(self.bars) == 0:
self.bars.append(Bar())
last_bar = self.bars[-1]
if last_bar.is_full():
self.bars.append(Bar(last_bar.key, last_bar.meter))
# warning should hold note if it doesn't fit
return self.bars[-1].place_notes(note, duration) | python | def add_notes(self, note, duration=None):
"""Add a Note, note as string or NoteContainer to the last Bar.
If the Bar is full, a new one will automatically be created.
If the Bar is not full but the note can't fit in, this method will
return False. True otherwise.
An InstrumentRangeError exception will be raised if an Instrument is
attached to the Track, but the note turns out not to be within the
range of the Instrument.
"""
if self.instrument != None:
if not self.instrument.can_play_notes(note):
raise InstrumentRangeError, \
"Note '%s' is not in range of the instrument (%s)" % (note,
self.instrument)
if duration == None:
duration = 4
# Check whether the last bar is full, if so create a new bar and add the
# note there
if len(self.bars) == 0:
self.bars.append(Bar())
last_bar = self.bars[-1]
if last_bar.is_full():
self.bars.append(Bar(last_bar.key, last_bar.meter))
# warning should hold note if it doesn't fit
return self.bars[-1].place_notes(note, duration) | [
"def",
"add_notes",
"(",
"self",
",",
"note",
",",
"duration",
"=",
"None",
")",
":",
"if",
"self",
".",
"instrument",
"!=",
"None",
":",
"if",
"not",
"self",
".",
"instrument",
".",
"can_play_notes",
"(",
"note",
")",
":",
"raise",
"InstrumentRangeError",
",",
"\"Note '%s' is not in range of the instrument (%s)\"",
"%",
"(",
"note",
",",
"self",
".",
"instrument",
")",
"if",
"duration",
"==",
"None",
":",
"duration",
"=",
"4",
"# Check whether the last bar is full, if so create a new bar and add the",
"# note there",
"if",
"len",
"(",
"self",
".",
"bars",
")",
"==",
"0",
":",
"self",
".",
"bars",
".",
"append",
"(",
"Bar",
"(",
")",
")",
"last_bar",
"=",
"self",
".",
"bars",
"[",
"-",
"1",
"]",
"if",
"last_bar",
".",
"is_full",
"(",
")",
":",
"self",
".",
"bars",
".",
"append",
"(",
"Bar",
"(",
"last_bar",
".",
"key",
",",
"last_bar",
".",
"meter",
")",
")",
"# warning should hold note if it doesn't fit",
"return",
"self",
".",
"bars",
"[",
"-",
"1",
"]",
".",
"place_notes",
"(",
"note",
",",
"duration",
")"
] | Add a Note, note as string or NoteContainer to the last Bar.
If the Bar is full, a new one will automatically be created.
If the Bar is not full but the note can't fit in, this method will
return False. True otherwise.
An InstrumentRangeError exception will be raised if an Instrument is
attached to the Track, but the note turns out not to be within the
range of the Instrument. | [
"Add",
"a",
"Note",
"note",
"as",
"string",
"or",
"NoteContainer",
"to",
"the",
"last",
"Bar",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L51-L80 |
3,326 | bspaans/python-mingus | mingus/containers/track.py | Track.get_notes | def get_notes(self):
"""Return an iterator that iterates through every bar in the this
track."""
for bar in self.bars:
for beat, duration, notes in bar:
yield beat, duration, notes | python | def get_notes(self):
"""Return an iterator that iterates through every bar in the this
track."""
for bar in self.bars:
for beat, duration, notes in bar:
yield beat, duration, notes | [
"def",
"get_notes",
"(",
"self",
")",
":",
"for",
"bar",
"in",
"self",
".",
"bars",
":",
"for",
"beat",
",",
"duration",
",",
"notes",
"in",
"bar",
":",
"yield",
"beat",
",",
"duration",
",",
"notes"
] | Return an iterator that iterates through every bar in the this
track. | [
"Return",
"an",
"iterator",
"that",
"iterates",
"through",
"every",
"bar",
"in",
"the",
"this",
"track",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L82-L87 |
3,327 | bspaans/python-mingus | mingus/containers/track.py | Track.from_chords | def from_chords(self, chords, duration=1):
"""Add chords to the Track.
The given chords should be a list of shorthand strings or list of
list of shorthand strings, etc.
Each sublist divides the value by 2.
If a tuning is set, chords will be expanded so they have a proper
fingering.
Example:
>>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1)
"""
tun = self.get_tuning()
def add_chord(chord, duration):
if type(chord) == list:
for c in chord:
add_chord(c, duration * 2)
else:
chord = NoteContainer().from_chord(chord)
if tun:
chord = tun.find_chord_fingering(chord,
return_best_as_NoteContainer=True)
if not self.add_notes(chord, duration):
# This should be the standard behaviour of add_notes
dur = self.bars[-1].value_left()
self.add_notes(chord, dur)
# warning should hold note
self.add_notes(chord, value.subtract(duration, dur))
for c in chords:
if c is not None:
add_chord(c, duration)
else:
self.add_notes(None, duration)
return self | python | def from_chords(self, chords, duration=1):
"""Add chords to the Track.
The given chords should be a list of shorthand strings or list of
list of shorthand strings, etc.
Each sublist divides the value by 2.
If a tuning is set, chords will be expanded so they have a proper
fingering.
Example:
>>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1)
"""
tun = self.get_tuning()
def add_chord(chord, duration):
if type(chord) == list:
for c in chord:
add_chord(c, duration * 2)
else:
chord = NoteContainer().from_chord(chord)
if tun:
chord = tun.find_chord_fingering(chord,
return_best_as_NoteContainer=True)
if not self.add_notes(chord, duration):
# This should be the standard behaviour of add_notes
dur = self.bars[-1].value_left()
self.add_notes(chord, dur)
# warning should hold note
self.add_notes(chord, value.subtract(duration, dur))
for c in chords:
if c is not None:
add_chord(c, duration)
else:
self.add_notes(None, duration)
return self | [
"def",
"from_chords",
"(",
"self",
",",
"chords",
",",
"duration",
"=",
"1",
")",
":",
"tun",
"=",
"self",
".",
"get_tuning",
"(",
")",
"def",
"add_chord",
"(",
"chord",
",",
"duration",
")",
":",
"if",
"type",
"(",
"chord",
")",
"==",
"list",
":",
"for",
"c",
"in",
"chord",
":",
"add_chord",
"(",
"c",
",",
"duration",
"*",
"2",
")",
"else",
":",
"chord",
"=",
"NoteContainer",
"(",
")",
".",
"from_chord",
"(",
"chord",
")",
"if",
"tun",
":",
"chord",
"=",
"tun",
".",
"find_chord_fingering",
"(",
"chord",
",",
"return_best_as_NoteContainer",
"=",
"True",
")",
"if",
"not",
"self",
".",
"add_notes",
"(",
"chord",
",",
"duration",
")",
":",
"# This should be the standard behaviour of add_notes",
"dur",
"=",
"self",
".",
"bars",
"[",
"-",
"1",
"]",
".",
"value_left",
"(",
")",
"self",
".",
"add_notes",
"(",
"chord",
",",
"dur",
")",
"# warning should hold note",
"self",
".",
"add_notes",
"(",
"chord",
",",
"value",
".",
"subtract",
"(",
"duration",
",",
"dur",
")",
")",
"for",
"c",
"in",
"chords",
":",
"if",
"c",
"is",
"not",
"None",
":",
"add_chord",
"(",
"c",
",",
"duration",
")",
"else",
":",
"self",
".",
"add_notes",
"(",
"None",
",",
"duration",
")",
"return",
"self"
] | Add chords to the Track.
The given chords should be a list of shorthand strings or list of
list of shorthand strings, etc.
Each sublist divides the value by 2.
If a tuning is set, chords will be expanded so they have a proper
fingering.
Example:
>>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1) | [
"Add",
"chords",
"to",
"the",
"Track",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L89-L127 |
3,328 | bspaans/python-mingus | mingus/containers/track.py | Track.get_tuning | def get_tuning(self):
"""Return a StringTuning object.
If an instrument is set and has a tuning it will be returned.
Otherwise the track's one will be used.
"""
if self.instrument and self.instrument.tuning:
return self.instrument.tuning
return self.tuning | python | def get_tuning(self):
"""Return a StringTuning object.
If an instrument is set and has a tuning it will be returned.
Otherwise the track's one will be used.
"""
if self.instrument and self.instrument.tuning:
return self.instrument.tuning
return self.tuning | [
"def",
"get_tuning",
"(",
"self",
")",
":",
"if",
"self",
".",
"instrument",
"and",
"self",
".",
"instrument",
".",
"tuning",
":",
"return",
"self",
".",
"instrument",
".",
"tuning",
"return",
"self",
".",
"tuning"
] | Return a StringTuning object.
If an instrument is set and has a tuning it will be returned.
Otherwise the track's one will be used. | [
"Return",
"a",
"StringTuning",
"object",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L129-L137 |
3,329 | bspaans/python-mingus | mingus/containers/track.py | Track.transpose | def transpose(self, interval, up=True):
"""Transpose all the notes in the track up or down the interval.
Call transpose() on every Bar.
"""
for bar in self.bars:
bar.transpose(interval, up)
return self | python | def transpose(self, interval, up=True):
"""Transpose all the notes in the track up or down the interval.
Call transpose() on every Bar.
"""
for bar in self.bars:
bar.transpose(interval, up)
return self | [
"def",
"transpose",
"(",
"self",
",",
"interval",
",",
"up",
"=",
"True",
")",
":",
"for",
"bar",
"in",
"self",
".",
"bars",
":",
"bar",
".",
"transpose",
"(",
"interval",
",",
"up",
")",
"return",
"self"
] | Transpose all the notes in the track up or down the interval.
Call transpose() on every Bar. | [
"Transpose",
"all",
"the",
"notes",
"in",
"the",
"track",
"up",
"or",
"down",
"the",
"interval",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L150-L157 |
3,330 | bspaans/python-mingus | mingus/containers/bar.py | Bar.set_meter | def set_meter(self, meter):
"""Set the meter of this bar.
Meters in mingus are represented by a single tuple.
If the format of the meter is not recognised, a MeterFormatError
will be raised.
"""
# warning should raise exception
if _meter.valid_beat_duration(meter[1]):
self.meter = (meter[0], meter[1])
self.length = meter[0] * (1.0 / meter[1])
elif meter == (0, 0):
self.meter = (0, 0)
self.length = 0.0
else:
raise MeterFormatError("The meter argument '%s' is not an "
"understood representation of a meter. "
"Expecting a tuple." % meter) | python | def set_meter(self, meter):
"""Set the meter of this bar.
Meters in mingus are represented by a single tuple.
If the format of the meter is not recognised, a MeterFormatError
will be raised.
"""
# warning should raise exception
if _meter.valid_beat_duration(meter[1]):
self.meter = (meter[0], meter[1])
self.length = meter[0] * (1.0 / meter[1])
elif meter == (0, 0):
self.meter = (0, 0)
self.length = 0.0
else:
raise MeterFormatError("The meter argument '%s' is not an "
"understood representation of a meter. "
"Expecting a tuple." % meter) | [
"def",
"set_meter",
"(",
"self",
",",
"meter",
")",
":",
"# warning should raise exception",
"if",
"_meter",
".",
"valid_beat_duration",
"(",
"meter",
"[",
"1",
"]",
")",
":",
"self",
".",
"meter",
"=",
"(",
"meter",
"[",
"0",
"]",
",",
"meter",
"[",
"1",
"]",
")",
"self",
".",
"length",
"=",
"meter",
"[",
"0",
"]",
"*",
"(",
"1.0",
"/",
"meter",
"[",
"1",
"]",
")",
"elif",
"meter",
"==",
"(",
"0",
",",
"0",
")",
":",
"self",
".",
"meter",
"=",
"(",
"0",
",",
"0",
")",
"self",
".",
"length",
"=",
"0.0",
"else",
":",
"raise",
"MeterFormatError",
"(",
"\"The meter argument '%s' is not an \"",
"\"understood representation of a meter. \"",
"\"Expecting a tuple.\"",
"%",
"meter",
")"
] | Set the meter of this bar.
Meters in mingus are represented by a single tuple.
If the format of the meter is not recognised, a MeterFormatError
will be raised. | [
"Set",
"the",
"meter",
"of",
"this",
"bar",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L54-L72 |
3,331 | bspaans/python-mingus | mingus/containers/bar.py | Bar.place_notes | def place_notes(self, notes, duration):
"""Place the notes on the current_beat.
Notes can be strings, Notes, list of strings, list of Notes or a
NoteContainer.
Raise a MeterFormatError if the duration is not valid.
Return True if succesful, False otherwise (ie. the Bar hasn't got
enough room for a note of that duration).
"""
# note should be able to be one of strings, lists, Notes or
# NoteContainers
if hasattr(notes, 'notes'):
pass
elif hasattr(notes, 'name'):
notes = NoteContainer(notes)
elif type(notes) == str:
notes = NoteContainer(notes)
elif type(notes) == list:
notes = NoteContainer(notes)
if self.current_beat + 1.0 / duration <= self.length or self.length\
== 0.0:
self.bar.append([self.current_beat, duration, notes])
self.current_beat += 1.0 / duration
return True
else:
return False | python | def place_notes(self, notes, duration):
"""Place the notes on the current_beat.
Notes can be strings, Notes, list of strings, list of Notes or a
NoteContainer.
Raise a MeterFormatError if the duration is not valid.
Return True if succesful, False otherwise (ie. the Bar hasn't got
enough room for a note of that duration).
"""
# note should be able to be one of strings, lists, Notes or
# NoteContainers
if hasattr(notes, 'notes'):
pass
elif hasattr(notes, 'name'):
notes = NoteContainer(notes)
elif type(notes) == str:
notes = NoteContainer(notes)
elif type(notes) == list:
notes = NoteContainer(notes)
if self.current_beat + 1.0 / duration <= self.length or self.length\
== 0.0:
self.bar.append([self.current_beat, duration, notes])
self.current_beat += 1.0 / duration
return True
else:
return False | [
"def",
"place_notes",
"(",
"self",
",",
"notes",
",",
"duration",
")",
":",
"# note should be able to be one of strings, lists, Notes or",
"# NoteContainers",
"if",
"hasattr",
"(",
"notes",
",",
"'notes'",
")",
":",
"pass",
"elif",
"hasattr",
"(",
"notes",
",",
"'name'",
")",
":",
"notes",
"=",
"NoteContainer",
"(",
"notes",
")",
"elif",
"type",
"(",
"notes",
")",
"==",
"str",
":",
"notes",
"=",
"NoteContainer",
"(",
"notes",
")",
"elif",
"type",
"(",
"notes",
")",
"==",
"list",
":",
"notes",
"=",
"NoteContainer",
"(",
"notes",
")",
"if",
"self",
".",
"current_beat",
"+",
"1.0",
"/",
"duration",
"<=",
"self",
".",
"length",
"or",
"self",
".",
"length",
"==",
"0.0",
":",
"self",
".",
"bar",
".",
"append",
"(",
"[",
"self",
".",
"current_beat",
",",
"duration",
",",
"notes",
"]",
")",
"self",
".",
"current_beat",
"+=",
"1.0",
"/",
"duration",
"return",
"True",
"else",
":",
"return",
"False"
] | Place the notes on the current_beat.
Notes can be strings, Notes, list of strings, list of Notes or a
NoteContainer.
Raise a MeterFormatError if the duration is not valid.
Return True if succesful, False otherwise (ie. the Bar hasn't got
enough room for a note of that duration). | [
"Place",
"the",
"notes",
"on",
"the",
"current_beat",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L74-L101 |
3,332 | bspaans/python-mingus | mingus/containers/bar.py | Bar.place_notes_at | def place_notes_at(self, notes, at):
"""Place notes at the given index."""
for x in self.bar:
if x[0] == at:
x[0][2] += notes | python | def place_notes_at(self, notes, at):
"""Place notes at the given index."""
for x in self.bar:
if x[0] == at:
x[0][2] += notes | [
"def",
"place_notes_at",
"(",
"self",
",",
"notes",
",",
"at",
")",
":",
"for",
"x",
"in",
"self",
".",
"bar",
":",
"if",
"x",
"[",
"0",
"]",
"==",
"at",
":",
"x",
"[",
"0",
"]",
"[",
"2",
"]",
"+=",
"notes"
] | Place notes at the given index. | [
"Place",
"notes",
"at",
"the",
"given",
"index",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L103-L107 |
3,333 | bspaans/python-mingus | mingus/containers/bar.py | Bar.remove_last_entry | def remove_last_entry(self):
"""Remove the last NoteContainer in the Bar."""
self.current_beat -= 1.0 / self.bar[-1][1]
self.bar = self.bar[:-1]
return self.current_beat | python | def remove_last_entry(self):
"""Remove the last NoteContainer in the Bar."""
self.current_beat -= 1.0 / self.bar[-1][1]
self.bar = self.bar[:-1]
return self.current_beat | [
"def",
"remove_last_entry",
"(",
"self",
")",
":",
"self",
".",
"current_beat",
"-=",
"1.0",
"/",
"self",
".",
"bar",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"self",
".",
"bar",
"=",
"self",
".",
"bar",
"[",
":",
"-",
"1",
"]",
"return",
"self",
".",
"current_beat"
] | Remove the last NoteContainer in the Bar. | [
"Remove",
"the",
"last",
"NoteContainer",
"in",
"the",
"Bar",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L116-L120 |
3,334 | bspaans/python-mingus | mingus/containers/bar.py | Bar.is_full | def is_full(self):
"""Return False if there is room in this Bar for another
NoteContainer, True otherwise."""
if self.length == 0.0:
return False
if len(self.bar) == 0:
return False
if self.current_beat >= self.length - 0.001:
return True
return False | python | def is_full(self):
"""Return False if there is room in this Bar for another
NoteContainer, True otherwise."""
if self.length == 0.0:
return False
if len(self.bar) == 0:
return False
if self.current_beat >= self.length - 0.001:
return True
return False | [
"def",
"is_full",
"(",
"self",
")",
":",
"if",
"self",
".",
"length",
"==",
"0.0",
":",
"return",
"False",
"if",
"len",
"(",
"self",
".",
"bar",
")",
"==",
"0",
":",
"return",
"False",
"if",
"self",
".",
"current_beat",
">=",
"self",
".",
"length",
"-",
"0.001",
":",
"return",
"True",
"return",
"False"
] | Return False if there is room in this Bar for another
NoteContainer, True otherwise. | [
"Return",
"False",
"if",
"there",
"is",
"room",
"in",
"this",
"Bar",
"for",
"another",
"NoteContainer",
"True",
"otherwise",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L122-L131 |
3,335 | bspaans/python-mingus | mingus/containers/bar.py | Bar.change_note_duration | def change_note_duration(self, at, to):
"""Change the note duration at the given index to the given
duration."""
if valid_beat_duration(to):
diff = 0
for x in self.bar:
if diff != 0:
x[0][0] -= diff
if x[0] == at:
cur = x[0][1]
x[0][1] = to
diff = 1 / cur - 1 / to | python | def change_note_duration(self, at, to):
"""Change the note duration at the given index to the given
duration."""
if valid_beat_duration(to):
diff = 0
for x in self.bar:
if diff != 0:
x[0][0] -= diff
if x[0] == at:
cur = x[0][1]
x[0][1] = to
diff = 1 / cur - 1 / to | [
"def",
"change_note_duration",
"(",
"self",
",",
"at",
",",
"to",
")",
":",
"if",
"valid_beat_duration",
"(",
"to",
")",
":",
"diff",
"=",
"0",
"for",
"x",
"in",
"self",
".",
"bar",
":",
"if",
"diff",
"!=",
"0",
":",
"x",
"[",
"0",
"]",
"[",
"0",
"]",
"-=",
"diff",
"if",
"x",
"[",
"0",
"]",
"==",
"at",
":",
"cur",
"=",
"x",
"[",
"0",
"]",
"[",
"1",
"]",
"x",
"[",
"0",
"]",
"[",
"1",
"]",
"=",
"to",
"diff",
"=",
"1",
"/",
"cur",
"-",
"1",
"/",
"to"
] | Change the note duration at the given index to the given
duration. | [
"Change",
"the",
"note",
"duration",
"at",
"the",
"given",
"index",
"to",
"the",
"given",
"duration",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L133-L144 |
3,336 | bspaans/python-mingus | mingus/containers/bar.py | Bar.get_range | def get_range(self):
"""Return the highest and the lowest note in a tuple."""
(min, max) = (100000, -1)
for cont in self.bar:
for note in cont[2]:
if int(note) < int(min):
min = note
elif int(note) > int(max):
max = note
return (min, max) | python | def get_range(self):
"""Return the highest and the lowest note in a tuple."""
(min, max) = (100000, -1)
for cont in self.bar:
for note in cont[2]:
if int(note) < int(min):
min = note
elif int(note) > int(max):
max = note
return (min, max) | [
"def",
"get_range",
"(",
"self",
")",
":",
"(",
"min",
",",
"max",
")",
"=",
"(",
"100000",
",",
"-",
"1",
")",
"for",
"cont",
"in",
"self",
".",
"bar",
":",
"for",
"note",
"in",
"cont",
"[",
"2",
"]",
":",
"if",
"int",
"(",
"note",
")",
"<",
"int",
"(",
"min",
")",
":",
"min",
"=",
"note",
"elif",
"int",
"(",
"note",
")",
">",
"int",
"(",
"max",
")",
":",
"max",
"=",
"note",
"return",
"(",
"min",
",",
"max",
")"
] | Return the highest and the lowest note in a tuple. | [
"Return",
"the",
"highest",
"and",
"the",
"lowest",
"note",
"in",
"a",
"tuple",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L146-L155 |
3,337 | bspaans/python-mingus | mingus/containers/bar.py | Bar.transpose | def transpose(self, interval, up=True):
"""Transpose the notes in the bar up or down the interval.
Call transpose() on all NoteContainers in the bar.
"""
for cont in self.bar:
cont[2].transpose(interval, up) | python | def transpose(self, interval, up=True):
"""Transpose the notes in the bar up or down the interval.
Call transpose() on all NoteContainers in the bar.
"""
for cont in self.bar:
cont[2].transpose(interval, up) | [
"def",
"transpose",
"(",
"self",
",",
"interval",
",",
"up",
"=",
"True",
")",
":",
"for",
"cont",
"in",
"self",
".",
"bar",
":",
"cont",
"[",
"2",
"]",
".",
"transpose",
"(",
"interval",
",",
"up",
")"
] | Transpose the notes in the bar up or down the interval.
Call transpose() on all NoteContainers in the bar. | [
"Transpose",
"the",
"notes",
"in",
"the",
"bar",
"up",
"or",
"down",
"the",
"interval",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L175-L181 |
3,338 | bspaans/python-mingus | mingus/containers/bar.py | Bar.get_note_names | def get_note_names(self):
"""Return a list of unique note names in the Bar."""
res = []
for cont in self.bar:
for x in cont[2].get_note_names():
if x not in res:
res.append(x)
return res | python | def get_note_names(self):
"""Return a list of unique note names in the Bar."""
res = []
for cont in self.bar:
for x in cont[2].get_note_names():
if x not in res:
res.append(x)
return res | [
"def",
"get_note_names",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"for",
"cont",
"in",
"self",
".",
"bar",
":",
"for",
"x",
"in",
"cont",
"[",
"2",
"]",
".",
"get_note_names",
"(",
")",
":",
"if",
"x",
"not",
"in",
"res",
":",
"res",
".",
"append",
"(",
"x",
")",
"return",
"res"
] | Return a list of unique note names in the Bar. | [
"Return",
"a",
"list",
"of",
"unique",
"note",
"names",
"in",
"the",
"Bar",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L198-L205 |
3,339 | bspaans/python-mingus | mingus/midi/midi_file_in.py | MidiFile.parse_midi_file_header | def parse_midi_file_header(self, fp):
"""Read the header of a MIDI file and return a tuple containing the
format type, number of tracks and parsed time division information."""
# Check header
try:
if fp.read(4) != 'MThd':
raise HeaderError('Not a valid MIDI file header. Byte %d.'
% self.bytes_read)
self.bytes_read += 4
except:
raise IOError("Couldn't read from file.")
# Parse chunk size
try:
chunk_size = self.bytes_to_int(fp.read(4))
self.bytes_read += 4
except:
raise IOError("Couldn't read chunk size from file. Byte %d."
% self.bytes_read)
# Expect chunk size to be at least 6
if chunk_size < 6:
return False
try:
format_type = self.bytes_to_int(fp.read(2))
self.bytes_read += 2
if format_type not in [0, 1, 2]:
raise FormatError('%d is not a valid MIDI format.'
% format_type)
except:
raise IOError("Couldn't read format type from file.")
try:
number_of_tracks = self.bytes_to_int(fp.read(2))
time_division = self.parse_time_division(fp.read(2))
self.bytes_read += 4
except:
raise IOError("Couldn't read number of tracks "
"and/or time division from tracks.")
chunk_size -= 6
if chunk_size % 2 == 1:
raise FormatError("Won't parse this.")
fp.read(chunk_size / 2)
self.bytes_read += chunk_size / 2
return (format_type, number_of_tracks, time_division) | python | def parse_midi_file_header(self, fp):
"""Read the header of a MIDI file and return a tuple containing the
format type, number of tracks and parsed time division information."""
# Check header
try:
if fp.read(4) != 'MThd':
raise HeaderError('Not a valid MIDI file header. Byte %d.'
% self.bytes_read)
self.bytes_read += 4
except:
raise IOError("Couldn't read from file.")
# Parse chunk size
try:
chunk_size = self.bytes_to_int(fp.read(4))
self.bytes_read += 4
except:
raise IOError("Couldn't read chunk size from file. Byte %d."
% self.bytes_read)
# Expect chunk size to be at least 6
if chunk_size < 6:
return False
try:
format_type = self.bytes_to_int(fp.read(2))
self.bytes_read += 2
if format_type not in [0, 1, 2]:
raise FormatError('%d is not a valid MIDI format.'
% format_type)
except:
raise IOError("Couldn't read format type from file.")
try:
number_of_tracks = self.bytes_to_int(fp.read(2))
time_division = self.parse_time_division(fp.read(2))
self.bytes_read += 4
except:
raise IOError("Couldn't read number of tracks "
"and/or time division from tracks.")
chunk_size -= 6
if chunk_size % 2 == 1:
raise FormatError("Won't parse this.")
fp.read(chunk_size / 2)
self.bytes_read += chunk_size / 2
return (format_type, number_of_tracks, time_division) | [
"def",
"parse_midi_file_header",
"(",
"self",
",",
"fp",
")",
":",
"# Check header",
"try",
":",
"if",
"fp",
".",
"read",
"(",
"4",
")",
"!=",
"'MThd'",
":",
"raise",
"HeaderError",
"(",
"'Not a valid MIDI file header. Byte %d.'",
"%",
"self",
".",
"bytes_read",
")",
"self",
".",
"bytes_read",
"+=",
"4",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read from file.\"",
")",
"# Parse chunk size",
"try",
":",
"chunk_size",
"=",
"self",
".",
"bytes_to_int",
"(",
"fp",
".",
"read",
"(",
"4",
")",
")",
"self",
".",
"bytes_read",
"+=",
"4",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read chunk size from file. Byte %d.\"",
"%",
"self",
".",
"bytes_read",
")",
"# Expect chunk size to be at least 6",
"if",
"chunk_size",
"<",
"6",
":",
"return",
"False",
"try",
":",
"format_type",
"=",
"self",
".",
"bytes_to_int",
"(",
"fp",
".",
"read",
"(",
"2",
")",
")",
"self",
".",
"bytes_read",
"+=",
"2",
"if",
"format_type",
"not",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
":",
"raise",
"FormatError",
"(",
"'%d is not a valid MIDI format.'",
"%",
"format_type",
")",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read format type from file.\"",
")",
"try",
":",
"number_of_tracks",
"=",
"self",
".",
"bytes_to_int",
"(",
"fp",
".",
"read",
"(",
"2",
")",
")",
"time_division",
"=",
"self",
".",
"parse_time_division",
"(",
"fp",
".",
"read",
"(",
"2",
")",
")",
"self",
".",
"bytes_read",
"+=",
"4",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read number of tracks \"",
"\"and/or time division from tracks.\"",
")",
"chunk_size",
"-=",
"6",
"if",
"chunk_size",
"%",
"2",
"==",
"1",
":",
"raise",
"FormatError",
"(",
"\"Won't parse this.\"",
")",
"fp",
".",
"read",
"(",
"chunk_size",
"/",
"2",
")",
"self",
".",
"bytes_read",
"+=",
"chunk_size",
"/",
"2",
"return",
"(",
"format_type",
",",
"number_of_tracks",
",",
"time_division",
")"
] | Read the header of a MIDI file and return a tuple containing the
format type, number of tracks and parsed time division information. | [
"Read",
"the",
"header",
"of",
"a",
"MIDI",
"file",
"and",
"return",
"a",
"tuple",
"containing",
"the",
"format",
"type",
"number",
"of",
"tracks",
"and",
"parsed",
"time",
"division",
"information",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L171-L215 |
3,340 | bspaans/python-mingus | mingus/midi/midi_file_in.py | MidiFile.parse_time_division | def parse_time_division(self, bytes):
"""Parse the time division found in the header of a MIDI file and
return a dictionary with the boolean fps set to indicate whether to
use frames per second or ticks per beat.
If fps is True, the values SMPTE_frames and clock_ticks will also be
set. If fps is False, ticks_per_beat will hold the value.
"""
# If highest bit is set, time division is set in frames per second
# otherwise in ticks_per_beat
value = self.bytes_to_int(bytes)
if not value & 0x8000:
return {'fps': False, 'ticks_per_beat': value & 0x7FFF}
else:
SMPTE_frames = (value & 0x7F00) >> 2
if SMPTE_frames not in [24, 25, 29, 30]:
raise TimeDivisionError, \
"'%d' is not a valid value for the number of SMPTE frames"\
% SMPTE_frames
clock_ticks = (value & 0x00FF) >> 2
return {'fps': True, 'SMPTE_frames': SMPTE_frames,
'clock_ticks': clock_ticks} | python | def parse_time_division(self, bytes):
"""Parse the time division found in the header of a MIDI file and
return a dictionary with the boolean fps set to indicate whether to
use frames per second or ticks per beat.
If fps is True, the values SMPTE_frames and clock_ticks will also be
set. If fps is False, ticks_per_beat will hold the value.
"""
# If highest bit is set, time division is set in frames per second
# otherwise in ticks_per_beat
value = self.bytes_to_int(bytes)
if not value & 0x8000:
return {'fps': False, 'ticks_per_beat': value & 0x7FFF}
else:
SMPTE_frames = (value & 0x7F00) >> 2
if SMPTE_frames not in [24, 25, 29, 30]:
raise TimeDivisionError, \
"'%d' is not a valid value for the number of SMPTE frames"\
% SMPTE_frames
clock_ticks = (value & 0x00FF) >> 2
return {'fps': True, 'SMPTE_frames': SMPTE_frames,
'clock_ticks': clock_ticks} | [
"def",
"parse_time_division",
"(",
"self",
",",
"bytes",
")",
":",
"# If highest bit is set, time division is set in frames per second",
"# otherwise in ticks_per_beat",
"value",
"=",
"self",
".",
"bytes_to_int",
"(",
"bytes",
")",
"if",
"not",
"value",
"&",
"0x8000",
":",
"return",
"{",
"'fps'",
":",
"False",
",",
"'ticks_per_beat'",
":",
"value",
"&",
"0x7FFF",
"}",
"else",
":",
"SMPTE_frames",
"=",
"(",
"value",
"&",
"0x7F00",
")",
">>",
"2",
"if",
"SMPTE_frames",
"not",
"in",
"[",
"24",
",",
"25",
",",
"29",
",",
"30",
"]",
":",
"raise",
"TimeDivisionError",
",",
"\"'%d' is not a valid value for the number of SMPTE frames\"",
"%",
"SMPTE_frames",
"clock_ticks",
"=",
"(",
"value",
"&",
"0x00FF",
")",
">>",
"2",
"return",
"{",
"'fps'",
":",
"True",
",",
"'SMPTE_frames'",
":",
"SMPTE_frames",
",",
"'clock_ticks'",
":",
"clock_ticks",
"}"
] | Parse the time division found in the header of a MIDI file and
return a dictionary with the boolean fps set to indicate whether to
use frames per second or ticks per beat.
If fps is True, the values SMPTE_frames and clock_ticks will also be
set. If fps is False, ticks_per_beat will hold the value. | [
"Parse",
"the",
"time",
"division",
"found",
"in",
"the",
"header",
"of",
"a",
"MIDI",
"file",
"and",
"return",
"a",
"dictionary",
"with",
"the",
"boolean",
"fps",
"set",
"to",
"indicate",
"whether",
"to",
"use",
"frames",
"per",
"second",
"or",
"ticks",
"per",
"beat",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L220-L241 |
3,341 | bspaans/python-mingus | mingus/midi/midi_file_in.py | MidiFile.parse_track | def parse_track(self, fp):
"""Parse a MIDI track from its header to its events.
Return a list of events and the number of bytes that were read.
"""
events = []
chunk_size = self.parse_track_header(fp)
bytes = chunk_size
while chunk_size > 0:
(delta_time, chunk_delta) = self.parse_varbyte_as_int(fp)
chunk_size -= chunk_delta
(event, chunk_delta) = self.parse_midi_event(fp)
chunk_size -= chunk_delta
events.append([delta_time, event])
if chunk_size < 0:
print 'yikes.', self.bytes_read, chunk_size
return events | python | def parse_track(self, fp):
"""Parse a MIDI track from its header to its events.
Return a list of events and the number of bytes that were read.
"""
events = []
chunk_size = self.parse_track_header(fp)
bytes = chunk_size
while chunk_size > 0:
(delta_time, chunk_delta) = self.parse_varbyte_as_int(fp)
chunk_size -= chunk_delta
(event, chunk_delta) = self.parse_midi_event(fp)
chunk_size -= chunk_delta
events.append([delta_time, event])
if chunk_size < 0:
print 'yikes.', self.bytes_read, chunk_size
return events | [
"def",
"parse_track",
"(",
"self",
",",
"fp",
")",
":",
"events",
"=",
"[",
"]",
"chunk_size",
"=",
"self",
".",
"parse_track_header",
"(",
"fp",
")",
"bytes",
"=",
"chunk_size",
"while",
"chunk_size",
">",
"0",
":",
"(",
"delta_time",
",",
"chunk_delta",
")",
"=",
"self",
".",
"parse_varbyte_as_int",
"(",
"fp",
")",
"chunk_size",
"-=",
"chunk_delta",
"(",
"event",
",",
"chunk_delta",
")",
"=",
"self",
".",
"parse_midi_event",
"(",
"fp",
")",
"chunk_size",
"-=",
"chunk_delta",
"events",
".",
"append",
"(",
"[",
"delta_time",
",",
"event",
"]",
")",
"if",
"chunk_size",
"<",
"0",
":",
"print",
"'yikes.'",
",",
"self",
".",
"bytes_read",
",",
"chunk_size",
"return",
"events"
] | Parse a MIDI track from its header to its events.
Return a list of events and the number of bytes that were read. | [
"Parse",
"a",
"MIDI",
"track",
"from",
"its",
"header",
"to",
"its",
"events",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L243-L259 |
3,342 | bspaans/python-mingus | mingus/midi/midi_file_in.py | MidiFile.parse_midi_event | def parse_midi_event(self, fp):
"""Parse a MIDI event.
Return a dictionary and the number of bytes read.
"""
chunk_size = 0
try:
ec = self.bytes_to_int(fp.read(1))
chunk_size += 1
self.bytes_read += 1
except:
raise IOError("Couldn't read event type "
"and channel data from file.")
# Get the nibbles
event_type = (ec & 0xf0) >> 4
channel = ec & 0x0f
# I don't know what these events are supposed to do, but I keep finding
# them. The parser ignores them.
if event_type < 8:
raise FormatError('Unknown event type %d. Byte %d.' % (event_type,
self.bytes_read))
# Meta events can have strings of variable length
if event_type == 0x0f:
try:
meta_event = self.bytes_to_int(fp.read(1))
(length, chunk_delta) = self.parse_varbyte_as_int(fp)
data = fp.read(length)
chunk_size += 1 + chunk_delta + length
self.bytes_read += 1 + length
except:
raise IOError("Couldn't read meta event from file.")
return ({'event': event_type, 'meta_event': meta_event,
'data': data}, chunk_size)
elif event_type in [12, 13]:
# Program change and Channel aftertouch events only have one
# parameter
try:
param1 = fp.read(1)
chunk_size += 1
self.bytes_read += 1
except:
raise IOError("Couldn't read MIDI event parameters from file.")
param1 = self.bytes_to_int(param1)
return ({'event': event_type, 'channel': channel,
'param1': param1}, chunk_size)
else:
try:
param1 = fp.read(1)
param2 = fp.read(1)
chunk_size += 2
self.bytes_read += 2
except:
raise IOError("Couldn't read MIDI event parameters from file.")
param1 = self.bytes_to_int(param1)
param2 = self.bytes_to_int(param2)
return ({'event': event_type, 'channel': channel, 'param1': param1,
'param2': param2}, chunk_size) | python | def parse_midi_event(self, fp):
"""Parse a MIDI event.
Return a dictionary and the number of bytes read.
"""
chunk_size = 0
try:
ec = self.bytes_to_int(fp.read(1))
chunk_size += 1
self.bytes_read += 1
except:
raise IOError("Couldn't read event type "
"and channel data from file.")
# Get the nibbles
event_type = (ec & 0xf0) >> 4
channel = ec & 0x0f
# I don't know what these events are supposed to do, but I keep finding
# them. The parser ignores them.
if event_type < 8:
raise FormatError('Unknown event type %d. Byte %d.' % (event_type,
self.bytes_read))
# Meta events can have strings of variable length
if event_type == 0x0f:
try:
meta_event = self.bytes_to_int(fp.read(1))
(length, chunk_delta) = self.parse_varbyte_as_int(fp)
data = fp.read(length)
chunk_size += 1 + chunk_delta + length
self.bytes_read += 1 + length
except:
raise IOError("Couldn't read meta event from file.")
return ({'event': event_type, 'meta_event': meta_event,
'data': data}, chunk_size)
elif event_type in [12, 13]:
# Program change and Channel aftertouch events only have one
# parameter
try:
param1 = fp.read(1)
chunk_size += 1
self.bytes_read += 1
except:
raise IOError("Couldn't read MIDI event parameters from file.")
param1 = self.bytes_to_int(param1)
return ({'event': event_type, 'channel': channel,
'param1': param1}, chunk_size)
else:
try:
param1 = fp.read(1)
param2 = fp.read(1)
chunk_size += 2
self.bytes_read += 2
except:
raise IOError("Couldn't read MIDI event parameters from file.")
param1 = self.bytes_to_int(param1)
param2 = self.bytes_to_int(param2)
return ({'event': event_type, 'channel': channel, 'param1': param1,
'param2': param2}, chunk_size) | [
"def",
"parse_midi_event",
"(",
"self",
",",
"fp",
")",
":",
"chunk_size",
"=",
"0",
"try",
":",
"ec",
"=",
"self",
".",
"bytes_to_int",
"(",
"fp",
".",
"read",
"(",
"1",
")",
")",
"chunk_size",
"+=",
"1",
"self",
".",
"bytes_read",
"+=",
"1",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read event type \"",
"\"and channel data from file.\"",
")",
"# Get the nibbles",
"event_type",
"=",
"(",
"ec",
"&",
"0xf0",
")",
">>",
"4",
"channel",
"=",
"ec",
"&",
"0x0f",
"# I don't know what these events are supposed to do, but I keep finding",
"# them. The parser ignores them.",
"if",
"event_type",
"<",
"8",
":",
"raise",
"FormatError",
"(",
"'Unknown event type %d. Byte %d.'",
"%",
"(",
"event_type",
",",
"self",
".",
"bytes_read",
")",
")",
"# Meta events can have strings of variable length",
"if",
"event_type",
"==",
"0x0f",
":",
"try",
":",
"meta_event",
"=",
"self",
".",
"bytes_to_int",
"(",
"fp",
".",
"read",
"(",
"1",
")",
")",
"(",
"length",
",",
"chunk_delta",
")",
"=",
"self",
".",
"parse_varbyte_as_int",
"(",
"fp",
")",
"data",
"=",
"fp",
".",
"read",
"(",
"length",
")",
"chunk_size",
"+=",
"1",
"+",
"chunk_delta",
"+",
"length",
"self",
".",
"bytes_read",
"+=",
"1",
"+",
"length",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read meta event from file.\"",
")",
"return",
"(",
"{",
"'event'",
":",
"event_type",
",",
"'meta_event'",
":",
"meta_event",
",",
"'data'",
":",
"data",
"}",
",",
"chunk_size",
")",
"elif",
"event_type",
"in",
"[",
"12",
",",
"13",
"]",
":",
"# Program change and Channel aftertouch events only have one",
"# parameter",
"try",
":",
"param1",
"=",
"fp",
".",
"read",
"(",
"1",
")",
"chunk_size",
"+=",
"1",
"self",
".",
"bytes_read",
"+=",
"1",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read MIDI event parameters from file.\"",
")",
"param1",
"=",
"self",
".",
"bytes_to_int",
"(",
"param1",
")",
"return",
"(",
"{",
"'event'",
":",
"event_type",
",",
"'channel'",
":",
"channel",
",",
"'param1'",
":",
"param1",
"}",
",",
"chunk_size",
")",
"else",
":",
"try",
":",
"param1",
"=",
"fp",
".",
"read",
"(",
"1",
")",
"param2",
"=",
"fp",
".",
"read",
"(",
"1",
")",
"chunk_size",
"+=",
"2",
"self",
".",
"bytes_read",
"+=",
"2",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read MIDI event parameters from file.\"",
")",
"param1",
"=",
"self",
".",
"bytes_to_int",
"(",
"param1",
")",
"param2",
"=",
"self",
".",
"bytes_to_int",
"(",
"param2",
")",
"return",
"(",
"{",
"'event'",
":",
"event_type",
",",
"'channel'",
":",
"channel",
",",
"'param1'",
":",
"param1",
",",
"'param2'",
":",
"param2",
"}",
",",
"chunk_size",
")"
] | Parse a MIDI event.
Return a dictionary and the number of bytes read. | [
"Parse",
"a",
"MIDI",
"event",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L261-L320 |
3,343 | bspaans/python-mingus | mingus/midi/midi_file_in.py | MidiFile.parse_track_header | def parse_track_header(self, fp):
"""Return the size of the track chunk."""
# Check the header
try:
h = fp.read(4)
self.bytes_read += 4
except:
raise IOError("Couldn't read track header from file. Byte %d."
% self.bytes_read)
if h != 'MTrk':
raise HeaderError('Not a valid Track header. Byte %d.'
% self.bytes_read)
# Parse the size of the header
try:
chunk_size = fp.read(4)
self.bytes_read += 4
except:
raise IOError("Couldn't read track chunk size from file.")
chunk_size = self.bytes_to_int(chunk_size)
return chunk_size | python | def parse_track_header(self, fp):
"""Return the size of the track chunk."""
# Check the header
try:
h = fp.read(4)
self.bytes_read += 4
except:
raise IOError("Couldn't read track header from file. Byte %d."
% self.bytes_read)
if h != 'MTrk':
raise HeaderError('Not a valid Track header. Byte %d.'
% self.bytes_read)
# Parse the size of the header
try:
chunk_size = fp.read(4)
self.bytes_read += 4
except:
raise IOError("Couldn't read track chunk size from file.")
chunk_size = self.bytes_to_int(chunk_size)
return chunk_size | [
"def",
"parse_track_header",
"(",
"self",
",",
"fp",
")",
":",
"# Check the header",
"try",
":",
"h",
"=",
"fp",
".",
"read",
"(",
"4",
")",
"self",
".",
"bytes_read",
"+=",
"4",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read track header from file. Byte %d.\"",
"%",
"self",
".",
"bytes_read",
")",
"if",
"h",
"!=",
"'MTrk'",
":",
"raise",
"HeaderError",
"(",
"'Not a valid Track header. Byte %d.'",
"%",
"self",
".",
"bytes_read",
")",
"# Parse the size of the header",
"try",
":",
"chunk_size",
"=",
"fp",
".",
"read",
"(",
"4",
")",
"self",
".",
"bytes_read",
"+=",
"4",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read track chunk size from file.\"",
")",
"chunk_size",
"=",
"self",
".",
"bytes_to_int",
"(",
"chunk_size",
")",
"return",
"chunk_size"
] | Return the size of the track chunk. | [
"Return",
"the",
"size",
"of",
"the",
"track",
"chunk",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L322-L342 |
3,344 | bspaans/python-mingus | mingus/midi/midi_file_in.py | MidiFile.parse_varbyte_as_int | def parse_varbyte_as_int(self, fp, return_bytes_read=True):
"""Read a variable length byte from the file and return the
corresponding integer."""
result = 0
bytes_read = 0
r = 0x80
while r & 0x80:
try:
r = self.bytes_to_int(fp.read(1))
self.bytes_read += 1
except:
raise IOError("Couldn't read variable length byte from file.")
if r & 0x80:
result = (result << 7) + (r & 0x7F)
else:
result = (result << 7) + r
bytes_read += 1
if not return_bytes_read:
return result
else:
return (result, bytes_read) | python | def parse_varbyte_as_int(self, fp, return_bytes_read=True):
"""Read a variable length byte from the file and return the
corresponding integer."""
result = 0
bytes_read = 0
r = 0x80
while r & 0x80:
try:
r = self.bytes_to_int(fp.read(1))
self.bytes_read += 1
except:
raise IOError("Couldn't read variable length byte from file.")
if r & 0x80:
result = (result << 7) + (r & 0x7F)
else:
result = (result << 7) + r
bytes_read += 1
if not return_bytes_read:
return result
else:
return (result, bytes_read) | [
"def",
"parse_varbyte_as_int",
"(",
"self",
",",
"fp",
",",
"return_bytes_read",
"=",
"True",
")",
":",
"result",
"=",
"0",
"bytes_read",
"=",
"0",
"r",
"=",
"0x80",
"while",
"r",
"&",
"0x80",
":",
"try",
":",
"r",
"=",
"self",
".",
"bytes_to_int",
"(",
"fp",
".",
"read",
"(",
"1",
")",
")",
"self",
".",
"bytes_read",
"+=",
"1",
"except",
":",
"raise",
"IOError",
"(",
"\"Couldn't read variable length byte from file.\"",
")",
"if",
"r",
"&",
"0x80",
":",
"result",
"=",
"(",
"result",
"<<",
"7",
")",
"+",
"(",
"r",
"&",
"0x7F",
")",
"else",
":",
"result",
"=",
"(",
"result",
"<<",
"7",
")",
"+",
"r",
"bytes_read",
"+=",
"1",
"if",
"not",
"return_bytes_read",
":",
"return",
"result",
"else",
":",
"return",
"(",
"result",
",",
"bytes_read",
")"
] | Read a variable length byte from the file and return the
corresponding integer. | [
"Read",
"a",
"variable",
"length",
"byte",
"from",
"the",
"file",
"and",
"return",
"the",
"corresponding",
"integer",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L366-L386 |
3,345 | bspaans/python-mingus | mingus/containers/note.py | Note.set_note | def set_note(self, name='C', octave=4, dynamics={}):
"""Set the note to name in octave with dynamics.
Return the objects if it succeeded, raise an NoteFormatError
otherwise.
"""
dash_index = name.split('-')
if len(dash_index) == 1:
if notes.is_valid_note(name):
self.name = name
self.octave = octave
self.dynamics = dynamics
return self
else:
raise NoteFormatError("The string '%s' is not a valid "
"representation of a note in mingus" % name)
elif len(dash_index) == 2:
if notes.is_valid_note(dash_index[0]):
self.name = dash_index[0]
self.octave = int(dash_index[1])
self.dynamics = dynamics
return self
else:
raise NoteFormatError("The string '%s' is not a valid "
"representation of a note in mingus" % name)
return False | python | def set_note(self, name='C', octave=4, dynamics={}):
"""Set the note to name in octave with dynamics.
Return the objects if it succeeded, raise an NoteFormatError
otherwise.
"""
dash_index = name.split('-')
if len(dash_index) == 1:
if notes.is_valid_note(name):
self.name = name
self.octave = octave
self.dynamics = dynamics
return self
else:
raise NoteFormatError("The string '%s' is not a valid "
"representation of a note in mingus" % name)
elif len(dash_index) == 2:
if notes.is_valid_note(dash_index[0]):
self.name = dash_index[0]
self.octave = int(dash_index[1])
self.dynamics = dynamics
return self
else:
raise NoteFormatError("The string '%s' is not a valid "
"representation of a note in mingus" % name)
return False | [
"def",
"set_note",
"(",
"self",
",",
"name",
"=",
"'C'",
",",
"octave",
"=",
"4",
",",
"dynamics",
"=",
"{",
"}",
")",
":",
"dash_index",
"=",
"name",
".",
"split",
"(",
"'-'",
")",
"if",
"len",
"(",
"dash_index",
")",
"==",
"1",
":",
"if",
"notes",
".",
"is_valid_note",
"(",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"octave",
"=",
"octave",
"self",
".",
"dynamics",
"=",
"dynamics",
"return",
"self",
"else",
":",
"raise",
"NoteFormatError",
"(",
"\"The string '%s' is not a valid \"",
"\"representation of a note in mingus\"",
"%",
"name",
")",
"elif",
"len",
"(",
"dash_index",
")",
"==",
"2",
":",
"if",
"notes",
".",
"is_valid_note",
"(",
"dash_index",
"[",
"0",
"]",
")",
":",
"self",
".",
"name",
"=",
"dash_index",
"[",
"0",
"]",
"self",
".",
"octave",
"=",
"int",
"(",
"dash_index",
"[",
"1",
"]",
")",
"self",
".",
"dynamics",
"=",
"dynamics",
"return",
"self",
"else",
":",
"raise",
"NoteFormatError",
"(",
"\"The string '%s' is not a valid \"",
"\"representation of a note in mingus\"",
"%",
"name",
")",
"return",
"False"
] | Set the note to name in octave with dynamics.
Return the objects if it succeeded, raise an NoteFormatError
otherwise. | [
"Set",
"the",
"note",
"to",
"name",
"in",
"octave",
"with",
"dynamics",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L70-L95 |
3,346 | bspaans/python-mingus | mingus/containers/note.py | Note.change_octave | def change_octave(self, diff):
"""Change the octave of the note to the current octave + diff."""
self.octave += diff
if self.octave < 0:
self.octave = 0 | python | def change_octave(self, diff):
"""Change the octave of the note to the current octave + diff."""
self.octave += diff
if self.octave < 0:
self.octave = 0 | [
"def",
"change_octave",
"(",
"self",
",",
"diff",
")",
":",
"self",
".",
"octave",
"+=",
"diff",
"if",
"self",
".",
"octave",
"<",
"0",
":",
"self",
".",
"octave",
"=",
"0"
] | Change the octave of the note to the current octave + diff. | [
"Change",
"the",
"octave",
"of",
"the",
"note",
"to",
"the",
"current",
"octave",
"+",
"diff",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L111-L115 |
3,347 | bspaans/python-mingus | mingus/containers/note.py | Note.transpose | def transpose(self, interval, up=True):
"""Transpose the note up or down the interval.
Examples:
>>> a = Note('A')
>>> a.transpose('3')
>>> a
'C#-5'
>>> a.transpose('3', False)
>>> a
'A-4'
"""
(old, o_octave) = (self.name, self.octave)
self.name = intervals.from_shorthand(self.name, interval, up)
if up:
if self < Note(old, o_octave):
self.octave += 1
else:
if self > Note(old, o_octave):
self.octave -= 1 | python | def transpose(self, interval, up=True):
"""Transpose the note up or down the interval.
Examples:
>>> a = Note('A')
>>> a.transpose('3')
>>> a
'C#-5'
>>> a.transpose('3', False)
>>> a
'A-4'
"""
(old, o_octave) = (self.name, self.octave)
self.name = intervals.from_shorthand(self.name, interval, up)
if up:
if self < Note(old, o_octave):
self.octave += 1
else:
if self > Note(old, o_octave):
self.octave -= 1 | [
"def",
"transpose",
"(",
"self",
",",
"interval",
",",
"up",
"=",
"True",
")",
":",
"(",
"old",
",",
"o_octave",
")",
"=",
"(",
"self",
".",
"name",
",",
"self",
".",
"octave",
")",
"self",
".",
"name",
"=",
"intervals",
".",
"from_shorthand",
"(",
"self",
".",
"name",
",",
"interval",
",",
"up",
")",
"if",
"up",
":",
"if",
"self",
"<",
"Note",
"(",
"old",
",",
"o_octave",
")",
":",
"self",
".",
"octave",
"+=",
"1",
"else",
":",
"if",
"self",
">",
"Note",
"(",
"old",
",",
"o_octave",
")",
":",
"self",
".",
"octave",
"-=",
"1"
] | Transpose the note up or down the interval.
Examples:
>>> a = Note('A')
>>> a.transpose('3')
>>> a
'C#-5'
>>> a.transpose('3', False)
>>> a
'A-4' | [
"Transpose",
"the",
"note",
"up",
"or",
"down",
"the",
"interval",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L129-L148 |
3,348 | bspaans/python-mingus | mingus/containers/note.py | Note.from_int | def from_int(self, integer):
"""Set the Note corresponding to the integer.
0 is a C on octave 0, 12 is a C on octave 1, etc.
Example:
>>> Note().from_int(12)
'C-1'
"""
self.name = notes.int_to_note(integer % 12)
self.octave = integer // 12
return self | python | def from_int(self, integer):
"""Set the Note corresponding to the integer.
0 is a C on octave 0, 12 is a C on octave 1, etc.
Example:
>>> Note().from_int(12)
'C-1'
"""
self.name = notes.int_to_note(integer % 12)
self.octave = integer // 12
return self | [
"def",
"from_int",
"(",
"self",
",",
"integer",
")",
":",
"self",
".",
"name",
"=",
"notes",
".",
"int_to_note",
"(",
"integer",
"%",
"12",
")",
"self",
".",
"octave",
"=",
"integer",
"//",
"12",
"return",
"self"
] | Set the Note corresponding to the integer.
0 is a C on octave 0, 12 is a C on octave 1, etc.
Example:
>>> Note().from_int(12)
'C-1' | [
"Set",
"the",
"Note",
"corresponding",
"to",
"the",
"integer",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L150-L161 |
3,349 | bspaans/python-mingus | mingus/containers/note.py | Note.from_hertz | def from_hertz(self, hertz, standard_pitch=440):
"""Set the Note name and pitch, calculated from the hertz value.
The standard_pitch argument can be used to set the pitch of A-4,
from which the rest is calculated.
"""
value = ((log((float(hertz) * 1024) / standard_pitch, 2) +
1.0 / 24) * 12 + 9) # notes.note_to_int("A")
self.name = notes.int_to_note(int(value) % 12)
self.octave = int(value / 12) - 6
return self | python | def from_hertz(self, hertz, standard_pitch=440):
"""Set the Note name and pitch, calculated from the hertz value.
The standard_pitch argument can be used to set the pitch of A-4,
from which the rest is calculated.
"""
value = ((log((float(hertz) * 1024) / standard_pitch, 2) +
1.0 / 24) * 12 + 9) # notes.note_to_int("A")
self.name = notes.int_to_note(int(value) % 12)
self.octave = int(value / 12) - 6
return self | [
"def",
"from_hertz",
"(",
"self",
",",
"hertz",
",",
"standard_pitch",
"=",
"440",
")",
":",
"value",
"=",
"(",
"(",
"log",
"(",
"(",
"float",
"(",
"hertz",
")",
"*",
"1024",
")",
"/",
"standard_pitch",
",",
"2",
")",
"+",
"1.0",
"/",
"24",
")",
"*",
"12",
"+",
"9",
")",
"# notes.note_to_int(\"A\")",
"self",
".",
"name",
"=",
"notes",
".",
"int_to_note",
"(",
"int",
"(",
"value",
")",
"%",
"12",
")",
"self",
".",
"octave",
"=",
"int",
"(",
"value",
"/",
"12",
")",
"-",
"6",
"return",
"self"
] | Set the Note name and pitch, calculated from the hertz value.
The standard_pitch argument can be used to set the pitch of A-4,
from which the rest is calculated. | [
"Set",
"the",
"Note",
"name",
"and",
"pitch",
"calculated",
"from",
"the",
"hertz",
"value",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L184-L194 |
3,350 | bspaans/python-mingus | mingus/containers/note.py | Note.to_shorthand | def to_shorthand(self):
"""Give the traditional Helmhotz pitch notation.
Examples:
>>> Note('C-4').to_shorthand()
"c'"
>>> Note('C-3').to_shorthand()
'c'
>>> Note('C-2').to_shorthand()
'C'
>>> Note('C-1').to_shorthand()
'C,'
"""
if self.octave < 3:
res = self.name
else:
res = str.lower(self.name)
o = self.octave - 3
while o < -1:
res += ','
o += 1
while o > 0:
res += "'"
o -= 1
return res | python | def to_shorthand(self):
"""Give the traditional Helmhotz pitch notation.
Examples:
>>> Note('C-4').to_shorthand()
"c'"
>>> Note('C-3').to_shorthand()
'c'
>>> Note('C-2').to_shorthand()
'C'
>>> Note('C-1').to_shorthand()
'C,'
"""
if self.octave < 3:
res = self.name
else:
res = str.lower(self.name)
o = self.octave - 3
while o < -1:
res += ','
o += 1
while o > 0:
res += "'"
o -= 1
return res | [
"def",
"to_shorthand",
"(",
"self",
")",
":",
"if",
"self",
".",
"octave",
"<",
"3",
":",
"res",
"=",
"self",
".",
"name",
"else",
":",
"res",
"=",
"str",
".",
"lower",
"(",
"self",
".",
"name",
")",
"o",
"=",
"self",
".",
"octave",
"-",
"3",
"while",
"o",
"<",
"-",
"1",
":",
"res",
"+=",
"','",
"o",
"+=",
"1",
"while",
"o",
">",
"0",
":",
"res",
"+=",
"\"'\"",
"o",
"-=",
"1",
"return",
"res"
] | Give the traditional Helmhotz pitch notation.
Examples:
>>> Note('C-4').to_shorthand()
"c'"
>>> Note('C-3').to_shorthand()
'c'
>>> Note('C-2').to_shorthand()
'C'
>>> Note('C-1').to_shorthand()
'C,' | [
"Give",
"the",
"traditional",
"Helmhotz",
"pitch",
"notation",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L196-L220 |
3,351 | bspaans/python-mingus | mingus/containers/note.py | Note.from_shorthand | def from_shorthand(self, shorthand):
"""Convert from traditional Helmhotz pitch notation.
Examples:
>>> Note().from_shorthand("C,,")
'C-0'
>>> Note().from_shorthand("C")
'C-2'
>>> Note().from_shorthand("c'")
'C-4'
"""
name = ''
octave = 0
for x in shorthand:
if x in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:
name = str.upper(x)
octave = 3
elif x in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
name = x
octave = 2
elif x in ['#', 'b']:
name += x
elif x == ',':
octave -= 1
elif x == "'":
octave += 1
return self.set_note(name, octave, {}) | python | def from_shorthand(self, shorthand):
"""Convert from traditional Helmhotz pitch notation.
Examples:
>>> Note().from_shorthand("C,,")
'C-0'
>>> Note().from_shorthand("C")
'C-2'
>>> Note().from_shorthand("c'")
'C-4'
"""
name = ''
octave = 0
for x in shorthand:
if x in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:
name = str.upper(x)
octave = 3
elif x in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
name = x
octave = 2
elif x in ['#', 'b']:
name += x
elif x == ',':
octave -= 1
elif x == "'":
octave += 1
return self.set_note(name, octave, {}) | [
"def",
"from_shorthand",
"(",
"self",
",",
"shorthand",
")",
":",
"name",
"=",
"''",
"octave",
"=",
"0",
"for",
"x",
"in",
"shorthand",
":",
"if",
"x",
"in",
"[",
"'a'",
",",
"'b'",
",",
"'c'",
",",
"'d'",
",",
"'e'",
",",
"'f'",
",",
"'g'",
"]",
":",
"name",
"=",
"str",
".",
"upper",
"(",
"x",
")",
"octave",
"=",
"3",
"elif",
"x",
"in",
"[",
"'A'",
",",
"'B'",
",",
"'C'",
",",
"'D'",
",",
"'E'",
",",
"'F'",
",",
"'G'",
"]",
":",
"name",
"=",
"x",
"octave",
"=",
"2",
"elif",
"x",
"in",
"[",
"'#'",
",",
"'b'",
"]",
":",
"name",
"+=",
"x",
"elif",
"x",
"==",
"','",
":",
"octave",
"-=",
"1",
"elif",
"x",
"==",
"\"'\"",
":",
"octave",
"+=",
"1",
"return",
"self",
".",
"set_note",
"(",
"name",
",",
"octave",
",",
"{",
"}",
")"
] | Convert from traditional Helmhotz pitch notation.
Examples:
>>> Note().from_shorthand("C,,")
'C-0'
>>> Note().from_shorthand("C")
'C-2'
>>> Note().from_shorthand("c'")
'C-4' | [
"Convert",
"from",
"traditional",
"Helmhotz",
"pitch",
"notation",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/note.py#L222-L248 |
3,352 | bspaans/python-mingus | mingus/core/intervals.py | interval | def interval(key, start_note, interval):
"""Return the note found at the interval starting from start_note in the
given key.
Raise a KeyError exception if start_note is not a valid note.
Example:
>>> interval('C', 'D', 1)
'E'
"""
if not notes.is_valid_note(start_note):
raise KeyError("The start note '%s' is not a valid note" % start_note)
notes_in_key = keys.get_notes(key)
for n in notes_in_key:
if n[0] == start_note[0]:
index = notes_in_key.index(n)
return notes_in_key[(index + interval) % 7] | python | def interval(key, start_note, interval):
"""Return the note found at the interval starting from start_note in the
given key.
Raise a KeyError exception if start_note is not a valid note.
Example:
>>> interval('C', 'D', 1)
'E'
"""
if not notes.is_valid_note(start_note):
raise KeyError("The start note '%s' is not a valid note" % start_note)
notes_in_key = keys.get_notes(key)
for n in notes_in_key:
if n[0] == start_note[0]:
index = notes_in_key.index(n)
return notes_in_key[(index + interval) % 7] | [
"def",
"interval",
"(",
"key",
",",
"start_note",
",",
"interval",
")",
":",
"if",
"not",
"notes",
".",
"is_valid_note",
"(",
"start_note",
")",
":",
"raise",
"KeyError",
"(",
"\"The start note '%s' is not a valid note\"",
"%",
"start_note",
")",
"notes_in_key",
"=",
"keys",
".",
"get_notes",
"(",
"key",
")",
"for",
"n",
"in",
"notes_in_key",
":",
"if",
"n",
"[",
"0",
"]",
"==",
"start_note",
"[",
"0",
"]",
":",
"index",
"=",
"notes_in_key",
".",
"index",
"(",
"n",
")",
"return",
"notes_in_key",
"[",
"(",
"index",
"+",
"interval",
")",
"%",
"7",
"]"
] | Return the note found at the interval starting from start_note in the
given key.
Raise a KeyError exception if start_note is not a valid note.
Example:
>>> interval('C', 'D', 1)
'E' | [
"Return",
"the",
"note",
"found",
"at",
"the",
"interval",
"starting",
"from",
"start_note",
"in",
"the",
"given",
"key",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L37-L53 |
3,353 | bspaans/python-mingus | mingus/core/intervals.py | measure | def measure(note1, note2):
"""Return an integer in the range of 0-11, determining the half note steps
between note1 and note2.
Examples:
>>> measure('C', 'D')
2
>>> measure('D', 'C')
10
"""
res = notes.note_to_int(note2) - notes.note_to_int(note1)
if res < 0:
return 12 - res * -1
else:
return res | python | def measure(note1, note2):
"""Return an integer in the range of 0-11, determining the half note steps
between note1 and note2.
Examples:
>>> measure('C', 'D')
2
>>> measure('D', 'C')
10
"""
res = notes.note_to_int(note2) - notes.note_to_int(note1)
if res < 0:
return 12 - res * -1
else:
return res | [
"def",
"measure",
"(",
"note1",
",",
"note2",
")",
":",
"res",
"=",
"notes",
".",
"note_to_int",
"(",
"note2",
")",
"-",
"notes",
".",
"note_to_int",
"(",
"note1",
")",
"if",
"res",
"<",
"0",
":",
"return",
"12",
"-",
"res",
"*",
"-",
"1",
"else",
":",
"return",
"res"
] | Return an integer in the range of 0-11, determining the half note steps
between note1 and note2.
Examples:
>>> measure('C', 'D')
2
>>> measure('D', 'C')
10 | [
"Return",
"an",
"integer",
"in",
"the",
"range",
"of",
"0",
"-",
"11",
"determining",
"the",
"half",
"note",
"steps",
"between",
"note1",
"and",
"note2",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L235-L249 |
3,354 | bspaans/python-mingus | mingus/core/intervals.py | augment_or_diminish_until_the_interval_is_right | def augment_or_diminish_until_the_interval_is_right(note1, note2, interval):
"""A helper function for the minor and major functions.
You should probably not use this directly.
"""
cur = measure(note1, note2)
while cur != interval:
if cur > interval:
note2 = notes.diminish(note2)
elif cur < interval:
note2 = notes.augment(note2)
cur = measure(note1, note2)
# We are practically done right now, but we need to be able to create the
# minor seventh of Cb and get Bbb instead of B######### as the result
val = 0
for token in note2[1:]:
if token == '#':
val += 1
elif token == 'b':
val -= 1
# These are some checks to see if we have generated too much #'s or too much
# b's. In these cases we need to convert #'s to b's and vice versa.
if val > 6:
val = val % 12
val = -12 + val
elif val < -6:
val = val % -12
val = 12 + val
# Rebuild the note
result = note2[0]
while val > 0:
result = notes.augment(result)
val -= 1
while val < 0:
result = notes.diminish(result)
val += 1
return result | python | def augment_or_diminish_until_the_interval_is_right(note1, note2, interval):
"""A helper function for the minor and major functions.
You should probably not use this directly.
"""
cur = measure(note1, note2)
while cur != interval:
if cur > interval:
note2 = notes.diminish(note2)
elif cur < interval:
note2 = notes.augment(note2)
cur = measure(note1, note2)
# We are practically done right now, but we need to be able to create the
# minor seventh of Cb and get Bbb instead of B######### as the result
val = 0
for token in note2[1:]:
if token == '#':
val += 1
elif token == 'b':
val -= 1
# These are some checks to see if we have generated too much #'s or too much
# b's. In these cases we need to convert #'s to b's and vice versa.
if val > 6:
val = val % 12
val = -12 + val
elif val < -6:
val = val % -12
val = 12 + val
# Rebuild the note
result = note2[0]
while val > 0:
result = notes.augment(result)
val -= 1
while val < 0:
result = notes.diminish(result)
val += 1
return result | [
"def",
"augment_or_diminish_until_the_interval_is_right",
"(",
"note1",
",",
"note2",
",",
"interval",
")",
":",
"cur",
"=",
"measure",
"(",
"note1",
",",
"note2",
")",
"while",
"cur",
"!=",
"interval",
":",
"if",
"cur",
">",
"interval",
":",
"note2",
"=",
"notes",
".",
"diminish",
"(",
"note2",
")",
"elif",
"cur",
"<",
"interval",
":",
"note2",
"=",
"notes",
".",
"augment",
"(",
"note2",
")",
"cur",
"=",
"measure",
"(",
"note1",
",",
"note2",
")",
"# We are practically done right now, but we need to be able to create the",
"# minor seventh of Cb and get Bbb instead of B######### as the result",
"val",
"=",
"0",
"for",
"token",
"in",
"note2",
"[",
"1",
":",
"]",
":",
"if",
"token",
"==",
"'#'",
":",
"val",
"+=",
"1",
"elif",
"token",
"==",
"'b'",
":",
"val",
"-=",
"1",
"# These are some checks to see if we have generated too much #'s or too much",
"# b's. In these cases we need to convert #'s to b's and vice versa.",
"if",
"val",
">",
"6",
":",
"val",
"=",
"val",
"%",
"12",
"val",
"=",
"-",
"12",
"+",
"val",
"elif",
"val",
"<",
"-",
"6",
":",
"val",
"=",
"val",
"%",
"-",
"12",
"val",
"=",
"12",
"+",
"val",
"# Rebuild the note",
"result",
"=",
"note2",
"[",
"0",
"]",
"while",
"val",
">",
"0",
":",
"result",
"=",
"notes",
".",
"augment",
"(",
"result",
")",
"val",
"-=",
"1",
"while",
"val",
"<",
"0",
":",
"result",
"=",
"notes",
".",
"diminish",
"(",
"result",
")",
"val",
"+=",
"1",
"return",
"result"
] | A helper function for the minor and major functions.
You should probably not use this directly. | [
"A",
"helper",
"function",
"for",
"the",
"minor",
"and",
"major",
"functions",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L251-L290 |
3,355 | bspaans/python-mingus | mingus/core/intervals.py | invert | def invert(interval):
"""Invert an interval.
Example:
>>> invert(['C', 'E'])
['E', 'C']
"""
interval.reverse()
res = list(interval)
interval.reverse()
return res | python | def invert(interval):
"""Invert an interval.
Example:
>>> invert(['C', 'E'])
['E', 'C']
"""
interval.reverse()
res = list(interval)
interval.reverse()
return res | [
"def",
"invert",
"(",
"interval",
")",
":",
"interval",
".",
"reverse",
"(",
")",
"res",
"=",
"list",
"(",
"interval",
")",
"interval",
".",
"reverse",
"(",
")",
"return",
"res"
] | Invert an interval.
Example:
>>> invert(['C', 'E'])
['E', 'C'] | [
"Invert",
"an",
"interval",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L292-L302 |
3,356 | bspaans/python-mingus | mingus/core/intervals.py | determine | def determine(note1, note2, shorthand=False):
"""Name the interval between note1 and note2.
Examples:
>>> determine('C', 'E')
'major third'
>>> determine('C', 'Eb')
'minor third'
>>> determine('C', 'E#')
'augmented third'
>>> determine('C', 'Ebb')
'diminished third'
This works for all intervals. Note that there are corner cases for major
fifths and fourths:
>>> determine('C', 'G')
'perfect fifth'
>>> determine('C', 'F')
'perfect fourth'
"""
# Corner case for unisons ('A' and 'Ab', for instance)
if note1[0] == note2[0]:
def get_val(note):
"""Private function: count the value of accidentals."""
r = 0
for x in note[1:]:
if x == 'b':
r -= 1
elif x == '#':
r += 1
return r
x = get_val(note1)
y = get_val(note2)
if x == y:
if not shorthand:
return 'major unison'
return '1'
elif x < y:
if not shorthand:
return 'augmented unison'
return '#1'
elif x - y == 1:
if not shorthand:
return 'minor unison'
return 'b1'
else:
if not shorthand:
return 'diminished unison'
return 'bb1'
# Other intervals
n1 = notes.fifths.index(note1[0])
n2 = notes.fifths.index(note2[0])
number_of_fifth_steps = n2 - n1
if n2 < n1:
number_of_fifth_steps = len(notes.fifths) - n1 + n2
# [name, shorthand_name, half notes for major version of this interval]
fifth_steps = [
['unison', '1', 0],
['fifth', '5', 7],
['second', '2', 2],
['sixth', '6', 9],
['third', '3', 4],
['seventh', '7', 11],
['fourth', '4', 5],
]
# Count half steps between note1 and note2
half_notes = measure(note1, note2)
# Get the proper list from the number of fifth steps
current = fifth_steps[number_of_fifth_steps]
# maj = number of major steps for this interval
maj = current[2]
# if maj is equal to the half steps between note1 and note2 the interval is
# major or perfect
if maj == half_notes:
# Corner cases for perfect fifths and fourths
if current[0] == 'fifth':
if not shorthand:
return 'perfect fifth'
elif current[0] == 'fourth':
if not shorthand:
return 'perfect fourth'
if not shorthand:
return 'major ' + current[0]
return current[1]
elif maj + 1 <= half_notes:
# if maj + 1 is equal to half_notes, the interval is augmented.
if not shorthand:
return 'augmented ' + current[0]
return '#' * (half_notes - maj) + current[1]
elif maj - 1 == half_notes:
# etc.
if not shorthand:
return 'minor ' + current[0]
return 'b' + current[1]
elif maj - 2 >= half_notes:
if not shorthand:
return 'diminished ' + current[0]
return 'b' * (maj - half_notes) + current[1] | python | def determine(note1, note2, shorthand=False):
"""Name the interval between note1 and note2.
Examples:
>>> determine('C', 'E')
'major third'
>>> determine('C', 'Eb')
'minor third'
>>> determine('C', 'E#')
'augmented third'
>>> determine('C', 'Ebb')
'diminished third'
This works for all intervals. Note that there are corner cases for major
fifths and fourths:
>>> determine('C', 'G')
'perfect fifth'
>>> determine('C', 'F')
'perfect fourth'
"""
# Corner case for unisons ('A' and 'Ab', for instance)
if note1[0] == note2[0]:
def get_val(note):
"""Private function: count the value of accidentals."""
r = 0
for x in note[1:]:
if x == 'b':
r -= 1
elif x == '#':
r += 1
return r
x = get_val(note1)
y = get_val(note2)
if x == y:
if not shorthand:
return 'major unison'
return '1'
elif x < y:
if not shorthand:
return 'augmented unison'
return '#1'
elif x - y == 1:
if not shorthand:
return 'minor unison'
return 'b1'
else:
if not shorthand:
return 'diminished unison'
return 'bb1'
# Other intervals
n1 = notes.fifths.index(note1[0])
n2 = notes.fifths.index(note2[0])
number_of_fifth_steps = n2 - n1
if n2 < n1:
number_of_fifth_steps = len(notes.fifths) - n1 + n2
# [name, shorthand_name, half notes for major version of this interval]
fifth_steps = [
['unison', '1', 0],
['fifth', '5', 7],
['second', '2', 2],
['sixth', '6', 9],
['third', '3', 4],
['seventh', '7', 11],
['fourth', '4', 5],
]
# Count half steps between note1 and note2
half_notes = measure(note1, note2)
# Get the proper list from the number of fifth steps
current = fifth_steps[number_of_fifth_steps]
# maj = number of major steps for this interval
maj = current[2]
# if maj is equal to the half steps between note1 and note2 the interval is
# major or perfect
if maj == half_notes:
# Corner cases for perfect fifths and fourths
if current[0] == 'fifth':
if not shorthand:
return 'perfect fifth'
elif current[0] == 'fourth':
if not shorthand:
return 'perfect fourth'
if not shorthand:
return 'major ' + current[0]
return current[1]
elif maj + 1 <= half_notes:
# if maj + 1 is equal to half_notes, the interval is augmented.
if not shorthand:
return 'augmented ' + current[0]
return '#' * (half_notes - maj) + current[1]
elif maj - 1 == half_notes:
# etc.
if not shorthand:
return 'minor ' + current[0]
return 'b' + current[1]
elif maj - 2 >= half_notes:
if not shorthand:
return 'diminished ' + current[0]
return 'b' * (maj - half_notes) + current[1] | [
"def",
"determine",
"(",
"note1",
",",
"note2",
",",
"shorthand",
"=",
"False",
")",
":",
"# Corner case for unisons ('A' and 'Ab', for instance)",
"if",
"note1",
"[",
"0",
"]",
"==",
"note2",
"[",
"0",
"]",
":",
"def",
"get_val",
"(",
"note",
")",
":",
"\"\"\"Private function: count the value of accidentals.\"\"\"",
"r",
"=",
"0",
"for",
"x",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"x",
"==",
"'b'",
":",
"r",
"-=",
"1",
"elif",
"x",
"==",
"'#'",
":",
"r",
"+=",
"1",
"return",
"r",
"x",
"=",
"get_val",
"(",
"note1",
")",
"y",
"=",
"get_val",
"(",
"note2",
")",
"if",
"x",
"==",
"y",
":",
"if",
"not",
"shorthand",
":",
"return",
"'major unison'",
"return",
"'1'",
"elif",
"x",
"<",
"y",
":",
"if",
"not",
"shorthand",
":",
"return",
"'augmented unison'",
"return",
"'#1'",
"elif",
"x",
"-",
"y",
"==",
"1",
":",
"if",
"not",
"shorthand",
":",
"return",
"'minor unison'",
"return",
"'b1'",
"else",
":",
"if",
"not",
"shorthand",
":",
"return",
"'diminished unison'",
"return",
"'bb1'",
"# Other intervals",
"n1",
"=",
"notes",
".",
"fifths",
".",
"index",
"(",
"note1",
"[",
"0",
"]",
")",
"n2",
"=",
"notes",
".",
"fifths",
".",
"index",
"(",
"note2",
"[",
"0",
"]",
")",
"number_of_fifth_steps",
"=",
"n2",
"-",
"n1",
"if",
"n2",
"<",
"n1",
":",
"number_of_fifth_steps",
"=",
"len",
"(",
"notes",
".",
"fifths",
")",
"-",
"n1",
"+",
"n2",
"# [name, shorthand_name, half notes for major version of this interval]",
"fifth_steps",
"=",
"[",
"[",
"'unison'",
",",
"'1'",
",",
"0",
"]",
",",
"[",
"'fifth'",
",",
"'5'",
",",
"7",
"]",
",",
"[",
"'second'",
",",
"'2'",
",",
"2",
"]",
",",
"[",
"'sixth'",
",",
"'6'",
",",
"9",
"]",
",",
"[",
"'third'",
",",
"'3'",
",",
"4",
"]",
",",
"[",
"'seventh'",
",",
"'7'",
",",
"11",
"]",
",",
"[",
"'fourth'",
",",
"'4'",
",",
"5",
"]",
",",
"]",
"# Count half steps between note1 and note2",
"half_notes",
"=",
"measure",
"(",
"note1",
",",
"note2",
")",
"# Get the proper list from the number of fifth steps",
"current",
"=",
"fifth_steps",
"[",
"number_of_fifth_steps",
"]",
"# maj = number of major steps for this interval",
"maj",
"=",
"current",
"[",
"2",
"]",
"# if maj is equal to the half steps between note1 and note2 the interval is",
"# major or perfect",
"if",
"maj",
"==",
"half_notes",
":",
"# Corner cases for perfect fifths and fourths",
"if",
"current",
"[",
"0",
"]",
"==",
"'fifth'",
":",
"if",
"not",
"shorthand",
":",
"return",
"'perfect fifth'",
"elif",
"current",
"[",
"0",
"]",
"==",
"'fourth'",
":",
"if",
"not",
"shorthand",
":",
"return",
"'perfect fourth'",
"if",
"not",
"shorthand",
":",
"return",
"'major '",
"+",
"current",
"[",
"0",
"]",
"return",
"current",
"[",
"1",
"]",
"elif",
"maj",
"+",
"1",
"<=",
"half_notes",
":",
"# if maj + 1 is equal to half_notes, the interval is augmented.",
"if",
"not",
"shorthand",
":",
"return",
"'augmented '",
"+",
"current",
"[",
"0",
"]",
"return",
"'#'",
"*",
"(",
"half_notes",
"-",
"maj",
")",
"+",
"current",
"[",
"1",
"]",
"elif",
"maj",
"-",
"1",
"==",
"half_notes",
":",
"# etc.",
"if",
"not",
"shorthand",
":",
"return",
"'minor '",
"+",
"current",
"[",
"0",
"]",
"return",
"'b'",
"+",
"current",
"[",
"1",
"]",
"elif",
"maj",
"-",
"2",
">=",
"half_notes",
":",
"if",
"not",
"shorthand",
":",
"return",
"'diminished '",
"+",
"current",
"[",
"0",
"]",
"return",
"'b'",
"*",
"(",
"maj",
"-",
"half_notes",
")",
"+",
"current",
"[",
"1",
"]"
] | Name the interval between note1 and note2.
Examples:
>>> determine('C', 'E')
'major third'
>>> determine('C', 'Eb')
'minor third'
>>> determine('C', 'E#')
'augmented third'
>>> determine('C', 'Ebb')
'diminished third'
This works for all intervals. Note that there are corner cases for major
fifths and fourths:
>>> determine('C', 'G')
'perfect fifth'
>>> determine('C', 'F')
'perfect fourth' | [
"Name",
"the",
"interval",
"between",
"note1",
"and",
"note2",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L304-L408 |
3,357 | bspaans/python-mingus | mingus/core/intervals.py | from_shorthand | def from_shorthand(note, interval, up=True):
"""Return the note on interval up or down.
Examples:
>>> from_shorthand('A', 'b3')
'C'
>>> from_shorthand('D', '2')
'E'
>>> from_shorthand('E', '2', False)
'D'
"""
# warning should be a valid note.
if not notes.is_valid_note(note):
return False
# [shorthand, interval function up, interval function down]
shorthand_lookup = [
['1', major_unison, major_unison],
['2', major_second, minor_seventh],
['3', major_third, minor_sixth],
['4', major_fourth, major_fifth],
['5', major_fifth, major_fourth],
['6', major_sixth, minor_third],
['7', major_seventh, minor_second],
]
# Looking up last character in interval in shorthand_lookup and calling that
# function.
val = False
for shorthand in shorthand_lookup:
if shorthand[0] == interval[-1]:
if up:
val = shorthand[1](note)
else:
val = shorthand[2](note)
# warning Last character in interval should be 1-7
if val == False:
return False
# Collect accidentals
for x in interval:
if x == '#':
if up:
val = notes.augment(val)
else:
val = notes.diminish(val)
elif x == 'b':
if up:
val = notes.diminish(val)
else:
val = notes.augment(val)
else:
return val | python | def from_shorthand(note, interval, up=True):
"""Return the note on interval up or down.
Examples:
>>> from_shorthand('A', 'b3')
'C'
>>> from_shorthand('D', '2')
'E'
>>> from_shorthand('E', '2', False)
'D'
"""
# warning should be a valid note.
if not notes.is_valid_note(note):
return False
# [shorthand, interval function up, interval function down]
shorthand_lookup = [
['1', major_unison, major_unison],
['2', major_second, minor_seventh],
['3', major_third, minor_sixth],
['4', major_fourth, major_fifth],
['5', major_fifth, major_fourth],
['6', major_sixth, minor_third],
['7', major_seventh, minor_second],
]
# Looking up last character in interval in shorthand_lookup and calling that
# function.
val = False
for shorthand in shorthand_lookup:
if shorthand[0] == interval[-1]:
if up:
val = shorthand[1](note)
else:
val = shorthand[2](note)
# warning Last character in interval should be 1-7
if val == False:
return False
# Collect accidentals
for x in interval:
if x == '#':
if up:
val = notes.augment(val)
else:
val = notes.diminish(val)
elif x == 'b':
if up:
val = notes.diminish(val)
else:
val = notes.augment(val)
else:
return val | [
"def",
"from_shorthand",
"(",
"note",
",",
"interval",
",",
"up",
"=",
"True",
")",
":",
"# warning should be a valid note.",
"if",
"not",
"notes",
".",
"is_valid_note",
"(",
"note",
")",
":",
"return",
"False",
"# [shorthand, interval function up, interval function down]",
"shorthand_lookup",
"=",
"[",
"[",
"'1'",
",",
"major_unison",
",",
"major_unison",
"]",
",",
"[",
"'2'",
",",
"major_second",
",",
"minor_seventh",
"]",
",",
"[",
"'3'",
",",
"major_third",
",",
"minor_sixth",
"]",
",",
"[",
"'4'",
",",
"major_fourth",
",",
"major_fifth",
"]",
",",
"[",
"'5'",
",",
"major_fifth",
",",
"major_fourth",
"]",
",",
"[",
"'6'",
",",
"major_sixth",
",",
"minor_third",
"]",
",",
"[",
"'7'",
",",
"major_seventh",
",",
"minor_second",
"]",
",",
"]",
"# Looking up last character in interval in shorthand_lookup and calling that",
"# function.",
"val",
"=",
"False",
"for",
"shorthand",
"in",
"shorthand_lookup",
":",
"if",
"shorthand",
"[",
"0",
"]",
"==",
"interval",
"[",
"-",
"1",
"]",
":",
"if",
"up",
":",
"val",
"=",
"shorthand",
"[",
"1",
"]",
"(",
"note",
")",
"else",
":",
"val",
"=",
"shorthand",
"[",
"2",
"]",
"(",
"note",
")",
"# warning Last character in interval should be 1-7",
"if",
"val",
"==",
"False",
":",
"return",
"False",
"# Collect accidentals",
"for",
"x",
"in",
"interval",
":",
"if",
"x",
"==",
"'#'",
":",
"if",
"up",
":",
"val",
"=",
"notes",
".",
"augment",
"(",
"val",
")",
"else",
":",
"val",
"=",
"notes",
".",
"diminish",
"(",
"val",
")",
"elif",
"x",
"==",
"'b'",
":",
"if",
"up",
":",
"val",
"=",
"notes",
".",
"diminish",
"(",
"val",
")",
"else",
":",
"val",
"=",
"notes",
".",
"augment",
"(",
"val",
")",
"else",
":",
"return",
"val"
] | Return the note on interval up or down.
Examples:
>>> from_shorthand('A', 'b3')
'C'
>>> from_shorthand('D', '2')
'E'
>>> from_shorthand('E', '2', False)
'D' | [
"Return",
"the",
"note",
"on",
"interval",
"up",
"or",
"down",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L410-L463 |
3,358 | bspaans/python-mingus | mingus/core/intervals.py | is_consonant | def is_consonant(note1, note2, include_fourths=True):
"""Return True if the interval is consonant.
A consonance is a harmony, chord, or interval considered stable, as
opposed to a dissonance.
This function tests whether the given interval is consonant. This
basically means that it checks whether the interval is (or sounds like)
a unison, third, sixth, perfect fourth or perfect fifth.
In classical music the fourth is considered dissonant when used
contrapuntal, which is why you can choose to exclude it.
"""
return (is_perfect_consonant(note1, note2, include_fourths) or
is_imperfect_consonant(note1, note2)) | python | def is_consonant(note1, note2, include_fourths=True):
"""Return True if the interval is consonant.
A consonance is a harmony, chord, or interval considered stable, as
opposed to a dissonance.
This function tests whether the given interval is consonant. This
basically means that it checks whether the interval is (or sounds like)
a unison, third, sixth, perfect fourth or perfect fifth.
In classical music the fourth is considered dissonant when used
contrapuntal, which is why you can choose to exclude it.
"""
return (is_perfect_consonant(note1, note2, include_fourths) or
is_imperfect_consonant(note1, note2)) | [
"def",
"is_consonant",
"(",
"note1",
",",
"note2",
",",
"include_fourths",
"=",
"True",
")",
":",
"return",
"(",
"is_perfect_consonant",
"(",
"note1",
",",
"note2",
",",
"include_fourths",
")",
"or",
"is_imperfect_consonant",
"(",
"note1",
",",
"note2",
")",
")"
] | Return True if the interval is consonant.
A consonance is a harmony, chord, or interval considered stable, as
opposed to a dissonance.
This function tests whether the given interval is consonant. This
basically means that it checks whether the interval is (or sounds like)
a unison, third, sixth, perfect fourth or perfect fifth.
In classical music the fourth is considered dissonant when used
contrapuntal, which is why you can choose to exclude it. | [
"Return",
"True",
"if",
"the",
"interval",
"is",
"consonant",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L465-L479 |
3,359 | bspaans/python-mingus | mingus/core/intervals.py | is_perfect_consonant | def is_perfect_consonant(note1, note2, include_fourths=True):
"""Return True if the interval is a perfect consonant one.
Perfect consonances are either unisons, perfect fourths or fifths, or
octaves (which is the same as a unison in this model).
Perfect fourths are usually included as well, but are considered
dissonant when used contrapuntal, which is why you can exclude them.
"""
dhalf = measure(note1, note2)
return dhalf in [0, 7] or include_fourths and dhalf == 5 | python | def is_perfect_consonant(note1, note2, include_fourths=True):
"""Return True if the interval is a perfect consonant one.
Perfect consonances are either unisons, perfect fourths or fifths, or
octaves (which is the same as a unison in this model).
Perfect fourths are usually included as well, but are considered
dissonant when used contrapuntal, which is why you can exclude them.
"""
dhalf = measure(note1, note2)
return dhalf in [0, 7] or include_fourths and dhalf == 5 | [
"def",
"is_perfect_consonant",
"(",
"note1",
",",
"note2",
",",
"include_fourths",
"=",
"True",
")",
":",
"dhalf",
"=",
"measure",
"(",
"note1",
",",
"note2",
")",
"return",
"dhalf",
"in",
"[",
"0",
",",
"7",
"]",
"or",
"include_fourths",
"and",
"dhalf",
"==",
"5"
] | Return True if the interval is a perfect consonant one.
Perfect consonances are either unisons, perfect fourths or fifths, or
octaves (which is the same as a unison in this model).
Perfect fourths are usually included as well, but are considered
dissonant when used contrapuntal, which is why you can exclude them. | [
"Return",
"True",
"if",
"the",
"interval",
"is",
"a",
"perfect",
"consonant",
"one",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/intervals.py#L481-L491 |
3,360 | bspaans/python-mingus | mingus/containers/composition.py | Composition.add_track | def add_track(self, track):
"""Add a track to the composition.
Raise an UnexpectedObjectError if the argument is not a
mingus.containers.Track object.
"""
if not hasattr(track, 'bars'):
raise UnexpectedObjectError("Unexpected object '%s', "
"expecting a mingus.containers.Track object" % track)
self.tracks.append(track)
self.selected_tracks = [len(self.tracks) - 1] | python | def add_track(self, track):
"""Add a track to the composition.
Raise an UnexpectedObjectError if the argument is not a
mingus.containers.Track object.
"""
if not hasattr(track, 'bars'):
raise UnexpectedObjectError("Unexpected object '%s', "
"expecting a mingus.containers.Track object" % track)
self.tracks.append(track)
self.selected_tracks = [len(self.tracks) - 1] | [
"def",
"add_track",
"(",
"self",
",",
"track",
")",
":",
"if",
"not",
"hasattr",
"(",
"track",
",",
"'bars'",
")",
":",
"raise",
"UnexpectedObjectError",
"(",
"\"Unexpected object '%s', \"",
"\"expecting a mingus.containers.Track object\"",
"%",
"track",
")",
"self",
".",
"tracks",
".",
"append",
"(",
"track",
")",
"self",
".",
"selected_tracks",
"=",
"[",
"len",
"(",
"self",
".",
"tracks",
")",
"-",
"1",
"]"
] | Add a track to the composition.
Raise an UnexpectedObjectError if the argument is not a
mingus.containers.Track object. | [
"Add",
"a",
"track",
"to",
"the",
"composition",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/composition.py#L55-L65 |
3,361 | bspaans/python-mingus | mingus/containers/composition.py | Composition.add_note | def add_note(self, note):
"""Add a note to the selected tracks.
Everything container.Track supports in __add__ is accepted.
"""
for n in self.selected_tracks:
self.tracks[n] + note | python | def add_note(self, note):
"""Add a note to the selected tracks.
Everything container.Track supports in __add__ is accepted.
"""
for n in self.selected_tracks:
self.tracks[n] + note | [
"def",
"add_note",
"(",
"self",
",",
"note",
")",
":",
"for",
"n",
"in",
"self",
".",
"selected_tracks",
":",
"self",
".",
"tracks",
"[",
"n",
"]",
"+",
"note"
] | Add a note to the selected tracks.
Everything container.Track supports in __add__ is accepted. | [
"Add",
"a",
"note",
"to",
"the",
"selected",
"tracks",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/composition.py#L67-L73 |
3,362 | bspaans/python-mingus | mingus/midi/pyfluidsynth.py | cfunc | def cfunc(name, result, *args):
"""Build and apply a ctypes prototype complete with parameter flags."""
atypes = []
aflags = []
for arg in args:
atypes.append(arg[1])
aflags.append((arg[2], arg[0]) + arg[3:])
return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags)) | python | def cfunc(name, result, *args):
"""Build and apply a ctypes prototype complete with parameter flags."""
atypes = []
aflags = []
for arg in args:
atypes.append(arg[1])
aflags.append((arg[2], arg[0]) + arg[3:])
return CFUNCTYPE(result, *atypes)((name, _fl), tuple(aflags)) | [
"def",
"cfunc",
"(",
"name",
",",
"result",
",",
"*",
"args",
")",
":",
"atypes",
"=",
"[",
"]",
"aflags",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"atypes",
".",
"append",
"(",
"arg",
"[",
"1",
"]",
")",
"aflags",
".",
"append",
"(",
"(",
"arg",
"[",
"2",
"]",
",",
"arg",
"[",
"0",
"]",
")",
"+",
"arg",
"[",
"3",
":",
"]",
")",
"return",
"CFUNCTYPE",
"(",
"result",
",",
"*",
"atypes",
")",
"(",
"(",
"name",
",",
"_fl",
")",
",",
"tuple",
"(",
"aflags",
")",
")"
] | Build and apply a ctypes prototype complete with parameter flags. | [
"Build",
"and",
"apply",
"a",
"ctypes",
"prototype",
"complete",
"with",
"parameter",
"flags",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L41-L48 |
3,363 | bspaans/python-mingus | mingus/midi/pyfluidsynth.py | fluid_synth_write_s16_stereo | def fluid_synth_write_s16_stereo(synth, len):
"""Return generated samples in stereo 16-bit format.
Return value is a Numpy array of samples.
"""
import numpy
buf = create_string_buffer(len * 4)
fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2)
return numpy.fromstring(buf[:], dtype=numpy.int16) | python | def fluid_synth_write_s16_stereo(synth, len):
"""Return generated samples in stereo 16-bit format.
Return value is a Numpy array of samples.
"""
import numpy
buf = create_string_buffer(len * 4)
fluid_synth_write_s16(synth, len, buf, 0, 2, buf, 1, 2)
return numpy.fromstring(buf[:], dtype=numpy.int16) | [
"def",
"fluid_synth_write_s16_stereo",
"(",
"synth",
",",
"len",
")",
":",
"import",
"numpy",
"buf",
"=",
"create_string_buffer",
"(",
"len",
"*",
"4",
")",
"fluid_synth_write_s16",
"(",
"synth",
",",
"len",
",",
"buf",
",",
"0",
",",
"2",
",",
"buf",
",",
"1",
",",
"2",
")",
"return",
"numpy",
".",
"fromstring",
"(",
"buf",
"[",
":",
"]",
",",
"dtype",
"=",
"numpy",
".",
"int16",
")"
] | Return generated samples in stereo 16-bit format.
Return value is a Numpy array of samples. | [
"Return",
"generated",
"samples",
"in",
"stereo",
"16",
"-",
"bit",
"format",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L132-L140 |
3,364 | bspaans/python-mingus | mingus/midi/pyfluidsynth.py | Synth.start | def start(self, driver=None):
"""Start audio output driver in separate background thread.
Call this function any time after creating the Synth object.
If you don't call this function, use get_samples() to generate
samples.
Optional keyword argument:
driver: which audio driver to use for output
Possible choices:
'alsa', 'oss', 'jack', 'portaudio'
'sndmgr', 'coreaudio', 'Direct Sound',
'dsound', 'pulseaudio'
Not all drivers will be available for every platform, it depends on
which drivers were compiled into FluidSynth for your platform.
"""
if driver is not None:
assert driver in [
'alsa',
'oss',
'jack',
'portaudio',
'sndmgr',
'coreaudio',
'Direct Sound',
'dsound',
'pulseaudio'
]
fluid_settings_setstr(self.settings, 'audio.driver', driver)
self.audio_driver = new_fluid_audio_driver(self.settings, self.synth) | python | def start(self, driver=None):
"""Start audio output driver in separate background thread.
Call this function any time after creating the Synth object.
If you don't call this function, use get_samples() to generate
samples.
Optional keyword argument:
driver: which audio driver to use for output
Possible choices:
'alsa', 'oss', 'jack', 'portaudio'
'sndmgr', 'coreaudio', 'Direct Sound',
'dsound', 'pulseaudio'
Not all drivers will be available for every platform, it depends on
which drivers were compiled into FluidSynth for your platform.
"""
if driver is not None:
assert driver in [
'alsa',
'oss',
'jack',
'portaudio',
'sndmgr',
'coreaudio',
'Direct Sound',
'dsound',
'pulseaudio'
]
fluid_settings_setstr(self.settings, 'audio.driver', driver)
self.audio_driver = new_fluid_audio_driver(self.settings, self.synth) | [
"def",
"start",
"(",
"self",
",",
"driver",
"=",
"None",
")",
":",
"if",
"driver",
"is",
"not",
"None",
":",
"assert",
"driver",
"in",
"[",
"'alsa'",
",",
"'oss'",
",",
"'jack'",
",",
"'portaudio'",
",",
"'sndmgr'",
",",
"'coreaudio'",
",",
"'Direct Sound'",
",",
"'dsound'",
",",
"'pulseaudio'",
"]",
"fluid_settings_setstr",
"(",
"self",
".",
"settings",
",",
"'audio.driver'",
",",
"driver",
")",
"self",
".",
"audio_driver",
"=",
"new_fluid_audio_driver",
"(",
"self",
".",
"settings",
",",
"self",
".",
"synth",
")"
] | Start audio output driver in separate background thread.
Call this function any time after creating the Synth object.
If you don't call this function, use get_samples() to generate
samples.
Optional keyword argument:
driver: which audio driver to use for output
Possible choices:
'alsa', 'oss', 'jack', 'portaudio'
'sndmgr', 'coreaudio', 'Direct Sound',
'dsound', 'pulseaudio'
Not all drivers will be available for every platform, it depends on
which drivers were compiled into FluidSynth for your platform. | [
"Start",
"audio",
"output",
"driver",
"in",
"separate",
"background",
"thread",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L164-L194 |
3,365 | bspaans/python-mingus | mingus/midi/pyfluidsynth.py | Synth.program_select | def program_select(self, chan, sfid, bank, preset):
"""Select a program."""
return fluid_synth_program_select(self.synth, chan, sfid, bank, preset) | python | def program_select(self, chan, sfid, bank, preset):
"""Select a program."""
return fluid_synth_program_select(self.synth, chan, sfid, bank, preset) | [
"def",
"program_select",
"(",
"self",
",",
"chan",
",",
"sfid",
",",
"bank",
",",
"preset",
")",
":",
"return",
"fluid_synth_program_select",
"(",
"self",
".",
"synth",
",",
"chan",
",",
"sfid",
",",
"bank",
",",
"preset",
")"
] | Select a program. | [
"Select",
"a",
"program",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L210-L212 |
3,366 | bspaans/python-mingus | mingus/midi/pyfluidsynth.py | Synth.noteon | def noteon(self, chan, key, vel):
"""Play a note."""
if key < 0 or key > 128:
return False
if chan < 0:
return False
if vel < 0 or vel > 128:
return False
return fluid_synth_noteon(self.synth, chan, key, vel) | python | def noteon(self, chan, key, vel):
"""Play a note."""
if key < 0 or key > 128:
return False
if chan < 0:
return False
if vel < 0 or vel > 128:
return False
return fluid_synth_noteon(self.synth, chan, key, vel) | [
"def",
"noteon",
"(",
"self",
",",
"chan",
",",
"key",
",",
"vel",
")",
":",
"if",
"key",
"<",
"0",
"or",
"key",
">",
"128",
":",
"return",
"False",
"if",
"chan",
"<",
"0",
":",
"return",
"False",
"if",
"vel",
"<",
"0",
"or",
"vel",
">",
"128",
":",
"return",
"False",
"return",
"fluid_synth_noteon",
"(",
"self",
".",
"synth",
",",
"chan",
",",
"key",
",",
"vel",
")"
] | Play a note. | [
"Play",
"a",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L214-L222 |
3,367 | bspaans/python-mingus | mingus/midi/pyfluidsynth.py | Synth.noteoff | def noteoff(self, chan, key):
"""Stop a note."""
if key < 0 or key > 128:
return False
if chan < 0:
return False
return fluid_synth_noteoff(self.synth, chan, key) | python | def noteoff(self, chan, key):
"""Stop a note."""
if key < 0 or key > 128:
return False
if chan < 0:
return False
return fluid_synth_noteoff(self.synth, chan, key) | [
"def",
"noteoff",
"(",
"self",
",",
"chan",
",",
"key",
")",
":",
"if",
"key",
"<",
"0",
"or",
"key",
">",
"128",
":",
"return",
"False",
"if",
"chan",
"<",
"0",
":",
"return",
"False",
"return",
"fluid_synth_noteoff",
"(",
"self",
".",
"synth",
",",
"chan",
",",
"key",
")"
] | Stop a note. | [
"Stop",
"a",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L224-L230 |
3,368 | bspaans/python-mingus | mingus/midi/pyfluidsynth.py | Synth.cc | def cc(self, chan, ctrl, val):
"""Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft to loud)
64: sustain
91: reverb
93: chorus
"""
return fluid_synth_cc(self.synth, chan, ctrl, val) | python | def cc(self, chan, ctrl, val):
"""Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft to loud)
64: sustain
91: reverb
93: chorus
"""
return fluid_synth_cc(self.synth, chan, ctrl, val) | [
"def",
"cc",
"(",
"self",
",",
"chan",
",",
"ctrl",
",",
"val",
")",
":",
"return",
"fluid_synth_cc",
"(",
"self",
".",
"synth",
",",
"chan",
",",
"ctrl",
",",
"val",
")"
] | Send control change value.
The controls that are recognized are dependent on the
SoundFont. Values are always 0 to 127. Typical controls
include:
1: vibrato
7: volume
10: pan (left to right)
11: expression (soft to loud)
64: sustain
91: reverb
93: chorus | [
"Send",
"control",
"change",
"value",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/pyfluidsynth.py#L242-L256 |
3,369 | bspaans/python-mingus | mingus/core/notes.py | is_valid_note | def is_valid_note(note):
"""Return True if note is in a recognised format. False if not."""
if not _note_dict.has_key(note[0]):
return False
for post in note[1:]:
if post != 'b' and post != '#':
return False
return True | python | def is_valid_note(note):
"""Return True if note is in a recognised format. False if not."""
if not _note_dict.has_key(note[0]):
return False
for post in note[1:]:
if post != 'b' and post != '#':
return False
return True | [
"def",
"is_valid_note",
"(",
"note",
")",
":",
"if",
"not",
"_note_dict",
".",
"has_key",
"(",
"note",
"[",
"0",
"]",
")",
":",
"return",
"False",
"for",
"post",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"post",
"!=",
"'b'",
"and",
"post",
"!=",
"'#'",
":",
"return",
"False",
"return",
"True"
] | Return True if note is in a recognised format. False if not. | [
"Return",
"True",
"if",
"note",
"is",
"in",
"a",
"recognised",
"format",
".",
"False",
"if",
"not",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L73-L80 |
3,370 | bspaans/python-mingus | mingus/core/notes.py | reduce_accidentals | def reduce_accidentals(note):
"""Reduce any extra accidentals to proper notes.
Example:
>>> reduce_accidentals('C####')
'E'
"""
val = note_to_int(note[0])
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '#':
val += 1
else:
raise NoteFormatError("Unknown note format '%s'" % note)
if val >= note_to_int(note[0]):
return int_to_note(val%12)
else:
return int_to_note(val%12, 'b') | python | def reduce_accidentals(note):
"""Reduce any extra accidentals to proper notes.
Example:
>>> reduce_accidentals('C####')
'E'
"""
val = note_to_int(note[0])
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '#':
val += 1
else:
raise NoteFormatError("Unknown note format '%s'" % note)
if val >= note_to_int(note[0]):
return int_to_note(val%12)
else:
return int_to_note(val%12, 'b') | [
"def",
"reduce_accidentals",
"(",
"note",
")",
":",
"val",
"=",
"note_to_int",
"(",
"note",
"[",
"0",
"]",
")",
"for",
"token",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"token",
"==",
"'b'",
":",
"val",
"-=",
"1",
"elif",
"token",
"==",
"'#'",
":",
"val",
"+=",
"1",
"else",
":",
"raise",
"NoteFormatError",
"(",
"\"Unknown note format '%s'\"",
"%",
"note",
")",
"if",
"val",
">=",
"note_to_int",
"(",
"note",
"[",
"0",
"]",
")",
":",
"return",
"int_to_note",
"(",
"val",
"%",
"12",
")",
"else",
":",
"return",
"int_to_note",
"(",
"val",
"%",
"12",
",",
"'b'",
")"
] | Reduce any extra accidentals to proper notes.
Example:
>>> reduce_accidentals('C####')
'E' | [
"Reduce",
"any",
"extra",
"accidentals",
"to",
"proper",
"notes",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L101-L119 |
3,371 | bspaans/python-mingus | mingus/core/notes.py | remove_redundant_accidentals | def remove_redundant_accidentals(note):
"""Remove redundant sharps and flats from the given note.
Examples:
>>> remove_redundant_accidentals('C##b')
'C#'
>>> remove_redundant_accidentals('Eb##b')
'E'
"""
val = 0
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '#':
val += 1
result = note[0]
while val > 0:
result = augment(result)
val -= 1
while val < 0:
result = diminish(result)
val += 1
return result | python | def remove_redundant_accidentals(note):
"""Remove redundant sharps and flats from the given note.
Examples:
>>> remove_redundant_accidentals('C##b')
'C#'
>>> remove_redundant_accidentals('Eb##b')
'E'
"""
val = 0
for token in note[1:]:
if token == 'b':
val -= 1
elif token == '#':
val += 1
result = note[0]
while val > 0:
result = augment(result)
val -= 1
while val < 0:
result = diminish(result)
val += 1
return result | [
"def",
"remove_redundant_accidentals",
"(",
"note",
")",
":",
"val",
"=",
"0",
"for",
"token",
"in",
"note",
"[",
"1",
":",
"]",
":",
"if",
"token",
"==",
"'b'",
":",
"val",
"-=",
"1",
"elif",
"token",
"==",
"'#'",
":",
"val",
"+=",
"1",
"result",
"=",
"note",
"[",
"0",
"]",
"while",
"val",
">",
"0",
":",
"result",
"=",
"augment",
"(",
"result",
")",
"val",
"-=",
"1",
"while",
"val",
"<",
"0",
":",
"result",
"=",
"diminish",
"(",
"result",
")",
"val",
"+=",
"1",
"return",
"result"
] | Remove redundant sharps and flats from the given note.
Examples:
>>> remove_redundant_accidentals('C##b')
'C#'
>>> remove_redundant_accidentals('Eb##b')
'E' | [
"Remove",
"redundant",
"sharps",
"and",
"flats",
"from",
"the",
"given",
"note",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/notes.py#L121-L143 |
3,372 | bspaans/python-mingus | mingus/extra/musicxml.py | _gcd | def _gcd(a=None, b=None, terms=None):
"""Return greatest common divisor using Euclid's Algorithm."""
if terms:
return reduce(lambda a, b: _gcd(a, b), terms)
else:
while b:
(a, b) = (b, a % b)
return a | python | def _gcd(a=None, b=None, terms=None):
"""Return greatest common divisor using Euclid's Algorithm."""
if terms:
return reduce(lambda a, b: _gcd(a, b), terms)
else:
while b:
(a, b) = (b, a % b)
return a | [
"def",
"_gcd",
"(",
"a",
"=",
"None",
",",
"b",
"=",
"None",
",",
"terms",
"=",
"None",
")",
":",
"if",
"terms",
":",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"_gcd",
"(",
"a",
",",
"b",
")",
",",
"terms",
")",
"else",
":",
"while",
"b",
":",
"(",
"a",
",",
"b",
")",
"=",
"(",
"b",
",",
"a",
"%",
"b",
")",
"return",
"a"
] | Return greatest common divisor using Euclid's Algorithm. | [
"Return",
"greatest",
"common",
"divisor",
"using",
"Euclid",
"s",
"Algorithm",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/musicxml.py#L43-L50 |
3,373 | bspaans/python-mingus | mingus/core/keys.py | get_key_signature | def get_key_signature(key='C'):
"""Return the key signature.
0 for C or a, negative numbers for flat key signatures, positive numbers
for sharp key signatures.
"""
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
for couple in keys:
if key in couple:
accidentals = keys.index(couple) - 7
return accidentals | python | def get_key_signature(key='C'):
"""Return the key signature.
0 for C or a, negative numbers for flat key signatures, positive numbers
for sharp key signatures.
"""
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
for couple in keys:
if key in couple:
accidentals = keys.index(couple) - 7
return accidentals | [
"def",
"get_key_signature",
"(",
"key",
"=",
"'C'",
")",
":",
"if",
"not",
"is_valid_key",
"(",
"key",
")",
":",
"raise",
"NoteFormatError",
"(",
"\"unrecognized format for key '%s'\"",
"%",
"key",
")",
"for",
"couple",
"in",
"keys",
":",
"if",
"key",
"in",
"couple",
":",
"accidentals",
"=",
"keys",
".",
"index",
"(",
"couple",
")",
"-",
"7",
"return",
"accidentals"
] | Return the key signature.
0 for C or a, negative numbers for flat key signatures, positive numbers
for sharp key signatures. | [
"Return",
"the",
"key",
"signature",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L73-L85 |
3,374 | bspaans/python-mingus | mingus/core/keys.py | get_key_signature_accidentals | def get_key_signature_accidentals(key='C'):
"""Return the list of accidentals present into the key signature."""
accidentals = get_key_signature(key)
res = []
if accidentals < 0:
for i in range(-accidentals):
res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b'))
elif accidentals > 0:
for i in range(accidentals):
res.append('{0}{1}'.format(notes.fifths[i], '#'))
return res | python | def get_key_signature_accidentals(key='C'):
"""Return the list of accidentals present into the key signature."""
accidentals = get_key_signature(key)
res = []
if accidentals < 0:
for i in range(-accidentals):
res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b'))
elif accidentals > 0:
for i in range(accidentals):
res.append('{0}{1}'.format(notes.fifths[i], '#'))
return res | [
"def",
"get_key_signature_accidentals",
"(",
"key",
"=",
"'C'",
")",
":",
"accidentals",
"=",
"get_key_signature",
"(",
"key",
")",
"res",
"=",
"[",
"]",
"if",
"accidentals",
"<",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"-",
"accidentals",
")",
":",
"res",
".",
"append",
"(",
"'{0}{1}'",
".",
"format",
"(",
"list",
"(",
"reversed",
"(",
"notes",
".",
"fifths",
")",
")",
"[",
"i",
"]",
",",
"'b'",
")",
")",
"elif",
"accidentals",
">",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"accidentals",
")",
":",
"res",
".",
"append",
"(",
"'{0}{1}'",
".",
"format",
"(",
"notes",
".",
"fifths",
"[",
"i",
"]",
",",
"'#'",
")",
")",
"return",
"res"
] | Return the list of accidentals present into the key signature. | [
"Return",
"the",
"list",
"of",
"accidentals",
"present",
"into",
"the",
"key",
"signature",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L87-L98 |
3,375 | bspaans/python-mingus | mingus/core/keys.py | get_notes | def get_notes(key='C'):
"""Return an ordered list of the notes in this natural key.
Examples:
>>> get_notes('F')
['F', 'G', 'A', 'Bb', 'C', 'D', 'E']
>>> get_notes('c')
['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb']
"""
if _key_cache.has_key(key):
return _key_cache[key]
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
result = []
# Calculate notes
altered_notes = map(operator.itemgetter(0),
get_key_signature_accidentals(key))
if get_key_signature(key) < 0:
symbol = 'b'
elif get_key_signature(key) > 0:
symbol = '#'
raw_tonic_index = base_scale.index(key.upper()[0])
for note in islice(cycle(base_scale), raw_tonic_index, raw_tonic_index+7):
if note in altered_notes:
result.append('%s%s' % (note, symbol))
else:
result.append(note)
# Save result to cache
_key_cache[key] = result
return result | python | def get_notes(key='C'):
"""Return an ordered list of the notes in this natural key.
Examples:
>>> get_notes('F')
['F', 'G', 'A', 'Bb', 'C', 'D', 'E']
>>> get_notes('c')
['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb']
"""
if _key_cache.has_key(key):
return _key_cache[key]
if not is_valid_key(key):
raise NoteFormatError("unrecognized format for key '%s'" % key)
result = []
# Calculate notes
altered_notes = map(operator.itemgetter(0),
get_key_signature_accidentals(key))
if get_key_signature(key) < 0:
symbol = 'b'
elif get_key_signature(key) > 0:
symbol = '#'
raw_tonic_index = base_scale.index(key.upper()[0])
for note in islice(cycle(base_scale), raw_tonic_index, raw_tonic_index+7):
if note in altered_notes:
result.append('%s%s' % (note, symbol))
else:
result.append(note)
# Save result to cache
_key_cache[key] = result
return result | [
"def",
"get_notes",
"(",
"key",
"=",
"'C'",
")",
":",
"if",
"_key_cache",
".",
"has_key",
"(",
"key",
")",
":",
"return",
"_key_cache",
"[",
"key",
"]",
"if",
"not",
"is_valid_key",
"(",
"key",
")",
":",
"raise",
"NoteFormatError",
"(",
"\"unrecognized format for key '%s'\"",
"%",
"key",
")",
"result",
"=",
"[",
"]",
"# Calculate notes",
"altered_notes",
"=",
"map",
"(",
"operator",
".",
"itemgetter",
"(",
"0",
")",
",",
"get_key_signature_accidentals",
"(",
"key",
")",
")",
"if",
"get_key_signature",
"(",
"key",
")",
"<",
"0",
":",
"symbol",
"=",
"'b'",
"elif",
"get_key_signature",
"(",
"key",
")",
">",
"0",
":",
"symbol",
"=",
"'#'",
"raw_tonic_index",
"=",
"base_scale",
".",
"index",
"(",
"key",
".",
"upper",
"(",
")",
"[",
"0",
"]",
")",
"for",
"note",
"in",
"islice",
"(",
"cycle",
"(",
"base_scale",
")",
",",
"raw_tonic_index",
",",
"raw_tonic_index",
"+",
"7",
")",
":",
"if",
"note",
"in",
"altered_notes",
":",
"result",
".",
"append",
"(",
"'%s%s'",
"%",
"(",
"note",
",",
"symbol",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"note",
")",
"# Save result to cache",
"_key_cache",
"[",
"key",
"]",
"=",
"result",
"return",
"result"
] | Return an ordered list of the notes in this natural key.
Examples:
>>> get_notes('F')
['F', 'G', 'A', 'Bb', 'C', 'D', 'E']
>>> get_notes('c')
['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb'] | [
"Return",
"an",
"ordered",
"list",
"of",
"the",
"notes",
"in",
"this",
"natural",
"key",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/core/keys.py#L100-L134 |
3,376 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.attach | def attach(self, listener):
"""Attach an object that should be notified of events.
The object should have a notify(msg_type, param_dict) function.
"""
if listener not in self.listeners:
self.listeners.append(listener) | python | def attach(self, listener):
"""Attach an object that should be notified of events.
The object should have a notify(msg_type, param_dict) function.
"""
if listener not in self.listeners:
self.listeners.append(listener) | [
"def",
"attach",
"(",
"self",
",",
"listener",
")",
":",
"if",
"listener",
"not",
"in",
"self",
".",
"listeners",
":",
"self",
".",
"listeners",
".",
"append",
"(",
"listener",
")"
] | Attach an object that should be notified of events.
The object should have a notify(msg_type, param_dict) function. | [
"Attach",
"an",
"object",
"that",
"should",
"be",
"notified",
"of",
"events",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L90-L96 |
3,377 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.detach | def detach(self, listener):
"""Detach a listening object so that it won't receive any events
anymore."""
if listener in self.listeners:
self.listeners.remove(listener) | python | def detach(self, listener):
"""Detach a listening object so that it won't receive any events
anymore."""
if listener in self.listeners:
self.listeners.remove(listener) | [
"def",
"detach",
"(",
"self",
",",
"listener",
")",
":",
"if",
"listener",
"in",
"self",
".",
"listeners",
":",
"self",
".",
"listeners",
".",
"remove",
"(",
"listener",
")"
] | Detach a listening object so that it won't receive any events
anymore. | [
"Detach",
"a",
"listening",
"object",
"so",
"that",
"it",
"won",
"t",
"receive",
"any",
"events",
"anymore",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L98-L102 |
3,378 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.notify_listeners | def notify_listeners(self, msg_type, params):
"""Send a message to all the observers."""
for c in self.listeners:
c.notify(msg_type, params) | python | def notify_listeners(self, msg_type, params):
"""Send a message to all the observers."""
for c in self.listeners:
c.notify(msg_type, params) | [
"def",
"notify_listeners",
"(",
"self",
",",
"msg_type",
",",
"params",
")",
":",
"for",
"c",
"in",
"self",
".",
"listeners",
":",
"c",
".",
"notify",
"(",
"msg_type",
",",
"params",
")"
] | Send a message to all the observers. | [
"Send",
"a",
"message",
"to",
"all",
"the",
"observers",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L104-L107 |
3,379 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.set_instrument | def set_instrument(self, channel, instr, bank=0):
"""Set the channel to the instrument _instr_."""
self.instr_event(channel, instr, bank)
self.notify_listeners(self.MSG_INSTR, {'channel': int(channel),
'instr': int(instr), 'bank': int(bank)}) | python | def set_instrument(self, channel, instr, bank=0):
"""Set the channel to the instrument _instr_."""
self.instr_event(channel, instr, bank)
self.notify_listeners(self.MSG_INSTR, {'channel': int(channel),
'instr': int(instr), 'bank': int(bank)}) | [
"def",
"set_instrument",
"(",
"self",
",",
"channel",
",",
"instr",
",",
"bank",
"=",
"0",
")",
":",
"self",
".",
"instr_event",
"(",
"channel",
",",
"instr",
",",
"bank",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_INSTR",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'instr'",
":",
"int",
"(",
"instr",
")",
",",
"'bank'",
":",
"int",
"(",
"bank",
")",
"}",
")"
] | Set the channel to the instrument _instr_. | [
"Set",
"the",
"channel",
"to",
"the",
"instrument",
"_instr_",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L109-L113 |
3,380 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.control_change | def control_change(self, channel, control, value):
"""Send a control change message.
See the MIDI specification for more information.
"""
if control < 0 or control > 128:
return False
if value < 0 or value > 128:
return False
self.cc_event(channel, control, value)
self.notify_listeners(self.MSG_CC, {'channel': int(channel),
'control': int(control), 'value': int(value)})
return True | python | def control_change(self, channel, control, value):
"""Send a control change message.
See the MIDI specification for more information.
"""
if control < 0 or control > 128:
return False
if value < 0 or value > 128:
return False
self.cc_event(channel, control, value)
self.notify_listeners(self.MSG_CC, {'channel': int(channel),
'control': int(control), 'value': int(value)})
return True | [
"def",
"control_change",
"(",
"self",
",",
"channel",
",",
"control",
",",
"value",
")",
":",
"if",
"control",
"<",
"0",
"or",
"control",
">",
"128",
":",
"return",
"False",
"if",
"value",
"<",
"0",
"or",
"value",
">",
"128",
":",
"return",
"False",
"self",
".",
"cc_event",
"(",
"channel",
",",
"control",
",",
"value",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_CC",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'control'",
":",
"int",
"(",
"control",
")",
",",
"'value'",
":",
"int",
"(",
"value",
")",
"}",
")",
"return",
"True"
] | Send a control change message.
See the MIDI specification for more information. | [
"Send",
"a",
"control",
"change",
"message",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L115-L127 |
3,381 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.stop_Note | def stop_Note(self, note, channel=1):
"""Stop a note on a channel.
If Note.channel is set, it will take presedence over the channel
argument given here.
"""
if hasattr(note, 'channel'):
channel = note.channel
self.stop_event(int(note) + 12, int(channel))
self.notify_listeners(self.MSG_STOP_INT, {'channel': int(channel),
'note': int(note) + 12})
self.notify_listeners(self.MSG_STOP_NOTE, {'channel': int(channel),
'note': note})
return True | python | def stop_Note(self, note, channel=1):
"""Stop a note on a channel.
If Note.channel is set, it will take presedence over the channel
argument given here.
"""
if hasattr(note, 'channel'):
channel = note.channel
self.stop_event(int(note) + 12, int(channel))
self.notify_listeners(self.MSG_STOP_INT, {'channel': int(channel),
'note': int(note) + 12})
self.notify_listeners(self.MSG_STOP_NOTE, {'channel': int(channel),
'note': note})
return True | [
"def",
"stop_Note",
"(",
"self",
",",
"note",
",",
"channel",
"=",
"1",
")",
":",
"if",
"hasattr",
"(",
"note",
",",
"'channel'",
")",
":",
"channel",
"=",
"note",
".",
"channel",
"self",
".",
"stop_event",
"(",
"int",
"(",
"note",
")",
"+",
"12",
",",
"int",
"(",
"channel",
")",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_STOP_INT",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'note'",
":",
"int",
"(",
"note",
")",
"+",
"12",
"}",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_STOP_NOTE",
",",
"{",
"'channel'",
":",
"int",
"(",
"channel",
")",
",",
"'note'",
":",
"note",
"}",
")",
"return",
"True"
] | Stop a note on a channel.
If Note.channel is set, it will take presedence over the channel
argument given here. | [
"Stop",
"a",
"note",
"on",
"a",
"channel",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L147-L160 |
3,382 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.stop_everything | def stop_everything(self):
"""Stop all the notes on all channels."""
for x in range(118):
for c in range(16):
self.stop_Note(x, c) | python | def stop_everything(self):
"""Stop all the notes on all channels."""
for x in range(118):
for c in range(16):
self.stop_Note(x, c) | [
"def",
"stop_everything",
"(",
"self",
")",
":",
"for",
"x",
"in",
"range",
"(",
"118",
")",
":",
"for",
"c",
"in",
"range",
"(",
"16",
")",
":",
"self",
".",
"stop_Note",
"(",
"x",
",",
"c",
")"
] | Stop all the notes on all channels. | [
"Stop",
"all",
"the",
"notes",
"on",
"all",
"channels",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L162-L166 |
3,383 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.play_NoteContainer | def play_NoteContainer(self, nc, channel=1, velocity=100):
"""Play the Notes in the NoteContainer nc."""
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel, 'velocity': velocity})
if nc is None:
return True
for note in nc:
if not self.play_Note(note, channel, velocity):
return False
return True | python | def play_NoteContainer(self, nc, channel=1, velocity=100):
"""Play the Notes in the NoteContainer nc."""
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel, 'velocity': velocity})
if nc is None:
return True
for note in nc:
if not self.play_Note(note, channel, velocity):
return False
return True | [
"def",
"play_NoteContainer",
"(",
"self",
",",
"nc",
",",
"channel",
"=",
"1",
",",
"velocity",
"=",
"100",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_NC",
",",
"{",
"'notes'",
":",
"nc",
",",
"'channel'",
":",
"channel",
",",
"'velocity'",
":",
"velocity",
"}",
")",
"if",
"nc",
"is",
"None",
":",
"return",
"True",
"for",
"note",
"in",
"nc",
":",
"if",
"not",
"self",
".",
"play_Note",
"(",
"note",
",",
"channel",
",",
"velocity",
")",
":",
"return",
"False",
"return",
"True"
] | Play the Notes in the NoteContainer nc. | [
"Play",
"the",
"Notes",
"in",
"the",
"NoteContainer",
"nc",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L168-L177 |
3,384 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.stop_NoteContainer | def stop_NoteContainer(self, nc, channel=1):
"""Stop playing the notes in NoteContainer nc."""
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel})
if nc is None:
return True
for note in nc:
if not self.stop_Note(note, channel):
return False
return True | python | def stop_NoteContainer(self, nc, channel=1):
"""Stop playing the notes in NoteContainer nc."""
self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc,
'channel': channel})
if nc is None:
return True
for note in nc:
if not self.stop_Note(note, channel):
return False
return True | [
"def",
"stop_NoteContainer",
"(",
"self",
",",
"nc",
",",
"channel",
"=",
"1",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_NC",
",",
"{",
"'notes'",
":",
"nc",
",",
"'channel'",
":",
"channel",
"}",
")",
"if",
"nc",
"is",
"None",
":",
"return",
"True",
"for",
"note",
"in",
"nc",
":",
"if",
"not",
"self",
".",
"stop_Note",
"(",
"note",
",",
"channel",
")",
":",
"return",
"False",
"return",
"True"
] | Stop playing the notes in NoteContainer nc. | [
"Stop",
"playing",
"the",
"notes",
"in",
"NoteContainer",
"nc",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L179-L188 |
3,385 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.play_Bar | def play_Bar(self, bar, channel=1, bpm=120):
"""Play a Bar object.
Return a dictionary with the bpm lemma set on success, an empty dict
on some kind of failure.
The tempo can be changed by setting the bpm attribute on a
NoteContainer.
"""
self.notify_listeners(self.MSG_PLAY_BAR, {'bar': bar, 'channel'
: channel, 'bpm': bpm})
# length of a quarter note
qn_length = 60.0 / bpm
for nc in bar:
if not self.play_NoteContainer(nc[2], channel, 100):
return {}
# Change the quarter note length if the NoteContainer has a bpm
# attribute
if hasattr(nc[2], 'bpm'):
bpm = nc[2].bpm
qn_length = 60.0 / bpm
ms = qn_length * (4.0 / nc[1])
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
self.stop_NoteContainer(nc[2], channel)
return {'bpm': bpm} | python | def play_Bar(self, bar, channel=1, bpm=120):
"""Play a Bar object.
Return a dictionary with the bpm lemma set on success, an empty dict
on some kind of failure.
The tempo can be changed by setting the bpm attribute on a
NoteContainer.
"""
self.notify_listeners(self.MSG_PLAY_BAR, {'bar': bar, 'channel'
: channel, 'bpm': bpm})
# length of a quarter note
qn_length = 60.0 / bpm
for nc in bar:
if not self.play_NoteContainer(nc[2], channel, 100):
return {}
# Change the quarter note length if the NoteContainer has a bpm
# attribute
if hasattr(nc[2], 'bpm'):
bpm = nc[2].bpm
qn_length = 60.0 / bpm
ms = qn_length * (4.0 / nc[1])
self.sleep(ms)
self.notify_listeners(self.MSG_SLEEP, {'s': ms})
self.stop_NoteContainer(nc[2], channel)
return {'bpm': bpm} | [
"def",
"play_Bar",
"(",
"self",
",",
"bar",
",",
"channel",
"=",
"1",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_BAR",
",",
"{",
"'bar'",
":",
"bar",
",",
"'channel'",
":",
"channel",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"# length of a quarter note",
"qn_length",
"=",
"60.0",
"/",
"bpm",
"for",
"nc",
"in",
"bar",
":",
"if",
"not",
"self",
".",
"play_NoteContainer",
"(",
"nc",
"[",
"2",
"]",
",",
"channel",
",",
"100",
")",
":",
"return",
"{",
"}",
"# Change the quarter note length if the NoteContainer has a bpm",
"# attribute",
"if",
"hasattr",
"(",
"nc",
"[",
"2",
"]",
",",
"'bpm'",
")",
":",
"bpm",
"=",
"nc",
"[",
"2",
"]",
".",
"bpm",
"qn_length",
"=",
"60.0",
"/",
"bpm",
"ms",
"=",
"qn_length",
"*",
"(",
"4.0",
"/",
"nc",
"[",
"1",
"]",
")",
"self",
".",
"sleep",
"(",
"ms",
")",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_SLEEP",
",",
"{",
"'s'",
":",
"ms",
"}",
")",
"self",
".",
"stop_NoteContainer",
"(",
"nc",
"[",
"2",
"]",
",",
"channel",
")",
"return",
"{",
"'bpm'",
":",
"bpm",
"}"
] | Play a Bar object.
Return a dictionary with the bpm lemma set on success, an empty dict
on some kind of failure.
The tempo can be changed by setting the bpm attribute on a
NoteContainer. | [
"Play",
"a",
"Bar",
"object",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L190-L217 |
3,386 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.play_Track | def play_Track(self, track, channel=1, bpm=120):
"""Play a Track object."""
self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel'
: channel, 'bpm': bpm})
for bar in track:
res = self.play_Bar(bar, channel, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
return {'bpm': bpm} | python | def play_Track(self, track, channel=1, bpm=120):
"""Play a Track object."""
self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel'
: channel, 'bpm': bpm})
for bar in track:
res = self.play_Bar(bar, channel, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
return {'bpm': bpm} | [
"def",
"play_Track",
"(",
"self",
",",
"track",
",",
"channel",
"=",
"1",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_TRACK",
",",
"{",
"'track'",
":",
"track",
",",
"'channel'",
":",
"channel",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"for",
"bar",
"in",
"track",
":",
"res",
"=",
"self",
".",
"play_Bar",
"(",
"bar",
",",
"channel",
",",
"bpm",
")",
"if",
"res",
"!=",
"{",
"}",
":",
"bpm",
"=",
"res",
"[",
"'bpm'",
"]",
"else",
":",
"return",
"{",
"}",
"return",
"{",
"'bpm'",
":",
"bpm",
"}"
] | Play a Track object. | [
"Play",
"a",
"Track",
"object",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L296-L306 |
3,387 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.play_Tracks | def play_Tracks(self, tracks, channels, bpm=120):
"""Play a list of Tracks.
If an instance of MidiInstrument is used then the instrument will be
set automatically.
"""
self.notify_listeners(self.MSG_PLAY_TRACKS, {'tracks': tracks,
'channels': channels, 'bpm': bpm})
# Set the right instruments
for x in range(len(tracks)):
instr = tracks[x].instrument
if isinstance(instr, MidiInstrument):
try:
i = instr.names.index(instr.name)
except:
i = 1
self.set_instrument(channels[x], i)
else:
self.set_instrument(channels[x], 1)
current_bar = 0
max_bar = len(tracks[0])
# Play the bars
while current_bar < max_bar:
playbars = []
for tr in tracks:
playbars.append(tr[current_bar])
res = self.play_Bars(playbars, channels, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
current_bar += 1
return {'bpm': bpm} | python | def play_Tracks(self, tracks, channels, bpm=120):
"""Play a list of Tracks.
If an instance of MidiInstrument is used then the instrument will be
set automatically.
"""
self.notify_listeners(self.MSG_PLAY_TRACKS, {'tracks': tracks,
'channels': channels, 'bpm': bpm})
# Set the right instruments
for x in range(len(tracks)):
instr = tracks[x].instrument
if isinstance(instr, MidiInstrument):
try:
i = instr.names.index(instr.name)
except:
i = 1
self.set_instrument(channels[x], i)
else:
self.set_instrument(channels[x], 1)
current_bar = 0
max_bar = len(tracks[0])
# Play the bars
while current_bar < max_bar:
playbars = []
for tr in tracks:
playbars.append(tr[current_bar])
res = self.play_Bars(playbars, channels, bpm)
if res != {}:
bpm = res['bpm']
else:
return {}
current_bar += 1
return {'bpm': bpm} | [
"def",
"play_Tracks",
"(",
"self",
",",
"tracks",
",",
"channels",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_TRACKS",
",",
"{",
"'tracks'",
":",
"tracks",
",",
"'channels'",
":",
"channels",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"# Set the right instruments",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"tracks",
")",
")",
":",
"instr",
"=",
"tracks",
"[",
"x",
"]",
".",
"instrument",
"if",
"isinstance",
"(",
"instr",
",",
"MidiInstrument",
")",
":",
"try",
":",
"i",
"=",
"instr",
".",
"names",
".",
"index",
"(",
"instr",
".",
"name",
")",
"except",
":",
"i",
"=",
"1",
"self",
".",
"set_instrument",
"(",
"channels",
"[",
"x",
"]",
",",
"i",
")",
"else",
":",
"self",
".",
"set_instrument",
"(",
"channels",
"[",
"x",
"]",
",",
"1",
")",
"current_bar",
"=",
"0",
"max_bar",
"=",
"len",
"(",
"tracks",
"[",
"0",
"]",
")",
"# Play the bars",
"while",
"current_bar",
"<",
"max_bar",
":",
"playbars",
"=",
"[",
"]",
"for",
"tr",
"in",
"tracks",
":",
"playbars",
".",
"append",
"(",
"tr",
"[",
"current_bar",
"]",
")",
"res",
"=",
"self",
".",
"play_Bars",
"(",
"playbars",
",",
"channels",
",",
"bpm",
")",
"if",
"res",
"!=",
"{",
"}",
":",
"bpm",
"=",
"res",
"[",
"'bpm'",
"]",
"else",
":",
"return",
"{",
"}",
"current_bar",
"+=",
"1",
"return",
"{",
"'bpm'",
":",
"bpm",
"}"
] | Play a list of Tracks.
If an instance of MidiInstrument is used then the instrument will be
set automatically. | [
"Play",
"a",
"list",
"of",
"Tracks",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L308-L342 |
3,388 | bspaans/python-mingus | mingus/midi/sequencer.py | Sequencer.play_Composition | def play_Composition(self, composition, channels=None, bpm=120):
"""Play a Composition object."""
self.notify_listeners(self.MSG_PLAY_COMPOSITION, {'composition'
: composition, 'channels': channels, 'bpm': bpm})
if channels == None:
channels = map(lambda x: x + 1, range(len(composition.tracks)))
return self.play_Tracks(composition.tracks, channels, bpm) | python | def play_Composition(self, composition, channels=None, bpm=120):
"""Play a Composition object."""
self.notify_listeners(self.MSG_PLAY_COMPOSITION, {'composition'
: composition, 'channels': channels, 'bpm': bpm})
if channels == None:
channels = map(lambda x: x + 1, range(len(composition.tracks)))
return self.play_Tracks(composition.tracks, channels, bpm) | [
"def",
"play_Composition",
"(",
"self",
",",
"composition",
",",
"channels",
"=",
"None",
",",
"bpm",
"=",
"120",
")",
":",
"self",
".",
"notify_listeners",
"(",
"self",
".",
"MSG_PLAY_COMPOSITION",
",",
"{",
"'composition'",
":",
"composition",
",",
"'channels'",
":",
"channels",
",",
"'bpm'",
":",
"bpm",
"}",
")",
"if",
"channels",
"==",
"None",
":",
"channels",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
"+",
"1",
",",
"range",
"(",
"len",
"(",
"composition",
".",
"tracks",
")",
")",
")",
"return",
"self",
".",
"play_Tracks",
"(",
"composition",
".",
"tracks",
",",
"channels",
",",
"bpm",
")"
] | Play a Composition object. | [
"Play",
"a",
"Composition",
"object",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/sequencer.py#L344-L350 |
3,389 | bspaans/python-mingus | mingus/extra/fft.py | _find_log_index | def _find_log_index(f):
"""Look up the index of the frequency f in the frequency table.
Return the nearest index.
"""
global _last_asked, _log_cache
(begin, end) = (0, 128)
# Most calls are sequential, this keeps track of the last value asked for so
# that we need to search much, much less.
if _last_asked is not None:
(lastn, lastval) = _last_asked
if f >= lastval:
if f <= _log_cache[lastn]:
_last_asked = (lastn, f)
return lastn
elif f <= _log_cache[lastn + 1]:
_last_asked = (lastn + 1, f)
return lastn + 1
begin = lastn
# Do some range checking
if f > _log_cache[127] or f <= 0:
return 128
# Binary search related algorithm to find the index
while begin != end:
n = (begin + end) // 2
c = _log_cache[n]
cp = _log_cache[n - 1] if n != 0 else 0
if cp < f <= c:
_last_asked = (n, f)
return n
if f < c:
end = n
else:
begin = n
_last_asked = (begin, f)
return begin | python | def _find_log_index(f):
"""Look up the index of the frequency f in the frequency table.
Return the nearest index.
"""
global _last_asked, _log_cache
(begin, end) = (0, 128)
# Most calls are sequential, this keeps track of the last value asked for so
# that we need to search much, much less.
if _last_asked is not None:
(lastn, lastval) = _last_asked
if f >= lastval:
if f <= _log_cache[lastn]:
_last_asked = (lastn, f)
return lastn
elif f <= _log_cache[lastn + 1]:
_last_asked = (lastn + 1, f)
return lastn + 1
begin = lastn
# Do some range checking
if f > _log_cache[127] or f <= 0:
return 128
# Binary search related algorithm to find the index
while begin != end:
n = (begin + end) // 2
c = _log_cache[n]
cp = _log_cache[n - 1] if n != 0 else 0
if cp < f <= c:
_last_asked = (n, f)
return n
if f < c:
end = n
else:
begin = n
_last_asked = (begin, f)
return begin | [
"def",
"_find_log_index",
"(",
"f",
")",
":",
"global",
"_last_asked",
",",
"_log_cache",
"(",
"begin",
",",
"end",
")",
"=",
"(",
"0",
",",
"128",
")",
"# Most calls are sequential, this keeps track of the last value asked for so",
"# that we need to search much, much less.",
"if",
"_last_asked",
"is",
"not",
"None",
":",
"(",
"lastn",
",",
"lastval",
")",
"=",
"_last_asked",
"if",
"f",
">=",
"lastval",
":",
"if",
"f",
"<=",
"_log_cache",
"[",
"lastn",
"]",
":",
"_last_asked",
"=",
"(",
"lastn",
",",
"f",
")",
"return",
"lastn",
"elif",
"f",
"<=",
"_log_cache",
"[",
"lastn",
"+",
"1",
"]",
":",
"_last_asked",
"=",
"(",
"lastn",
"+",
"1",
",",
"f",
")",
"return",
"lastn",
"+",
"1",
"begin",
"=",
"lastn",
"# Do some range checking",
"if",
"f",
">",
"_log_cache",
"[",
"127",
"]",
"or",
"f",
"<=",
"0",
":",
"return",
"128",
"# Binary search related algorithm to find the index",
"while",
"begin",
"!=",
"end",
":",
"n",
"=",
"(",
"begin",
"+",
"end",
")",
"//",
"2",
"c",
"=",
"_log_cache",
"[",
"n",
"]",
"cp",
"=",
"_log_cache",
"[",
"n",
"-",
"1",
"]",
"if",
"n",
"!=",
"0",
"else",
"0",
"if",
"cp",
"<",
"f",
"<=",
"c",
":",
"_last_asked",
"=",
"(",
"n",
",",
"f",
")",
"return",
"n",
"if",
"f",
"<",
"c",
":",
"end",
"=",
"n",
"else",
":",
"begin",
"=",
"n",
"_last_asked",
"=",
"(",
"begin",
",",
"f",
")",
"return",
"begin"
] | Look up the index of the frequency f in the frequency table.
Return the nearest index. | [
"Look",
"up",
"the",
"index",
"of",
"the",
"frequency",
"f",
"in",
"the",
"frequency",
"table",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L45-L83 |
3,390 | bspaans/python-mingus | mingus/extra/fft.py | find_frequencies | def find_frequencies(data, freq=44100, bits=16):
"""Convert audio data into a frequency-amplitude table using fast fourier
transformation.
Return a list of tuples (frequency, amplitude).
Data should only contain one channel of audio.
"""
# Fast fourier transform
n = len(data)
p = _fft(data)
uniquePts = numpy.ceil((n + 1) / 2.0)
# Scale by the length (n) and square the value to get the amplitude
p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]]
p[0] = p[0] / 2
if n % 2 == 0:
p[-1] = p[-1] / 2
# Generate the frequencies and zip with the amplitudes
s = freq / float(n)
freqArray = numpy.arange(0, uniquePts * s, s)
return zip(freqArray, p) | python | def find_frequencies(data, freq=44100, bits=16):
"""Convert audio data into a frequency-amplitude table using fast fourier
transformation.
Return a list of tuples (frequency, amplitude).
Data should only contain one channel of audio.
"""
# Fast fourier transform
n = len(data)
p = _fft(data)
uniquePts = numpy.ceil((n + 1) / 2.0)
# Scale by the length (n) and square the value to get the amplitude
p = [(abs(x) / float(n)) ** 2 * 2 for x in p[0:uniquePts]]
p[0] = p[0] / 2
if n % 2 == 0:
p[-1] = p[-1] / 2
# Generate the frequencies and zip with the amplitudes
s = freq / float(n)
freqArray = numpy.arange(0, uniquePts * s, s)
return zip(freqArray, p) | [
"def",
"find_frequencies",
"(",
"data",
",",
"freq",
"=",
"44100",
",",
"bits",
"=",
"16",
")",
":",
"# Fast fourier transform",
"n",
"=",
"len",
"(",
"data",
")",
"p",
"=",
"_fft",
"(",
"data",
")",
"uniquePts",
"=",
"numpy",
".",
"ceil",
"(",
"(",
"n",
"+",
"1",
")",
"/",
"2.0",
")",
"# Scale by the length (n) and square the value to get the amplitude",
"p",
"=",
"[",
"(",
"abs",
"(",
"x",
")",
"/",
"float",
"(",
"n",
")",
")",
"**",
"2",
"*",
"2",
"for",
"x",
"in",
"p",
"[",
"0",
":",
"uniquePts",
"]",
"]",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"0",
"]",
"/",
"2",
"if",
"n",
"%",
"2",
"==",
"0",
":",
"p",
"[",
"-",
"1",
"]",
"=",
"p",
"[",
"-",
"1",
"]",
"/",
"2",
"# Generate the frequencies and zip with the amplitudes",
"s",
"=",
"freq",
"/",
"float",
"(",
"n",
")",
"freqArray",
"=",
"numpy",
".",
"arange",
"(",
"0",
",",
"uniquePts",
"*",
"s",
",",
"s",
")",
"return",
"zip",
"(",
"freqArray",
",",
"p",
")"
] | Convert audio data into a frequency-amplitude table using fast fourier
transformation.
Return a list of tuples (frequency, amplitude).
Data should only contain one channel of audio. | [
"Convert",
"audio",
"data",
"into",
"a",
"frequency",
"-",
"amplitude",
"table",
"using",
"fast",
"fourier",
"transformation",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L85-L107 |
3,391 | bspaans/python-mingus | mingus/extra/fft.py | find_Note | def find_Note(data, freq, bits):
"""Get the frequencies, feed them to find_notes and the return the Note
with the highest amplitude."""
data = find_frequencies(data, freq, bits)
return sorted(find_notes(data), key=operator.itemgetter(1))[-1][0] | python | def find_Note(data, freq, bits):
"""Get the frequencies, feed them to find_notes and the return the Note
with the highest amplitude."""
data = find_frequencies(data, freq, bits)
return sorted(find_notes(data), key=operator.itemgetter(1))[-1][0] | [
"def",
"find_Note",
"(",
"data",
",",
"freq",
",",
"bits",
")",
":",
"data",
"=",
"find_frequencies",
"(",
"data",
",",
"freq",
",",
"bits",
")",
"return",
"sorted",
"(",
"find_notes",
"(",
"data",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")",
"[",
"-",
"1",
"]",
"[",
"0",
"]"
] | Get the frequencies, feed them to find_notes and the return the Note
with the highest amplitude. | [
"Get",
"the",
"frequencies",
"feed",
"them",
"to",
"find_notes",
"and",
"the",
"return",
"the",
"Note",
"with",
"the",
"highest",
"amplitude",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L146-L150 |
3,392 | bspaans/python-mingus | mingus/extra/fft.py | analyze_chunks | def analyze_chunks(data, freq, bits, chunksize=512):
"""Cut the one channel data in chunks and analyzes them separately.
Making the chunksize a power of two works fastest.
"""
res = []
while data != []:
f = find_frequencies(data[:chunksize], freq, bits)
res.append(sorted(find_notes(f), key=operator.itemgetter(1))[-1][0])
data = data[chunksize:]
return res | python | def analyze_chunks(data, freq, bits, chunksize=512):
"""Cut the one channel data in chunks and analyzes them separately.
Making the chunksize a power of two works fastest.
"""
res = []
while data != []:
f = find_frequencies(data[:chunksize], freq, bits)
res.append(sorted(find_notes(f), key=operator.itemgetter(1))[-1][0])
data = data[chunksize:]
return res | [
"def",
"analyze_chunks",
"(",
"data",
",",
"freq",
",",
"bits",
",",
"chunksize",
"=",
"512",
")",
":",
"res",
"=",
"[",
"]",
"while",
"data",
"!=",
"[",
"]",
":",
"f",
"=",
"find_frequencies",
"(",
"data",
"[",
":",
"chunksize",
"]",
",",
"freq",
",",
"bits",
")",
"res",
".",
"append",
"(",
"sorted",
"(",
"find_notes",
"(",
"f",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
")",
"data",
"=",
"data",
"[",
"chunksize",
":",
"]",
"return",
"res"
] | Cut the one channel data in chunks and analyzes them separately.
Making the chunksize a power of two works fastest. | [
"Cut",
"the",
"one",
"channel",
"data",
"in",
"chunks",
"and",
"analyzes",
"them",
"separately",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L152-L162 |
3,393 | bspaans/python-mingus | mingus/extra/fft.py | find_melody | def find_melody(file='440_480_clean.wav', chunksize=512):
"""Cut the sample into chunks and analyze each chunk.
Return a list [(Note, chunks)] where chunks is the number of chunks
where that note is the most dominant.
If two consequent chunks turn out to return the same Note they are
grouped together.
This is an experimental function.
"""
(data, freq, bits) = data_from_file(file)
res = []
for d in analyze_chunks(data, freq, bits, chunksize):
if res != []:
if res[-1][0] == d:
val = res[-1][1]
res[-1] = (d, val + 1)
else:
res.append((d, 1))
else:
res.append((d, 1))
return [(x, freq) for (x, freq) in res] | python | def find_melody(file='440_480_clean.wav', chunksize=512):
"""Cut the sample into chunks and analyze each chunk.
Return a list [(Note, chunks)] where chunks is the number of chunks
where that note is the most dominant.
If two consequent chunks turn out to return the same Note they are
grouped together.
This is an experimental function.
"""
(data, freq, bits) = data_from_file(file)
res = []
for d in analyze_chunks(data, freq, bits, chunksize):
if res != []:
if res[-1][0] == d:
val = res[-1][1]
res[-1] = (d, val + 1)
else:
res.append((d, 1))
else:
res.append((d, 1))
return [(x, freq) for (x, freq) in res] | [
"def",
"find_melody",
"(",
"file",
"=",
"'440_480_clean.wav'",
",",
"chunksize",
"=",
"512",
")",
":",
"(",
"data",
",",
"freq",
",",
"bits",
")",
"=",
"data_from_file",
"(",
"file",
")",
"res",
"=",
"[",
"]",
"for",
"d",
"in",
"analyze_chunks",
"(",
"data",
",",
"freq",
",",
"bits",
",",
"chunksize",
")",
":",
"if",
"res",
"!=",
"[",
"]",
":",
"if",
"res",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"==",
"d",
":",
"val",
"=",
"res",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
"res",
"[",
"-",
"1",
"]",
"=",
"(",
"d",
",",
"val",
"+",
"1",
")",
"else",
":",
"res",
".",
"append",
"(",
"(",
"d",
",",
"1",
")",
")",
"else",
":",
"res",
".",
"append",
"(",
"(",
"d",
",",
"1",
")",
")",
"return",
"[",
"(",
"x",
",",
"freq",
")",
"for",
"(",
"x",
",",
"freq",
")",
"in",
"res",
"]"
] | Cut the sample into chunks and analyze each chunk.
Return a list [(Note, chunks)] where chunks is the number of chunks
where that note is the most dominant.
If two consequent chunks turn out to return the same Note they are
grouped together.
This is an experimental function. | [
"Cut",
"the",
"sample",
"into",
"chunks",
"and",
"analyze",
"each",
"chunk",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/fft.py#L164-L186 |
3,394 | bspaans/python-mingus | mingus/midi/midi_file_out.py | write_Note | def write_Note(file, note, bpm=120, repeat=0, verbose=False):
"""Expect a Note object from mingus.containers and save it into a MIDI
file, specified in file.
You can set the velocity and channel in Note.velocity and Note.channel.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_Note(note)
t.set_deltatime("\x48")
t.stop_Note(note)
repeat -= 1
return m.write_file(file, verbose) | python | def write_Note(file, note, bpm=120, repeat=0, verbose=False):
"""Expect a Note object from mingus.containers and save it into a MIDI
file, specified in file.
You can set the velocity and channel in Note.velocity and Note.channel.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_Note(note)
t.set_deltatime("\x48")
t.stop_Note(note)
repeat -= 1
return m.write_file(file, verbose) | [
"def",
"write_Note",
"(",
"file",
",",
"note",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"set_deltatime",
"(",
"'\\x00'",
")",
"t",
".",
"play_Note",
"(",
"note",
")",
"t",
".",
"set_deltatime",
"(",
"\"\\x48\"",
")",
"t",
".",
"stop_Note",
"(",
"note",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] | Expect a Note object from mingus.containers and save it into a MIDI
file, specified in file.
You can set the velocity and channel in Note.velocity and Note.channel. | [
"Expect",
"a",
"Note",
"object",
"from",
"mingus",
".",
"containers",
"and",
"save",
"it",
"into",
"a",
"MIDI",
"file",
"specified",
"in",
"file",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L71-L86 |
3,395 | bspaans/python-mingus | mingus/midi/midi_file_out.py | write_NoteContainer | def write_NoteContainer(file, notecontainer, bpm=120, repeat=0, verbose=False):
"""Write a mingus.NoteContainer to a MIDI file."""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_NoteContainer(notecontainer)
t.set_deltatime("\x48")
t.stop_NoteContainer(notecontainer)
repeat -= 1
return m.write_file(file, verbose) | python | def write_NoteContainer(file, notecontainer, bpm=120, repeat=0, verbose=False):
"""Write a mingus.NoteContainer to a MIDI file."""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.set_deltatime('\x00')
t.play_NoteContainer(notecontainer)
t.set_deltatime("\x48")
t.stop_NoteContainer(notecontainer)
repeat -= 1
return m.write_file(file, verbose) | [
"def",
"write_NoteContainer",
"(",
"file",
",",
"notecontainer",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"set_deltatime",
"(",
"'\\x00'",
")",
"t",
".",
"play_NoteContainer",
"(",
"notecontainer",
")",
"t",
".",
"set_deltatime",
"(",
"\"\\x48\"",
")",
"t",
".",
"stop_NoteContainer",
"(",
"notecontainer",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] | Write a mingus.NoteContainer to a MIDI file. | [
"Write",
"a",
"mingus",
".",
"NoteContainer",
"to",
"a",
"MIDI",
"file",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L88-L99 |
3,396 | bspaans/python-mingus | mingus/midi/midi_file_out.py | write_Bar | def write_Bar(file, bar, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Bar to a MIDI file.
Both the key and the meter are written to the file as well.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Bar(bar)
repeat -= 1
return m.write_file(file, verbose) | python | def write_Bar(file, bar, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Bar to a MIDI file.
Both the key and the meter are written to the file as well.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Bar(bar)
repeat -= 1
return m.write_file(file, verbose) | [
"def",
"write_Bar",
"(",
"file",
",",
"bar",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"play_Bar",
"(",
"bar",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] | Write a mingus.Bar to a MIDI file.
Both the key and the meter are written to the file as well. | [
"Write",
"a",
"mingus",
".",
"Bar",
"to",
"a",
"MIDI",
"file",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L101-L112 |
3,397 | bspaans/python-mingus | mingus/midi/midi_file_out.py | write_Track | def write_Track(file, track, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Track to a MIDI file.
Write the name to the file and set the instrument if the instrument has
the attribute instrument_nr, which represents the MIDI instrument
number. The class MidiInstrument in mingus.containers.Instrument has
this attribute by default.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Track(track)
repeat -= 1
return m.write_file(file, verbose) | python | def write_Track(file, track, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Track to a MIDI file.
Write the name to the file and set the instrument if the instrument has
the attribute instrument_nr, which represents the MIDI instrument
number. The class MidiInstrument in mingus.containers.Instrument has
this attribute by default.
"""
m = MidiFile()
t = MidiTrack(bpm)
m.tracks = [t]
while repeat >= 0:
t.play_Track(track)
repeat -= 1
return m.write_file(file, verbose) | [
"def",
"write_Track",
"(",
"file",
",",
"track",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"MidiTrack",
"(",
"bpm",
")",
"m",
".",
"tracks",
"=",
"[",
"t",
"]",
"while",
"repeat",
">=",
"0",
":",
"t",
".",
"play_Track",
"(",
"track",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] | Write a mingus.Track to a MIDI file.
Write the name to the file and set the instrument if the instrument has
the attribute instrument_nr, which represents the MIDI instrument
number. The class MidiInstrument in mingus.containers.Instrument has
this attribute by default. | [
"Write",
"a",
"mingus",
".",
"Track",
"to",
"a",
"MIDI",
"file",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L114-L128 |
3,398 | bspaans/python-mingus | mingus/midi/midi_file_out.py | write_Composition | def write_Composition(file, composition, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Composition to a MIDI file."""
m = MidiFile()
t = []
for x in range(len(composition.tracks)):
t += [MidiTrack(bpm)]
m.tracks = t
while repeat >= 0:
for i in range(len(composition.tracks)):
m.tracks[i].play_Track(composition.tracks[i])
repeat -= 1
return m.write_file(file, verbose) | python | def write_Composition(file, composition, bpm=120, repeat=0, verbose=False):
"""Write a mingus.Composition to a MIDI file."""
m = MidiFile()
t = []
for x in range(len(composition.tracks)):
t += [MidiTrack(bpm)]
m.tracks = t
while repeat >= 0:
for i in range(len(composition.tracks)):
m.tracks[i].play_Track(composition.tracks[i])
repeat -= 1
return m.write_file(file, verbose) | [
"def",
"write_Composition",
"(",
"file",
",",
"composition",
",",
"bpm",
"=",
"120",
",",
"repeat",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"m",
"=",
"MidiFile",
"(",
")",
"t",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"composition",
".",
"tracks",
")",
")",
":",
"t",
"+=",
"[",
"MidiTrack",
"(",
"bpm",
")",
"]",
"m",
".",
"tracks",
"=",
"t",
"while",
"repeat",
">=",
"0",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"composition",
".",
"tracks",
")",
")",
":",
"m",
".",
"tracks",
"[",
"i",
"]",
".",
"play_Track",
"(",
"composition",
".",
"tracks",
"[",
"i",
"]",
")",
"repeat",
"-=",
"1",
"return",
"m",
".",
"write_file",
"(",
"file",
",",
"verbose",
")"
] | Write a mingus.Composition to a MIDI file. | [
"Write",
"a",
"mingus",
".",
"Composition",
"to",
"a",
"MIDI",
"file",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L130-L141 |
3,399 | bspaans/python-mingus | mingus/midi/midi_file_out.py | MidiFile.get_midi_data | def get_midi_data(self):
"""Collect and return the raw, binary MIDI data from the tracks."""
tracks = [t.get_midi_data() for t in self.tracks if t.track_data != '']
return self.header() + ''.join(tracks) | python | def get_midi_data(self):
"""Collect and return the raw, binary MIDI data from the tracks."""
tracks = [t.get_midi_data() for t in self.tracks if t.track_data != '']
return self.header() + ''.join(tracks) | [
"def",
"get_midi_data",
"(",
"self",
")",
":",
"tracks",
"=",
"[",
"t",
".",
"get_midi_data",
"(",
")",
"for",
"t",
"in",
"self",
".",
"tracks",
"if",
"t",
".",
"track_data",
"!=",
"''",
"]",
"return",
"self",
".",
"header",
"(",
")",
"+",
"''",
".",
"join",
"(",
"tracks",
")"
] | Collect and return the raw, binary MIDI data from the tracks. | [
"Collect",
"and",
"return",
"the",
"raw",
"binary",
"MIDI",
"data",
"from",
"the",
"tracks",
"."
] | aa5a5d992d45ada61be0f9f86261380731bd7749 | https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_out.py#L37-L40 |
Subsets and Splits