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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,100 | iotile/coretools | iotileemulate/iotile/emulate/virtual/emulated_device.py | EmulatedDevice.load_metascenario | def load_metascenario(self, scenario_list):
"""Load one or more scenarios from a list.
Each entry in scenario_list should be a dict containing at least a
name key and an optional tile key and args key. If tile is present
and its value is not None, the scenario specified will be loaded into
the given tile only. Otherwise it will be loaded into the entire
device.
If the args key is specified is will be passed as keyword arguments
to load_scenario.
Args:
scenario_list (list): A list of dicts for each scenario that should
be loaded.
"""
for scenario in scenario_list:
name = scenario.get('name')
if name is None:
raise DataError("Scenario in scenario list is missing a name parameter", scenario=scenario)
tile_address = scenario.get('tile')
args = scenario.get('args', {})
dest = self
if tile_address is not None:
dest = self._tiles.get(tile_address)
if dest is None:
raise DataError("Attempted to load a scenario into a tile address that does not exist", address=tile_address, valid_addresses=list(self._tiles))
dest.load_scenario(name, **args) | python | def load_metascenario(self, scenario_list):
for scenario in scenario_list:
name = scenario.get('name')
if name is None:
raise DataError("Scenario in scenario list is missing a name parameter", scenario=scenario)
tile_address = scenario.get('tile')
args = scenario.get('args', {})
dest = self
if tile_address is not None:
dest = self._tiles.get(tile_address)
if dest is None:
raise DataError("Attempted to load a scenario into a tile address that does not exist", address=tile_address, valid_addresses=list(self._tiles))
dest.load_scenario(name, **args) | [
"def",
"load_metascenario",
"(",
"self",
",",
"scenario_list",
")",
":",
"for",
"scenario",
"in",
"scenario_list",
":",
"name",
"=",
"scenario",
".",
"get",
"(",
"'name'",
")",
"if",
"name",
"is",
"None",
":",
"raise",
"DataError",
"(",
"\"Scenario in scenar... | Load one or more scenarios from a list.
Each entry in scenario_list should be a dict containing at least a
name key and an optional tile key and args key. If tile is present
and its value is not None, the scenario specified will be loaded into
the given tile only. Otherwise it will be loaded into the entire
device.
If the args key is specified is will be passed as keyword arguments
to load_scenario.
Args:
scenario_list (list): A list of dicts for each scenario that should
be loaded. | [
"Load",
"one",
"or",
"more",
"scenarios",
"from",
"a",
"list",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulated_device.py#L320-L352 |
24,101 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStream.associated_stream | def associated_stream(self):
"""Return the corresponding output or storage stream for an important system input.
Certain system inputs are designed as important and automatically
copied to output streams without requiring any manual interaction.
This method returns the corresponding stream for an important system
input. It will raise an InternalError unlesss the self.important
property is True.
Returns:
DataStream: The corresponding output or storage stream.
Raises:
InternalError: If this stream is not marked as an important system input.
"""
if not self.important:
raise InternalError("You may only call autocopied_stream on when DataStream.important is True", stream=self)
if self.stream_id >= DataStream.ImportantSystemStorageStart:
stream_type = DataStream.BufferedType
else:
stream_type = DataStream.OutputType
return DataStream(stream_type, self.stream_id, True) | python | def associated_stream(self):
if not self.important:
raise InternalError("You may only call autocopied_stream on when DataStream.important is True", stream=self)
if self.stream_id >= DataStream.ImportantSystemStorageStart:
stream_type = DataStream.BufferedType
else:
stream_type = DataStream.OutputType
return DataStream(stream_type, self.stream_id, True) | [
"def",
"associated_stream",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"important",
":",
"raise",
"InternalError",
"(",
"\"You may only call autocopied_stream on when DataStream.important is True\"",
",",
"stream",
"=",
"self",
")",
"if",
"self",
".",
"stream_id... | Return the corresponding output or storage stream for an important system input.
Certain system inputs are designed as important and automatically
copied to output streams without requiring any manual interaction.
This method returns the corresponding stream for an important system
input. It will raise an InternalError unlesss the self.important
property is True.
Returns:
DataStream: The corresponding output or storage stream.
Raises:
InternalError: If this stream is not marked as an important system input. | [
"Return",
"the",
"corresponding",
"output",
"or",
"storage",
"stream",
"for",
"an",
"important",
"system",
"input",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L80-L105 |
24,102 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStream.FromString | def FromString(cls, string_rep):
"""Create a DataStream from a string representation.
The format for stream designators when encoded as strings is:
[system] (buffered|unbuffered|constant|input|count|output) <integer>
Args:
string_rep (str): The string representation to turn into a
DataStream
"""
rep = str(string_rep)
parts = rep.split()
if len(parts) > 3:
raise ArgumentError("Too many whitespace separated parts of stream designator", input_string=string_rep)
elif len(parts) == 3 and parts[0] != u'system':
raise ArgumentError("Too many whitespace separated parts of stream designator", input_string=string_rep)
elif len(parts) < 2:
raise ArgumentError("Too few components in stream designator", input_string=string_rep)
# Now actually parse the string
if len(parts) == 3:
system = True
stream_type = parts[1]
stream_id = parts[2]
else:
system = False
stream_type = parts[0]
stream_id = parts[1]
try:
stream_id = int(stream_id, 0)
except ValueError as exc:
raise ArgumentError("Could not convert stream id to integer", error_string=str(exc), stream_id=stream_id)
try:
stream_type = cls.StringToType[stream_type]
except KeyError:
raise ArgumentError("Invalid stream type given", stream_type=stream_type, known_types=cls.StringToType.keys())
return DataStream(stream_type, stream_id, system) | python | def FromString(cls, string_rep):
rep = str(string_rep)
parts = rep.split()
if len(parts) > 3:
raise ArgumentError("Too many whitespace separated parts of stream designator", input_string=string_rep)
elif len(parts) == 3 and parts[0] != u'system':
raise ArgumentError("Too many whitespace separated parts of stream designator", input_string=string_rep)
elif len(parts) < 2:
raise ArgumentError("Too few components in stream designator", input_string=string_rep)
# Now actually parse the string
if len(parts) == 3:
system = True
stream_type = parts[1]
stream_id = parts[2]
else:
system = False
stream_type = parts[0]
stream_id = parts[1]
try:
stream_id = int(stream_id, 0)
except ValueError as exc:
raise ArgumentError("Could not convert stream id to integer", error_string=str(exc), stream_id=stream_id)
try:
stream_type = cls.StringToType[stream_type]
except KeyError:
raise ArgumentError("Invalid stream type given", stream_type=stream_type, known_types=cls.StringToType.keys())
return DataStream(stream_type, stream_id, system) | [
"def",
"FromString",
"(",
"cls",
",",
"string_rep",
")",
":",
"rep",
"=",
"str",
"(",
"string_rep",
")",
"parts",
"=",
"rep",
".",
"split",
"(",
")",
"if",
"len",
"(",
"parts",
")",
">",
"3",
":",
"raise",
"ArgumentError",
"(",
"\"Too many whitespace s... | Create a DataStream from a string representation.
The format for stream designators when encoded as strings is:
[system] (buffered|unbuffered|constant|input|count|output) <integer>
Args:
string_rep (str): The string representation to turn into a
DataStream | [
"Create",
"a",
"DataStream",
"from",
"a",
"string",
"representation",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L108-L149 |
24,103 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStream.FromEncoded | def FromEncoded(self, encoded):
"""Create a DataStream from an encoded 16-bit unsigned integer.
Returns:
DataStream: The decoded DataStream object
"""
stream_type = (encoded >> 12) & 0b1111
stream_system = bool(encoded & (1 << 11))
stream_id = (encoded & ((1 << 11) - 1))
return DataStream(stream_type, stream_id, stream_system) | python | def FromEncoded(self, encoded):
stream_type = (encoded >> 12) & 0b1111
stream_system = bool(encoded & (1 << 11))
stream_id = (encoded & ((1 << 11) - 1))
return DataStream(stream_type, stream_id, stream_system) | [
"def",
"FromEncoded",
"(",
"self",
",",
"encoded",
")",
":",
"stream_type",
"=",
"(",
"encoded",
">>",
"12",
")",
"&",
"0b1111",
"stream_system",
"=",
"bool",
"(",
"encoded",
"&",
"(",
"1",
"<<",
"11",
")",
")",
"stream_id",
"=",
"(",
"encoded",
"&",... | Create a DataStream from an encoded 16-bit unsigned integer.
Returns:
DataStream: The decoded DataStream object | [
"Create",
"a",
"DataStream",
"from",
"an",
"encoded",
"16",
"-",
"bit",
"unsigned",
"integer",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L152-L163 |
24,104 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStreamSelector.as_stream | def as_stream(self):
"""Convert this selector to a DataStream.
This function will only work if this is a singular selector that
matches exactly one DataStream.
"""
if not self.singular:
raise ArgumentError("Attempted to convert a non-singular selector to a data stream, it matches multiple", selector=self)
return DataStream(self.match_type, self.match_id, self.match_spec == DataStreamSelector.MatchSystemOnly) | python | def as_stream(self):
if not self.singular:
raise ArgumentError("Attempted to convert a non-singular selector to a data stream, it matches multiple", selector=self)
return DataStream(self.match_type, self.match_id, self.match_spec == DataStreamSelector.MatchSystemOnly) | [
"def",
"as_stream",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"singular",
":",
"raise",
"ArgumentError",
"(",
"\"Attempted to convert a non-singular selector to a data stream, it matches multiple\"",
",",
"selector",
"=",
"self",
")",
"return",
"DataStream",
"(",... | Convert this selector to a DataStream.
This function will only work if this is a singular selector that
matches exactly one DataStream. | [
"Convert",
"this",
"selector",
"to",
"a",
"DataStream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L270-L280 |
24,105 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStreamSelector.FromStream | def FromStream(cls, stream):
"""Create a DataStreamSelector from a DataStream.
Args:
stream (DataStream): The data stream that we want to convert.
"""
if stream.system:
specifier = DataStreamSelector.MatchSystemOnly
else:
specifier = DataStreamSelector.MatchUserOnly
return DataStreamSelector(stream.stream_type, stream.stream_id, specifier) | python | def FromStream(cls, stream):
if stream.system:
specifier = DataStreamSelector.MatchSystemOnly
else:
specifier = DataStreamSelector.MatchUserOnly
return DataStreamSelector(stream.stream_type, stream.stream_id, specifier) | [
"def",
"FromStream",
"(",
"cls",
",",
"stream",
")",
":",
"if",
"stream",
".",
"system",
":",
"specifier",
"=",
"DataStreamSelector",
".",
"MatchSystemOnly",
"else",
":",
"specifier",
"=",
"DataStreamSelector",
".",
"MatchUserOnly",
"return",
"DataStreamSelector",... | Create a DataStreamSelector from a DataStream.
Args:
stream (DataStream): The data stream that we want to convert. | [
"Create",
"a",
"DataStreamSelector",
"from",
"a",
"DataStream",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L283-L295 |
24,106 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStreamSelector.FromEncoded | def FromEncoded(cls, encoded):
"""Create a DataStreamSelector from an encoded 16-bit value.
The binary value must be equivalent to what is produced by
a call to self.encode() and will turn that value back into
a a DataStreamSelector.
Note that the following operation is a no-op:
DataStreamSelector.FromEncode(value).encode()
Args:
encoded (int): The encoded binary representation of a
DataStreamSelector.
Returns:
DataStreamSelector: The decoded selector.
"""
match_spec = encoded & ((1 << 11) | (1 << 15))
match_type = (encoded & (0b111 << 12)) >> 12
match_id = encoded & ((1 << 11) - 1)
if match_spec not in cls.SpecifierEncodingMap:
raise ArgumentError("Unknown encoded match specifier", match_spec=match_spec, known_specifiers=cls.SpecifierEncodingMap.keys())
spec_name = cls.SpecifierEncodingMap[match_spec]
# Handle wildcard matches
if match_id == cls.MatchAllCode:
match_id = None
return DataStreamSelector(match_type, match_id, spec_name) | python | def FromEncoded(cls, encoded):
match_spec = encoded & ((1 << 11) | (1 << 15))
match_type = (encoded & (0b111 << 12)) >> 12
match_id = encoded & ((1 << 11) - 1)
if match_spec not in cls.SpecifierEncodingMap:
raise ArgumentError("Unknown encoded match specifier", match_spec=match_spec, known_specifiers=cls.SpecifierEncodingMap.keys())
spec_name = cls.SpecifierEncodingMap[match_spec]
# Handle wildcard matches
if match_id == cls.MatchAllCode:
match_id = None
return DataStreamSelector(match_type, match_id, spec_name) | [
"def",
"FromEncoded",
"(",
"cls",
",",
"encoded",
")",
":",
"match_spec",
"=",
"encoded",
"&",
"(",
"(",
"1",
"<<",
"11",
")",
"|",
"(",
"1",
"<<",
"15",
")",
")",
"match_type",
"=",
"(",
"encoded",
"&",
"(",
"0b111",
"<<",
"12",
")",
")",
">>"... | Create a DataStreamSelector from an encoded 16-bit value.
The binary value must be equivalent to what is produced by
a call to self.encode() and will turn that value back into
a a DataStreamSelector.
Note that the following operation is a no-op:
DataStreamSelector.FromEncode(value).encode()
Args:
encoded (int): The encoded binary representation of a
DataStreamSelector.
Returns:
DataStreamSelector: The decoded selector. | [
"Create",
"a",
"DataStreamSelector",
"from",
"an",
"encoded",
"16",
"-",
"bit",
"value",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L298-L330 |
24,107 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStreamSelector.FromString | def FromString(cls, string_rep):
"""Create a DataStreamSelector from a string.
The format of the string should either be:
all <type>
OR
<type> <id>
Where type is [system] <stream type>, with <stream type>
defined as in DataStream
Args:
rep (str): The string representation to convert to a DataStreamSelector
"""
rep = str(string_rep)
rep = rep.replace(u'node', '')
rep = rep.replace(u'nodes', '')
if rep.startswith(u'all'):
parts = rep.split()
spec_string = u''
if len(parts) == 3:
spec_string = parts[1]
stream_type = parts[2]
elif len(parts) == 2:
stream_type = parts[1]
else:
raise ArgumentError("Invalid wildcard stream selector", string_rep=string_rep)
try:
# Remove pluralization that can come with e.g. 'all system outputs'
if stream_type.endswith(u's'):
stream_type = stream_type[:-1]
stream_type = DataStream.StringToType[stream_type]
except KeyError:
raise ArgumentError("Invalid stream type given", stream_type=stream_type, known_types=DataStream.StringToType.keys())
stream_spec = DataStreamSelector.SpecifierNames.get(spec_string, None)
if stream_spec is None:
raise ArgumentError("Invalid stream specifier given (should be system, user, combined or blank)", string_rep=string_rep, spec_string=spec_string)
return DataStreamSelector(stream_type, None, stream_spec)
# If we're not matching a wildcard stream type, then the match is exactly
# the same as a DataStream identifier, so use that to match it.
stream = DataStream.FromString(rep)
return DataStreamSelector.FromStream(stream) | python | def FromString(cls, string_rep):
rep = str(string_rep)
rep = rep.replace(u'node', '')
rep = rep.replace(u'nodes', '')
if rep.startswith(u'all'):
parts = rep.split()
spec_string = u''
if len(parts) == 3:
spec_string = parts[1]
stream_type = parts[2]
elif len(parts) == 2:
stream_type = parts[1]
else:
raise ArgumentError("Invalid wildcard stream selector", string_rep=string_rep)
try:
# Remove pluralization that can come with e.g. 'all system outputs'
if stream_type.endswith(u's'):
stream_type = stream_type[:-1]
stream_type = DataStream.StringToType[stream_type]
except KeyError:
raise ArgumentError("Invalid stream type given", stream_type=stream_type, known_types=DataStream.StringToType.keys())
stream_spec = DataStreamSelector.SpecifierNames.get(spec_string, None)
if stream_spec is None:
raise ArgumentError("Invalid stream specifier given (should be system, user, combined or blank)", string_rep=string_rep, spec_string=spec_string)
return DataStreamSelector(stream_type, None, stream_spec)
# If we're not matching a wildcard stream type, then the match is exactly
# the same as a DataStream identifier, so use that to match it.
stream = DataStream.FromString(rep)
return DataStreamSelector.FromStream(stream) | [
"def",
"FromString",
"(",
"cls",
",",
"string_rep",
")",
":",
"rep",
"=",
"str",
"(",
"string_rep",
")",
"rep",
"=",
"rep",
".",
"replace",
"(",
"u'node'",
",",
"''",
")",
"rep",
"=",
"rep",
".",
"replace",
"(",
"u'nodes'",
",",
"''",
")",
"if",
... | Create a DataStreamSelector from a string.
The format of the string should either be:
all <type>
OR
<type> <id>
Where type is [system] <stream type>, with <stream type>
defined as in DataStream
Args:
rep (str): The string representation to convert to a DataStreamSelector | [
"Create",
"a",
"DataStreamSelector",
"from",
"a",
"string",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L333-L386 |
24,108 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStreamSelector.matches | def matches(self, stream):
"""Check if this selector matches the given stream
Args:
stream (DataStream): The stream to check
Returns:
bool: True if this selector matches the stream
"""
if self.match_type != stream.stream_type:
return False
if self.match_id is not None:
return self.match_id == stream.stream_id
if self.match_spec == DataStreamSelector.MatchUserOnly:
return not stream.system
elif self.match_spec == DataStreamSelector.MatchSystemOnly:
return stream.system
elif self.match_spec == DataStreamSelector.MatchUserAndBreaks:
return (not stream.system) or (stream.system and (stream.stream_id in DataStream.KnownBreakStreams))
# The other case is that match_spec is MatchCombined, which matches everything
# regardless of system of user flag
return True | python | def matches(self, stream):
if self.match_type != stream.stream_type:
return False
if self.match_id is not None:
return self.match_id == stream.stream_id
if self.match_spec == DataStreamSelector.MatchUserOnly:
return not stream.system
elif self.match_spec == DataStreamSelector.MatchSystemOnly:
return stream.system
elif self.match_spec == DataStreamSelector.MatchUserAndBreaks:
return (not stream.system) or (stream.system and (stream.stream_id in DataStream.KnownBreakStreams))
# The other case is that match_spec is MatchCombined, which matches everything
# regardless of system of user flag
return True | [
"def",
"matches",
"(",
"self",
",",
"stream",
")",
":",
"if",
"self",
".",
"match_type",
"!=",
"stream",
".",
"stream_type",
":",
"return",
"False",
"if",
"self",
".",
"match_id",
"is",
"not",
"None",
":",
"return",
"self",
".",
"match_id",
"==",
"stre... | Check if this selector matches the given stream
Args:
stream (DataStream): The stream to check
Returns:
bool: True if this selector matches the stream | [
"Check",
"if",
"this",
"selector",
"matches",
"the",
"given",
"stream"
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L407-L432 |
24,109 | iotile/coretools | iotilesensorgraph/iotile/sg/stream.py | DataStreamSelector.encode | def encode(self):
"""Encode this stream as a packed 16-bit unsigned integer.
Returns:
int: The packed encoded stream
"""
match_id = self.match_id
if match_id is None:
match_id = (1 << 11) - 1
return (self.match_type << 12) | DataStreamSelector.SpecifierEncodings[self.match_spec] | match_id | python | def encode(self):
match_id = self.match_id
if match_id is None:
match_id = (1 << 11) - 1
return (self.match_type << 12) | DataStreamSelector.SpecifierEncodings[self.match_spec] | match_id | [
"def",
"encode",
"(",
"self",
")",
":",
"match_id",
"=",
"self",
".",
"match_id",
"if",
"match_id",
"is",
"None",
":",
"match_id",
"=",
"(",
"1",
"<<",
"11",
")",
"-",
"1",
"return",
"(",
"self",
".",
"match_type",
"<<",
"12",
")",
"|",
"DataStream... | Encode this stream as a packed 16-bit unsigned integer.
Returns:
int: The packed encoded stream | [
"Encode",
"this",
"stream",
"as",
"a",
"packed",
"16",
"-",
"bit",
"unsigned",
"integer",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/stream.py#L434-L445 |
24,110 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/m4.py | generate | def generate(env):
"""Add Builders and construction variables for m4 to an Environment."""
M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR')
bld = SCons.Builder.Builder(action = M4Action, src_suffix = '.m4')
env['BUILDERS']['M4'] = bld
# .m4 files might include other files, and it would be pretty hard
# to write a scanner for it, so let's just cd to the dir of the m4
# file and run from there.
# The src_suffix setup is like so: file.c.m4 -> file.c,
# file.cpp.m4 -> file.cpp etc.
env['M4'] = 'm4'
env['M4FLAGS'] = SCons.Util.CLVar('-E')
env['M4COM'] = 'cd ${SOURCE.rsrcdir} && $M4 $M4FLAGS < ${SOURCE.file} > ${TARGET.abspath}' | python | def generate(env):
M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR')
bld = SCons.Builder.Builder(action = M4Action, src_suffix = '.m4')
env['BUILDERS']['M4'] = bld
# .m4 files might include other files, and it would be pretty hard
# to write a scanner for it, so let's just cd to the dir of the m4
# file and run from there.
# The src_suffix setup is like so: file.c.m4 -> file.c,
# file.cpp.m4 -> file.cpp etc.
env['M4'] = 'm4'
env['M4FLAGS'] = SCons.Util.CLVar('-E')
env['M4COM'] = 'cd ${SOURCE.rsrcdir} && $M4 $M4FLAGS < ${SOURCE.file} > ${TARGET.abspath}' | [
"def",
"generate",
"(",
"env",
")",
":",
"M4Action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"'$M4COM'",
",",
"'$M4COMSTR'",
")",
"bld",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(",
"action",
"=",
"M4Action",
",",
"src_suffix",
"=",
"'.m... | Add Builders and construction variables for m4 to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"m4",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/m4.py#L40-L54 |
24,111 | iotile/coretools | iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/latex.py | generate | def generate(env):
"""Add Builders and construction variables for LaTeX to an Environment."""
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
from . import dvi
dvi.generate(env)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.ltx', LaTeXAuxAction)
bld.add_action('.latex', LaTeXAuxAction)
bld.add_emitter('.ltx', SCons.Tool.tex.tex_eps_emitter)
bld.add_emitter('.latex', SCons.Tool.tex.tex_eps_emitter)
SCons.Tool.tex.generate_common(env) | python | def generate(env):
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
from . import dvi
dvi.generate(env)
from . import pdf
pdf.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.ltx', LaTeXAuxAction)
bld.add_action('.latex', LaTeXAuxAction)
bld.add_emitter('.ltx', SCons.Tool.tex.tex_eps_emitter)
bld.add_emitter('.latex', SCons.Tool.tex.tex_eps_emitter)
SCons.Tool.tex.generate_common(env) | [
"def",
"generate",
"(",
"env",
")",
":",
"env",
".",
"AppendUnique",
"(",
"LATEXSUFFIXES",
"=",
"SCons",
".",
"Tool",
".",
"LaTeXSuffixes",
")",
"from",
".",
"import",
"dvi",
"dvi",
".",
"generate",
"(",
"env",
")",
"from",
".",
"import",
"pdf",
"pdf",... | Add Builders and construction variables for LaTeX to an Environment. | [
"Add",
"Builders",
"and",
"construction",
"variables",
"for",
"LaTeX",
"to",
"an",
"Environment",
"."
] | 2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec | https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/latex.py#L53-L70 |
24,112 | jobec/rfc5424-logging-handler | rfc5424logging/handler.py | Rfc5424SysLogHandler.encode_priority | def encode_priority(self, facility, priority):
"""
Encode the facility and priority. You can pass in strings or
integers - if strings are passed, the facility_names and
priority_names mapping dictionaries are used to convert them to
integers.
"""
return (facility << 3) | self.priority_map.get(priority, self.LOG_WARNING) | python | def encode_priority(self, facility, priority):
return (facility << 3) | self.priority_map.get(priority, self.LOG_WARNING) | [
"def",
"encode_priority",
"(",
"self",
",",
"facility",
",",
"priority",
")",
":",
"return",
"(",
"facility",
"<<",
"3",
")",
"|",
"self",
".",
"priority_map",
".",
"get",
"(",
"priority",
",",
"self",
".",
"LOG_WARNING",
")"
] | Encode the facility and priority. You can pass in strings or
integers - if strings are passed, the facility_names and
priority_names mapping dictionaries are used to convert them to
integers. | [
"Encode",
"the",
"facility",
"and",
"priority",
".",
"You",
"can",
"pass",
"in",
"strings",
"or",
"integers",
"-",
"if",
"strings",
"are",
"passed",
"the",
"facility_names",
"and",
"priority_names",
"mapping",
"dictionaries",
"are",
"used",
"to",
"convert",
"t... | 9c4f669c5e54cf382936cd950e2204caeb6d05f0 | https://github.com/jobec/rfc5424-logging-handler/blob/9c4f669c5e54cf382936cd950e2204caeb6d05f0/rfc5424logging/handler.py#L250-L257 |
24,113 | jobec/rfc5424-logging-handler | rfc5424logging/handler.py | Rfc5424SysLogHandler.close | def close(self):
"""
Closes the socket.
"""
self.acquire()
try:
if self.transport is not None:
self.transport.close()
super(Rfc5424SysLogHandler, self).close()
finally:
self.release() | python | def close(self):
self.acquire()
try:
if self.transport is not None:
self.transport.close()
super(Rfc5424SysLogHandler, self).close()
finally:
self.release() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"transport",
"is",
"not",
"None",
":",
"self",
".",
"transport",
".",
"close",
"(",
")",
"super",
"(",
"Rfc5424SysLogHandler",
",",
"self",
")",
... | Closes the socket. | [
"Closes",
"the",
"socket",
"."
] | 9c4f669c5e54cf382936cd950e2204caeb6d05f0 | https://github.com/jobec/rfc5424-logging-handler/blob/9c4f669c5e54cf382936cd950e2204caeb6d05f0/rfc5424logging/handler.py#L478-L488 |
24,114 | benedictpaten/sonLib | misc.py | sonTraceRootPath | def sonTraceRootPath():
"""
function for finding external location
"""
import sonLib.bioio
i = os.path.abspath(sonLib.bioio.__file__)
return os.path.split(os.path.split(os.path.split(i)[0])[0])[0] | python | def sonTraceRootPath():
import sonLib.bioio
i = os.path.abspath(sonLib.bioio.__file__)
return os.path.split(os.path.split(os.path.split(i)[0])[0])[0] | [
"def",
"sonTraceRootPath",
"(",
")",
":",
"import",
"sonLib",
".",
"bioio",
"i",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"sonLib",
".",
"bioio",
".",
"__file__",
")",
"return",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"spl... | function for finding external location | [
"function",
"for",
"finding",
"external",
"location"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/misc.py#L20-L26 |
24,115 | benedictpaten/sonLib | misc.py | linOriginRegression | def linOriginRegression(points):
"""
computes a linear regression starting at zero
"""
j = sum([ i[0] for i in points ])
k = sum([ i[1] for i in points ])
if j != 0:
return k/j, j, k
return 1, j, k | python | def linOriginRegression(points):
j = sum([ i[0] for i in points ])
k = sum([ i[1] for i in points ])
if j != 0:
return k/j, j, k
return 1, j, k | [
"def",
"linOriginRegression",
"(",
"points",
")",
":",
"j",
"=",
"sum",
"(",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"points",
"]",
")",
"k",
"=",
"sum",
"(",
"[",
"i",
"[",
"1",
"]",
"for",
"i",
"in",
"points",
"]",
")",
"if",
"j",
"!="... | computes a linear regression starting at zero | [
"computes",
"a",
"linear",
"regression",
"starting",
"at",
"zero"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/misc.py#L28-L36 |
24,116 | benedictpaten/sonLib | misc.py | close | def close(i, j, tolerance):
"""
check two float values are within a bound of one another
"""
return i <= j + tolerance and i >= j - tolerance | python | def close(i, j, tolerance):
return i <= j + tolerance and i >= j - tolerance | [
"def",
"close",
"(",
"i",
",",
"j",
",",
"tolerance",
")",
":",
"return",
"i",
"<=",
"j",
"+",
"tolerance",
"and",
"i",
">=",
"j",
"-",
"tolerance"
] | check two float values are within a bound of one another | [
"check",
"two",
"float",
"values",
"are",
"within",
"a",
"bound",
"of",
"one",
"another"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/misc.py#L38-L42 |
24,117 | benedictpaten/sonLib | misc.py | filterOverlappingAlignments | def filterOverlappingAlignments(alignments):
"""Filter alignments to be non-overlapping.
"""
l = []
alignments = alignments[:]
sortAlignments(alignments)
alignments.reverse()
for pA1 in alignments:
for pA2 in l:
if pA1.contig1 == pA2.contig1 and getPositiveCoordinateRangeOverlap(pA1.start1+1, pA1.end1, pA2.start1+1, pA2.end1) is not None: #One offset, inclusive coordinates
break
if pA1.contig2 == pA2.contig2 and getPositiveCoordinateRangeOverlap(pA1.start2+1, pA1.end2, pA2.start2+1, pA2.end2) is not None: #One offset, inclusive coordinates
break
if pA1.contig2 == pA2.contig1 and getPositiveCoordinateRangeOverlap(pA1.start2+1, pA1.end2, pA2.start1+1, pA2.end1) is not None: #One offset, inclusive coordinates
break
if pA1.contig1 == pA2.contig2 and getPositiveCoordinateRangeOverlap(pA1.start1+1, pA1.end1, pA2.start2+1, pA2.end2) is not None: #One offset, inclusive coordinates
break
else:
l.append(pA1)
l.reverse()
return l | python | def filterOverlappingAlignments(alignments):
l = []
alignments = alignments[:]
sortAlignments(alignments)
alignments.reverse()
for pA1 in alignments:
for pA2 in l:
if pA1.contig1 == pA2.contig1 and getPositiveCoordinateRangeOverlap(pA1.start1+1, pA1.end1, pA2.start1+1, pA2.end1) is not None: #One offset, inclusive coordinates
break
if pA1.contig2 == pA2.contig2 and getPositiveCoordinateRangeOverlap(pA1.start2+1, pA1.end2, pA2.start2+1, pA2.end2) is not None: #One offset, inclusive coordinates
break
if pA1.contig2 == pA2.contig1 and getPositiveCoordinateRangeOverlap(pA1.start2+1, pA1.end2, pA2.start1+1, pA2.end1) is not None: #One offset, inclusive coordinates
break
if pA1.contig1 == pA2.contig2 and getPositiveCoordinateRangeOverlap(pA1.start1+1, pA1.end1, pA2.start2+1, pA2.end2) is not None: #One offset, inclusive coordinates
break
else:
l.append(pA1)
l.reverse()
return l | [
"def",
"filterOverlappingAlignments",
"(",
"alignments",
")",
":",
"l",
"=",
"[",
"]",
"alignments",
"=",
"alignments",
"[",
":",
"]",
"sortAlignments",
"(",
"alignments",
")",
"alignments",
".",
"reverse",
"(",
")",
"for",
"pA1",
"in",
"alignments",
":",
... | Filter alignments to be non-overlapping. | [
"Filter",
"alignments",
"to",
"be",
"non",
"-",
"overlapping",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/misc.py#L86-L106 |
24,118 | benedictpaten/sonLib | tree.py | binaryTree_depthFirstNumbers | def binaryTree_depthFirstNumbers(binaryTree, labelTree=True, dontStopAtID=True):
"""
get mid-order depth first tree numbers
"""
traversalIDs = {}
def traverse(binaryTree, mid=0, leafNo=0):
if binaryTree.internal and (dontStopAtID or binaryTree.iD is None):
midStart = mid
j, leafNo = traverse(binaryTree.left, mid, leafNo)
mid = j
j, leafNo = traverse(binaryTree.right, j+1, leafNo)
traversalIDs[binaryTree] = TraversalID(midStart, mid, j)
return j, leafNo
traversalID = TraversalID(mid, mid, mid+1)
traversalID.leafNo = leafNo
#thus nodes must be unique
traversalIDs[binaryTree] = traversalID
return mid+1, leafNo+1
traverse(binaryTree)
if labelTree:
for binaryTree in traversalIDs.keys():
binaryTree.traversalID = traversalIDs[binaryTree]
return traversalIDs | python | def binaryTree_depthFirstNumbers(binaryTree, labelTree=True, dontStopAtID=True):
traversalIDs = {}
def traverse(binaryTree, mid=0, leafNo=0):
if binaryTree.internal and (dontStopAtID or binaryTree.iD is None):
midStart = mid
j, leafNo = traverse(binaryTree.left, mid, leafNo)
mid = j
j, leafNo = traverse(binaryTree.right, j+1, leafNo)
traversalIDs[binaryTree] = TraversalID(midStart, mid, j)
return j, leafNo
traversalID = TraversalID(mid, mid, mid+1)
traversalID.leafNo = leafNo
#thus nodes must be unique
traversalIDs[binaryTree] = traversalID
return mid+1, leafNo+1
traverse(binaryTree)
if labelTree:
for binaryTree in traversalIDs.keys():
binaryTree.traversalID = traversalIDs[binaryTree]
return traversalIDs | [
"def",
"binaryTree_depthFirstNumbers",
"(",
"binaryTree",
",",
"labelTree",
"=",
"True",
",",
"dontStopAtID",
"=",
"True",
")",
":",
"traversalIDs",
"=",
"{",
"}",
"def",
"traverse",
"(",
"binaryTree",
",",
"mid",
"=",
"0",
",",
"leafNo",
"=",
"0",
")",
... | get mid-order depth first tree numbers | [
"get",
"mid",
"-",
"order",
"depth",
"first",
"tree",
"numbers"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L52-L74 |
24,119 | benedictpaten/sonLib | tree.py | binaryTree_nodeNames | def binaryTree_nodeNames(binaryTree):
"""
creates names for the leave and internal nodes
of the newick tree from the leaf labels
"""
def fn(binaryTree, labels):
if binaryTree.internal:
fn(binaryTree.left, labels)
fn(binaryTree.right, labels)
labels[binaryTree.traversalID.mid] = labels[binaryTree.left.traversalID.mid] + "_" + labels[binaryTree.right.traversalID.mid]
return labels[binaryTree.traversalID.mid]
else:
labels[binaryTree.traversalID.mid] = str(binaryTree.iD)
return labels[binaryTree.traversalID.mid]
labels = [None]*binaryTree.traversalID.midEnd
fn(binaryTree, labels)
return labels | python | def binaryTree_nodeNames(binaryTree):
def fn(binaryTree, labels):
if binaryTree.internal:
fn(binaryTree.left, labels)
fn(binaryTree.right, labels)
labels[binaryTree.traversalID.mid] = labels[binaryTree.left.traversalID.mid] + "_" + labels[binaryTree.right.traversalID.mid]
return labels[binaryTree.traversalID.mid]
else:
labels[binaryTree.traversalID.mid] = str(binaryTree.iD)
return labels[binaryTree.traversalID.mid]
labels = [None]*binaryTree.traversalID.midEnd
fn(binaryTree, labels)
return labels | [
"def",
"binaryTree_nodeNames",
"(",
"binaryTree",
")",
":",
"def",
"fn",
"(",
"binaryTree",
",",
"labels",
")",
":",
"if",
"binaryTree",
".",
"internal",
":",
"fn",
"(",
"binaryTree",
".",
"left",
",",
"labels",
")",
"fn",
"(",
"binaryTree",
".",
"right"... | creates names for the leave and internal nodes
of the newick tree from the leaf labels | [
"creates",
"names",
"for",
"the",
"leave",
"and",
"internal",
"nodes",
"of",
"the",
"newick",
"tree",
"from",
"the",
"leaf",
"labels"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L76-L92 |
24,120 | benedictpaten/sonLib | tree.py | makeRandomBinaryTree | def makeRandomBinaryTree(leafNodeNumber=None):
"""Creates a random binary tree.
"""
while True:
nodeNo = [-1]
def fn():
nodeNo[0] += 1
if random.random() > 0.6:
i = str(nodeNo[0])
return BinaryTree(0.00001 + random.random()*0.8, True, fn(), fn(), i)
else:
return BinaryTree(0.00001 + random.random()*0.8, False, None, None, str(nodeNo[0]))
tree = fn()
def fn2(tree):
if tree.internal:
return fn2(tree.left) + fn2(tree.right)
return 1
if leafNodeNumber is None or fn2(tree) == leafNodeNumber:
return tree | python | def makeRandomBinaryTree(leafNodeNumber=None):
while True:
nodeNo = [-1]
def fn():
nodeNo[0] += 1
if random.random() > 0.6:
i = str(nodeNo[0])
return BinaryTree(0.00001 + random.random()*0.8, True, fn(), fn(), i)
else:
return BinaryTree(0.00001 + random.random()*0.8, False, None, None, str(nodeNo[0]))
tree = fn()
def fn2(tree):
if tree.internal:
return fn2(tree.left) + fn2(tree.right)
return 1
if leafNodeNumber is None or fn2(tree) == leafNodeNumber:
return tree | [
"def",
"makeRandomBinaryTree",
"(",
"leafNodeNumber",
"=",
"None",
")",
":",
"while",
"True",
":",
"nodeNo",
"=",
"[",
"-",
"1",
"]",
"def",
"fn",
"(",
")",
":",
"nodeNo",
"[",
"0",
"]",
"+=",
"1",
"if",
"random",
".",
"random",
"(",
")",
">",
"0... | Creates a random binary tree. | [
"Creates",
"a",
"random",
"binary",
"tree",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L123-L141 |
24,121 | benedictpaten/sonLib | tree.py | getRandomBinaryTreeLeafNode | def getRandomBinaryTreeLeafNode(binaryTree):
"""Get random binary tree node.
"""
if binaryTree.internal == True:
if random.random() > 0.5:
return getRandomBinaryTreeLeafNode(binaryTree.left)
else:
return getRandomBinaryTreeLeafNode(binaryTree.right)
else:
return binaryTree | python | def getRandomBinaryTreeLeafNode(binaryTree):
if binaryTree.internal == True:
if random.random() > 0.5:
return getRandomBinaryTreeLeafNode(binaryTree.left)
else:
return getRandomBinaryTreeLeafNode(binaryTree.right)
else:
return binaryTree | [
"def",
"getRandomBinaryTreeLeafNode",
"(",
"binaryTree",
")",
":",
"if",
"binaryTree",
".",
"internal",
"==",
"True",
":",
"if",
"random",
".",
"random",
"(",
")",
">",
"0.5",
":",
"return",
"getRandomBinaryTreeLeafNode",
"(",
"binaryTree",
".",
"left",
")",
... | Get random binary tree node. | [
"Get",
"random",
"binary",
"tree",
"node",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L143-L152 |
24,122 | benedictpaten/sonLib | tree.py | transformByDistance | def transformByDistance(wV, subModel, alphabetSize=4):
"""
transform wV by given substitution matrix
"""
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | python | def transformByDistance(wV, subModel, alphabetSize=4):
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | [
"def",
"transformByDistance",
"(",
"wV",
",",
"subModel",
",",
"alphabetSize",
"=",
"4",
")",
":",
"nc",
"=",
"[",
"0.0",
"]",
"*",
"alphabetSize",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"alphabetSize",
")",
":",
"j",
"=",
"wV",
"[",
"i",
"]",
... | transform wV by given substitution matrix | [
"transform",
"wV",
"by",
"given",
"substitution",
"matrix"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L162-L172 |
24,123 | benedictpaten/sonLib | tree.py | normaliseWV | def normaliseWV(wV, normFac=1.0):
"""
make char probs divisible by one
"""
f = sum(wV) / normFac
return [ i/f for i in wV ] | python | def normaliseWV(wV, normFac=1.0):
f = sum(wV) / normFac
return [ i/f for i in wV ] | [
"def",
"normaliseWV",
"(",
"wV",
",",
"normFac",
"=",
"1.0",
")",
":",
"f",
"=",
"sum",
"(",
"wV",
")",
"/",
"normFac",
"return",
"[",
"i",
"/",
"f",
"for",
"i",
"in",
"wV",
"]"
] | make char probs divisible by one | [
"make",
"char",
"probs",
"divisible",
"by",
"one"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L180-L185 |
24,124 | benedictpaten/sonLib | tree.py | felsensteins | def felsensteins(binaryTree, subMatrices, ancestorProbs, leaves, alphabetSize):
"""
calculates the un-normalised probabilties of each non-gap residue position
"""
l = {}
def upPass(binaryTree):
if binaryTree.internal: #is internal binaryTree
i = branchUp(binaryTree.left)
j = branchUp(binaryTree.right)
k = multiplyWV(i, j, alphabetSize)
l[binaryTree.traversalID.mid] = (k, i, j)
return k
l[binaryTree.traversalID.mid] = leaves[binaryTree.traversalID.leafNo]
return leaves[binaryTree.traversalID.leafNo]
def downPass(binaryTree, ancestorProbs):
if binaryTree.internal: #is internal binaryTree
i = l[binaryTree.traversalID.mid]
l[binaryTree.traversalID.mid] = multiplyWV(ancestorProbs, i[0], alphabetSize)
branchDown(binaryTree.left, multiplyWV(ancestorProbs, i[2], alphabetSize))
branchDown(binaryTree.right, multiplyWV(ancestorProbs, i[1], alphabetSize))
def branchUp(binaryTree):
return transformByDistance(upPass(binaryTree), subMatrices[binaryTree.traversalID.mid], alphabetSize)
def branchDown(binaryTree, ancestorProbs):
downPass(binaryTree, transformByDistance(ancestorProbs, subMatrices[binaryTree.traversalID.mid], alphabetSize))
upPass(binaryTree)
downPass(binaryTree, ancestorProbs)
return l | python | def felsensteins(binaryTree, subMatrices, ancestorProbs, leaves, alphabetSize):
l = {}
def upPass(binaryTree):
if binaryTree.internal: #is internal binaryTree
i = branchUp(binaryTree.left)
j = branchUp(binaryTree.right)
k = multiplyWV(i, j, alphabetSize)
l[binaryTree.traversalID.mid] = (k, i, j)
return k
l[binaryTree.traversalID.mid] = leaves[binaryTree.traversalID.leafNo]
return leaves[binaryTree.traversalID.leafNo]
def downPass(binaryTree, ancestorProbs):
if binaryTree.internal: #is internal binaryTree
i = l[binaryTree.traversalID.mid]
l[binaryTree.traversalID.mid] = multiplyWV(ancestorProbs, i[0], alphabetSize)
branchDown(binaryTree.left, multiplyWV(ancestorProbs, i[2], alphabetSize))
branchDown(binaryTree.right, multiplyWV(ancestorProbs, i[1], alphabetSize))
def branchUp(binaryTree):
return transformByDistance(upPass(binaryTree), subMatrices[binaryTree.traversalID.mid], alphabetSize)
def branchDown(binaryTree, ancestorProbs):
downPass(binaryTree, transformByDistance(ancestorProbs, subMatrices[binaryTree.traversalID.mid], alphabetSize))
upPass(binaryTree)
downPass(binaryTree, ancestorProbs)
return l | [
"def",
"felsensteins",
"(",
"binaryTree",
",",
"subMatrices",
",",
"ancestorProbs",
",",
"leaves",
",",
"alphabetSize",
")",
":",
"l",
"=",
"{",
"}",
"def",
"upPass",
"(",
"binaryTree",
")",
":",
"if",
"binaryTree",
".",
"internal",
":",
"#is internal binary... | calculates the un-normalised probabilties of each non-gap residue position | [
"calculates",
"the",
"un",
"-",
"normalised",
"probabilties",
"of",
"each",
"non",
"-",
"gap",
"residue",
"position"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L194-L220 |
24,125 | benedictpaten/sonLib | tree.py | annotateTree | def annotateTree(bT, fn):
"""
annotate a tree in an external array using the given function
"""
l = [None]*bT.traversalID.midEnd
def fn2(bT):
l[bT.traversalID.mid] = fn(bT)
if bT.internal:
fn2(bT.left)
fn2(bT.right)
fn2(bT)
return l | python | def annotateTree(bT, fn):
l = [None]*bT.traversalID.midEnd
def fn2(bT):
l[bT.traversalID.mid] = fn(bT)
if bT.internal:
fn2(bT.left)
fn2(bT.right)
fn2(bT)
return l | [
"def",
"annotateTree",
"(",
"bT",
",",
"fn",
")",
":",
"l",
"=",
"[",
"None",
"]",
"*",
"bT",
".",
"traversalID",
".",
"midEnd",
"def",
"fn2",
"(",
"bT",
")",
":",
"l",
"[",
"bT",
".",
"traversalID",
".",
"mid",
"]",
"=",
"fn",
"(",
"bT",
")"... | annotate a tree in an external array using the given function | [
"annotate",
"a",
"tree",
"in",
"an",
"external",
"array",
"using",
"the",
"given",
"function"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L543-L554 |
24,126 | benedictpaten/sonLib | tree.py | remodelTreeRemovingRoot | def remodelTreeRemovingRoot(root, node):
"""
Node is mid order number
"""
import bioio
assert root.traversalID.mid != node
hash = {}
def fn(bT):
if bT.traversalID.mid == node:
assert bT.internal == False
return [ bT ]
elif bT.internal:
i = fn(bT.left)
if i is None:
i = fn(bT.right)
if i is not None:
hash[i[-1]]= bT
i.append(bT)
return i
return None
l = fn(root)
def fn2(i, j):
if i.left == j:
return i.right
assert i.right == j
return i.left
def fn3(bT):
if hash[bT] == root:
s = '(' + bioio.printBinaryTree(fn2(hash[bT], bT), bT, True)[:-1] + ')'
else:
s = '(' + bioio.printBinaryTree(fn2(hash[bT], bT), bT, True)[:-1] + ',' + fn3(hash[bT]) + ')'
return s + ":" + str(bT.distance)
s = fn3(l[0]) + ';'
t = bioio.newickTreeParser(s)
return t | python | def remodelTreeRemovingRoot(root, node):
import bioio
assert root.traversalID.mid != node
hash = {}
def fn(bT):
if bT.traversalID.mid == node:
assert bT.internal == False
return [ bT ]
elif bT.internal:
i = fn(bT.left)
if i is None:
i = fn(bT.right)
if i is not None:
hash[i[-1]]= bT
i.append(bT)
return i
return None
l = fn(root)
def fn2(i, j):
if i.left == j:
return i.right
assert i.right == j
return i.left
def fn3(bT):
if hash[bT] == root:
s = '(' + bioio.printBinaryTree(fn2(hash[bT], bT), bT, True)[:-1] + ')'
else:
s = '(' + bioio.printBinaryTree(fn2(hash[bT], bT), bT, True)[:-1] + ',' + fn3(hash[bT]) + ')'
return s + ":" + str(bT.distance)
s = fn3(l[0]) + ';'
t = bioio.newickTreeParser(s)
return t | [
"def",
"remodelTreeRemovingRoot",
"(",
"root",
",",
"node",
")",
":",
"import",
"bioio",
"assert",
"root",
".",
"traversalID",
".",
"mid",
"!=",
"node",
"hash",
"=",
"{",
"}",
"def",
"fn",
"(",
"bT",
")",
":",
"if",
"bT",
".",
"traversalID",
".",
"mi... | Node is mid order number | [
"Node",
"is",
"mid",
"order",
"number"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L595-L629 |
24,127 | benedictpaten/sonLib | tree.py | moveRoot | def moveRoot(root, branch):
"""
Removes the old root and places the new root at the mid point along the given branch
"""
import bioio
if root.traversalID.mid == branch:
return bioio.newickTreeParser(bioio.printBinaryTree(root, True))
def fn2(tree, seq):
if seq is not None:
return '(' + bioio.printBinaryTree(tree, True)[:-1] + ',' + seq + ')'
return bioio.printBinaryTree(tree, True)[:-1]
def fn(tree, seq):
if tree.traversalID.mid == branch:
i = tree.distance
tree.distance /= 2
seq = '(' + bioio.printBinaryTree(tree, True)[:-1] + ',(' + seq + ('):%s' % tree.distance) + ');'
tree.distance = i
return seq
if tree.internal:
if branch < tree.traversalID.mid:
seq = fn2(tree.right, seq)
return fn(tree.left, seq)
else:
assert branch > tree.traversalID.mid
seq = fn2(tree.left, seq)
return fn(tree.right, seq)
else:
return bioio.printBinaryTree(tree, True)[:-1]
s = fn(root, None)
return bioio.newickTreeParser(s) | python | def moveRoot(root, branch):
import bioio
if root.traversalID.mid == branch:
return bioio.newickTreeParser(bioio.printBinaryTree(root, True))
def fn2(tree, seq):
if seq is not None:
return '(' + bioio.printBinaryTree(tree, True)[:-1] + ',' + seq + ')'
return bioio.printBinaryTree(tree, True)[:-1]
def fn(tree, seq):
if tree.traversalID.mid == branch:
i = tree.distance
tree.distance /= 2
seq = '(' + bioio.printBinaryTree(tree, True)[:-1] + ',(' + seq + ('):%s' % tree.distance) + ');'
tree.distance = i
return seq
if tree.internal:
if branch < tree.traversalID.mid:
seq = fn2(tree.right, seq)
return fn(tree.left, seq)
else:
assert branch > tree.traversalID.mid
seq = fn2(tree.left, seq)
return fn(tree.right, seq)
else:
return bioio.printBinaryTree(tree, True)[:-1]
s = fn(root, None)
return bioio.newickTreeParser(s) | [
"def",
"moveRoot",
"(",
"root",
",",
"branch",
")",
":",
"import",
"bioio",
"if",
"root",
".",
"traversalID",
".",
"mid",
"==",
"branch",
":",
"return",
"bioio",
".",
"newickTreeParser",
"(",
"bioio",
".",
"printBinaryTree",
"(",
"root",
",",
"True",
")"... | Removes the old root and places the new root at the mid point along the given branch | [
"Removes",
"the",
"old",
"root",
"and",
"places",
"the",
"new",
"root",
"at",
"the",
"mid",
"point",
"along",
"the",
"given",
"branch"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L631-L660 |
24,128 | benedictpaten/sonLib | tree.py | checkGeneTreeMatchesSpeciesTree | def checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID):
"""
Function to check ids in gene tree all match nodes in species tree
"""
def fn(tree, l):
if tree.internal:
fn(tree.left, l)
fn(tree.right, l)
else:
l.append(processID(tree.iD))
l = []
fn(speciesTree, l)
l2 = []
fn(geneTree, l2)
for i in l2:
#print "node", i, l
assert i in l | python | def checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID):
def fn(tree, l):
if tree.internal:
fn(tree.left, l)
fn(tree.right, l)
else:
l.append(processID(tree.iD))
l = []
fn(speciesTree, l)
l2 = []
fn(geneTree, l2)
for i in l2:
#print "node", i, l
assert i in l | [
"def",
"checkGeneTreeMatchesSpeciesTree",
"(",
"speciesTree",
",",
"geneTree",
",",
"processID",
")",
":",
"def",
"fn",
"(",
"tree",
",",
"l",
")",
":",
"if",
"tree",
".",
"internal",
":",
"fn",
"(",
"tree",
".",
"left",
",",
"l",
")",
"fn",
"(",
"tr... | Function to check ids in gene tree all match nodes in species tree | [
"Function",
"to",
"check",
"ids",
"in",
"gene",
"tree",
"all",
"match",
"nodes",
"in",
"species",
"tree"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L662-L678 |
24,129 | benedictpaten/sonLib | tree.py | calculateProbableRootOfGeneTree | def calculateProbableRootOfGeneTree(speciesTree, geneTree, processID=lambda x : x):
"""
Goes through each root possible branch making it the root.
Returns tree that requires the minimum number of duplications.
"""
#get all rooted trees
#run dup calc on each tree
#return tree with fewest number of dups
if geneTree.traversalID.midEnd <= 3:
return (0, 0, geneTree)
checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID)
l = []
def fn(tree):
if tree.traversalID.mid != geneTree.left.traversalID.mid and tree.traversalID.mid != geneTree.right.traversalID.mid:
newGeneTree = moveRoot(geneTree, tree.traversalID.mid)
binaryTree_depthFirstNumbers(newGeneTree)
dupCount, lossCount = calculateDupsAndLossesByReconcilingTrees(speciesTree, newGeneTree, processID)
l.append((dupCount, lossCount, newGeneTree))
if tree.internal:
fn(tree.left)
fn(tree.right)
fn(geneTree)
l.sort()
return l[0][2], l[0][0], l[0][1] | python | def calculateProbableRootOfGeneTree(speciesTree, geneTree, processID=lambda x : x):
#get all rooted trees
#run dup calc on each tree
#return tree with fewest number of dups
if geneTree.traversalID.midEnd <= 3:
return (0, 0, geneTree)
checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID)
l = []
def fn(tree):
if tree.traversalID.mid != geneTree.left.traversalID.mid and tree.traversalID.mid != geneTree.right.traversalID.mid:
newGeneTree = moveRoot(geneTree, tree.traversalID.mid)
binaryTree_depthFirstNumbers(newGeneTree)
dupCount, lossCount = calculateDupsAndLossesByReconcilingTrees(speciesTree, newGeneTree, processID)
l.append((dupCount, lossCount, newGeneTree))
if tree.internal:
fn(tree.left)
fn(tree.right)
fn(geneTree)
l.sort()
return l[0][2], l[0][0], l[0][1] | [
"def",
"calculateProbableRootOfGeneTree",
"(",
"speciesTree",
",",
"geneTree",
",",
"processID",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"#get all rooted trees",
"#run dup calc on each tree",
"#return tree with fewest number of dups",
"if",
"geneTree",
".",
"traversalID",
... | Goes through each root possible branch making it the root.
Returns tree that requires the minimum number of duplications. | [
"Goes",
"through",
"each",
"root",
"possible",
"branch",
"making",
"it",
"the",
"root",
".",
"Returns",
"tree",
"that",
"requires",
"the",
"minimum",
"number",
"of",
"duplications",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/tree.py#L753-L776 |
24,130 | benedictpaten/sonLib | bioio.py | redirectLoggerStreamHandlers | def redirectLoggerStreamHandlers(oldStream, newStream):
"""Redirect the stream of a stream handler to a different stream
"""
for handler in list(logger.handlers): #Remove old handlers
if handler.stream == oldStream:
handler.close()
logger.removeHandler(handler)
for handler in logger.handlers: #Do not add a duplicate handler
if handler.stream == newStream:
return
logger.addHandler(logging.StreamHandler(newStream)) | python | def redirectLoggerStreamHandlers(oldStream, newStream):
for handler in list(logger.handlers): #Remove old handlers
if handler.stream == oldStream:
handler.close()
logger.removeHandler(handler)
for handler in logger.handlers: #Do not add a duplicate handler
if handler.stream == newStream:
return
logger.addHandler(logging.StreamHandler(newStream)) | [
"def",
"redirectLoggerStreamHandlers",
"(",
"oldStream",
",",
"newStream",
")",
":",
"for",
"handler",
"in",
"list",
"(",
"logger",
".",
"handlers",
")",
":",
"#Remove old handlers",
"if",
"handler",
".",
"stream",
"==",
"oldStream",
":",
"handler",
".",
"clos... | Redirect the stream of a stream handler to a different stream | [
"Redirect",
"the",
"stream",
"of",
"a",
"stream",
"handler",
"to",
"a",
"different",
"stream"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L52-L62 |
24,131 | benedictpaten/sonLib | bioio.py | popen | def popen(command, tempFile):
"""Runs a command and captures standard out in the given temp file.
"""
fileHandle = open(tempFile, 'w')
logger.debug("Running the command: %s" % command)
sts = subprocess.call(command, shell=True, stdout=fileHandle, bufsize=-1)
fileHandle.close()
if sts != 0:
raise RuntimeError("Command: %s exited with non-zero status %i" % (command, sts))
return sts | python | def popen(command, tempFile):
fileHandle = open(tempFile, 'w')
logger.debug("Running the command: %s" % command)
sts = subprocess.call(command, shell=True, stdout=fileHandle, bufsize=-1)
fileHandle.close()
if sts != 0:
raise RuntimeError("Command: %s exited with non-zero status %i" % (command, sts))
return sts | [
"def",
"popen",
"(",
"command",
",",
"tempFile",
")",
":",
"fileHandle",
"=",
"open",
"(",
"tempFile",
",",
"'w'",
")",
"logger",
".",
"debug",
"(",
"\"Running the command: %s\"",
"%",
"command",
")",
"sts",
"=",
"subprocess",
".",
"call",
"(",
"command",
... | Runs a command and captures standard out in the given temp file. | [
"Runs",
"a",
"command",
"and",
"captures",
"standard",
"out",
"in",
"the",
"given",
"temp",
"file",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L188-L197 |
24,132 | benedictpaten/sonLib | bioio.py | popenCatch | def popenCatch(command, stdinString=None):
"""Runs a command and return standard out.
"""
logger.debug("Running the command: %s" % command)
if stdinString != None:
process = subprocess.Popen(command, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=-1)
output, nothing = process.communicate(stdinString)
else:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=sys.stderr, bufsize=-1)
output, nothing = process.communicate() #process.stdout.read().strip()
sts = process.wait()
if sts != 0:
raise RuntimeError("Command: %s with stdin string '%s' exited with non-zero status %i" % (command, stdinString, sts))
return output | python | def popenCatch(command, stdinString=None):
logger.debug("Running the command: %s" % command)
if stdinString != None:
process = subprocess.Popen(command, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=-1)
output, nothing = process.communicate(stdinString)
else:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=sys.stderr, bufsize=-1)
output, nothing = process.communicate() #process.stdout.read().strip()
sts = process.wait()
if sts != 0:
raise RuntimeError("Command: %s with stdin string '%s' exited with non-zero status %i" % (command, stdinString, sts))
return output | [
"def",
"popenCatch",
"(",
"command",
",",
"stdinString",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"Running the command: %s\"",
"%",
"command",
")",
"if",
"stdinString",
"!=",
"None",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command... | Runs a command and return standard out. | [
"Runs",
"a",
"command",
"and",
"return",
"standard",
"out",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L199-L213 |
24,133 | benedictpaten/sonLib | bioio.py | getTotalCpuTimeAndMemoryUsage | def getTotalCpuTimeAndMemoryUsage():
"""Gives the total cpu time and memory usage of itself and its children.
"""
me = resource.getrusage(resource.RUSAGE_SELF)
childs = resource.getrusage(resource.RUSAGE_CHILDREN)
totalCpuTime = me.ru_utime+me.ru_stime+childs.ru_utime+childs.ru_stime
totalMemoryUsage = me.ru_maxrss+ me.ru_maxrss
return totalCpuTime, totalMemoryUsage | python | def getTotalCpuTimeAndMemoryUsage():
me = resource.getrusage(resource.RUSAGE_SELF)
childs = resource.getrusage(resource.RUSAGE_CHILDREN)
totalCpuTime = me.ru_utime+me.ru_stime+childs.ru_utime+childs.ru_stime
totalMemoryUsage = me.ru_maxrss+ me.ru_maxrss
return totalCpuTime, totalMemoryUsage | [
"def",
"getTotalCpuTimeAndMemoryUsage",
"(",
")",
":",
"me",
"=",
"resource",
".",
"getrusage",
"(",
"resource",
".",
"RUSAGE_SELF",
")",
"childs",
"=",
"resource",
".",
"getrusage",
"(",
"resource",
".",
"RUSAGE_CHILDREN",
")",
"totalCpuTime",
"=",
"me",
".",... | Gives the total cpu time and memory usage of itself and its children. | [
"Gives",
"the",
"total",
"cpu",
"time",
"and",
"memory",
"usage",
"of",
"itself",
"and",
"its",
"children",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L231-L238 |
24,134 | benedictpaten/sonLib | bioio.py | saveInputs | def saveInputs(savedInputsDir, listOfFilesAndDirsToSave):
"""Copies the list of files to a directory created in the save inputs dir,
and returns the name of this directory.
"""
logger.info("Saving the inputs: %s to the directory: %s" % (" ".join(listOfFilesAndDirsToSave), savedInputsDir))
assert os.path.isdir(savedInputsDir)
#savedInputsDir = getTempDirectory(saveInputsDir)
createdFiles = []
for fileName in listOfFilesAndDirsToSave:
if os.path.isfile(fileName):
copiedFileName = os.path.join(savedInputsDir, os.path.split(fileName)[-1])
system("cp %s %s" % (fileName, copiedFileName))
else:
copiedFileName = os.path.join(savedInputsDir, os.path.split(fileName)[-1]) + ".tar"
system("tar -cf %s %s" % (copiedFileName, fileName))
createdFiles.append(copiedFileName)
return createdFiles | python | def saveInputs(savedInputsDir, listOfFilesAndDirsToSave):
logger.info("Saving the inputs: %s to the directory: %s" % (" ".join(listOfFilesAndDirsToSave), savedInputsDir))
assert os.path.isdir(savedInputsDir)
#savedInputsDir = getTempDirectory(saveInputsDir)
createdFiles = []
for fileName in listOfFilesAndDirsToSave:
if os.path.isfile(fileName):
copiedFileName = os.path.join(savedInputsDir, os.path.split(fileName)[-1])
system("cp %s %s" % (fileName, copiedFileName))
else:
copiedFileName = os.path.join(savedInputsDir, os.path.split(fileName)[-1]) + ".tar"
system("tar -cf %s %s" % (copiedFileName, fileName))
createdFiles.append(copiedFileName)
return createdFiles | [
"def",
"saveInputs",
"(",
"savedInputsDir",
",",
"listOfFilesAndDirsToSave",
")",
":",
"logger",
".",
"info",
"(",
"\"Saving the inputs: %s to the directory: %s\"",
"%",
"(",
"\" \"",
".",
"join",
"(",
"listOfFilesAndDirsToSave",
")",
",",
"savedInputsDir",
")",
")",
... | Copies the list of files to a directory created in the save inputs dir,
and returns the name of this directory. | [
"Copies",
"the",
"list",
"of",
"files",
"to",
"a",
"directory",
"created",
"in",
"the",
"save",
"inputs",
"dir",
"and",
"returns",
"the",
"name",
"of",
"this",
"directory",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L318-L334 |
24,135 | benedictpaten/sonLib | bioio.py | nameValue | def nameValue(name, value, valueType=str, quotes=False):
"""Little function to make it easier to make name value strings for commands.
"""
if valueType == bool:
if value:
return "--%s" % name
return ""
if value is None:
return ""
if quotes:
return "--%s '%s'" % (name, valueType(value))
return "--%s %s" % (name, valueType(value)) | python | def nameValue(name, value, valueType=str, quotes=False):
if valueType == bool:
if value:
return "--%s" % name
return ""
if value is None:
return ""
if quotes:
return "--%s '%s'" % (name, valueType(value))
return "--%s %s" % (name, valueType(value)) | [
"def",
"nameValue",
"(",
"name",
",",
"value",
",",
"valueType",
"=",
"str",
",",
"quotes",
"=",
"False",
")",
":",
"if",
"valueType",
"==",
"bool",
":",
"if",
"value",
":",
"return",
"\"--%s\"",
"%",
"name",
"return",
"\"\"",
"if",
"value",
"is",
"N... | Little function to make it easier to make name value strings for commands. | [
"Little",
"function",
"to",
"make",
"it",
"easier",
"to",
"make",
"name",
"value",
"strings",
"for",
"commands",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L400-L411 |
24,136 | benedictpaten/sonLib | bioio.py | makeSubDir | def makeSubDir(dirName):
"""Makes a given subdirectory if it doesn't already exist, making sure it us public.
"""
if not os.path.exists(dirName):
os.mkdir(dirName)
os.chmod(dirName, 0777)
return dirName | python | def makeSubDir(dirName):
if not os.path.exists(dirName):
os.mkdir(dirName)
os.chmod(dirName, 0777)
return dirName | [
"def",
"makeSubDir",
"(",
"dirName",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
")",
":",
"os",
".",
"mkdir",
"(",
"dirName",
")",
"os",
".",
"chmod",
"(",
"dirName",
",",
"0777",
")",
"return",
"dirName"
] | Makes a given subdirectory if it doesn't already exist, making sure it us public. | [
"Makes",
"a",
"given",
"subdirectory",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"making",
"sure",
"it",
"us",
"public",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L426-L432 |
24,137 | benedictpaten/sonLib | bioio.py | getTempFile | def getTempFile(suffix="", rootDir=None):
"""Returns a string representing a temporary file, that must be manually deleted
"""
if rootDir is None:
handle, tmpFile = tempfile.mkstemp(suffix)
os.close(handle)
return tmpFile
else:
tmpFile = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString() + suffix)
open(tmpFile, 'w').close()
os.chmod(tmpFile, 0777) #Ensure everyone has access to the file.
return tmpFile | python | def getTempFile(suffix="", rootDir=None):
if rootDir is None:
handle, tmpFile = tempfile.mkstemp(suffix)
os.close(handle)
return tmpFile
else:
tmpFile = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString() + suffix)
open(tmpFile, 'w').close()
os.chmod(tmpFile, 0777) #Ensure everyone has access to the file.
return tmpFile | [
"def",
"getTempFile",
"(",
"suffix",
"=",
"\"\"",
",",
"rootDir",
"=",
"None",
")",
":",
"if",
"rootDir",
"is",
"None",
":",
"handle",
",",
"tmpFile",
"=",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
")",
"os",
".",
"close",
"(",
"handle",
")",
"retur... | Returns a string representing a temporary file, that must be manually deleted | [
"Returns",
"a",
"string",
"representing",
"a",
"temporary",
"file",
"that",
"must",
"be",
"manually",
"deleted"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L434-L445 |
24,138 | benedictpaten/sonLib | bioio.py | getTempDirectory | def getTempDirectory(rootDir=None):
"""
returns a temporary directory that must be manually deleted. rootDir will be
created if it does not exist.
"""
if rootDir is None:
return tempfile.mkdtemp()
else:
if not os.path.exists(rootDir):
try:
os.makedirs(rootDir)
except OSError:
# Maybe it got created between the test and the makedirs call?
pass
while True:
# Keep trying names until we find one that doesn't exist. If one
# does exist, don't nest inside it, because someone else may be
# using it for something.
tmpDir = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString())
if not os.path.exists(tmpDir):
break
os.mkdir(tmpDir)
os.chmod(tmpDir, 0777) #Ensure everyone has access to the file.
return tmpDir | python | def getTempDirectory(rootDir=None):
if rootDir is None:
return tempfile.mkdtemp()
else:
if not os.path.exists(rootDir):
try:
os.makedirs(rootDir)
except OSError:
# Maybe it got created between the test and the makedirs call?
pass
while True:
# Keep trying names until we find one that doesn't exist. If one
# does exist, don't nest inside it, because someone else may be
# using it for something.
tmpDir = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString())
if not os.path.exists(tmpDir):
break
os.mkdir(tmpDir)
os.chmod(tmpDir, 0777) #Ensure everyone has access to the file.
return tmpDir | [
"def",
"getTempDirectory",
"(",
"rootDir",
"=",
"None",
")",
":",
"if",
"rootDir",
"is",
"None",
":",
"return",
"tempfile",
".",
"mkdtemp",
"(",
")",
"else",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"rootDir",
")",
":",
"try",
":",
... | returns a temporary directory that must be manually deleted. rootDir will be
created if it does not exist. | [
"returns",
"a",
"temporary",
"directory",
"that",
"must",
"be",
"manually",
"deleted",
".",
"rootDir",
"will",
"be",
"created",
"if",
"it",
"does",
"not",
"exist",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L447-L472 |
24,139 | benedictpaten/sonLib | bioio.py | catFiles | def catFiles(filesToCat, catFile):
"""Cats a bunch of files into one file. Ensures a no more than maxCat files
are concatenated at each step.
"""
if len(filesToCat) == 0: #We must handle this case or the cat call will hang waiting for input
open(catFile, 'w').close()
return
maxCat = 25
system("cat %s > %s" % (" ".join(filesToCat[:maxCat]), catFile))
filesToCat = filesToCat[maxCat:]
while len(filesToCat) > 0:
system("cat %s >> %s" % (" ".join(filesToCat[:maxCat]), catFile))
filesToCat = filesToCat[maxCat:] | python | def catFiles(filesToCat, catFile):
if len(filesToCat) == 0: #We must handle this case or the cat call will hang waiting for input
open(catFile, 'w').close()
return
maxCat = 25
system("cat %s > %s" % (" ".join(filesToCat[:maxCat]), catFile))
filesToCat = filesToCat[maxCat:]
while len(filesToCat) > 0:
system("cat %s >> %s" % (" ".join(filesToCat[:maxCat]), catFile))
filesToCat = filesToCat[maxCat:] | [
"def",
"catFiles",
"(",
"filesToCat",
",",
"catFile",
")",
":",
"if",
"len",
"(",
"filesToCat",
")",
"==",
"0",
":",
"#We must handle this case or the cat call will hang waiting for input",
"open",
"(",
"catFile",
",",
"'w'",
")",
".",
"close",
"(",
")",
"return... | Cats a bunch of files into one file. Ensures a no more than maxCat files
are concatenated at each step. | [
"Cats",
"a",
"bunch",
"of",
"files",
"into",
"one",
"file",
".",
"Ensures",
"a",
"no",
"more",
"than",
"maxCat",
"files",
"are",
"concatenated",
"at",
"each",
"step",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L651-L663 |
24,140 | benedictpaten/sonLib | bioio.py | prettyXml | def prettyXml(elem):
""" Return a pretty-printed XML string for the ElementTree Element.
"""
roughString = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(roughString)
return reparsed.toprettyxml(indent=" ") | python | def prettyXml(elem):
roughString = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(roughString)
return reparsed.toprettyxml(indent=" ") | [
"def",
"prettyXml",
"(",
"elem",
")",
":",
"roughString",
"=",
"ET",
".",
"tostring",
"(",
"elem",
",",
"\"utf-8\"",
")",
"reparsed",
"=",
"minidom",
".",
"parseString",
"(",
"roughString",
")",
"return",
"reparsed",
".",
"toprettyxml",
"(",
"indent",
"=",... | Return a pretty-printed XML string for the ElementTree Element. | [
"Return",
"a",
"pretty",
"-",
"printed",
"XML",
"string",
"for",
"the",
"ElementTree",
"Element",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L665-L670 |
24,141 | benedictpaten/sonLib | bioio.py | fastaEncodeHeader | def fastaEncodeHeader(attributes):
"""Decodes the fasta header
"""
for i in attributes:
assert len(str(i).split()) == 1
return "|".join([ str(i) for i in attributes ]) | python | def fastaEncodeHeader(attributes):
for i in attributes:
assert len(str(i).split()) == 1
return "|".join([ str(i) for i in attributes ]) | [
"def",
"fastaEncodeHeader",
"(",
"attributes",
")",
":",
"for",
"i",
"in",
"attributes",
":",
"assert",
"len",
"(",
"str",
"(",
"i",
")",
".",
"split",
"(",
")",
")",
"==",
"1",
"return",
"\"|\"",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for... | Decodes the fasta header | [
"Decodes",
"the",
"fasta",
"header"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L700-L705 |
24,142 | benedictpaten/sonLib | bioio.py | fastaWrite | def fastaWrite(fileHandleOrFile, name, seq, mode="w"):
"""Writes out fasta file
"""
fileHandle = _getFileHandle(fileHandleOrFile, mode)
valid_chars = {x for x in string.ascii_letters + "-"}
try:
assert any([isinstance(seq, unicode), isinstance(seq, str)])
except AssertionError:
raise RuntimeError("Sequence is not unicode or string")
try:
assert all(x in valid_chars for x in seq)
except AssertionError:
bad_chars = {x for x in seq if x not in valid_chars}
raise RuntimeError("Invalid FASTA character(s) see in fasta sequence: {}".format(bad_chars))
fileHandle.write(">%s\n" % name)
chunkSize = 100
for i in xrange(0, len(seq), chunkSize):
fileHandle.write("%s\n" % seq[i:i+chunkSize])
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close() | python | def fastaWrite(fileHandleOrFile, name, seq, mode="w"):
fileHandle = _getFileHandle(fileHandleOrFile, mode)
valid_chars = {x for x in string.ascii_letters + "-"}
try:
assert any([isinstance(seq, unicode), isinstance(seq, str)])
except AssertionError:
raise RuntimeError("Sequence is not unicode or string")
try:
assert all(x in valid_chars for x in seq)
except AssertionError:
bad_chars = {x for x in seq if x not in valid_chars}
raise RuntimeError("Invalid FASTA character(s) see in fasta sequence: {}".format(bad_chars))
fileHandle.write(">%s\n" % name)
chunkSize = 100
for i in xrange(0, len(seq), chunkSize):
fileHandle.write("%s\n" % seq[i:i+chunkSize])
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close() | [
"def",
"fastaWrite",
"(",
"fileHandleOrFile",
",",
"name",
",",
"seq",
",",
"mode",
"=",
"\"w\"",
")",
":",
"fileHandle",
"=",
"_getFileHandle",
"(",
"fileHandleOrFile",
",",
"mode",
")",
"valid_chars",
"=",
"{",
"x",
"for",
"x",
"in",
"string",
".",
"as... | Writes out fasta file | [
"Writes",
"out",
"fasta",
"file"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L741-L760 |
24,143 | benedictpaten/sonLib | bioio.py | fastqRead | def fastqRead(fileHandleOrFile):
"""Reads a fastq file iteratively
"""
fileHandle = _getFileHandle(fileHandleOrFile)
line = fileHandle.readline()
while line != '':
if line[0] == '@':
name = line[1:-1]
seq = fileHandle.readline()[:-1]
plus = fileHandle.readline()
if plus[0] != '+':
raise RuntimeError("Got unexpected line: %s" % plus)
qualValues = [ ord(i) for i in fileHandle.readline()[:-1] ]
if len(seq) != len(qualValues):
logger.critical("Got a mismatch between the number of sequence characters (%s) and number of qual values (%s) for sequence: %s, ignoring returning None" % (len(seq), len(qualValues), name))
qualValues = None
else:
for i in qualValues:
if i < 33 or i > 126:
raise RuntimeError("Got a qual value out of range %s (range is 33 to 126)" % i)
for i in seq:
#For safety and sanity I only allows roman alphabet characters in fasta sequences.
if not ((i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z') or i == '-'):
raise RuntimeError("Invalid FASTQ character, ASCII code = \'%d\', found in input sequence %s" % (ord(i), name))
yield name, seq, qualValues
line = fileHandle.readline()
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close() | python | def fastqRead(fileHandleOrFile):
fileHandle = _getFileHandle(fileHandleOrFile)
line = fileHandle.readline()
while line != '':
if line[0] == '@':
name = line[1:-1]
seq = fileHandle.readline()[:-1]
plus = fileHandle.readline()
if plus[0] != '+':
raise RuntimeError("Got unexpected line: %s" % plus)
qualValues = [ ord(i) for i in fileHandle.readline()[:-1] ]
if len(seq) != len(qualValues):
logger.critical("Got a mismatch between the number of sequence characters (%s) and number of qual values (%s) for sequence: %s, ignoring returning None" % (len(seq), len(qualValues), name))
qualValues = None
else:
for i in qualValues:
if i < 33 or i > 126:
raise RuntimeError("Got a qual value out of range %s (range is 33 to 126)" % i)
for i in seq:
#For safety and sanity I only allows roman alphabet characters in fasta sequences.
if not ((i >= 'A' and i <= 'Z') or (i >= 'a' and i <= 'z') or i == '-'):
raise RuntimeError("Invalid FASTQ character, ASCII code = \'%d\', found in input sequence %s" % (ord(i), name))
yield name, seq, qualValues
line = fileHandle.readline()
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close() | [
"def",
"fastqRead",
"(",
"fileHandleOrFile",
")",
":",
"fileHandle",
"=",
"_getFileHandle",
"(",
"fileHandleOrFile",
")",
"line",
"=",
"fileHandle",
".",
"readline",
"(",
")",
"while",
"line",
"!=",
"''",
":",
"if",
"line",
"[",
"0",
"]",
"==",
"'@'",
":... | Reads a fastq file iteratively | [
"Reads",
"a",
"fastq",
"file",
"iteratively"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L762-L789 |
24,144 | benedictpaten/sonLib | bioio.py | _getMultiFastaOffsets | def _getMultiFastaOffsets(fasta):
"""Reads in columns of multiple alignment and returns them iteratively
"""
f = open(fasta, 'r')
i = 0
j = f.read(1)
l = []
while j != '':
i += 1
if j == '>':
i += 1
while f.read(1) != '\n':
i += 1
l.append(i)
j = f.read(1)
f.close()
return l | python | def _getMultiFastaOffsets(fasta):
f = open(fasta, 'r')
i = 0
j = f.read(1)
l = []
while j != '':
i += 1
if j == '>':
i += 1
while f.read(1) != '\n':
i += 1
l.append(i)
j = f.read(1)
f.close()
return l | [
"def",
"_getMultiFastaOffsets",
"(",
"fasta",
")",
":",
"f",
"=",
"open",
"(",
"fasta",
",",
"'r'",
")",
"i",
"=",
"0",
"j",
"=",
"f",
".",
"read",
"(",
"1",
")",
"l",
"=",
"[",
"]",
"while",
"j",
"!=",
"''",
":",
"i",
"+=",
"1",
"if",
"j",... | Reads in columns of multiple alignment and returns them iteratively | [
"Reads",
"in",
"columns",
"of",
"multiple",
"alignment",
"and",
"returns",
"them",
"iteratively"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L811-L827 |
24,145 | benedictpaten/sonLib | bioio.py | fastaReadHeaders | def fastaReadHeaders(fasta):
"""Returns a list of fasta header lines, excluding
"""
headers = []
fileHandle = open(fasta, 'r')
line = fileHandle.readline()
while line != '':
assert line[-1] == '\n'
if line[0] == '>':
headers.append(line[1:-1])
line = fileHandle.readline()
fileHandle.close()
return headers | python | def fastaReadHeaders(fasta):
headers = []
fileHandle = open(fasta, 'r')
line = fileHandle.readline()
while line != '':
assert line[-1] == '\n'
if line[0] == '>':
headers.append(line[1:-1])
line = fileHandle.readline()
fileHandle.close()
return headers | [
"def",
"fastaReadHeaders",
"(",
"fasta",
")",
":",
"headers",
"=",
"[",
"]",
"fileHandle",
"=",
"open",
"(",
"fasta",
",",
"'r'",
")",
"line",
"=",
"fileHandle",
".",
"readline",
"(",
")",
"while",
"line",
"!=",
"''",
":",
"assert",
"line",
"[",
"-",... | Returns a list of fasta header lines, excluding | [
"Returns",
"a",
"list",
"of",
"fasta",
"header",
"lines",
"excluding"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L829-L841 |
24,146 | benedictpaten/sonLib | bioio.py | fastaAlignmentRead | def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None):
"""
reads in columns of multiple alignment and returns them iteratively
"""
if l is None:
l = _getMultiFastaOffsets(fasta)
else:
l = l[:]
seqNo = len(l)
for i in xrange(0, seqNo):
j = open(fasta, 'r')
j.seek(l[i])
l[i] = j
column = [sys.maxint]*seqNo
if seqNo != 0:
while True:
for j in xrange(0, seqNo):
i = l[j].read(1)
while i == '\n':
i = l[j].read(1)
column[j] = i
if column[0] == '>' or column[0] == '':
for j in xrange(1, seqNo):
assert column[j] == '>' or column[j] == ''
break
for j in xrange(1, seqNo):
assert column[j] != '>' and column[j] != ''
column[j] = mapFn(column[j])
yield column[:]
for i in l:
i.close() | python | def fastaAlignmentRead(fasta, mapFn=(lambda x : x), l=None):
if l is None:
l = _getMultiFastaOffsets(fasta)
else:
l = l[:]
seqNo = len(l)
for i in xrange(0, seqNo):
j = open(fasta, 'r')
j.seek(l[i])
l[i] = j
column = [sys.maxint]*seqNo
if seqNo != 0:
while True:
for j in xrange(0, seqNo):
i = l[j].read(1)
while i == '\n':
i = l[j].read(1)
column[j] = i
if column[0] == '>' or column[0] == '':
for j in xrange(1, seqNo):
assert column[j] == '>' or column[j] == ''
break
for j in xrange(1, seqNo):
assert column[j] != '>' and column[j] != ''
column[j] = mapFn(column[j])
yield column[:]
for i in l:
i.close() | [
"def",
"fastaAlignmentRead",
"(",
"fasta",
",",
"mapFn",
"=",
"(",
"lambda",
"x",
":",
"x",
")",
",",
"l",
"=",
"None",
")",
":",
"if",
"l",
"is",
"None",
":",
"l",
"=",
"_getMultiFastaOffsets",
"(",
"fasta",
")",
"else",
":",
"l",
"=",
"l",
"[",... | reads in columns of multiple alignment and returns them iteratively | [
"reads",
"in",
"columns",
"of",
"multiple",
"alignment",
"and",
"returns",
"them",
"iteratively"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L843-L873 |
24,147 | benedictpaten/sonLib | bioio.py | fastaAlignmentWrite | def fastaAlignmentWrite(columnAlignment, names, seqNo, fastaFile,
filter=lambda x : True):
"""
Writes out column alignment to given file multi-fasta format
"""
fastaFile = open(fastaFile, 'w')
columnAlignment = [ i for i in columnAlignment if filter(i) ]
for seq in xrange(0, seqNo):
fastaFile.write(">%s\n" % names[seq])
for column in columnAlignment:
fastaFile.write(column[seq])
fastaFile.write("\n")
fastaFile.close() | python | def fastaAlignmentWrite(columnAlignment, names, seqNo, fastaFile,
filter=lambda x : True):
fastaFile = open(fastaFile, 'w')
columnAlignment = [ i for i in columnAlignment if filter(i) ]
for seq in xrange(0, seqNo):
fastaFile.write(">%s\n" % names[seq])
for column in columnAlignment:
fastaFile.write(column[seq])
fastaFile.write("\n")
fastaFile.close() | [
"def",
"fastaAlignmentWrite",
"(",
"columnAlignment",
",",
"names",
",",
"seqNo",
",",
"fastaFile",
",",
"filter",
"=",
"lambda",
"x",
":",
"True",
")",
":",
"fastaFile",
"=",
"open",
"(",
"fastaFile",
",",
"'w'",
")",
"columnAlignment",
"=",
"[",
"i",
"... | Writes out column alignment to given file multi-fasta format | [
"Writes",
"out",
"column",
"alignment",
"to",
"given",
"file",
"multi",
"-",
"fasta",
"format"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L875-L887 |
24,148 | benedictpaten/sonLib | bioio.py | getRandomSequence | def getRandomSequence(length=500):
"""Generates a random name and sequence.
"""
fastaHeader = ""
for i in xrange(int(random.random()*100)):
fastaHeader = fastaHeader + random.choice([ 'A', 'C', '0', '9', ' ', '\t' ])
return (fastaHeader, \
"".join([ random.choice([ 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'N' ]) for i in xrange((int)(random.random() * length))])) | python | def getRandomSequence(length=500):
fastaHeader = ""
for i in xrange(int(random.random()*100)):
fastaHeader = fastaHeader + random.choice([ 'A', 'C', '0', '9', ' ', '\t' ])
return (fastaHeader, \
"".join([ random.choice([ 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'A', 'C', 'T', 'G', 'N' ]) for i in xrange((int)(random.random() * length))])) | [
"def",
"getRandomSequence",
"(",
"length",
"=",
"500",
")",
":",
"fastaHeader",
"=",
"\"\"",
"for",
"i",
"in",
"xrange",
"(",
"int",
"(",
"random",
".",
"random",
"(",
")",
"*",
"100",
")",
")",
":",
"fastaHeader",
"=",
"fastaHeader",
"+",
"random",
... | Generates a random name and sequence. | [
"Generates",
"a",
"random",
"name",
"and",
"sequence",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L889-L896 |
24,149 | benedictpaten/sonLib | bioio.py | mutateSequence | def mutateSequence(seq, distance):
"""Mutates the DNA sequence for use in testing.
"""
subProb=distance
inProb=0.05*distance
deProb=0.05*distance
contProb=0.9
l = []
bases = [ 'A', 'C', 'T', 'G' ]
i=0
while i < len(seq):
if random.random() < subProb:
l.append(random.choice(bases))
else:
l.append(seq[i])
if random.random() < inProb:
l += getRandomSequence(_expLength(0, contProb))[1]
if random.random() < deProb:
i += int(_expLength(0, contProb))
i += 1
return "".join(l) | python | def mutateSequence(seq, distance):
subProb=distance
inProb=0.05*distance
deProb=0.05*distance
contProb=0.9
l = []
bases = [ 'A', 'C', 'T', 'G' ]
i=0
while i < len(seq):
if random.random() < subProb:
l.append(random.choice(bases))
else:
l.append(seq[i])
if random.random() < inProb:
l += getRandomSequence(_expLength(0, contProb))[1]
if random.random() < deProb:
i += int(_expLength(0, contProb))
i += 1
return "".join(l) | [
"def",
"mutateSequence",
"(",
"seq",
",",
"distance",
")",
":",
"subProb",
"=",
"distance",
"inProb",
"=",
"0.05",
"*",
"distance",
"deProb",
"=",
"0.05",
"*",
"distance",
"contProb",
"=",
"0.9",
"l",
"=",
"[",
"]",
"bases",
"=",
"[",
"'A'",
",",
"'C... | Mutates the DNA sequence for use in testing. | [
"Mutates",
"the",
"DNA",
"sequence",
"for",
"use",
"in",
"testing",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L903-L923 |
24,150 | benedictpaten/sonLib | bioio.py | newickTreeParser | def newickTreeParser(newickTree, defaultDistance=DEFAULT_DISTANCE, \
sortNonBinaryNodes=False, reportUnaryNodes=False):
"""
lax newick tree parser
"""
newickTree = newickTree.replace("(", " ( ")
newickTree = newickTree.replace(")", " ) ")
newickTree = newickTree.replace(":", " : ")
newickTree = newickTree.replace(";", "")
newickTree = newickTree.replace(",", " , ")
newickTree = re.compile("[\s]*").split(newickTree)
while "" in newickTree:
newickTree.remove("")
def fn(newickTree, i):
if i[0] < len(newickTree):
if newickTree[i[0]] == ':':
d = float(newickTree[i[0]+1])
i[0] += 2
return d
return defaultDistance
def fn2(newickTree, i):
if i[0] < len(newickTree):
j = newickTree[i[0]]
if j != ':' and j != ')' and j != ',':
i[0] += 1
return j
return None
def fn3(newickTree, i):
if newickTree[i[0]] == '(':
#subTree1 = None
subTreeList = []
i[0] += 1
k = []
while newickTree[i[0]] != ')':
if newickTree[i[0]] == ',':
i[0] += 1
subTreeList.append(fn3(newickTree, i))
i[0] += 1
def cmp(i, j):
if i.distance < j.distance:
return -1
if i.distance > j.distance:
return 1
return 0
if sortNonBinaryNodes:
subTreeList.sort(cmp)
subTree1 = subTreeList[0]
if len(subTreeList) > 1:
for subTree2 in subTreeList[1:]:
subTree1 = BinaryTree(0.0, True, subTree1, subTree2, None)
subTree1.iD = fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)
elif reportUnaryNodes:
subTree1 = BinaryTree(0.0, True, subTree1, None, None)
subTree1.iD = fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)
else:
fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)
return subTree1
leafID = fn2(newickTree, i)
return BinaryTree(fn(newickTree, i), False, None, None, leafID)
return fn3(newickTree, [0]) | python | def newickTreeParser(newickTree, defaultDistance=DEFAULT_DISTANCE, \
sortNonBinaryNodes=False, reportUnaryNodes=False):
newickTree = newickTree.replace("(", " ( ")
newickTree = newickTree.replace(")", " ) ")
newickTree = newickTree.replace(":", " : ")
newickTree = newickTree.replace(";", "")
newickTree = newickTree.replace(",", " , ")
newickTree = re.compile("[\s]*").split(newickTree)
while "" in newickTree:
newickTree.remove("")
def fn(newickTree, i):
if i[0] < len(newickTree):
if newickTree[i[0]] == ':':
d = float(newickTree[i[0]+1])
i[0] += 2
return d
return defaultDistance
def fn2(newickTree, i):
if i[0] < len(newickTree):
j = newickTree[i[0]]
if j != ':' and j != ')' and j != ',':
i[0] += 1
return j
return None
def fn3(newickTree, i):
if newickTree[i[0]] == '(':
#subTree1 = None
subTreeList = []
i[0] += 1
k = []
while newickTree[i[0]] != ')':
if newickTree[i[0]] == ',':
i[0] += 1
subTreeList.append(fn3(newickTree, i))
i[0] += 1
def cmp(i, j):
if i.distance < j.distance:
return -1
if i.distance > j.distance:
return 1
return 0
if sortNonBinaryNodes:
subTreeList.sort(cmp)
subTree1 = subTreeList[0]
if len(subTreeList) > 1:
for subTree2 in subTreeList[1:]:
subTree1 = BinaryTree(0.0, True, subTree1, subTree2, None)
subTree1.iD = fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)
elif reportUnaryNodes:
subTree1 = BinaryTree(0.0, True, subTree1, None, None)
subTree1.iD = fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)
else:
fn2(newickTree, i)
subTree1.distance += fn(newickTree, i)
return subTree1
leafID = fn2(newickTree, i)
return BinaryTree(fn(newickTree, i), False, None, None, leafID)
return fn3(newickTree, [0]) | [
"def",
"newickTreeParser",
"(",
"newickTree",
",",
"defaultDistance",
"=",
"DEFAULT_DISTANCE",
",",
"sortNonBinaryNodes",
"=",
"False",
",",
"reportUnaryNodes",
"=",
"False",
")",
":",
"newickTree",
"=",
"newickTree",
".",
"replace",
"(",
"\"(\"",
",",
"\" ( \"",
... | lax newick tree parser | [
"lax",
"newick",
"tree",
"parser"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L944-L1007 |
24,151 | benedictpaten/sonLib | bioio.py | pWMRead | def pWMRead(fileHandle, alphabetSize=4):
"""reads in standard position weight matrix format,
rows are different types of base, columns are individual residues
"""
lines = fileHandle.readlines()
assert len(lines) == alphabetSize
l = [ [ float(i) ] for i in lines[0].split() ]
for line in lines[1:]:
l2 = [ float(i) for i in line.split() ]
assert len(l) == len(l2)
for i in xrange(0, len(l)):
l[i].append(l2[i])
for i in xrange(0, len(l)):
j = sum(l[i]) + 0.0
l[i] = [ k/j for k in l[i] ]
return l | python | def pWMRead(fileHandle, alphabetSize=4):
lines = fileHandle.readlines()
assert len(lines) == alphabetSize
l = [ [ float(i) ] for i in lines[0].split() ]
for line in lines[1:]:
l2 = [ float(i) for i in line.split() ]
assert len(l) == len(l2)
for i in xrange(0, len(l)):
l[i].append(l2[i])
for i in xrange(0, len(l)):
j = sum(l[i]) + 0.0
l[i] = [ k/j for k in l[i] ]
return l | [
"def",
"pWMRead",
"(",
"fileHandle",
",",
"alphabetSize",
"=",
"4",
")",
":",
"lines",
"=",
"fileHandle",
".",
"readlines",
"(",
")",
"assert",
"len",
"(",
"lines",
")",
"==",
"alphabetSize",
"l",
"=",
"[",
"[",
"float",
"(",
"i",
")",
"]",
"for",
... | reads in standard position weight matrix format,
rows are different types of base, columns are individual residues | [
"reads",
"in",
"standard",
"position",
"weight",
"matrix",
"format",
"rows",
"are",
"different",
"types",
"of",
"base",
"columns",
"are",
"individual",
"residues"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L1036-L1051 |
24,152 | benedictpaten/sonLib | bioio.py | pWMWrite | def pWMWrite(fileHandle, pWM, alphabetSize=4):
"""Writes file in standard PWM format, is reverse of pWMParser
"""
for i in xrange(0, alphabetSize):
fileHandle.write("%s\n" % ' '.join([ str(pWM[j][i]) for j in xrange(0, len(pWM)) ])) | python | def pWMWrite(fileHandle, pWM, alphabetSize=4):
for i in xrange(0, alphabetSize):
fileHandle.write("%s\n" % ' '.join([ str(pWM[j][i]) for j in xrange(0, len(pWM)) ])) | [
"def",
"pWMWrite",
"(",
"fileHandle",
",",
"pWM",
",",
"alphabetSize",
"=",
"4",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"alphabetSize",
")",
":",
"fileHandle",
".",
"write",
"(",
"\"%s\\n\"",
"%",
"' '",
".",
"join",
"(",
"[",
"str",
... | Writes file in standard PWM format, is reverse of pWMParser | [
"Writes",
"file",
"in",
"standard",
"PWM",
"format",
"is",
"reverse",
"of",
"pWMParser"
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L1053-L1057 |
24,153 | benedictpaten/sonLib | bioio.py | cigarRead | def cigarRead(fileHandleOrFile):
"""Reads a list of pairwise alignments into a pairwise alignment structure.
Query and target are reversed!
"""
fileHandle = _getFileHandle(fileHandleOrFile)
#p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+(.*)\\s*)*")
p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+([^\\s]+)(\\s+(.*)\\s*)*")
line = fileHandle.readline()
while line != '':
pA = cigarReadFromString(line)
if pA != None:
yield pA
line = fileHandle.readline()
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close() | python | def cigarRead(fileHandleOrFile):
fileHandle = _getFileHandle(fileHandleOrFile)
#p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+(.*)\\s*)*")
p = re.compile("cigar:\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+(.+)\\s+([0-9]+)\\s+([0-9]+)\\s+([\\+\\-\\.])\\s+([^\\s]+)(\\s+(.*)\\s*)*")
line = fileHandle.readline()
while line != '':
pA = cigarReadFromString(line)
if pA != None:
yield pA
line = fileHandle.readline()
if isinstance(fileHandleOrFile, "".__class__):
fileHandle.close() | [
"def",
"cigarRead",
"(",
"fileHandleOrFile",
")",
":",
"fileHandle",
"=",
"_getFileHandle",
"(",
"fileHandleOrFile",
")",
"#p = re.compile(\"cigar:\\\\s+(.+)\\\\s+([0-9]+)\\\\s+([0-9]+)\\\\s+([\\\\+\\\\-\\\\.])\\\\s+(.+)\\\\s+([0-9]+)\\\\s+([0-9]+)\\\\s+([\\\\+\\\\-\\\\.])\\\\s+(.+)\\\\s+(.*... | Reads a list of pairwise alignments into a pairwise alignment structure.
Query and target are reversed! | [
"Reads",
"a",
"list",
"of",
"pairwise",
"alignments",
"into",
"a",
"pairwise",
"alignment",
"structure",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L1184-L1199 |
24,154 | benedictpaten/sonLib | bioio.py | cigarWrite | def cigarWrite(fileHandle, pairwiseAlignment, withProbs=True):
"""Writes out the pairwiseAlignment to the file stream.
Query and target are reversed from normal order.
"""
if len(pairwiseAlignment.operationList) == 0:
logger.info("Writing zero length pairwiseAlignment to file!")
strand1 = "+"
if not pairwiseAlignment.strand1:
strand1 = "-"
strand2 = "+"
if not pairwiseAlignment.strand2:
strand2 = "-"
fileHandle.write("cigar: %s %i %i %s %s %i %i %s %f" % (pairwiseAlignment.contig2, pairwiseAlignment.start2, pairwiseAlignment.end2, strand2,\
pairwiseAlignment.contig1, pairwiseAlignment.start1, pairwiseAlignment.end1, strand1,\
pairwiseAlignment.score))
if withProbs == True:
hashMap = { PairwiseAlignment.PAIRWISE_INDEL_Y:'Z',PairwiseAlignment.PAIRWISE_INDEL_X:'Y', PairwiseAlignment.PAIRWISE_MATCH:'X' }
for op in pairwiseAlignment.operationList:
fileHandle.write(' %s %i %f' % (hashMap[op.type], op.length, op.score))
else:
hashMap = { PairwiseAlignment.PAIRWISE_INDEL_Y:'I',PairwiseAlignment.PAIRWISE_INDEL_X:'D', PairwiseAlignment.PAIRWISE_MATCH:'M' }
for op in pairwiseAlignment.operationList:
fileHandle.write(' %s %i' % (hashMap[op.type], op.length))
fileHandle.write("\n") | python | def cigarWrite(fileHandle, pairwiseAlignment, withProbs=True):
if len(pairwiseAlignment.operationList) == 0:
logger.info("Writing zero length pairwiseAlignment to file!")
strand1 = "+"
if not pairwiseAlignment.strand1:
strand1 = "-"
strand2 = "+"
if not pairwiseAlignment.strand2:
strand2 = "-"
fileHandle.write("cigar: %s %i %i %s %s %i %i %s %f" % (pairwiseAlignment.contig2, pairwiseAlignment.start2, pairwiseAlignment.end2, strand2,\
pairwiseAlignment.contig1, pairwiseAlignment.start1, pairwiseAlignment.end1, strand1,\
pairwiseAlignment.score))
if withProbs == True:
hashMap = { PairwiseAlignment.PAIRWISE_INDEL_Y:'Z',PairwiseAlignment.PAIRWISE_INDEL_X:'Y', PairwiseAlignment.PAIRWISE_MATCH:'X' }
for op in pairwiseAlignment.operationList:
fileHandle.write(' %s %i %f' % (hashMap[op.type], op.length, op.score))
else:
hashMap = { PairwiseAlignment.PAIRWISE_INDEL_Y:'I',PairwiseAlignment.PAIRWISE_INDEL_X:'D', PairwiseAlignment.PAIRWISE_MATCH:'M' }
for op in pairwiseAlignment.operationList:
fileHandle.write(' %s %i' % (hashMap[op.type], op.length))
fileHandle.write("\n") | [
"def",
"cigarWrite",
"(",
"fileHandle",
",",
"pairwiseAlignment",
",",
"withProbs",
"=",
"True",
")",
":",
"if",
"len",
"(",
"pairwiseAlignment",
".",
"operationList",
")",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"\"Writing zero length pairwiseAlignment to fil... | Writes out the pairwiseAlignment to the file stream.
Query and target are reversed from normal order. | [
"Writes",
"out",
"the",
"pairwiseAlignment",
"to",
"the",
"file",
"stream",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L1201-L1228 |
24,155 | benedictpaten/sonLib | bioio.py | getRandomPairwiseAlignment | def getRandomPairwiseAlignment():
"""Gets a random pairwiseAlignment.
"""
i, j, k, l = _getRandomSegment()
m, n, o, p = _getRandomSegment()
score = random.choice(xrange(-1000, 1000))
return PairwiseAlignment(i, j, k, l, m, n, o, p, score, getRandomOperationList(abs(k - j), abs(o - n))) | python | def getRandomPairwiseAlignment():
i, j, k, l = _getRandomSegment()
m, n, o, p = _getRandomSegment()
score = random.choice(xrange(-1000, 1000))
return PairwiseAlignment(i, j, k, l, m, n, o, p, score, getRandomOperationList(abs(k - j), abs(o - n))) | [
"def",
"getRandomPairwiseAlignment",
"(",
")",
":",
"i",
",",
"j",
",",
"k",
",",
"l",
"=",
"_getRandomSegment",
"(",
")",
"m",
",",
"n",
",",
"o",
",",
"p",
"=",
"_getRandomSegment",
"(",
")",
"score",
"=",
"random",
".",
"choice",
"(",
"xrange",
... | Gets a random pairwiseAlignment. | [
"Gets",
"a",
"random",
"pairwiseAlignment",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L1260-L1266 |
24,156 | benedictpaten/sonLib | bioio.py | addEdgeToGraph | def addEdgeToGraph(parentNodeName, childNodeName, graphFileHandle, colour="black", length="10", weight="1", dir="none", label="", style=""):
"""Links two nodes in the graph together.
"""
graphFileHandle.write('edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % (colour, length, weight, dir, label, style))
graphFileHandle.write("%s -- %s;\n" % (parentNodeName, childNodeName)) | python | def addEdgeToGraph(parentNodeName, childNodeName, graphFileHandle, colour="black", length="10", weight="1", dir="none", label="", style=""):
graphFileHandle.write('edge[color=%s,len=%s,weight=%s,dir=%s,label="%s",style=%s];\n' % (colour, length, weight, dir, label, style))
graphFileHandle.write("%s -- %s;\n" % (parentNodeName, childNodeName)) | [
"def",
"addEdgeToGraph",
"(",
"parentNodeName",
",",
"childNodeName",
",",
"graphFileHandle",
",",
"colour",
"=",
"\"black\"",
",",
"length",
"=",
"\"10\"",
",",
"weight",
"=",
"\"1\"",
",",
"dir",
"=",
"\"none\"",
",",
"label",
"=",
"\"\"",
",",
"style",
... | Links two nodes in the graph together. | [
"Links",
"two",
"nodes",
"in",
"the",
"graph",
"together",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L1282-L1286 |
24,157 | benedictpaten/sonLib | bioio.py | TempFileTree.destroyTempFile | def destroyTempFile(self, tempFile):
"""Removes the temporary file in the temp file dir, checking its in the temp file tree.
"""
#Do basic assertions for goodness of the function
assert os.path.isfile(tempFile)
assert os.path.commonprefix((self.rootDir, tempFile)) == self.rootDir #Checks file is part of tree
#Update stats.
self.tempFilesDestroyed += 1
#Do the actual removal
os.remove(tempFile)
self.__destroyFile(tempFile) | python | def destroyTempFile(self, tempFile):
#Do basic assertions for goodness of the function
assert os.path.isfile(tempFile)
assert os.path.commonprefix((self.rootDir, tempFile)) == self.rootDir #Checks file is part of tree
#Update stats.
self.tempFilesDestroyed += 1
#Do the actual removal
os.remove(tempFile)
self.__destroyFile(tempFile) | [
"def",
"destroyTempFile",
"(",
"self",
",",
"tempFile",
")",
":",
"#Do basic assertions for goodness of the function",
"assert",
"os",
".",
"path",
".",
"isfile",
"(",
"tempFile",
")",
"assert",
"os",
".",
"path",
".",
"commonprefix",
"(",
"(",
"self",
".",
"r... | Removes the temporary file in the temp file dir, checking its in the temp file tree. | [
"Removes",
"the",
"temporary",
"file",
"in",
"the",
"temp",
"file",
"dir",
"checking",
"its",
"in",
"the",
"temp",
"file",
"tree",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L557-L567 |
24,158 | benedictpaten/sonLib | bioio.py | TempFileTree.destroyTempDir | def destroyTempDir(self, tempDir):
"""Removes a temporary directory in the temp file dir, checking its in the temp file tree.
The dir will be removed regardless of if it is empty.
"""
#Do basic assertions for goodness of the function
assert os.path.isdir(tempDir)
assert os.path.commonprefix((self.rootDir, tempDir)) == self.rootDir #Checks file is part of tree
#Update stats.
self.tempFilesDestroyed += 1
#Do the actual removal
try:
os.rmdir(tempDir)
except OSError:
shutil.rmtree(tempDir)
#system("rm -rf %s" % tempDir)
self.__destroyFile(tempDir) | python | def destroyTempDir(self, tempDir):
#Do basic assertions for goodness of the function
assert os.path.isdir(tempDir)
assert os.path.commonprefix((self.rootDir, tempDir)) == self.rootDir #Checks file is part of tree
#Update stats.
self.tempFilesDestroyed += 1
#Do the actual removal
try:
os.rmdir(tempDir)
except OSError:
shutil.rmtree(tempDir)
#system("rm -rf %s" % tempDir)
self.__destroyFile(tempDir) | [
"def",
"destroyTempDir",
"(",
"self",
",",
"tempDir",
")",
":",
"#Do basic assertions for goodness of the function",
"assert",
"os",
".",
"path",
".",
"isdir",
"(",
"tempDir",
")",
"assert",
"os",
".",
"path",
".",
"commonprefix",
"(",
"(",
"self",
".",
"rootD... | Removes a temporary directory in the temp file dir, checking its in the temp file tree.
The dir will be removed regardless of if it is empty. | [
"Removes",
"a",
"temporary",
"directory",
"in",
"the",
"temp",
"file",
"dir",
"checking",
"its",
"in",
"the",
"temp",
"file",
"tree",
".",
"The",
"dir",
"will",
"be",
"removed",
"regardless",
"of",
"if",
"it",
"is",
"empty",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L569-L584 |
24,159 | benedictpaten/sonLib | bioio.py | TempFileTree.destroyTempFiles | def destroyTempFiles(self):
"""Destroys all temp temp file hierarchy, getting rid of all files.
"""
os.system("rm -rf %s" % self.rootDir)
logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed)) | python | def destroyTempFiles(self):
os.system("rm -rf %s" % self.rootDir)
logger.debug("Temp files created: %s, temp files actively destroyed: %s" % (self.tempFilesCreated, self.tempFilesDestroyed)) | [
"def",
"destroyTempFiles",
"(",
"self",
")",
":",
"os",
".",
"system",
"(",
"\"rm -rf %s\"",
"%",
"self",
".",
"rootDir",
")",
"logger",
".",
"debug",
"(",
"\"Temp files created: %s, temp files actively destroyed: %s\"",
"%",
"(",
"self",
".",
"tempFilesCreated",
... | Destroys all temp temp file hierarchy, getting rid of all files. | [
"Destroys",
"all",
"temp",
"temp",
"file",
"hierarchy",
"getting",
"rid",
"of",
"all",
"files",
"."
] | 1decb75bb439b70721ec776f685ce98e25217d26 | https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L605-L609 |
24,160 | penguinolog/sqlalchemy_jsonfield | sqlalchemy_jsonfield/jsonfield.py | mutable_json_field | def mutable_json_field( # pylint: disable=keyword-arg-before-vararg
enforce_string=False, # type: bool
enforce_unicode=False, # type: bool
json=json, # type: typing.Union[types.ModuleType, typing.Any]
*args, # type: typing.Any
**kwargs # type: typing.Any
): # type: (...) -> JSONField
"""Mutable JSONField creator.
:param enforce_string: enforce String(UnicodeText) type usage
:type enforce_string: bool
:param enforce_unicode: do not encode non-ascii data
:type enforce_unicode: bool
:param json: JSON encoding/decoding library.
By default: standard json package.
:return: Mutable JSONField via MutableDict.as_mutable
:rtype: JSONField
"""
return sqlalchemy.ext.mutable.MutableDict.as_mutable(
JSONField(enforce_string=enforce_string, enforce_unicode=enforce_unicode, json=json, *args, **kwargs)
) | python | def mutable_json_field( # pylint: disable=keyword-arg-before-vararg
enforce_string=False, # type: bool
enforce_unicode=False, # type: bool
json=json, # type: typing.Union[types.ModuleType, typing.Any]
*args, # type: typing.Any
**kwargs # type: typing.Any
): # type: (...) -> JSONField
return sqlalchemy.ext.mutable.MutableDict.as_mutable(
JSONField(enforce_string=enforce_string, enforce_unicode=enforce_unicode, json=json, *args, **kwargs)
) | [
"def",
"mutable_json_field",
"(",
"# pylint: disable=keyword-arg-before-vararg",
"enforce_string",
"=",
"False",
",",
"# type: bool",
"enforce_unicode",
"=",
"False",
",",
"# type: bool",
"json",
"=",
"json",
",",
"# type: typing.Union[types.ModuleType, typing.Any]",
"*",
"ar... | Mutable JSONField creator.
:param enforce_string: enforce String(UnicodeText) type usage
:type enforce_string: bool
:param enforce_unicode: do not encode non-ascii data
:type enforce_unicode: bool
:param json: JSON encoding/decoding library.
By default: standard json package.
:return: Mutable JSONField via MutableDict.as_mutable
:rtype: JSONField | [
"Mutable",
"JSONField",
"creator",
"."
] | a2af90e64d82a3a28185e1e0828757bf2829be06 | https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L103-L123 |
24,161 | penguinolog/sqlalchemy_jsonfield | sqlalchemy_jsonfield/jsonfield.py | JSONField.load_dialect_impl | def load_dialect_impl(self, dialect): # type: (DefaultDialect) -> TypeEngine
"""Select impl by dialect."""
if self.__use_json(dialect):
return dialect.type_descriptor(self.__json_type)
return dialect.type_descriptor(sqlalchemy.UnicodeText) | python | def load_dialect_impl(self, dialect): # type: (DefaultDialect) -> TypeEngine
if self.__use_json(dialect):
return dialect.type_descriptor(self.__json_type)
return dialect.type_descriptor(sqlalchemy.UnicodeText) | [
"def",
"load_dialect_impl",
"(",
"self",
",",
"dialect",
")",
":",
"# type: (DefaultDialect) -> TypeEngine",
"if",
"self",
".",
"__use_json",
"(",
"dialect",
")",
":",
"return",
"dialect",
".",
"type_descriptor",
"(",
"self",
".",
"__json_type",
")",
"return",
"... | Select impl by dialect. | [
"Select",
"impl",
"by",
"dialect",
"."
] | a2af90e64d82a3a28185e1e0828757bf2829be06 | https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L78-L82 |
24,162 | penguinolog/sqlalchemy_jsonfield | sqlalchemy_jsonfield/jsonfield.py | JSONField.process_bind_param | def process_bind_param(self, value, dialect): # type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any]
"""Encode data, if required."""
if self.__use_json(dialect) or value is None:
return value
return self.__json_codec.dumps(value, ensure_ascii=not self.__enforce_unicode) | python | def process_bind_param(self, value, dialect): # type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any]
if self.__use_json(dialect) or value is None:
return value
return self.__json_codec.dumps(value, ensure_ascii=not self.__enforce_unicode) | [
"def",
"process_bind_param",
"(",
"self",
",",
"value",
",",
"dialect",
")",
":",
"# type: (typing.Any, DefaultDialect) -> typing.Union[str, typing.Any]",
"if",
"self",
".",
"__use_json",
"(",
"dialect",
")",
"or",
"value",
"is",
"None",
":",
"return",
"value",
"ret... | Encode data, if required. | [
"Encode",
"data",
"if",
"required",
"."
] | a2af90e64d82a3a28185e1e0828757bf2829be06 | https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L84-L89 |
24,163 | penguinolog/sqlalchemy_jsonfield | sqlalchemy_jsonfield/jsonfield.py | JSONField.process_result_value | def process_result_value(
self,
value, # type: typing.Union[str, typing.Any]
dialect # type: DefaultDialect
): # type: (...) -> typing.Any
"""Decode data, if required."""
if self.__use_json(dialect) or value is None:
return value
return self.__json_codec.loads(value) | python | def process_result_value(
self,
value, # type: typing.Union[str, typing.Any]
dialect # type: DefaultDialect
): # type: (...) -> typing.Any
if self.__use_json(dialect) or value is None:
return value
return self.__json_codec.loads(value) | [
"def",
"process_result_value",
"(",
"self",
",",
"value",
",",
"# type: typing.Union[str, typing.Any]",
"dialect",
"# type: DefaultDialect",
")",
":",
"# type: (...) -> typing.Any",
"if",
"self",
".",
"__use_json",
"(",
"dialect",
")",
"or",
"value",
"is",
"None",
":"... | Decode data, if required. | [
"Decode",
"data",
"if",
"required",
"."
] | a2af90e64d82a3a28185e1e0828757bf2829be06 | https://github.com/penguinolog/sqlalchemy_jsonfield/blob/a2af90e64d82a3a28185e1e0828757bf2829be06/sqlalchemy_jsonfield/jsonfield.py#L91-L100 |
24,164 | icgood/pymap | pymap/backend/mailbox.py | MailboxDataInterface.get | async def get(self, uid: int, cached_msg: CachedMessage = None,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> Optional[MessageT]:
"""Return the message with the given UID.
Args:
uid: The message UID.
cached_msg: The last known cached message.
requirement: The data required from each message.
Raises:
IndexError: The UID is not valid in the mailbox.
"""
... | python | async def get(self, uid: int, cached_msg: CachedMessage = None,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> Optional[MessageT]:
... | [
"async",
"def",
"get",
"(",
"self",
",",
"uid",
":",
"int",
",",
"cached_msg",
":",
"CachedMessage",
"=",
"None",
",",
"requirement",
":",
"FetchRequirement",
"=",
"FetchRequirement",
".",
"METADATA",
")",
"->",
"Optional",
"[",
"MessageT",
"]",
":",
"..."... | Return the message with the given UID.
Args:
uid: The message UID.
cached_msg: The last known cached message.
requirement: The data required from each message.
Raises:
IndexError: The UID is not valid in the mailbox. | [
"Return",
"the",
"message",
"with",
"the",
"given",
"UID",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L120-L134 |
24,165 | icgood/pymap | pymap/backend/mailbox.py | MailboxDataInterface.update_flags | async def update_flags(self, messages: Sequence[MessageT],
flag_set: FrozenSet[Flag], mode: FlagOp) -> None:
"""Update the permanent flags of each messages.
Args:
messages: The message objects.
flag_set: The set of flags for the update operation.
flag_op: The mode to change the flags.
"""
... | python | async def update_flags(self, messages: Sequence[MessageT],
flag_set: FrozenSet[Flag], mode: FlagOp) -> None:
... | [
"async",
"def",
"update_flags",
"(",
"self",
",",
"messages",
":",
"Sequence",
"[",
"MessageT",
"]",
",",
"flag_set",
":",
"FrozenSet",
"[",
"Flag",
"]",
",",
"mode",
":",
"FlagOp",
")",
"->",
"None",
":",
"..."
] | Update the permanent flags of each messages.
Args:
messages: The message objects.
flag_set: The set of flags for the update operation.
flag_op: The mode to change the flags. | [
"Update",
"the",
"permanent",
"flags",
"of",
"each",
"messages",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L158-L168 |
24,166 | icgood/pymap | pymap/backend/mailbox.py | MailboxDataInterface.find | async def find(self, seq_set: SequenceSet, selected: SelectedMailbox,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> AsyncIterable[Tuple[int, MessageT]]:
"""Find the active message UID and message pairs in the mailbox that
are contained in the given sequences set. Message sequence numbers
are resolved by the selected mailbox session.
Args:
seq_set: The sequence set of the desired messages.
selected: The selected mailbox session.
requirement: The data required from each message.
"""
for seq, cached_msg in selected.messages.get_all(seq_set):
msg = await self.get(cached_msg.uid, cached_msg, requirement)
if msg is not None:
yield (seq, msg) | python | async def find(self, seq_set: SequenceSet, selected: SelectedMailbox,
requirement: FetchRequirement = FetchRequirement.METADATA) \
-> AsyncIterable[Tuple[int, MessageT]]:
for seq, cached_msg in selected.messages.get_all(seq_set):
msg = await self.get(cached_msg.uid, cached_msg, requirement)
if msg is not None:
yield (seq, msg) | [
"async",
"def",
"find",
"(",
"self",
",",
"seq_set",
":",
"SequenceSet",
",",
"selected",
":",
"SelectedMailbox",
",",
"requirement",
":",
"FetchRequirement",
"=",
"FetchRequirement",
".",
"METADATA",
")",
"->",
"AsyncIterable",
"[",
"Tuple",
"[",
"int",
",",
... | Find the active message UID and message pairs in the mailbox that
are contained in the given sequences set. Message sequence numbers
are resolved by the selected mailbox session.
Args:
seq_set: The sequence set of the desired messages.
selected: The selected mailbox session.
requirement: The data required from each message. | [
"Find",
"the",
"active",
"message",
"UID",
"and",
"message",
"pairs",
"in",
"the",
"mailbox",
"that",
"are",
"contained",
"in",
"the",
"given",
"sequences",
"set",
".",
"Message",
"sequence",
"numbers",
"are",
"resolved",
"by",
"the",
"selected",
"mailbox",
... | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L186-L202 |
24,167 | icgood/pymap | pymap/backend/mailbox.py | MailboxDataInterface.find_deleted | async def find_deleted(self, seq_set: SequenceSet,
selected: SelectedMailbox) -> Sequence[int]:
"""Return all the active message UIDs that have the ``\\Deleted`` flag.
Args:
seq_set: The sequence set of the possible messages.
selected: The selected mailbox session.
"""
session_flags = selected.session_flags
return [msg.uid async for _, msg in self.find(seq_set, selected)
if Deleted in msg.get_flags(session_flags)] | python | async def find_deleted(self, seq_set: SequenceSet,
selected: SelectedMailbox) -> Sequence[int]:
session_flags = selected.session_flags
return [msg.uid async for _, msg in self.find(seq_set, selected)
if Deleted in msg.get_flags(session_flags)] | [
"async",
"def",
"find_deleted",
"(",
"self",
",",
"seq_set",
":",
"SequenceSet",
",",
"selected",
":",
"SelectedMailbox",
")",
"->",
"Sequence",
"[",
"int",
"]",
":",
"session_flags",
"=",
"selected",
".",
"session_flags",
"return",
"[",
"msg",
".",
"uid",
... | Return all the active message UIDs that have the ``\\Deleted`` flag.
Args:
seq_set: The sequence set of the possible messages.
selected: The selected mailbox session. | [
"Return",
"all",
"the",
"active",
"message",
"UIDs",
"that",
"have",
"the",
"\\\\",
"Deleted",
"flag",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/backend/mailbox.py#L204-L215 |
24,168 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.content_type | def content_type(self) -> Optional[ContentTypeHeader]:
"""The ``Content-Type`` header."""
try:
return cast(ContentTypeHeader, self[b'content-type'][0])
except (KeyError, IndexError):
return None | python | def content_type(self) -> Optional[ContentTypeHeader]:
try:
return cast(ContentTypeHeader, self[b'content-type'][0])
except (KeyError, IndexError):
return None | [
"def",
"content_type",
"(",
"self",
")",
"->",
"Optional",
"[",
"ContentTypeHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"ContentTypeHeader",
",",
"self",
"[",
"b'content-type'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"IndexError... | The ``Content-Type`` header. | [
"The",
"Content",
"-",
"Type",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L63-L68 |
24,169 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.date | def date(self) -> Optional[DateHeader]:
"""The ``Date`` header."""
try:
return cast(DateHeader, self[b'date'][0])
except (KeyError, IndexError):
return None | python | def date(self) -> Optional[DateHeader]:
try:
return cast(DateHeader, self[b'date'][0])
except (KeyError, IndexError):
return None | [
"def",
"date",
"(",
"self",
")",
"->",
"Optional",
"[",
"DateHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"DateHeader",
",",
"self",
"[",
"b'date'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"return",
... | The ``Date`` header. | [
"The",
"Date",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L71-L76 |
24,170 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.subject | def subject(self) -> Optional[UnstructuredHeader]:
"""The ``Subject`` header."""
try:
return cast(UnstructuredHeader, self[b'subject'][0])
except (KeyError, IndexError):
return None | python | def subject(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'subject'][0])
except (KeyError, IndexError):
return None | [
"def",
"subject",
"(",
"self",
")",
"->",
"Optional",
"[",
"UnstructuredHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"UnstructuredHeader",
",",
"self",
"[",
"b'subject'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"IndexError",
")"... | The ``Subject`` header. | [
"The",
"Subject",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L79-L84 |
24,171 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.from_ | def from_(self) -> Optional[Sequence[AddressHeader]]:
"""The ``From`` header."""
try:
return cast(Sequence[AddressHeader], self[b'from'])
except KeyError:
return None | python | def from_(self) -> Optional[Sequence[AddressHeader]]:
try:
return cast(Sequence[AddressHeader], self[b'from'])
except KeyError:
return None | [
"def",
"from_",
"(",
"self",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"AddressHeader",
"]",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"Sequence",
"[",
"AddressHeader",
"]",
",",
"self",
"[",
"b'from'",
"]",
")",
"except",
"KeyError",
":",
"retur... | The ``From`` header. | [
"The",
"From",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L87-L92 |
24,172 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.sender | def sender(self) -> Optional[Sequence[SingleAddressHeader]]:
"""The ``Sender`` header."""
try:
return cast(Sequence[SingleAddressHeader], self[b'sender'])
except KeyError:
return None | python | def sender(self) -> Optional[Sequence[SingleAddressHeader]]:
try:
return cast(Sequence[SingleAddressHeader], self[b'sender'])
except KeyError:
return None | [
"def",
"sender",
"(",
"self",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"SingleAddressHeader",
"]",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"Sequence",
"[",
"SingleAddressHeader",
"]",
",",
"self",
"[",
"b'sender'",
"]",
")",
"except",
"KeyError",
... | The ``Sender`` header. | [
"The",
"Sender",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L95-L100 |
24,173 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.reply_to | def reply_to(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Reply-To`` header."""
try:
return cast(Sequence[AddressHeader], self[b'reply-to'])
except KeyError:
return None | python | def reply_to(self) -> Optional[Sequence[AddressHeader]]:
try:
return cast(Sequence[AddressHeader], self[b'reply-to'])
except KeyError:
return None | [
"def",
"reply_to",
"(",
"self",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"AddressHeader",
"]",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"Sequence",
"[",
"AddressHeader",
"]",
",",
"self",
"[",
"b'reply-to'",
"]",
")",
"except",
"KeyError",
":",
... | The ``Reply-To`` header. | [
"The",
"Reply",
"-",
"To",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L103-L108 |
24,174 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.to | def to(self) -> Optional[Sequence[AddressHeader]]:
"""The ``To`` header."""
try:
return cast(Sequence[AddressHeader], self[b'to'])
except KeyError:
return None | python | def to(self) -> Optional[Sequence[AddressHeader]]:
try:
return cast(Sequence[AddressHeader], self[b'to'])
except KeyError:
return None | [
"def",
"to",
"(",
"self",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"AddressHeader",
"]",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"Sequence",
"[",
"AddressHeader",
"]",
",",
"self",
"[",
"b'to'",
"]",
")",
"except",
"KeyError",
":",
"return",
... | The ``To`` header. | [
"The",
"To",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L111-L116 |
24,175 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.cc | def cc(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Cc`` header."""
try:
return cast(Sequence[AddressHeader], self[b'cc'])
except KeyError:
return None | python | def cc(self) -> Optional[Sequence[AddressHeader]]:
try:
return cast(Sequence[AddressHeader], self[b'cc'])
except KeyError:
return None | [
"def",
"cc",
"(",
"self",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"AddressHeader",
"]",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"Sequence",
"[",
"AddressHeader",
"]",
",",
"self",
"[",
"b'cc'",
"]",
")",
"except",
"KeyError",
":",
"return",
... | The ``Cc`` header. | [
"The",
"Cc",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L119-L124 |
24,176 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.bcc | def bcc(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Bcc`` header."""
try:
return cast(Sequence[AddressHeader], self[b'bcc'])
except KeyError:
return None | python | def bcc(self) -> Optional[Sequence[AddressHeader]]:
try:
return cast(Sequence[AddressHeader], self[b'bcc'])
except KeyError:
return None | [
"def",
"bcc",
"(",
"self",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"AddressHeader",
"]",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"Sequence",
"[",
"AddressHeader",
"]",
",",
"self",
"[",
"b'bcc'",
"]",
")",
"except",
"KeyError",
":",
"return",... | The ``Bcc`` header. | [
"The",
"Bcc",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L127-L132 |
24,177 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.in_reply_to | def in_reply_to(self) -> Optional[UnstructuredHeader]:
"""The ``In-Reply-To`` header."""
try:
return cast(UnstructuredHeader, self[b'in-reply-to'][0])
except (KeyError, IndexError):
return None | python | def in_reply_to(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'in-reply-to'][0])
except (KeyError, IndexError):
return None | [
"def",
"in_reply_to",
"(",
"self",
")",
"->",
"Optional",
"[",
"UnstructuredHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"UnstructuredHeader",
",",
"self",
"[",
"b'in-reply-to'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"IndexError... | The ``In-Reply-To`` header. | [
"The",
"In",
"-",
"Reply",
"-",
"To",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L135-L140 |
24,178 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.message_id | def message_id(self) -> Optional[UnstructuredHeader]:
"""The ``Message-Id`` header."""
try:
return cast(UnstructuredHeader, self[b'message-id'][0])
except (KeyError, IndexError):
return None | python | def message_id(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'message-id'][0])
except (KeyError, IndexError):
return None | [
"def",
"message_id",
"(",
"self",
")",
"->",
"Optional",
"[",
"UnstructuredHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"UnstructuredHeader",
",",
"self",
"[",
"b'message-id'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"IndexError",... | The ``Message-Id`` header. | [
"The",
"Message",
"-",
"Id",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L143-L148 |
24,179 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.content_disposition | def content_disposition(self) -> Optional[ContentDispositionHeader]:
"""The ``Content-Disposition`` header."""
try:
return cast(ContentDispositionHeader,
self[b'content-disposition'][0])
except (KeyError, IndexError):
return None | python | def content_disposition(self) -> Optional[ContentDispositionHeader]:
try:
return cast(ContentDispositionHeader,
self[b'content-disposition'][0])
except (KeyError, IndexError):
return None | [
"def",
"content_disposition",
"(",
"self",
")",
"->",
"Optional",
"[",
"ContentDispositionHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"ContentDispositionHeader",
",",
"self",
"[",
"b'content-disposition'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"Key... | The ``Content-Disposition`` header. | [
"The",
"Content",
"-",
"Disposition",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L151-L157 |
24,180 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.content_language | def content_language(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Language`` header."""
try:
return cast(UnstructuredHeader, self[b'content-language'][0])
except (KeyError, IndexError):
return None | python | def content_language(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'content-language'][0])
except (KeyError, IndexError):
return None | [
"def",
"content_language",
"(",
"self",
")",
"->",
"Optional",
"[",
"UnstructuredHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"UnstructuredHeader",
",",
"self",
"[",
"b'content-language'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"... | The ``Content-Language`` header. | [
"The",
"Content",
"-",
"Language",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L160-L165 |
24,181 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.content_location | def content_location(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Location`` header."""
try:
return cast(UnstructuredHeader, self[b'content-location'][0])
except (KeyError, IndexError):
return None | python | def content_location(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'content-location'][0])
except (KeyError, IndexError):
return None | [
"def",
"content_location",
"(",
"self",
")",
"->",
"Optional",
"[",
"UnstructuredHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"UnstructuredHeader",
",",
"self",
"[",
"b'content-location'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"... | The ``Content-Location`` header. | [
"The",
"Content",
"-",
"Location",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L168-L173 |
24,182 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.content_id | def content_id(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Id`` header."""
try:
return cast(UnstructuredHeader, self[b'content-id'][0])
except (KeyError, IndexError):
return None | python | def content_id(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'content-id'][0])
except (KeyError, IndexError):
return None | [
"def",
"content_id",
"(",
"self",
")",
"->",
"Optional",
"[",
"UnstructuredHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"UnstructuredHeader",
",",
"self",
"[",
"b'content-id'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",",
"IndexError",... | The ``Content-Id`` header. | [
"The",
"Content",
"-",
"Id",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L176-L181 |
24,183 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.content_description | def content_description(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Description`` header."""
try:
return cast(UnstructuredHeader, self[b'content-description'][0])
except (KeyError, IndexError):
return None | python | def content_description(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'content-description'][0])
except (KeyError, IndexError):
return None | [
"def",
"content_description",
"(",
"self",
")",
"->",
"Optional",
"[",
"UnstructuredHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"UnstructuredHeader",
",",
"self",
"[",
"b'content-description'",
"]",
"[",
"0",
"]",
")",
"except",
"(",
"KeyError",
",... | The ``Content-Description`` header. | [
"The",
"Content",
"-",
"Description",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L184-L189 |
24,184 | icgood/pymap | pymap/mime/parsed.py | ParsedHeaders.content_transfer_encoding | def content_transfer_encoding(self) \
-> Optional[ContentTransferEncodingHeader]:
"""The ``Content-Transfer-Encoding`` header."""
try:
return cast(ContentTransferEncodingHeader,
self[b'content-transfer-encoding'][0])
except (KeyError, IndexError):
return None | python | def content_transfer_encoding(self) \
-> Optional[ContentTransferEncodingHeader]:
try:
return cast(ContentTransferEncodingHeader,
self[b'content-transfer-encoding'][0])
except (KeyError, IndexError):
return None | [
"def",
"content_transfer_encoding",
"(",
"self",
")",
"->",
"Optional",
"[",
"ContentTransferEncodingHeader",
"]",
":",
"try",
":",
"return",
"cast",
"(",
"ContentTransferEncodingHeader",
",",
"self",
"[",
"b'content-transfer-encoding'",
"]",
"[",
"0",
"]",
")",
"... | The ``Content-Transfer-Encoding`` header. | [
"The",
"Content",
"-",
"Transfer",
"-",
"Encoding",
"header",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/mime/parsed.py#L192-L199 |
24,185 | icgood/pymap | pymap/parsing/__init__.py | Params.copy | def copy(self, *, continuations: List[memoryview] = None,
expected: Sequence[Type['Parseable']] = None,
list_expected: Sequence[Type['Parseable']] = None,
command_name: bytes = None,
uid: bool = None,
charset: str = None,
tag: bytes = None,
max_append_len: int = None,
allow_continuations: bool = None) -> 'Params':
"""Copy the parameters, possibly replacing a subset."""
kwargs: Dict[str, Any] = {}
self._set_if_none(kwargs, 'continuations', continuations)
self._set_if_none(kwargs, 'expected', expected)
self._set_if_none(kwargs, 'list_expected', list_expected)
self._set_if_none(kwargs, 'command_name', command_name)
self._set_if_none(kwargs, 'uid', uid)
self._set_if_none(kwargs, 'charset', charset)
self._set_if_none(kwargs, 'tag', tag)
self._set_if_none(kwargs, 'max_append_len', max_append_len)
self._set_if_none(kwargs, 'allow_continuations', allow_continuations)
return Params(**kwargs) | python | def copy(self, *, continuations: List[memoryview] = None,
expected: Sequence[Type['Parseable']] = None,
list_expected: Sequence[Type['Parseable']] = None,
command_name: bytes = None,
uid: bool = None,
charset: str = None,
tag: bytes = None,
max_append_len: int = None,
allow_continuations: bool = None) -> 'Params':
kwargs: Dict[str, Any] = {}
self._set_if_none(kwargs, 'continuations', continuations)
self._set_if_none(kwargs, 'expected', expected)
self._set_if_none(kwargs, 'list_expected', list_expected)
self._set_if_none(kwargs, 'command_name', command_name)
self._set_if_none(kwargs, 'uid', uid)
self._set_if_none(kwargs, 'charset', charset)
self._set_if_none(kwargs, 'tag', tag)
self._set_if_none(kwargs, 'max_append_len', max_append_len)
self._set_if_none(kwargs, 'allow_continuations', allow_continuations)
return Params(**kwargs) | [
"def",
"copy",
"(",
"self",
",",
"*",
",",
"continuations",
":",
"List",
"[",
"memoryview",
"]",
"=",
"None",
",",
"expected",
":",
"Sequence",
"[",
"Type",
"[",
"'Parseable'",
"]",
"]",
"=",
"None",
",",
"list_expected",
":",
"Sequence",
"[",
"Type",
... | Copy the parameters, possibly replacing a subset. | [
"Copy",
"the",
"parameters",
"possibly",
"replacing",
"a",
"subset",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/__init__.py#L66-L86 |
24,186 | icgood/pymap | pymap/parsing/response/code.py | Capability.string | def string(self) -> bytes:
"""The capabilities string without the enclosing square brackets."""
if self._raw is not None:
return self._raw
self._raw = raw = BytesFormat(b' ').join(
[b'CAPABILITY', b'IMAP4rev1'] + self.capabilities)
return raw | python | def string(self) -> bytes:
if self._raw is not None:
return self._raw
self._raw = raw = BytesFormat(b' ').join(
[b'CAPABILITY', b'IMAP4rev1'] + self.capabilities)
return raw | [
"def",
"string",
"(",
"self",
")",
"->",
"bytes",
":",
"if",
"self",
".",
"_raw",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_raw",
"self",
".",
"_raw",
"=",
"raw",
"=",
"BytesFormat",
"(",
"b' '",
")",
".",
"join",
"(",
"[",
"b'CAPABILITY'"... | The capabilities string without the enclosing square brackets. | [
"The",
"capabilities",
"string",
"without",
"the",
"enclosing",
"square",
"brackets",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/code.py#L29-L35 |
24,187 | icgood/pymap | pymap/parsing/response/__init__.py | Response.text | def text(self) -> bytes:
"""The response text."""
if self.condition:
if self.code:
return BytesFormat(b'%b %b %b') \
% (self.condition, self.code, self._text)
else:
return BytesFormat(b'%b %b') % (self.condition, self._text)
else:
return bytes(self._text) | python | def text(self) -> bytes:
if self.condition:
if self.code:
return BytesFormat(b'%b %b %b') \
% (self.condition, self.code, self._text)
else:
return BytesFormat(b'%b %b') % (self.condition, self._text)
else:
return bytes(self._text) | [
"def",
"text",
"(",
"self",
")",
"->",
"bytes",
":",
"if",
"self",
".",
"condition",
":",
"if",
"self",
".",
"code",
":",
"return",
"BytesFormat",
"(",
"b'%b %b %b'",
")",
"%",
"(",
"self",
".",
"condition",
",",
"self",
".",
"code",
",",
"self",
"... | The response text. | [
"The",
"response",
"text",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L81-L90 |
24,188 | icgood/pymap | pymap/parsing/response/__init__.py | Response.add_untagged | def add_untagged(self, *responses: 'Response') -> None:
"""Add an untagged response. These responses are shown before the
parent response.
Args:
responses: The untagged responses to add.
"""
for resp in responses:
try:
merge_key = resp.merge_key
except TypeError:
self._untagged.append(resp)
else:
key = (type(resp), merge_key)
try:
untagged_idx = self._mergeable[key]
except KeyError:
untagged_idx = len(self._untagged)
self._mergeable[key] = untagged_idx
self._untagged.append(resp)
else:
merged = self._untagged[untagged_idx].merge(resp)
self._untagged[untagged_idx] = merged
self._raw = None | python | def add_untagged(self, *responses: 'Response') -> None:
for resp in responses:
try:
merge_key = resp.merge_key
except TypeError:
self._untagged.append(resp)
else:
key = (type(resp), merge_key)
try:
untagged_idx = self._mergeable[key]
except KeyError:
untagged_idx = len(self._untagged)
self._mergeable[key] = untagged_idx
self._untagged.append(resp)
else:
merged = self._untagged[untagged_idx].merge(resp)
self._untagged[untagged_idx] = merged
self._raw = None | [
"def",
"add_untagged",
"(",
"self",
",",
"*",
"responses",
":",
"'Response'",
")",
"->",
"None",
":",
"for",
"resp",
"in",
"responses",
":",
"try",
":",
"merge_key",
"=",
"resp",
".",
"merge_key",
"except",
"TypeError",
":",
"self",
".",
"_untagged",
"."... | Add an untagged response. These responses are shown before the
parent response.
Args:
responses: The untagged responses to add. | [
"Add",
"an",
"untagged",
"response",
".",
"These",
"responses",
"are",
"shown",
"before",
"the",
"parent",
"response",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L102-L126 |
24,189 | icgood/pymap | pymap/parsing/response/__init__.py | Response.add_untagged_ok | def add_untagged_ok(self, text: MaybeBytes,
code: Optional[ResponseCode] = None) -> None:
"""Add an untagged ``OK`` response.
See Also:
:meth:`.add_untagged`, :class:`ResponseOk`
Args:
text: The response text.
code: Optional response code.
"""
response = ResponseOk(b'*', text, code)
self.add_untagged(response) | python | def add_untagged_ok(self, text: MaybeBytes,
code: Optional[ResponseCode] = None) -> None:
response = ResponseOk(b'*', text, code)
self.add_untagged(response) | [
"def",
"add_untagged_ok",
"(",
"self",
",",
"text",
":",
"MaybeBytes",
",",
"code",
":",
"Optional",
"[",
"ResponseCode",
"]",
"=",
"None",
")",
"->",
"None",
":",
"response",
"=",
"ResponseOk",
"(",
"b'*'",
",",
"text",
",",
"code",
")",
"self",
".",
... | Add an untagged ``OK`` response.
See Also:
:meth:`.add_untagged`, :class:`ResponseOk`
Args:
text: The response text.
code: Optional response code. | [
"Add",
"an",
"untagged",
"OK",
"response",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L128-L141 |
24,190 | icgood/pymap | pymap/parsing/response/__init__.py | Response.is_terminal | def is_terminal(self) -> bool:
"""True if the response contained an untagged ``BYE`` response
indicating that the session should be terminated.
"""
for resp in self._untagged:
if resp.is_terminal:
return True
return False | python | def is_terminal(self) -> bool:
for resp in self._untagged:
if resp.is_terminal:
return True
return False | [
"def",
"is_terminal",
"(",
"self",
")",
"->",
"bool",
":",
"for",
"resp",
"in",
"self",
".",
"_untagged",
":",
"if",
"resp",
".",
"is_terminal",
":",
"return",
"True",
"return",
"False"
] | True if the response contained an untagged ``BYE`` response
indicating that the session should be terminated. | [
"True",
"if",
"the",
"response",
"contained",
"an",
"untagged",
"BYE",
"response",
"indicating",
"that",
"the",
"session",
"should",
"be",
"terminated",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/response/__init__.py#L144-L152 |
24,191 | icgood/pymap | pymap/parsing/specials/sequenceset.py | SequenceSet.is_all | def is_all(self) -> bool:
"""True if the sequence set starts at ``1`` and ends at the maximum
value.
This may be used to optimize cases of checking for a value in the set,
avoiding the need to provide ``max_value`` in :meth:`.flatten` or
:meth:`.iter`.
"""
first = self.sequences[0]
return isinstance(first, tuple) \
and first[0] == 1 and isinstance(first[1], MaxValue) | python | def is_all(self) -> bool:
first = self.sequences[0]
return isinstance(first, tuple) \
and first[0] == 1 and isinstance(first[1], MaxValue) | [
"def",
"is_all",
"(",
"self",
")",
"->",
"bool",
":",
"first",
"=",
"self",
".",
"sequences",
"[",
"0",
"]",
"return",
"isinstance",
"(",
"first",
",",
"tuple",
")",
"and",
"first",
"[",
"0",
"]",
"==",
"1",
"and",
"isinstance",
"(",
"first",
"[",
... | True if the sequence set starts at ``1`` and ends at the maximum
value.
This may be used to optimize cases of checking for a value in the set,
avoiding the need to provide ``max_value`` in :meth:`.flatten` or
:meth:`.iter`. | [
"True",
"if",
"the",
"sequence",
"set",
"starts",
"at",
"1",
"and",
"ends",
"at",
"the",
"maximum",
"value",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/sequenceset.py#L61-L72 |
24,192 | icgood/pymap | pymap/parsing/specials/sequenceset.py | SequenceSet.flatten | def flatten(self, max_value: int) -> FrozenSet[int]:
"""Return a set of all values contained in the sequence set.
Args:
max_value: The maximum value, in place of any ``*``.
"""
return frozenset(self.iter(max_value)) | python | def flatten(self, max_value: int) -> FrozenSet[int]:
return frozenset(self.iter(max_value)) | [
"def",
"flatten",
"(",
"self",
",",
"max_value",
":",
"int",
")",
"->",
"FrozenSet",
"[",
"int",
"]",
":",
"return",
"frozenset",
"(",
"self",
".",
"iter",
"(",
"max_value",
")",
")"
] | Return a set of all values contained in the sequence set.
Args:
max_value: The maximum value, in place of any ``*``. | [
"Return",
"a",
"set",
"of",
"all",
"values",
"contained",
"in",
"the",
"sequence",
"set",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/sequenceset.py#L96-L103 |
24,193 | icgood/pymap | pymap/parsing/specials/sequenceset.py | SequenceSet.build | def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet':
"""Build a new sequence set that contains the given values using as
few groups as possible.
Args:
seqs: The sequence values to build.
uid: True if the sequences refer to message UIDs.
"""
seqs_list = sorted(set(seqs))
groups: List[Union[int, Tuple[int, int]]] = []
group: Union[int, Tuple[int, int]] = seqs_list[0]
for i in range(1, len(seqs_list)):
group_i = seqs_list[i]
if isinstance(group, int):
if group_i == group + 1:
group = (group, group_i)
else:
groups.append(group)
group = group_i
elif isinstance(group, tuple):
if group_i == group[1] + 1:
group = (group[0], group_i)
else:
groups.append(group)
group = group_i
groups.append(group)
return SequenceSet(groups, uid) | python | def build(cls, seqs: Iterable[int], uid: bool = False) -> 'SequenceSet':
seqs_list = sorted(set(seqs))
groups: List[Union[int, Tuple[int, int]]] = []
group: Union[int, Tuple[int, int]] = seqs_list[0]
for i in range(1, len(seqs_list)):
group_i = seqs_list[i]
if isinstance(group, int):
if group_i == group + 1:
group = (group, group_i)
else:
groups.append(group)
group = group_i
elif isinstance(group, tuple):
if group_i == group[1] + 1:
group = (group[0], group_i)
else:
groups.append(group)
group = group_i
groups.append(group)
return SequenceSet(groups, uid) | [
"def",
"build",
"(",
"cls",
",",
"seqs",
":",
"Iterable",
"[",
"int",
"]",
",",
"uid",
":",
"bool",
"=",
"False",
")",
"->",
"'SequenceSet'",
":",
"seqs_list",
"=",
"sorted",
"(",
"set",
"(",
"seqs",
")",
")",
"groups",
":",
"List",
"[",
"Union",
... | Build a new sequence set that contains the given values using as
few groups as possible.
Args:
seqs: The sequence values to build.
uid: True if the sequences refer to message UIDs. | [
"Build",
"a",
"new",
"sequence",
"set",
"that",
"contains",
"the",
"given",
"values",
"using",
"as",
"few",
"groups",
"as",
"possible",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/parsing/specials/sequenceset.py#L173-L200 |
24,194 | icgood/pymap | pymap/listtree.py | ListTree.update | def update(self, *names: str) -> 'ListTree':
"""Add all the mailbox names to the tree, filling in any missing nodes.
Args:
names: The names of the mailboxes.
"""
for name in names:
parts = name.split(self._delimiter)
self._root.add(*parts)
return self | python | def update(self, *names: str) -> 'ListTree':
for name in names:
parts = name.split(self._delimiter)
self._root.add(*parts)
return self | [
"def",
"update",
"(",
"self",
",",
"*",
"names",
":",
"str",
")",
"->",
"'ListTree'",
":",
"for",
"name",
"in",
"names",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"self",
".",
"_delimiter",
")",
"self",
".",
"_root",
".",
"add",
"(",
"*",
"pa... | Add all the mailbox names to the tree, filling in any missing nodes.
Args:
names: The names of the mailboxes. | [
"Add",
"all",
"the",
"mailbox",
"names",
"to",
"the",
"tree",
"filling",
"in",
"any",
"missing",
"nodes",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L93-L103 |
24,195 | icgood/pymap | pymap/listtree.py | ListTree.set_marked | def set_marked(self, name: str, marked: bool = False,
unmarked: bool = False) -> None:
"""Add or remove the ``\\Marked`` and ``\\Unmarked`` mailbox
attributes.
Args:
name: The name of the mailbox.
marked: True if the ``\\Marked`` attribute should be added.
unmarked: True if the ``\\Unmarked`` attribute should be added.
"""
if marked:
self._marked[name] = True
elif unmarked:
self._marked[name] = False
else:
self._marked.pop(name, None) | python | def set_marked(self, name: str, marked: bool = False,
unmarked: bool = False) -> None:
if marked:
self._marked[name] = True
elif unmarked:
self._marked[name] = False
else:
self._marked.pop(name, None) | [
"def",
"set_marked",
"(",
"self",
",",
"name",
":",
"str",
",",
"marked",
":",
"bool",
"=",
"False",
",",
"unmarked",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"marked",
":",
"self",
".",
"_marked",
"[",
"name",
"]",
"=",
"True",
"... | Add or remove the ``\\Marked`` and ``\\Unmarked`` mailbox
attributes.
Args:
name: The name of the mailbox.
marked: True if the ``\\Marked`` attribute should be added.
unmarked: True if the ``\\Unmarked`` attribute should be added. | [
"Add",
"or",
"remove",
"the",
"\\\\",
"Marked",
"and",
"\\\\",
"Unmarked",
"mailbox",
"attributes",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L105-L121 |
24,196 | icgood/pymap | pymap/listtree.py | ListTree.get | def get(self, name: str) -> Optional[ListEntry]:
"""Return the named entry in the list tree.
Args:
name: The entry name.
"""
parts = name.split(self._delimiter)
try:
node = self._find(self._root, *parts)
except KeyError:
return None
else:
marked = self._marked.get(name)
return ListEntry(name, node.exists, marked, bool(node.children)) | python | def get(self, name: str) -> Optional[ListEntry]:
parts = name.split(self._delimiter)
try:
node = self._find(self._root, *parts)
except KeyError:
return None
else:
marked = self._marked.get(name)
return ListEntry(name, node.exists, marked, bool(node.children)) | [
"def",
"get",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Optional",
"[",
"ListEntry",
"]",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"self",
".",
"_delimiter",
")",
"try",
":",
"node",
"=",
"self",
".",
"_find",
"(",
"self",
".",
"_roo... | Return the named entry in the list tree.
Args:
name: The entry name. | [
"Return",
"the",
"named",
"entry",
"in",
"the",
"list",
"tree",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L142-L156 |
24,197 | icgood/pymap | pymap/listtree.py | ListTree.list | def list(self) -> Iterable[ListEntry]:
"""Return all the entries in the list tree."""
for entry in self._iter(self._root, ''):
yield entry | python | def list(self) -> Iterable[ListEntry]:
for entry in self._iter(self._root, ''):
yield entry | [
"def",
"list",
"(",
"self",
")",
"->",
"Iterable",
"[",
"ListEntry",
"]",
":",
"for",
"entry",
"in",
"self",
".",
"_iter",
"(",
"self",
".",
"_root",
",",
"''",
")",
":",
"yield",
"entry"
] | Return all the entries in the list tree. | [
"Return",
"all",
"the",
"entries",
"in",
"the",
"list",
"tree",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L186-L189 |
24,198 | icgood/pymap | pymap/listtree.py | ListTree.list_matching | def list_matching(self, ref_name: str, filter_: str) \
-> Iterable[ListEntry]:
"""Return all the entries in the list tree that match the given query.
Args:
ref_name: Mailbox reference name.
filter_: Mailbox name with possible wildcards.
"""
canonical, canonical_i = self._get_pattern(ref_name + filter_)
for entry in self.list():
if entry.name == 'INBOX':
if canonical_i.match('INBOX'):
yield entry
elif canonical.match(entry.name):
yield entry | python | def list_matching(self, ref_name: str, filter_: str) \
-> Iterable[ListEntry]:
canonical, canonical_i = self._get_pattern(ref_name + filter_)
for entry in self.list():
if entry.name == 'INBOX':
if canonical_i.match('INBOX'):
yield entry
elif canonical.match(entry.name):
yield entry | [
"def",
"list_matching",
"(",
"self",
",",
"ref_name",
":",
"str",
",",
"filter_",
":",
"str",
")",
"->",
"Iterable",
"[",
"ListEntry",
"]",
":",
"canonical",
",",
"canonical_i",
"=",
"self",
".",
"_get_pattern",
"(",
"ref_name",
"+",
"filter_",
")",
"for... | Return all the entries in the list tree that match the given query.
Args:
ref_name: Mailbox reference name.
filter_: Mailbox name with possible wildcards. | [
"Return",
"all",
"the",
"entries",
"in",
"the",
"list",
"tree",
"that",
"match",
"the",
"given",
"query",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/listtree.py#L203-L218 |
24,199 | icgood/pymap | pymap/selected.py | SynchronizedMessages.get | def get(self, uid: int) -> Optional[CachedMessage]:
"""Return the given cached message.
Args:
uid: The message UID.
"""
return self._cache.get(uid) | python | def get(self, uid: int) -> Optional[CachedMessage]:
return self._cache.get(uid) | [
"def",
"get",
"(",
"self",
",",
"uid",
":",
"int",
")",
"->",
"Optional",
"[",
"CachedMessage",
"]",
":",
"return",
"self",
".",
"_cache",
".",
"get",
"(",
"uid",
")"
] | Return the given cached message.
Args:
uid: The message UID. | [
"Return",
"the",
"given",
"cached",
"message",
"."
] | e77d9a54d760e3cbe044a548883bb4299ed61dc2 | https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/selected.py#L161-L168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.