repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
uwdata/draco | draco/run.py | run_clingo | def run_clingo(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
) -> Tuple[str, str]:
"""
Run draco and return stderr and stdout
"""
# default args
files = files or DRACO_LP
if relax_hard and "hard-integrity.lp" in files:
files.remove("hard-integrity.lp")
constants = constants or {}
options = ["--outf=2", "--quiet=1,2,2"]
if silence_warnings:
options.append("--warn=no-atom-undefined")
for name, value in constants.items():
options.append(f"-c {name}={value}")
cmd = ["clingo"] + options
logger.debug("Command: %s", " ".join(cmd))
proc = subprocess.Popen(
args=cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
program = "\n".join(draco_query)
file_names = [os.path.join(DRACO_LP_DIR, f) for f in files]
asp_program = b"\n".join(map(load_file, file_names)) + program.encode("utf8")
if debug:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as fd:
fd.write(program)
logger.info('Debug ASP with "clingo %s %s"', " ".join(file_names), fd.name)
stdout, stderr = proc.communicate(asp_program)
return (stderr, stdout) | python | def run_clingo(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
) -> Tuple[str, str]:
"""
Run draco and return stderr and stdout
"""
# default args
files = files or DRACO_LP
if relax_hard and "hard-integrity.lp" in files:
files.remove("hard-integrity.lp")
constants = constants or {}
options = ["--outf=2", "--quiet=1,2,2"]
if silence_warnings:
options.append("--warn=no-atom-undefined")
for name, value in constants.items():
options.append(f"-c {name}={value}")
cmd = ["clingo"] + options
logger.debug("Command: %s", " ".join(cmd))
proc = subprocess.Popen(
args=cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
program = "\n".join(draco_query)
file_names = [os.path.join(DRACO_LP_DIR, f) for f in files]
asp_program = b"\n".join(map(load_file, file_names)) + program.encode("utf8")
if debug:
with tempfile.NamedTemporaryFile(mode="w", delete=False) as fd:
fd.write(program)
logger.info('Debug ASP with "clingo %s %s"', " ".join(file_names), fd.name)
stdout, stderr = proc.communicate(asp_program)
return (stderr, stdout) | [
"def",
"run_clingo",
"(",
"draco_query",
":",
"List",
"[",
"str",
"]",
",",
"constants",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"files",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"relax_hard",
"=",
"False",
",",
"silence_... | Run draco and return stderr and stdout | [
"Run",
"draco",
"and",
"return",
"stderr",
"and",
"stdout"
] | b130b5ebdb369e18e046706c73dc9c29b8159f7f | https://github.com/uwdata/draco/blob/b130b5ebdb369e18e046706c73dc9c29b8159f7f/draco/run.py#L74-L118 | train | 34,800 |
uwdata/draco | draco/run.py | run | def run(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
clear_cache=False,
) -> Optional[Result]:
""" Run clingo to compute a completion of a partial spec or violations. """
# Clear file cache. useful during development in notebooks.
if clear_cache and file_cache:
logger.warning("Cleared file cache")
file_cache.clear()
stderr, stdout = run_clingo(
draco_query, constants, files, relax_hard, silence_warnings, debug
)
try:
json_result = json.loads(stdout)
except json.JSONDecodeError:
logger.error("stdout: %s", stdout)
logger.error("stderr: %s", stderr)
raise
if stderr:
logger.error(stderr)
result = json_result["Result"]
if result == "UNSATISFIABLE":
logger.info("Constraints are unsatisfiable.")
return None
elif result == "OPTIMUM FOUND":
# get the last witness, which is the best result
answers = json_result["Call"][0]["Witnesses"][-1]
logger.debug(answers["Value"])
return Result(
clyngor.Answers(answers["Value"]).sorted,
cost=json_result["Models"]["Costs"][0],
)
elif result == "SATISFIABLE":
answers = json_result["Call"][0]["Witnesses"][-1]
assert (
json_result["Models"]["Number"] == 1
), "Should not have more than one model if we don't optimize"
logger.debug(answers["Value"])
return Result(clyngor.Answers(answers["Value"]).sorted)
else:
logger.error("Unsupported result: %s", result)
return None | python | def run(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
clear_cache=False,
) -> Optional[Result]:
""" Run clingo to compute a completion of a partial spec or violations. """
# Clear file cache. useful during development in notebooks.
if clear_cache and file_cache:
logger.warning("Cleared file cache")
file_cache.clear()
stderr, stdout = run_clingo(
draco_query, constants, files, relax_hard, silence_warnings, debug
)
try:
json_result = json.loads(stdout)
except json.JSONDecodeError:
logger.error("stdout: %s", stdout)
logger.error("stderr: %s", stderr)
raise
if stderr:
logger.error(stderr)
result = json_result["Result"]
if result == "UNSATISFIABLE":
logger.info("Constraints are unsatisfiable.")
return None
elif result == "OPTIMUM FOUND":
# get the last witness, which is the best result
answers = json_result["Call"][0]["Witnesses"][-1]
logger.debug(answers["Value"])
return Result(
clyngor.Answers(answers["Value"]).sorted,
cost=json_result["Models"]["Costs"][0],
)
elif result == "SATISFIABLE":
answers = json_result["Call"][0]["Witnesses"][-1]
assert (
json_result["Models"]["Number"] == 1
), "Should not have more than one model if we don't optimize"
logger.debug(answers["Value"])
return Result(clyngor.Answers(answers["Value"]).sorted)
else:
logger.error("Unsupported result: %s", result)
return None | [
"def",
"run",
"(",
"draco_query",
":",
"List",
"[",
"str",
"]",
",",
"constants",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"files",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"relax_hard",
"=",
"False",
",",
"silence_warning... | Run clingo to compute a completion of a partial spec or violations. | [
"Run",
"clingo",
"to",
"compute",
"a",
"completion",
"of",
"a",
"partial",
"spec",
"or",
"violations",
"."
] | b130b5ebdb369e18e046706c73dc9c29b8159f7f | https://github.com/uwdata/draco/blob/b130b5ebdb369e18e046706c73dc9c29b8159f7f/draco/run.py#L121-L178 | train | 34,801 |
thiderman/doge | doge/wow.py | DogeDeque.get | def get(self):
"""
Get one item. This will rotate the deque one step. Repeated gets will
return different items.
"""
self.index += 1
# If we've gone through the entire deque once, shuffle it again to
# simulate ever-flowing random. self.shuffle() will run __init__(),
# which will reset the index to 0.
if self.index == len(self):
self.shuffle()
self.rotate(1)
try:
return self[0]
except:
return "wow" | python | def get(self):
"""
Get one item. This will rotate the deque one step. Repeated gets will
return different items.
"""
self.index += 1
# If we've gone through the entire deque once, shuffle it again to
# simulate ever-flowing random. self.shuffle() will run __init__(),
# which will reset the index to 0.
if self.index == len(self):
self.shuffle()
self.rotate(1)
try:
return self[0]
except:
return "wow" | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"index",
"+=",
"1",
"# If we've gone through the entire deque once, shuffle it again to",
"# simulate ever-flowing random. self.shuffle() will run __init__(),",
"# which will reset the index to 0.",
"if",
"self",
".",
"index",
"==... | Get one item. This will rotate the deque one step. Repeated gets will
return different items. | [
"Get",
"one",
"item",
".",
"This",
"will",
"rotate",
"the",
"deque",
"one",
"step",
".",
"Repeated",
"gets",
"will",
"return",
"different",
"items",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/wow.py#L29-L48 | train | 34,802 |
thiderman/doge | doge/wow.py | DogeDeque.shuffle | def shuffle(self):
"""
Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque.
"""
args = list(self)
random.shuffle(args)
self.clear()
super(DogeDeque, self).__init__(args) | python | def shuffle(self):
"""
Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque.
"""
args = list(self)
random.shuffle(args)
self.clear()
super(DogeDeque, self).__init__(args) | [
"def",
"shuffle",
"(",
"self",
")",
":",
"args",
"=",
"list",
"(",
"self",
")",
"random",
".",
"shuffle",
"(",
"args",
")",
"self",
".",
"clear",
"(",
")",
"super",
"(",
"DogeDeque",
",",
"self",
")",
".",
"__init__",
"(",
"args",
")"
] | Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque. | [
"Shuffle",
"the",
"deque"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/wow.py#L55-L68 | train | 34,803 |
thiderman/doge | doge/wow.py | FrequencyBasedDogeDeque.get | def get(self):
"""
Get one item and prepare to get an item with lower
rank on the next call.
"""
if len(self) < 1:
return "wow"
if self.index >= len(self):
self.index = 0
step = random.randint(1, min(self.step, len(self)))
res = self[0]
self.index += step
self.rotate(step)
return res | python | def get(self):
"""
Get one item and prepare to get an item with lower
rank on the next call.
"""
if len(self) < 1:
return "wow"
if self.index >= len(self):
self.index = 0
step = random.randint(1, min(self.step, len(self)))
res = self[0]
self.index += step
self.rotate(step)
return res | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"<",
"1",
":",
"return",
"\"wow\"",
"if",
"self",
".",
"index",
">=",
"len",
"(",
"self",
")",
":",
"self",
".",
"index",
"=",
"0",
"step",
"=",
"random",
".",
"randint",
"(",
... | Get one item and prepare to get an item with lower
rank on the next call. | [
"Get",
"one",
"item",
"and",
"prepare",
"to",
"get",
"an",
"item",
"with",
"lower",
"rank",
"on",
"the",
"next",
"call",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/wow.py#L86-L103 | train | 34,804 |
thiderman/doge | doge/core.py | onscreen_len | def onscreen_len(s):
"""
Calculate the length of a unicode string on screen,
accounting for double-width characters
"""
if sys.version_info < (3, 0) and isinstance(s, str):
return len(s)
length = 0
for ch in s:
length += 2 if unicodedata.east_asian_width(ch) == 'W' else 1
return length | python | def onscreen_len(s):
"""
Calculate the length of a unicode string on screen,
accounting for double-width characters
"""
if sys.version_info < (3, 0) and isinstance(s, str):
return len(s)
length = 0
for ch in s:
length += 2 if unicodedata.east_asian_width(ch) == 'W' else 1
return length | [
"def",
"onscreen_len",
"(",
"s",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
"and",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"len",
"(",
"s",
")",
"length",
"=",
"0",
"for",
"ch",
"in",
"s",
":",
"... | Calculate the length of a unicode string on screen,
accounting for double-width characters | [
"Calculate",
"the",
"length",
"of",
"a",
"unicode",
"string",
"on",
"screen",
"accounting",
"for",
"double",
"-",
"width",
"characters"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L400-L414 | train | 34,805 |
thiderman/doge | doge/core.py | Doge.setup_seasonal | def setup_seasonal(self):
"""
Check if there's some seasonal holiday going on, setup appropriate
Shibe picture and load holiday words.
Note: if there are two or more holidays defined for a certain date,
the first one takes precedence.
"""
# If we've specified a season, just run that one
if self.ns.season:
return self.load_season(self.ns.season)
# If we've specified another doge or no doge at all, it does not make
# sense to use seasons.
if self.ns.doge_path is not None and not self.ns.no_shibe:
return
now = datetime.datetime.now()
for season, data in wow.SEASONS.items():
start, end = data['dates']
start_dt = datetime.datetime(now.year, start[0], start[1])
# Be sane if the holiday season spans over New Year's day.
end_dt = datetime.datetime(
now.year + (start[0] > end[0] and 1 or 0), end[0], end[1])
if start_dt <= now <= end_dt:
# Wow, much holiday!
return self.load_season(season) | python | def setup_seasonal(self):
"""
Check if there's some seasonal holiday going on, setup appropriate
Shibe picture and load holiday words.
Note: if there are two or more holidays defined for a certain date,
the first one takes precedence.
"""
# If we've specified a season, just run that one
if self.ns.season:
return self.load_season(self.ns.season)
# If we've specified another doge or no doge at all, it does not make
# sense to use seasons.
if self.ns.doge_path is not None and not self.ns.no_shibe:
return
now = datetime.datetime.now()
for season, data in wow.SEASONS.items():
start, end = data['dates']
start_dt = datetime.datetime(now.year, start[0], start[1])
# Be sane if the holiday season spans over New Year's day.
end_dt = datetime.datetime(
now.year + (start[0] > end[0] and 1 or 0), end[0], end[1])
if start_dt <= now <= end_dt:
# Wow, much holiday!
return self.load_season(season) | [
"def",
"setup_seasonal",
"(",
"self",
")",
":",
"# If we've specified a season, just run that one",
"if",
"self",
".",
"ns",
".",
"season",
":",
"return",
"self",
".",
"load_season",
"(",
"self",
".",
"ns",
".",
"season",
")",
"# If we've specified another doge or n... | Check if there's some seasonal holiday going on, setup appropriate
Shibe picture and load holiday words.
Note: if there are two or more holidays defined for a certain date,
the first one takes precedence. | [
"Check",
"if",
"there",
"s",
"some",
"seasonal",
"holiday",
"going",
"on",
"setup",
"appropriate",
"Shibe",
"picture",
"and",
"load",
"holiday",
"words",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L75-L106 | train | 34,806 |
thiderman/doge | doge/core.py | Doge.apply_text | def apply_text(self):
"""
Apply text around doge
"""
# Calculate a random sampling of lines that are to have text applied
# onto them. Return value is a sorted list of line index integers.
linelen = len(self.lines)
affected = sorted(random.sample(range(linelen), int(linelen / 3.5)))
for i, target in enumerate(affected, start=1):
line = self.lines[target]
line = re.sub('\n', ' ', line)
word = self.words.get()
# If first or last line, or a random selection, use standalone wow.
if i == 1 or i == len(affected) or random.choice(range(20)) == 0:
word = 'wow'
# Generate a new DogeMessage, possibly based on a word.
self.lines[target] = DogeMessage(self, line, word).generate() | python | def apply_text(self):
"""
Apply text around doge
"""
# Calculate a random sampling of lines that are to have text applied
# onto them. Return value is a sorted list of line index integers.
linelen = len(self.lines)
affected = sorted(random.sample(range(linelen), int(linelen / 3.5)))
for i, target in enumerate(affected, start=1):
line = self.lines[target]
line = re.sub('\n', ' ', line)
word = self.words.get()
# If first or last line, or a random selection, use standalone wow.
if i == 1 or i == len(affected) or random.choice(range(20)) == 0:
word = 'wow'
# Generate a new DogeMessage, possibly based on a word.
self.lines[target] = DogeMessage(self, line, word).generate() | [
"def",
"apply_text",
"(",
"self",
")",
":",
"# Calculate a random sampling of lines that are to have text applied",
"# onto them. Return value is a sorted list of line index integers.",
"linelen",
"=",
"len",
"(",
"self",
".",
"lines",
")",
"affected",
"=",
"sorted",
"(",
"ra... | Apply text around doge | [
"Apply",
"text",
"around",
"doge"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L116-L138 | train | 34,807 |
thiderman/doge | doge/core.py | Doge.load_doge | def load_doge(self):
"""
Return pretty ASCII Shibe.
wow
"""
if self.ns.no_shibe:
return ['']
with open(self.doge_path) as f:
if sys.version_info < (3, 0):
if locale.getpreferredencoding() == 'UTF-8':
doge_lines = [l.decode('utf-8') for l in f.xreadlines()]
else:
# encode to printable characters, leaving a space in place
# of untranslatable characters, resulting in a slightly
# blockier doge on non-UTF8 terminals
doge_lines = [
l.decode('utf-8')
.encode(locale.getpreferredencoding(), 'replace')
.replace('?', ' ')
for l in f.xreadlines()
]
else:
doge_lines = [l for l in f.readlines()]
return doge_lines | python | def load_doge(self):
"""
Return pretty ASCII Shibe.
wow
"""
if self.ns.no_shibe:
return ['']
with open(self.doge_path) as f:
if sys.version_info < (3, 0):
if locale.getpreferredencoding() == 'UTF-8':
doge_lines = [l.decode('utf-8') for l in f.xreadlines()]
else:
# encode to printable characters, leaving a space in place
# of untranslatable characters, resulting in a slightly
# blockier doge on non-UTF8 terminals
doge_lines = [
l.decode('utf-8')
.encode(locale.getpreferredencoding(), 'replace')
.replace('?', ' ')
for l in f.xreadlines()
]
else:
doge_lines = [l for l in f.readlines()]
return doge_lines | [
"def",
"load_doge",
"(",
"self",
")",
":",
"if",
"self",
".",
"ns",
".",
"no_shibe",
":",
"return",
"[",
"''",
"]",
"with",
"open",
"(",
"self",
".",
"doge_path",
")",
"as",
"f",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
"... | Return pretty ASCII Shibe.
wow | [
"Return",
"pretty",
"ASCII",
"Shibe",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L140-L167 | train | 34,808 |
thiderman/doge | doge/core.py | Doge.get_real_data | def get_real_data(self):
"""
Grab actual data from the system
"""
ret = []
username = os.environ.get('USER')
if username:
ret.append(username)
editor = os.environ.get('EDITOR')
if editor:
editor = editor.split('/')[-1]
ret.append(editor)
# OS, hostname and... architechture (because lel)
if hasattr(os, 'uname'):
uname = os.uname()
ret.append(uname[0])
ret.append(uname[1])
ret.append(uname[4])
# Grab actual files from $HOME.
files = os.listdir(os.environ.get('HOME'))
if files:
ret.append(random.choice(files))
# Grab some processes
ret += self.get_processes()[:2]
# Prepare the returned data. First, lowercase it.
# If there is unicode data being returned from any of the above
# Python 2 needs to decode the UTF bytes to not crash. See issue #45.
func = str.lower
if sys.version_info < (3,):
func = lambda x: str.lower(x).decode('utf-8')
self.words.extend(map(func, ret)) | python | def get_real_data(self):
"""
Grab actual data from the system
"""
ret = []
username = os.environ.get('USER')
if username:
ret.append(username)
editor = os.environ.get('EDITOR')
if editor:
editor = editor.split('/')[-1]
ret.append(editor)
# OS, hostname and... architechture (because lel)
if hasattr(os, 'uname'):
uname = os.uname()
ret.append(uname[0])
ret.append(uname[1])
ret.append(uname[4])
# Grab actual files from $HOME.
files = os.listdir(os.environ.get('HOME'))
if files:
ret.append(random.choice(files))
# Grab some processes
ret += self.get_processes()[:2]
# Prepare the returned data. First, lowercase it.
# If there is unicode data being returned from any of the above
# Python 2 needs to decode the UTF bytes to not crash. See issue #45.
func = str.lower
if sys.version_info < (3,):
func = lambda x: str.lower(x).decode('utf-8')
self.words.extend(map(func, ret)) | [
"def",
"get_real_data",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'USER'",
")",
"if",
"username",
":",
"ret",
".",
"append",
"(",
"username",
")",
"editor",
"=",
"os",
".",
"environ",
".",... | Grab actual data from the system | [
"Grab",
"actual",
"data",
"from",
"the",
"system"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L169-L207 | train | 34,809 |
thiderman/doge | doge/core.py | Doge.get_stdin_data | def get_stdin_data(self):
"""
Get words from stdin.
"""
if self.tty.in_is_tty:
# No pipez found
return False
if sys.version_info < (3, 0):
stdin_lines = (l.decode('utf-8') for l in sys.stdin.xreadlines())
else:
stdin_lines = (l for l in sys.stdin.readlines())
rx_word = re.compile("\w+", re.UNICODE)
# If we have stdin data, we should remove everything else!
self.words.clear()
word_list = [match.group(0)
for line in stdin_lines
for match in rx_word.finditer(line.lower())]
if self.ns.filter_stopwords:
word_list = self.filter_words(
word_list, stopwords=wow.STOPWORDS,
min_length=self.ns.min_length)
self.words.extend(word_list)
return True | python | def get_stdin_data(self):
"""
Get words from stdin.
"""
if self.tty.in_is_tty:
# No pipez found
return False
if sys.version_info < (3, 0):
stdin_lines = (l.decode('utf-8') for l in sys.stdin.xreadlines())
else:
stdin_lines = (l for l in sys.stdin.readlines())
rx_word = re.compile("\w+", re.UNICODE)
# If we have stdin data, we should remove everything else!
self.words.clear()
word_list = [match.group(0)
for line in stdin_lines
for match in rx_word.finditer(line.lower())]
if self.ns.filter_stopwords:
word_list = self.filter_words(
word_list, stopwords=wow.STOPWORDS,
min_length=self.ns.min_length)
self.words.extend(word_list)
return True | [
"def",
"get_stdin_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"tty",
".",
"in_is_tty",
":",
"# No pipez found",
"return",
"False",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"stdin_lines",
"=",
"(",
"l",
".",
"decode",
... | Get words from stdin. | [
"Get",
"words",
"from",
"stdin",
"."
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L213-L242 | train | 34,810 |
thiderman/doge | doge/core.py | Doge.get_processes | def get_processes(self):
"""
Grab a shuffled list of all currently running process names
"""
procs = set()
try:
# POSIX ps, so it should work in most environments where doge would
p = sp.Popen(['ps', '-A', '-o', 'comm='], stdout=sp.PIPE)
output, error = p.communicate()
if sys.version_info > (3, 0):
output = output.decode('utf-8')
for comm in output.split('\n'):
name = comm.split('/')[-1]
# Filter short and weird ones
if name and len(name) >= 2 and ':' not in name:
procs.add(name)
finally:
# Either it executed properly or no ps was found.
proc_list = list(procs)
random.shuffle(proc_list)
return proc_list | python | def get_processes(self):
"""
Grab a shuffled list of all currently running process names
"""
procs = set()
try:
# POSIX ps, so it should work in most environments where doge would
p = sp.Popen(['ps', '-A', '-o', 'comm='], stdout=sp.PIPE)
output, error = p.communicate()
if sys.version_info > (3, 0):
output = output.decode('utf-8')
for comm in output.split('\n'):
name = comm.split('/')[-1]
# Filter short and weird ones
if name and len(name) >= 2 and ':' not in name:
procs.add(name)
finally:
# Either it executed properly or no ps was found.
proc_list = list(procs)
random.shuffle(proc_list)
return proc_list | [
"def",
"get_processes",
"(",
"self",
")",
":",
"procs",
"=",
"set",
"(",
")",
"try",
":",
"# POSIX ps, so it should work in most environments where doge would",
"p",
"=",
"sp",
".",
"Popen",
"(",
"[",
"'ps'",
",",
"'-A'",
",",
"'-o'",
",",
"'comm='",
"]",
",... | Grab a shuffled list of all currently running process names | [
"Grab",
"a",
"shuffled",
"list",
"of",
"all",
"currently",
"running",
"process",
"names"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L244-L270 | train | 34,811 |
thiderman/doge | doge/core.py | TTYHandler.get_tty_size | def get_tty_size(self):
"""
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does.
"""
if sys.platform == 'win32':
# stdin, stdout, stderr = -10, -11, -12
ret = self._tty_size_windows(-10)
ret = ret or self._tty_size_windows(-11)
ret = ret or self._tty_size_windows(-12)
else:
# stdin, stdout, stderr = 0, 1, 2
ret = self._tty_size_linux(0)
ret = ret or self._tty_size_linux(1)
ret = ret or self._tty_size_linux(2)
return ret or (25, 80) | python | def get_tty_size(self):
"""
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does.
"""
if sys.platform == 'win32':
# stdin, stdout, stderr = -10, -11, -12
ret = self._tty_size_windows(-10)
ret = ret or self._tty_size_windows(-11)
ret = ret or self._tty_size_windows(-12)
else:
# stdin, stdout, stderr = 0, 1, 2
ret = self._tty_size_linux(0)
ret = ret or self._tty_size_linux(1)
ret = ret or self._tty_size_linux(2)
return ret or (25, 80) | [
"def",
"get_tty_size",
"(",
"self",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"# stdin, stdout, stderr = -10, -11, -12",
"ret",
"=",
"self",
".",
"_tty_size_windows",
"(",
"-",
"10",
")",
"ret",
"=",
"ret",
"or",
"self",
".",
"_tty_size_w... | Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does. | [
"Get",
"the",
"current",
"terminal",
"size",
"without",
"using",
"a",
"subprocess"
] | cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f | https://github.com/thiderman/doge/blob/cea077d4f72929f9dcf44d0d16a7d1a6ee0e3e3f/doge/core.py#L365-L386 | train | 34,812 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | _coords | def _coords(shape):
"""
Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or more lists
of any interior coordinates.
"""
assert shape.geom_type == 'Polygon'
coords = [list(shape.exterior.coords)]
for interior in shape.interiors:
coords.append(list(interior.coords))
return coords | python | def _coords(shape):
"""
Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or more lists
of any interior coordinates.
"""
assert shape.geom_type == 'Polygon'
coords = [list(shape.exterior.coords)]
for interior in shape.interiors:
coords.append(list(interior.coords))
return coords | [
"def",
"_coords",
"(",
"shape",
")",
":",
"assert",
"shape",
".",
"geom_type",
"==",
"'Polygon'",
"coords",
"=",
"[",
"list",
"(",
"shape",
".",
"exterior",
".",
"coords",
")",
"]",
"for",
"interior",
"in",
"shape",
".",
"interiors",
":",
"coords",
"."... | Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or more lists
of any interior coordinates. | [
"Return",
"a",
"list",
"of",
"lists",
"of",
"coordinates",
"of",
"the",
"polygon",
".",
"The",
"list",
"consists",
"firstly",
"of",
"the",
"list",
"of",
"exterior",
"coordinates",
"followed",
"by",
"zero",
"or",
"more",
"lists",
"of",
"any",
"interior",
"c... | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L8-L19 | train | 34,813 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | _union_in_blocks | def _union_in_blocks(contours, block_size):
"""
Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them.
"""
n_contours = len(contours)
for i in range(0, n_contours, block_size):
j = min(i + block_size, n_contours)
inners = []
for c in contours[i:j]:
p = _contour_to_poly(c)
if p.type == 'Polygon':
inners.append(p)
elif p.type == 'MultiPolygon':
inners.extend(p.geoms)
holes = unary_union(inners)
assert holes.is_valid
yield holes | python | def _union_in_blocks(contours, block_size):
"""
Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them.
"""
n_contours = len(contours)
for i in range(0, n_contours, block_size):
j = min(i + block_size, n_contours)
inners = []
for c in contours[i:j]:
p = _contour_to_poly(c)
if p.type == 'Polygon':
inners.append(p)
elif p.type == 'MultiPolygon':
inners.extend(p.geoms)
holes = unary_union(inners)
assert holes.is_valid
yield holes | [
"def",
"_union_in_blocks",
"(",
"contours",
",",
"block_size",
")",
":",
"n_contours",
"=",
"len",
"(",
"contours",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"n_contours",
",",
"block_size",
")",
":",
"j",
"=",
"min",
"(",
"i",
"+",
"block_size",
... | Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them. | [
"Generator",
"which",
"yields",
"a",
"valid",
"shape",
"for",
"each",
"block_size",
"multiple",
"of",
"input",
"contours",
".",
"This",
"merges",
"together",
"the",
"contours",
"for",
"each",
"block",
"before",
"yielding",
"them",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L53-L74 | train | 34,814 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | _polytree_node_to_shapely | def _polytree_node_to_shapely(node):
"""
Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children)
"""
polygons = []
children = []
for ch in node.Childs:
p, c = _polytree_node_to_shapely(ch)
polygons.extend(p)
children.extend(c)
if node.IsHole:
# check expectations: a node should be a hole, _or_ return children.
# this is because children of holes must be outers, and should be on
# the polygons list.
assert len(children) == 0
if node.Contour:
children = [node.Contour]
else:
children = []
elif node.Contour:
poly = _contour_to_poly(node.Contour)
# we add each inner one-by-one so that we can reject them individually
# if they cause the polygon to become invalid. if the shape has lots
# of inners, then this can mean a proportional amount of work, and may
# take 1,000s of seconds. instead, we can group inners together, which
# reduces the number of times we call the expensive 'difference'
# method.
block_size = 200
if len(children) > block_size:
inners = _union_in_blocks(children, block_size)
else:
inners = _generate_polys(children)
for inner in inners:
# the difference of two valid polygons may fail, and in this
# situation we'd like to be able to display the polygon anyway.
# so we discard the bad inner and continue.
#
# see test_polygon_inners_crossing_outer for a test case.
try:
diff = poly.difference(inner)
except:
continue
if not diff.is_valid:
diff = diff.buffer(0)
# keep this for when https://trac.osgeo.org/geos/ticket/789 is
# resolved.
#
# assert diff.is_valid, \
# "Difference of %s and %s did not make valid polygon %s " \
# " because %s" \
# % (poly.wkt, inner.wkt, diff.wkt, explain_validity(diff))
#
# NOTE: this throws away the inner ring if we can't produce a
# valid difference. not ideal, but we'd rather produce something
# that's valid than nothing.
if diff.is_valid:
poly = diff
assert poly.is_valid
if poly.type == 'MultiPolygon':
polygons.extend(poly.geoms)
else:
polygons.append(poly)
children = []
else:
# check expectations: this branch gets executed if this node is not a
# hole, and has no contour. in that situation we'd expect that it has
# no children, as it would not be possible to subtract children from
# an empty outer contour.
assert len(children) == 0
return (polygons, children) | python | def _polytree_node_to_shapely(node):
"""
Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children)
"""
polygons = []
children = []
for ch in node.Childs:
p, c = _polytree_node_to_shapely(ch)
polygons.extend(p)
children.extend(c)
if node.IsHole:
# check expectations: a node should be a hole, _or_ return children.
# this is because children of holes must be outers, and should be on
# the polygons list.
assert len(children) == 0
if node.Contour:
children = [node.Contour]
else:
children = []
elif node.Contour:
poly = _contour_to_poly(node.Contour)
# we add each inner one-by-one so that we can reject them individually
# if they cause the polygon to become invalid. if the shape has lots
# of inners, then this can mean a proportional amount of work, and may
# take 1,000s of seconds. instead, we can group inners together, which
# reduces the number of times we call the expensive 'difference'
# method.
block_size = 200
if len(children) > block_size:
inners = _union_in_blocks(children, block_size)
else:
inners = _generate_polys(children)
for inner in inners:
# the difference of two valid polygons may fail, and in this
# situation we'd like to be able to display the polygon anyway.
# so we discard the bad inner and continue.
#
# see test_polygon_inners_crossing_outer for a test case.
try:
diff = poly.difference(inner)
except:
continue
if not diff.is_valid:
diff = diff.buffer(0)
# keep this for when https://trac.osgeo.org/geos/ticket/789 is
# resolved.
#
# assert diff.is_valid, \
# "Difference of %s and %s did not make valid polygon %s " \
# " because %s" \
# % (poly.wkt, inner.wkt, diff.wkt, explain_validity(diff))
#
# NOTE: this throws away the inner ring if we can't produce a
# valid difference. not ideal, but we'd rather produce something
# that's valid than nothing.
if diff.is_valid:
poly = diff
assert poly.is_valid
if poly.type == 'MultiPolygon':
polygons.extend(poly.geoms)
else:
polygons.append(poly)
children = []
else:
# check expectations: this branch gets executed if this node is not a
# hole, and has no contour. in that situation we'd expect that it has
# no children, as it would not be possible to subtract children from
# an empty outer contour.
assert len(children) == 0
return (polygons, children) | [
"def",
"_polytree_node_to_shapely",
"(",
"node",
")",
":",
"polygons",
"=",
"[",
"]",
"children",
"=",
"[",
"]",
"for",
"ch",
"in",
"node",
".",
"Childs",
":",
"p",
",",
"c",
"=",
"_polytree_node_to_shapely",
"(",
"ch",
")",
"polygons",
".",
"extend",
... | Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children) | [
"Recurses",
"down",
"a",
"Clipper",
"PolyTree",
"extracting",
"the",
"results",
"as",
"Shapely",
"objects",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L87-L169 | train | 34,815 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | make_valid_pyclipper | def make_valid_pyclipper(shape):
"""
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produce any additional degeneracies.
Before cleaning the polygon, we remove all degenerate inners. This is
useful to remove inners which have collapsed to points or lines, which can
interfere with the cleaning process.
"""
# drop all degenerate inners
clean_shape = _drop_degenerate_inners(shape)
pc = pyclipper.Pyclipper()
try:
pc.AddPaths(_coords(clean_shape), pyclipper.PT_SUBJECT, True)
# note: Execute2 returns the polygon tree, not the list of paths
result = pc.Execute2(pyclipper.CT_UNION, pyclipper.PFT_EVENODD)
except pyclipper.ClipperException:
return MultiPolygon([])
return _polytree_to_shapely(result) | python | def make_valid_pyclipper(shape):
"""
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produce any additional degeneracies.
Before cleaning the polygon, we remove all degenerate inners. This is
useful to remove inners which have collapsed to points or lines, which can
interfere with the cleaning process.
"""
# drop all degenerate inners
clean_shape = _drop_degenerate_inners(shape)
pc = pyclipper.Pyclipper()
try:
pc.AddPaths(_coords(clean_shape), pyclipper.PT_SUBJECT, True)
# note: Execute2 returns the polygon tree, not the list of paths
result = pc.Execute2(pyclipper.CT_UNION, pyclipper.PFT_EVENODD)
except pyclipper.ClipperException:
return MultiPolygon([])
return _polytree_to_shapely(result) | [
"def",
"make_valid_pyclipper",
"(",
"shape",
")",
":",
"# drop all degenerate inners",
"clean_shape",
"=",
"_drop_degenerate_inners",
"(",
"shape",
")",
"pc",
"=",
"pyclipper",
".",
"Pyclipper",
"(",
")",
"try",
":",
"pc",
".",
"AddPaths",
"(",
"_coords",
"(",
... | Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produce any additional degeneracies.
Before cleaning the polygon, we remove all degenerate inners. This is
useful to remove inners which have collapsed to points or lines, which can
interfere with the cleaning process. | [
"Use",
"the",
"pyclipper",
"library",
"to",
"union",
"a",
"polygon",
"on",
"its",
"own",
".",
"This",
"operation",
"uses",
"the",
"even",
"-",
"odd",
"rule",
"to",
"determine",
"which",
"points",
"are",
"in",
"the",
"interior",
"of",
"the",
"polygon",
"a... | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L184-L211 | train | 34,816 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | make_valid_polygon | def make_valid_polygon(shape):
"""
Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly union the polygon. Using this on its
own appears to be good for "cleaning" the polygon.
This might result in polygons which still have degeneracies according to
the OCG standard of validity - as pyclipper does not consider these to be
invalid. Therefore we follow by using the `buffer(0)` technique to attempt
to remove any remaining degeneracies.
"""
assert shape.geom_type == 'Polygon'
shape = make_valid_pyclipper(shape)
assert shape.is_valid
return shape | python | def make_valid_polygon(shape):
"""
Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly union the polygon. Using this on its
own appears to be good for "cleaning" the polygon.
This might result in polygons which still have degeneracies according to
the OCG standard of validity - as pyclipper does not consider these to be
invalid. Therefore we follow by using the `buffer(0)` technique to attempt
to remove any remaining degeneracies.
"""
assert shape.geom_type == 'Polygon'
shape = make_valid_pyclipper(shape)
assert shape.is_valid
return shape | [
"def",
"make_valid_polygon",
"(",
"shape",
")",
":",
"assert",
"shape",
".",
"geom_type",
"==",
"'Polygon'",
"shape",
"=",
"make_valid_pyclipper",
"(",
"shape",
")",
"assert",
"shape",
".",
"is_valid",
"return",
"shape"
] | Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly union the polygon. Using this on its
own appears to be good for "cleaning" the polygon.
This might result in polygons which still have degeneracies according to
the OCG standard of validity - as pyclipper does not consider these to be
invalid. Therefore we follow by using the `buffer(0)` technique to attempt
to remove any remaining degeneracies. | [
"Make",
"a",
"polygon",
"valid",
".",
"Polygons",
"can",
"be",
"invalid",
"in",
"many",
"ways",
"such",
"as",
"self",
"-",
"intersection",
"self",
"-",
"touching",
"and",
"degeneracy",
".",
"This",
"process",
"attempts",
"to",
"make",
"a",
"polygon",
"vali... | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L214-L234 | train | 34,817 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/polygon.py | make_it_valid | def make_it_valid(shape):
"""
Attempt to make any polygon or multipolygon valid.
"""
if shape.is_empty:
return shape
elif shape.type == 'MultiPolygon':
shape = make_valid_multipolygon(shape)
elif shape.type == 'Polygon':
shape = make_valid_polygon(shape)
return shape | python | def make_it_valid(shape):
"""
Attempt to make any polygon or multipolygon valid.
"""
if shape.is_empty:
return shape
elif shape.type == 'MultiPolygon':
shape = make_valid_multipolygon(shape)
elif shape.type == 'Polygon':
shape = make_valid_polygon(shape)
return shape | [
"def",
"make_it_valid",
"(",
"shape",
")",
":",
"if",
"shape",
".",
"is_empty",
":",
"return",
"shape",
"elif",
"shape",
".",
"type",
"==",
"'MultiPolygon'",
":",
"shape",
"=",
"make_valid_multipolygon",
"(",
"shape",
")",
"elif",
"shape",
".",
"type",
"==... | Attempt to make any polygon or multipolygon valid. | [
"Attempt",
"to",
"make",
"any",
"polygon",
"or",
"multipolygon",
"valid",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/polygon.py#L254-L268 | train | 34,818 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | _decode_lines | def _decode_lines(geom):
"""
Decode a linear MVT geometry into a list of Lines.
Each individual linestring in the MVT is extracted to a separate entry in
the list of lines.
"""
lines = []
current_line = []
current_moveto = None
# to keep track of the position. we'll adapt the move-to commands to all
# be relative to 0,0 at the beginning of each linestring.
x = 0
y = 0
end = len(geom)
i = 0
while i < end:
header = geom[i]
cmd = header & 7
run_length = header // 8
if cmd == 1: # move to
# flush previous line.
if current_moveto:
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
current_line = []
assert run_length == 1
x += unzigzag(geom[i+1])
y += unzigzag(geom[i+2])
i += 3
current_moveto = MoveTo(x, y)
elif cmd == 2: # line to
assert current_moveto
# we just copy this run, since it's encoding isn't going to change
next_i = i + 1 + run_length * 2
current_line.extend(geom[i:next_i])
# but we still need to decode it to figure out where each move-to
# command is in absolute space.
for j in xrange(0, run_length):
dx = unzigzag(geom[i + 1 + 2 * j])
dy = unzigzag(geom[i + 2 + 2 * j])
x += dx
y += dy
i = next_i
else:
raise ValueError('Unhandled command: %d' % cmd)
if current_line:
assert current_moveto
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
return lines | python | def _decode_lines(geom):
"""
Decode a linear MVT geometry into a list of Lines.
Each individual linestring in the MVT is extracted to a separate entry in
the list of lines.
"""
lines = []
current_line = []
current_moveto = None
# to keep track of the position. we'll adapt the move-to commands to all
# be relative to 0,0 at the beginning of each linestring.
x = 0
y = 0
end = len(geom)
i = 0
while i < end:
header = geom[i]
cmd = header & 7
run_length = header // 8
if cmd == 1: # move to
# flush previous line.
if current_moveto:
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
current_line = []
assert run_length == 1
x += unzigzag(geom[i+1])
y += unzigzag(geom[i+2])
i += 3
current_moveto = MoveTo(x, y)
elif cmd == 2: # line to
assert current_moveto
# we just copy this run, since it's encoding isn't going to change
next_i = i + 1 + run_length * 2
current_line.extend(geom[i:next_i])
# but we still need to decode it to figure out where each move-to
# command is in absolute space.
for j in xrange(0, run_length):
dx = unzigzag(geom[i + 1 + 2 * j])
dy = unzigzag(geom[i + 2 + 2 * j])
x += dx
y += dy
i = next_i
else:
raise ValueError('Unhandled command: %d' % cmd)
if current_line:
assert current_moveto
lines.append(Line(current_moveto, EndsAt(x, y), current_line))
return lines | [
"def",
"_decode_lines",
"(",
"geom",
")",
":",
"lines",
"=",
"[",
"]",
"current_line",
"=",
"[",
"]",
"current_moveto",
"=",
"None",
"# to keep track of the position. we'll adapt the move-to commands to all",
"# be relative to 0,0 at the beginning of each linestring.",
"x",
"... | Decode a linear MVT geometry into a list of Lines.
Each individual linestring in the MVT is extracted to a separate entry in
the list of lines. | [
"Decode",
"a",
"linear",
"MVT",
"geometry",
"into",
"a",
"list",
"of",
"Lines",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L85-L146 | train | 34,819 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | _reorder_lines | def _reorder_lines(lines):
"""
Reorder lines so that the distance from the end of one to the beginning of
the next is minimised.
"""
x = 0
y = 0
new_lines = []
# treat the list of lines as a stack, off which we keep popping the best
# one to add next.
while lines:
# looping over all the lines like this isn't terribly efficient, but
# in local tests seems to handle a few thousand lines without a
# problem.
min_dist = None
min_i = None
for i, line in enumerate(lines):
moveto, _, _ = line
dist = abs(moveto.x - x) + abs(moveto.y - y)
if min_dist is None or dist < min_dist:
min_dist = dist
min_i = i
assert min_i is not None
line = lines.pop(min_i)
_, endsat, _ = line
x = endsat.x
y = endsat.y
new_lines.append(line)
return new_lines | python | def _reorder_lines(lines):
"""
Reorder lines so that the distance from the end of one to the beginning of
the next is minimised.
"""
x = 0
y = 0
new_lines = []
# treat the list of lines as a stack, off which we keep popping the best
# one to add next.
while lines:
# looping over all the lines like this isn't terribly efficient, but
# in local tests seems to handle a few thousand lines without a
# problem.
min_dist = None
min_i = None
for i, line in enumerate(lines):
moveto, _, _ = line
dist = abs(moveto.x - x) + abs(moveto.y - y)
if min_dist is None or dist < min_dist:
min_dist = dist
min_i = i
assert min_i is not None
line = lines.pop(min_i)
_, endsat, _ = line
x = endsat.x
y = endsat.y
new_lines.append(line)
return new_lines | [
"def",
"_reorder_lines",
"(",
"lines",
")",
":",
"x",
"=",
"0",
"y",
"=",
"0",
"new_lines",
"=",
"[",
"]",
"# treat the list of lines as a stack, off which we keep popping the best",
"# one to add next.",
"while",
"lines",
":",
"# looping over all the lines like this isn't ... | Reorder lines so that the distance from the end of one to the beginning of
the next is minimised. | [
"Reorder",
"lines",
"so",
"that",
"the",
"distance",
"from",
"the",
"end",
"of",
"one",
"to",
"the",
"beginning",
"of",
"the",
"next",
"is",
"minimised",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L149-L182 | train | 34,820 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | _rewrite_geometry | def _rewrite_geometry(geom, new_lines):
"""
Re-encode a list of Lines with absolute MoveTos as a continuous stream of
MVT geometry commands, each relative to the last. Replace geom with that
stream.
"""
new_geom = []
x = 0
y = 0
for line in new_lines:
moveto, endsat, lineto_cmds = line
dx = moveto.x - x
dy = moveto.y - y
x = endsat.x
y = endsat.y
new_geom.append(9) # move to, run_length = 1
new_geom.append(zigzag(dx))
new_geom.append(zigzag(dy))
new_geom.extend(lineto_cmds)
# write the lines back out to geom
del geom[:]
geom.extend(new_geom) | python | def _rewrite_geometry(geom, new_lines):
"""
Re-encode a list of Lines with absolute MoveTos as a continuous stream of
MVT geometry commands, each relative to the last. Replace geom with that
stream.
"""
new_geom = []
x = 0
y = 0
for line in new_lines:
moveto, endsat, lineto_cmds = line
dx = moveto.x - x
dy = moveto.y - y
x = endsat.x
y = endsat.y
new_geom.append(9) # move to, run_length = 1
new_geom.append(zigzag(dx))
new_geom.append(zigzag(dy))
new_geom.extend(lineto_cmds)
# write the lines back out to geom
del geom[:]
geom.extend(new_geom) | [
"def",
"_rewrite_geometry",
"(",
"geom",
",",
"new_lines",
")",
":",
"new_geom",
"=",
"[",
"]",
"x",
"=",
"0",
"y",
"=",
"0",
"for",
"line",
"in",
"new_lines",
":",
"moveto",
",",
"endsat",
",",
"lineto_cmds",
"=",
"line",
"dx",
"=",
"moveto",
".",
... | Re-encode a list of Lines with absolute MoveTos as a continuous stream of
MVT geometry commands, each relative to the last. Replace geom with that
stream. | [
"Re",
"-",
"encode",
"a",
"list",
"of",
"Lines",
"with",
"absolute",
"MoveTos",
"as",
"a",
"continuous",
"stream",
"of",
"MVT",
"geometry",
"commands",
"each",
"relative",
"to",
"the",
"last",
".",
"Replace",
"geom",
"with",
"that",
"stream",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L185-L210 | train | 34,821 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/optimise.py | optimise_tile | def optimise_tile(tile_bytes):
"""
Decode a sequence of bytes as an MVT tile and reorder the string table of
its layers and the order of its multilinestrings to save a few bytes.
"""
t = tile()
t.ParseFromString(tile_bytes)
for layer in t.layers:
sto = StringTableOptimiser()
for feature in layer.features:
# (multi)linestrings only
if feature.type == 2:
optimise_multilinestring(feature.geometry)
sto.add_tags(feature.tags)
sto.update_string_table(layer)
return t.SerializeToString() | python | def optimise_tile(tile_bytes):
"""
Decode a sequence of bytes as an MVT tile and reorder the string table of
its layers and the order of its multilinestrings to save a few bytes.
"""
t = tile()
t.ParseFromString(tile_bytes)
for layer in t.layers:
sto = StringTableOptimiser()
for feature in layer.features:
# (multi)linestrings only
if feature.type == 2:
optimise_multilinestring(feature.geometry)
sto.add_tags(feature.tags)
sto.update_string_table(layer)
return t.SerializeToString() | [
"def",
"optimise_tile",
"(",
"tile_bytes",
")",
":",
"t",
"=",
"tile",
"(",
")",
"t",
".",
"ParseFromString",
"(",
"tile_bytes",
")",
"for",
"layer",
"in",
"t",
".",
"layers",
":",
"sto",
"=",
"StringTableOptimiser",
"(",
")",
"for",
"feature",
"in",
"... | Decode a sequence of bytes as an MVT tile and reorder the string table of
its layers and the order of its multilinestrings to save a few bytes. | [
"Decode",
"a",
"sequence",
"of",
"bytes",
"as",
"an",
"MVT",
"tile",
"and",
"reorder",
"the",
"string",
"table",
"of",
"its",
"layers",
"and",
"the",
"order",
"of",
"its",
"multilinestrings",
"to",
"save",
"a",
"few",
"bytes",
"."
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/optimise.py#L226-L247 | train | 34,822 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/geom_encoder.py | GeometryEncoder.coords_on_grid | def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if isinstance(y, float):
y = int(self._round(y))
if not self._y_coord_down:
y = self._extents - y
return x, y | python | def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if isinstance(y, float):
y = int(self._round(y))
if not self._y_coord_down:
y = self._extents - y
return x, y | [
"def",
"coords_on_grid",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"float",
")",
":",
"x",
"=",
"int",
"(",
"self",
".",
"_round",
"(",
"x",
")",
")",
"if",
"isinstance",
"(",
"y",
",",
"float",
")",
":",
"... | Snap coordinates on the grid with integer coordinates | [
"Snap",
"coordinates",
"on",
"the",
"grid",
"with",
"integer",
"coordinates"
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/geom_encoder.py#L39-L48 | train | 34,823 |
tilezen/mapbox-vector-tile | mapbox_vector_tile/geom_encoder.py | GeometryEncoder.encode_arc | def encode_arc(self, coords):
""" Appends commands to _geometry to create an arc.
- Returns False if nothing was added
- Returns True and moves _last_x, _last_y if
some points where added
"""
last_x, last_y = self._last_x, self._last_y
float_x, float_y = next(coords)
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
cmd_encoded = encode_cmd_length(CMD_MOVE_TO, 1)
commands = [cmd_encoded,
zigzag(dx),
zigzag(dy),
CMD_FAKE
]
pairs_added = 0
last_x, last_y = x, y
for float_x, float_y in coords:
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
if dx == 0 and dy == 0:
continue
commands.append(zigzag(dx))
commands.append(zigzag(dy))
last_x, last_y = x, y
pairs_added += 1
if pairs_added == 0:
return False
cmd_encoded = encode_cmd_length(CMD_LINE_TO, pairs_added)
commands[3] = cmd_encoded
self._geometry.extend(commands)
self._last_x, self._last_y = last_x, last_y
return True | python | def encode_arc(self, coords):
""" Appends commands to _geometry to create an arc.
- Returns False if nothing was added
- Returns True and moves _last_x, _last_y if
some points where added
"""
last_x, last_y = self._last_x, self._last_y
float_x, float_y = next(coords)
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
cmd_encoded = encode_cmd_length(CMD_MOVE_TO, 1)
commands = [cmd_encoded,
zigzag(dx),
zigzag(dy),
CMD_FAKE
]
pairs_added = 0
last_x, last_y = x, y
for float_x, float_y in coords:
x, y = self.coords_on_grid(float_x, float_y)
dx, dy = x - last_x, y - last_y
if dx == 0 and dy == 0:
continue
commands.append(zigzag(dx))
commands.append(zigzag(dy))
last_x, last_y = x, y
pairs_added += 1
if pairs_added == 0:
return False
cmd_encoded = encode_cmd_length(CMD_LINE_TO, pairs_added)
commands[3] = cmd_encoded
self._geometry.extend(commands)
self._last_x, self._last_y = last_x, last_y
return True | [
"def",
"encode_arc",
"(",
"self",
",",
"coords",
")",
":",
"last_x",
",",
"last_y",
"=",
"self",
".",
"_last_x",
",",
"self",
".",
"_last_y",
"float_x",
",",
"float_y",
"=",
"next",
"(",
"coords",
")",
"x",
",",
"y",
"=",
"self",
".",
"coords_on_grid... | Appends commands to _geometry to create an arc.
- Returns False if nothing was added
- Returns True and moves _last_x, _last_y if
some points where added | [
"Appends",
"commands",
"to",
"_geometry",
"to",
"create",
"an",
"arc",
".",
"-",
"Returns",
"False",
"if",
"nothing",
"was",
"added",
"-",
"Returns",
"True",
"and",
"moves",
"_last_x",
"_last_y",
"if",
"some",
"points",
"where",
"added"
] | 7327b8cff0aa2de1d5233e556bf00429ba2126a0 | https://github.com/tilezen/mapbox-vector-tile/blob/7327b8cff0aa2de1d5233e556bf00429ba2126a0/mapbox_vector_tile/geom_encoder.py#L63-L96 | train | 34,824 |
thesharp/daemonize | daemonize.py | Daemonize.sigterm | def sigterm(self, signum, frame):
"""
These actions will be done after SIGTERM.
"""
self.logger.warning("Caught signal %s. Stopping daemon." % signum)
sys.exit(0) | python | def sigterm(self, signum, frame):
"""
These actions will be done after SIGTERM.
"""
self.logger.warning("Caught signal %s. Stopping daemon." % signum)
sys.exit(0) | [
"def",
"sigterm",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Caught signal %s. Stopping daemon.\"",
"%",
"signum",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | These actions will be done after SIGTERM. | [
"These",
"actions",
"will",
"be",
"done",
"after",
"SIGTERM",
"."
] | 39a880f74c1d8ea09fa44fe2b99dec1c961201a9 | https://github.com/thesharp/daemonize/blob/39a880f74c1d8ea09fa44fe2b99dec1c961201a9/daemonize.py#L59-L64 | train | 34,825 |
thesharp/daemonize | daemonize.py | Daemonize.exit | def exit(self):
"""
Cleanup pid file at exit.
"""
self.logger.warning("Stopping daemon.")
os.remove(self.pid)
sys.exit(0) | python | def exit(self):
"""
Cleanup pid file at exit.
"""
self.logger.warning("Stopping daemon.")
os.remove(self.pid)
sys.exit(0) | [
"def",
"exit",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"Stopping daemon.\"",
")",
"os",
".",
"remove",
"(",
"self",
".",
"pid",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | Cleanup pid file at exit. | [
"Cleanup",
"pid",
"file",
"at",
"exit",
"."
] | 39a880f74c1d8ea09fa44fe2b99dec1c961201a9 | https://github.com/thesharp/daemonize/blob/39a880f74c1d8ea09fa44fe2b99dec1c961201a9/daemonize.py#L66-L72 | train | 34,826 |
ierror/django-js-reverse | django_js_reverse/templatetags/js_reverse.py | js_reverse_inline | def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
"""
if 'request' in context:
default_urlresolver = get_resolver(getattr(context['request'], 'urlconf', None))
else:
default_urlresolver = get_resolver(None)
return mark_safe(generate_js(default_urlresolver)) | python | def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
"""
if 'request' in context:
default_urlresolver = get_resolver(getattr(context['request'], 'urlconf', None))
else:
default_urlresolver = get_resolver(None)
return mark_safe(generate_js(default_urlresolver)) | [
"def",
"js_reverse_inline",
"(",
"context",
")",
":",
"if",
"'request'",
"in",
"context",
":",
"default_urlresolver",
"=",
"get_resolver",
"(",
"getattr",
"(",
"context",
"[",
"'request'",
"]",
",",
"'urlconf'",
",",
"None",
")",
")",
"else",
":",
"default_u... | Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs. | [
"Outputs",
"a",
"string",
"of",
"javascript",
"that",
"can",
"generate",
"URLs",
"via",
"the",
"use",
"of",
"the",
"names",
"given",
"to",
"those",
"URLs",
"."
] | 58320a8acec040636e8ad718754c2d472d0d504d | https://github.com/ierror/django-js-reverse/blob/58320a8acec040636e8ad718754c2d472d0d504d/django_js_reverse/templatetags/js_reverse.py#L16-L25 | train | 34,827 |
webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator._iterate_records | def _iterate_records(self):
""" iterate over each record
"""
raise_invalid_gzip = False
empty_record = False
while True:
try:
self.record = self._next_record(self.next_line)
if raise_invalid_gzip:
self._raise_invalid_gzip_err()
yield self.record
except EOFError:
empty_record = True
self.read_to_end()
if self.reader.decompressor:
# if another gzip member, continue
if self.reader.read_next_member():
continue
# if empty record, then we're done
elif empty_record:
break
# otherwise, probably a gzip
# containing multiple non-chunked records
# raise this as an error
else:
raise_invalid_gzip = True
# non-gzip, so we're done
elif empty_record:
break
self.close() | python | def _iterate_records(self):
""" iterate over each record
"""
raise_invalid_gzip = False
empty_record = False
while True:
try:
self.record = self._next_record(self.next_line)
if raise_invalid_gzip:
self._raise_invalid_gzip_err()
yield self.record
except EOFError:
empty_record = True
self.read_to_end()
if self.reader.decompressor:
# if another gzip member, continue
if self.reader.read_next_member():
continue
# if empty record, then we're done
elif empty_record:
break
# otherwise, probably a gzip
# containing multiple non-chunked records
# raise this as an error
else:
raise_invalid_gzip = True
# non-gzip, so we're done
elif empty_record:
break
self.close() | [
"def",
"_iterate_records",
"(",
"self",
")",
":",
"raise_invalid_gzip",
"=",
"False",
"empty_record",
"=",
"False",
"while",
"True",
":",
"try",
":",
"self",
".",
"record",
"=",
"self",
".",
"_next_record",
"(",
"self",
".",
"next_line",
")",
"if",
"raise_... | iterate over each record | [
"iterate",
"over",
"each",
"record"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L80-L118 | train | 34,828 |
webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator._consume_blanklines | def _consume_blanklines(self):
""" Consume blank lines that are between records
- For warcs, there are usually 2
- For arcs, may be 1 or 0
- For block gzipped files, these are at end of each gzip envelope
and are included in record length which is the full gzip envelope
- For uncompressed, they are between records and so are NOT part of
the record length
count empty_size so that it can be substracted from
the record length for uncompressed
if first line read is not blank, likely error in WARC/ARC,
display a warning
"""
empty_size = 0
first_line = True
while True:
line = self.reader.readline()
if len(line) == 0:
return None, empty_size
stripped = line.rstrip()
if len(stripped) == 0 or first_line:
empty_size += len(line)
if len(stripped) != 0:
# if first line is not blank,
# likely content-length was invalid, display warning
err_offset = self.fh.tell() - self.reader.rem_length() - empty_size
sys.stderr.write(self.INC_RECORD.format(err_offset, line))
self.err_count += 1
first_line = False
continue
return line, empty_size | python | def _consume_blanklines(self):
""" Consume blank lines that are between records
- For warcs, there are usually 2
- For arcs, may be 1 or 0
- For block gzipped files, these are at end of each gzip envelope
and are included in record length which is the full gzip envelope
- For uncompressed, they are between records and so are NOT part of
the record length
count empty_size so that it can be substracted from
the record length for uncompressed
if first line read is not blank, likely error in WARC/ARC,
display a warning
"""
empty_size = 0
first_line = True
while True:
line = self.reader.readline()
if len(line) == 0:
return None, empty_size
stripped = line.rstrip()
if len(stripped) == 0 or first_line:
empty_size += len(line)
if len(stripped) != 0:
# if first line is not blank,
# likely content-length was invalid, display warning
err_offset = self.fh.tell() - self.reader.rem_length() - empty_size
sys.stderr.write(self.INC_RECORD.format(err_offset, line))
self.err_count += 1
first_line = False
continue
return line, empty_size | [
"def",
"_consume_blanklines",
"(",
"self",
")",
":",
"empty_size",
"=",
"0",
"first_line",
"=",
"True",
"while",
"True",
":",
"line",
"=",
"self",
".",
"reader",
".",
"readline",
"(",
")",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"return",
"Non... | Consume blank lines that are between records
- For warcs, there are usually 2
- For arcs, may be 1 or 0
- For block gzipped files, these are at end of each gzip envelope
and are included in record length which is the full gzip envelope
- For uncompressed, they are between records and so are NOT part of
the record length
count empty_size so that it can be substracted from
the record length for uncompressed
if first line read is not blank, likely error in WARC/ARC,
display a warning | [
"Consume",
"blank",
"lines",
"that",
"are",
"between",
"records",
"-",
"For",
"warcs",
"there",
"are",
"usually",
"2",
"-",
"For",
"arcs",
"may",
"be",
"1",
"or",
"0",
"-",
"For",
"block",
"gzipped",
"files",
"these",
"are",
"at",
"end",
"of",
"each",
... | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L133-L171 | train | 34,829 |
webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator.read_to_end | def read_to_end(self, record=None):
""" Read remainder of the stream
If a digester is included, update it
with the data read
"""
# no current record to read
if not self.record:
return None
# already at end of this record, don't read until it is consumed
if self.member_info:
return None
curr_offset = self.offset
while True:
b = self.record.raw_stream.read(BUFF_SIZE)
if not b:
break
"""
- For compressed files, blank lines are consumed
since they are part of record length
- For uncompressed files, blank lines are read later,
and not included in the record length
"""
#if self.reader.decompressor:
self.next_line, empty_size = self._consume_blanklines()
self.offset = self.fh.tell() - self.reader.rem_length()
#if self.offset < 0:
# raise Exception('Not Gzipped Properly')
if self.next_line:
self.offset -= len(self.next_line)
length = self.offset - curr_offset
if not self.reader.decompressor:
length -= empty_size
self.member_info = (curr_offset, length) | python | def read_to_end(self, record=None):
""" Read remainder of the stream
If a digester is included, update it
with the data read
"""
# no current record to read
if not self.record:
return None
# already at end of this record, don't read until it is consumed
if self.member_info:
return None
curr_offset = self.offset
while True:
b = self.record.raw_stream.read(BUFF_SIZE)
if not b:
break
"""
- For compressed files, blank lines are consumed
since they are part of record length
- For uncompressed files, blank lines are read later,
and not included in the record length
"""
#if self.reader.decompressor:
self.next_line, empty_size = self._consume_blanklines()
self.offset = self.fh.tell() - self.reader.rem_length()
#if self.offset < 0:
# raise Exception('Not Gzipped Properly')
if self.next_line:
self.offset -= len(self.next_line)
length = self.offset - curr_offset
if not self.reader.decompressor:
length -= empty_size
self.member_info = (curr_offset, length) | [
"def",
"read_to_end",
"(",
"self",
",",
"record",
"=",
"None",
")",
":",
"# no current record to read",
"if",
"not",
"self",
".",
"record",
":",
"return",
"None",
"# already at end of this record, don't read until it is consumed",
"if",
"self",
".",
"member_info",
":"... | Read remainder of the stream
If a digester is included, update it
with the data read | [
"Read",
"remainder",
"of",
"the",
"stream",
"If",
"a",
"digester",
"is",
"included",
"update",
"it",
"with",
"the",
"data",
"read"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L173-L215 | train | 34,830 |
webrecorder/warcio | warcio/archiveiterator.py | ArchiveIterator._next_record | def _next_record(self, next_line):
""" Use loader to parse the record from the reader stream
Supporting warc and arc records
"""
record = self.loader.parse_record_stream(self.reader,
next_line,
self.known_format,
self.no_record_parse,
self.ensure_http_headers)
self.member_info = None
# Track known format for faster parsing of other records
if not self.mixed_arc_warc:
self.known_format = record.format
return record | python | def _next_record(self, next_line):
""" Use loader to parse the record from the reader stream
Supporting warc and arc records
"""
record = self.loader.parse_record_stream(self.reader,
next_line,
self.known_format,
self.no_record_parse,
self.ensure_http_headers)
self.member_info = None
# Track known format for faster parsing of other records
if not self.mixed_arc_warc:
self.known_format = record.format
return record | [
"def",
"_next_record",
"(",
"self",
",",
"next_line",
")",
":",
"record",
"=",
"self",
".",
"loader",
".",
"parse_record_stream",
"(",
"self",
".",
"reader",
",",
"next_line",
",",
"self",
".",
"known_format",
",",
"self",
".",
"no_record_parse",
",",
"sel... | Use loader to parse the record from the reader stream
Supporting warc and arc records | [
"Use",
"loader",
"to",
"parse",
"the",
"record",
"from",
"the",
"reader",
"stream",
"Supporting",
"warc",
"and",
"arc",
"records"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/archiveiterator.py#L231-L247 | train | 34,831 |
webrecorder/warcio | warcio/limitreader.py | LimitReader.wrap_stream | def wrap_stream(stream, content_length):
"""
If given content_length is an int > 0, wrap the stream
in a LimitReader. Otherwise, return the stream unaltered
"""
try:
content_length = int(content_length)
if content_length >= 0:
# optimize: if already a LimitStream, set limit to
# the smaller of the two limits
if isinstance(stream, LimitReader):
stream.limit = min(stream.limit, content_length)
else:
stream = LimitReader(stream, content_length)
except (ValueError, TypeError):
pass
return stream | python | def wrap_stream(stream, content_length):
"""
If given content_length is an int > 0, wrap the stream
in a LimitReader. Otherwise, return the stream unaltered
"""
try:
content_length = int(content_length)
if content_length >= 0:
# optimize: if already a LimitStream, set limit to
# the smaller of the two limits
if isinstance(stream, LimitReader):
stream.limit = min(stream.limit, content_length)
else:
stream = LimitReader(stream, content_length)
except (ValueError, TypeError):
pass
return stream | [
"def",
"wrap_stream",
"(",
"stream",
",",
"content_length",
")",
":",
"try",
":",
"content_length",
"=",
"int",
"(",
"content_length",
")",
"if",
"content_length",
">=",
"0",
":",
"# optimize: if already a LimitStream, set limit to",
"# the smaller of the two limits",
"... | If given content_length is an int > 0, wrap the stream
in a LimitReader. Otherwise, return the stream unaltered | [
"If",
"given",
"content_length",
"is",
"an",
"int",
">",
"0",
"wrap",
"the",
"stream",
"in",
"a",
"LimitReader",
".",
"Otherwise",
"return",
"the",
"stream",
"unaltered"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/limitreader.py#L50-L68 | train | 34,832 |
webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeaders.replace_header | def replace_header(self, name, value):
"""
replace header with new value or add new header
return old header value, if any
"""
name_lower = name.lower()
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
if curr_name.lower() == name_lower:
self.headers[index] = (curr_name, value)
return curr_value
self.headers.append((name, value))
return None | python | def replace_header(self, name, value):
"""
replace header with new value or add new header
return old header value, if any
"""
name_lower = name.lower()
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
if curr_name.lower() == name_lower:
self.headers[index] = (curr_name, value)
return curr_value
self.headers.append((name, value))
return None | [
"def",
"replace_header",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"name_lower",
"=",
"name",
".",
"lower",
"(",
")",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"headers",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
"... | replace header with new value or add new header
return old header value, if any | [
"replace",
"header",
"with",
"new",
"value",
"or",
"add",
"new",
"header",
"return",
"old",
"header",
"value",
"if",
"any"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L49-L62 | train | 34,833 |
webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeaders.validate_statusline | def validate_statusline(self, valid_statusline):
"""
Check that the statusline is valid, eg. starts with a numeric
code. If not, replace with passed in valid_statusline
"""
code = self.get_statuscode()
try:
code = int(code)
assert(code > 0)
return True
except(ValueError, AssertionError):
self.statusline = valid_statusline
return False | python | def validate_statusline(self, valid_statusline):
"""
Check that the statusline is valid, eg. starts with a numeric
code. If not, replace with passed in valid_statusline
"""
code = self.get_statuscode()
try:
code = int(code)
assert(code > 0)
return True
except(ValueError, AssertionError):
self.statusline = valid_statusline
return False | [
"def",
"validate_statusline",
"(",
"self",
",",
"valid_statusline",
")",
":",
"code",
"=",
"self",
".",
"get_statuscode",
"(",
")",
"try",
":",
"code",
"=",
"int",
"(",
"code",
")",
"assert",
"(",
"code",
">",
"0",
")",
"return",
"True",
"except",
"(",... | Check that the statusline is valid, eg. starts with a numeric
code. If not, replace with passed in valid_statusline | [
"Check",
"that",
"the",
"statusline",
"is",
"valid",
"eg",
".",
"starts",
"with",
"a",
"numeric",
"code",
".",
"If",
"not",
"replace",
"with",
"passed",
"in",
"valid_statusline"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L85-L97 | train | 34,834 |
webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeaders.add_range | def add_range(self, start, part_len, total_len):
"""
Add range headers indicating that this a partial response
"""
content_range = 'bytes {0}-{1}/{2}'.format(start,
start + part_len - 1,
total_len)
self.statusline = '206 Partial Content'
self.replace_header('Content-Range', content_range)
self.replace_header('Content-Length', str(part_len))
self.replace_header('Accept-Ranges', 'bytes')
return self | python | def add_range(self, start, part_len, total_len):
"""
Add range headers indicating that this a partial response
"""
content_range = 'bytes {0}-{1}/{2}'.format(start,
start + part_len - 1,
total_len)
self.statusline = '206 Partial Content'
self.replace_header('Content-Range', content_range)
self.replace_header('Content-Length', str(part_len))
self.replace_header('Accept-Ranges', 'bytes')
return self | [
"def",
"add_range",
"(",
"self",
",",
"start",
",",
"part_len",
",",
"total_len",
")",
":",
"content_range",
"=",
"'bytes {0}-{1}/{2}'",
".",
"format",
"(",
"start",
",",
"start",
"+",
"part_len",
"-",
"1",
",",
"total_len",
")",
"self",
".",
"statusline",... | Add range headers indicating that this a partial response | [
"Add",
"range",
"headers",
"indicating",
"that",
"this",
"a",
"partial",
"response"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L99-L111 | train | 34,835 |
webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeadersParser.parse | def parse(self, stream, full_statusline=None):
"""
parse stream for status line and headers
return a StatusAndHeaders object
support continuation headers starting with space or tab
"""
# status line w newlines intact
if full_statusline is None:
full_statusline = stream.readline()
full_statusline = self.decode_header(full_statusline)
statusline, total_read = _strip_count(full_statusline, 0)
headers = []
# at end of stream
if total_read == 0:
raise EOFError()
elif not statusline:
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol='',
total_len=total_read)
# validate only if verify is set
if self.verify:
protocol_status = self.split_prefix(statusline, self.statuslist)
if not protocol_status:
msg = 'Expected Status Line starting with {0} - Found: {1}'
msg = msg.format(self.statuslist, statusline)
raise StatusAndHeadersParserException(msg, full_statusline)
else:
protocol_status = statusline.split(' ', 1)
line, total_read = _strip_count(self.decode_header(stream.readline()), total_read)
while line:
result = line.split(':', 1)
if len(result) == 2:
name = result[0].rstrip(' \t')
value = result[1].lstrip()
else:
name = result[0]
value = None
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
# append continuation lines, if any
while next_line and next_line.startswith((' ', '\t')):
if value is not None:
value += next_line
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
if value is not None:
header = (name, value)
headers.append(header)
line = next_line
if len(protocol_status) > 1:
statusline = protocol_status[1].strip()
else:
statusline = ''
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol=protocol_status[0],
total_len=total_read) | python | def parse(self, stream, full_statusline=None):
"""
parse stream for status line and headers
return a StatusAndHeaders object
support continuation headers starting with space or tab
"""
# status line w newlines intact
if full_statusline is None:
full_statusline = stream.readline()
full_statusline = self.decode_header(full_statusline)
statusline, total_read = _strip_count(full_statusline, 0)
headers = []
# at end of stream
if total_read == 0:
raise EOFError()
elif not statusline:
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol='',
total_len=total_read)
# validate only if verify is set
if self.verify:
protocol_status = self.split_prefix(statusline, self.statuslist)
if not protocol_status:
msg = 'Expected Status Line starting with {0} - Found: {1}'
msg = msg.format(self.statuslist, statusline)
raise StatusAndHeadersParserException(msg, full_statusline)
else:
protocol_status = statusline.split(' ', 1)
line, total_read = _strip_count(self.decode_header(stream.readline()), total_read)
while line:
result = line.split(':', 1)
if len(result) == 2:
name = result[0].rstrip(' \t')
value = result[1].lstrip()
else:
name = result[0]
value = None
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
# append continuation lines, if any
while next_line and next_line.startswith((' ', '\t')):
if value is not None:
value += next_line
next_line, total_read = _strip_count(self.decode_header(stream.readline()),
total_read)
if value is not None:
header = (name, value)
headers.append(header)
line = next_line
if len(protocol_status) > 1:
statusline = protocol_status[1].strip()
else:
statusline = ''
return StatusAndHeaders(statusline=statusline,
headers=headers,
protocol=protocol_status[0],
total_len=total_read) | [
"def",
"parse",
"(",
"self",
",",
"stream",
",",
"full_statusline",
"=",
"None",
")",
":",
"# status line w newlines intact",
"if",
"full_statusline",
"is",
"None",
":",
"full_statusline",
"=",
"stream",
".",
"readline",
"(",
")",
"full_statusline",
"=",
"self",... | parse stream for status line and headers
return a StatusAndHeaders object
support continuation headers starting with space or tab | [
"parse",
"stream",
"for",
"status",
"line",
"and",
"headers",
"return",
"a",
"StatusAndHeaders",
"object"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L223-L295 | train | 34,836 |
webrecorder/warcio | warcio/statusandheaders.py | StatusAndHeadersParser.split_prefix | def split_prefix(key, prefixs):
"""
split key string into prefix and remainder
for first matching prefix from a list
"""
key_upper = key.upper()
for prefix in prefixs:
if key_upper.startswith(prefix):
plen = len(prefix)
return (key_upper[:plen], key[plen:]) | python | def split_prefix(key, prefixs):
"""
split key string into prefix and remainder
for first matching prefix from a list
"""
key_upper = key.upper()
for prefix in prefixs:
if key_upper.startswith(prefix):
plen = len(prefix)
return (key_upper[:plen], key[plen:]) | [
"def",
"split_prefix",
"(",
"key",
",",
"prefixs",
")",
":",
"key_upper",
"=",
"key",
".",
"upper",
"(",
")",
"for",
"prefix",
"in",
"prefixs",
":",
"if",
"key_upper",
".",
"startswith",
"(",
"prefix",
")",
":",
"plen",
"=",
"len",
"(",
"prefix",
")"... | split key string into prefix and remainder
for first matching prefix from a list | [
"split",
"key",
"string",
"into",
"prefix",
"and",
"remainder",
"for",
"first",
"matching",
"prefix",
"from",
"a",
"list"
] | c64c4394805e13256695f51af072c95389397ee9 | https://github.com/webrecorder/warcio/blob/c64c4394805e13256695f51af072c95389397ee9/warcio/statusandheaders.py#L298-L307 | train | 34,837 |
nickjj/ansigenome | ansigenome/config.py | Config.ask_questions | def ask_questions(self):
"""
Obtain config settings from the user.
"""
out_config = {}
for key in c.CONFIG_QUESTIONS:
section = key[1]
print
for question in section:
answer = utils.ask(question[1], question[2])
out_config["{0}_{1}".format(key[0], question[0])] = answer
for key in c.CONFIG_MULTIPLE_CHOICE_QUESTIONS:
section = key[1]
print
# keep going until we get what we want
while True:
input = utils.ask(section[1], "")
if (input.isdigit() and
int(input) > 0 and
int(input) <= section[0]):
answer = input
break
print
# store the answer as 1 less than it is, we're dealing with
# a list to select the number which is 0 indexed
answer = int(input) - 1
if key[0] == "license":
out_config["license_type"] = c.LICENSE_TYPES[answer][0]
out_config["license_url"] = c.LICENSE_TYPES[answer][1]
# merge in defaults without asking questions
merged_config = dict(c.CONFIG_DEFAULTS.items() + out_config.items())
return merged_config | python | def ask_questions(self):
"""
Obtain config settings from the user.
"""
out_config = {}
for key in c.CONFIG_QUESTIONS:
section = key[1]
print
for question in section:
answer = utils.ask(question[1], question[2])
out_config["{0}_{1}".format(key[0], question[0])] = answer
for key in c.CONFIG_MULTIPLE_CHOICE_QUESTIONS:
section = key[1]
print
# keep going until we get what we want
while True:
input = utils.ask(section[1], "")
if (input.isdigit() and
int(input) > 0 and
int(input) <= section[0]):
answer = input
break
print
# store the answer as 1 less than it is, we're dealing with
# a list to select the number which is 0 indexed
answer = int(input) - 1
if key[0] == "license":
out_config["license_type"] = c.LICENSE_TYPES[answer][0]
out_config["license_url"] = c.LICENSE_TYPES[answer][1]
# merge in defaults without asking questions
merged_config = dict(c.CONFIG_DEFAULTS.items() + out_config.items())
return merged_config | [
"def",
"ask_questions",
"(",
"self",
")",
":",
"out_config",
"=",
"{",
"}",
"for",
"key",
"in",
"c",
".",
"CONFIG_QUESTIONS",
":",
"section",
"=",
"key",
"[",
"1",
"]",
"print",
"for",
"question",
"in",
"section",
":",
"answer",
"=",
"utils",
".",
"a... | Obtain config settings from the user. | [
"Obtain",
"config",
"settings",
"from",
"the",
"user",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/config.py#L45-L83 | train | 34,838 |
nickjj/ansigenome | ansigenome/ui.py | log | def log(color, *args):
"""
Print a message with a specific color.
"""
if color in c.LOG_COLOR.keys():
out_color = c.LOG_COLOR[color]
else:
out_color = color
for arg in args:
print clr.stringc(arg, out_color) | python | def log(color, *args):
"""
Print a message with a specific color.
"""
if color in c.LOG_COLOR.keys():
out_color = c.LOG_COLOR[color]
else:
out_color = color
for arg in args:
print clr.stringc(arg, out_color) | [
"def",
"log",
"(",
"color",
",",
"*",
"args",
")",
":",
"if",
"color",
"in",
"c",
".",
"LOG_COLOR",
".",
"keys",
"(",
")",
":",
"out_color",
"=",
"c",
".",
"LOG_COLOR",
"[",
"color",
"]",
"else",
":",
"out_color",
"=",
"color",
"for",
"arg",
"in"... | Print a message with a specific color. | [
"Print",
"a",
"message",
"with",
"a",
"specific",
"color",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L5-L15 | train | 34,839 |
nickjj/ansigenome | ansigenome/ui.py | usage | def usage():
"""
Return the usage for the help command.
"""
l_bracket = clr.stringc("[", "dark gray")
r_bracket = clr.stringc("]", "dark gray")
pipe = clr.stringc("|", "dark gray")
app_name = clr.stringc("%prog", "bright blue")
commands = clr.stringc("{0}".format(pipe).join(c.VALID_ACTIONS), "normal")
help = clr.stringc("--help", "green")
options = clr.stringc("options", "yellow")
guide = "\n\n"
for action in c.VALID_ACTIONS:
guide += command_name(app_name, action,
c.MESSAGES["help_" + action])
# remove the last line break
guide = guide[:-1]
return "{0} {1}{2}{3} {1}{4}{3} {1}{5}{3}\n{6}".format(app_name,
l_bracket,
commands,
r_bracket,
help,
options,
guide) | python | def usage():
"""
Return the usage for the help command.
"""
l_bracket = clr.stringc("[", "dark gray")
r_bracket = clr.stringc("]", "dark gray")
pipe = clr.stringc("|", "dark gray")
app_name = clr.stringc("%prog", "bright blue")
commands = clr.stringc("{0}".format(pipe).join(c.VALID_ACTIONS), "normal")
help = clr.stringc("--help", "green")
options = clr.stringc("options", "yellow")
guide = "\n\n"
for action in c.VALID_ACTIONS:
guide += command_name(app_name, action,
c.MESSAGES["help_" + action])
# remove the last line break
guide = guide[:-1]
return "{0} {1}{2}{3} {1}{4}{3} {1}{5}{3}\n{6}".format(app_name,
l_bracket,
commands,
r_bracket,
help,
options,
guide) | [
"def",
"usage",
"(",
")",
":",
"l_bracket",
"=",
"clr",
".",
"stringc",
"(",
"\"[\"",
",",
"\"dark gray\"",
")",
"r_bracket",
"=",
"clr",
".",
"stringc",
"(",
"\"]\"",
",",
"\"dark gray\"",
")",
"pipe",
"=",
"clr",
".",
"stringc",
"(",
"\"|\"",
",",
... | Return the usage for the help command. | [
"Return",
"the",
"usage",
"for",
"the",
"help",
"command",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L39-L66 | train | 34,840 |
nickjj/ansigenome | ansigenome/ui.py | epilogue | def epilogue(app_name):
"""
Return the epilogue for the help command.
"""
app_name = clr.stringc(app_name, "bright blue")
command = clr.stringc("command", "cyan")
help = clr.stringc("--help", "green")
return "\n%s %s %s for more info on a command\n" % (app_name,
command, help) | python | def epilogue(app_name):
"""
Return the epilogue for the help command.
"""
app_name = clr.stringc(app_name, "bright blue")
command = clr.stringc("command", "cyan")
help = clr.stringc("--help", "green")
return "\n%s %s %s for more info on a command\n" % (app_name,
command, help) | [
"def",
"epilogue",
"(",
"app_name",
")",
":",
"app_name",
"=",
"clr",
".",
"stringc",
"(",
"app_name",
",",
"\"bright blue\"",
")",
"command",
"=",
"clr",
".",
"stringc",
"(",
"\"command\"",
",",
"\"cyan\"",
")",
"help",
"=",
"clr",
".",
"stringc",
"(",
... | Return the epilogue for the help command. | [
"Return",
"the",
"epilogue",
"for",
"the",
"help",
"command",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L69-L78 | train | 34,841 |
nickjj/ansigenome | ansigenome/ui.py | command_name | def command_name(app_name, command, help_text):
"""
Return a snippet of help text for this command.
"""
command = clr.stringc(command, "cyan")
help = clr.stringc("--help", "green")
return "{0} {1} {2}\n{3}\n\n".format(app_name, command,
help, help_text) | python | def command_name(app_name, command, help_text):
"""
Return a snippet of help text for this command.
"""
command = clr.stringc(command, "cyan")
help = clr.stringc("--help", "green")
return "{0} {1} {2}\n{3}\n\n".format(app_name, command,
help, help_text) | [
"def",
"command_name",
"(",
"app_name",
",",
"command",
",",
"help_text",
")",
":",
"command",
"=",
"clr",
".",
"stringc",
"(",
"command",
",",
"\"cyan\"",
")",
"help",
"=",
"clr",
".",
"stringc",
"(",
"\"--help\"",
",",
"\"green\"",
")",
"return",
"\"{0... | Return a snippet of help text for this command. | [
"Return",
"a",
"snippet",
"of",
"help",
"text",
"for",
"this",
"command",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L81-L89 | train | 34,842 |
nickjj/ansigenome | ansigenome/ui.py | role | def role(name, report, role_name_length):
"""
Print the role information.
"""
pad_role_name_by = 11 + role_name_length
defaults = field_value(report["total_defaults"], "defaults", "blue", 16)
facts = field_value(report["total_facts"], "facts", "purple", 16)
files = field_value(report["total_files"], "files", "dark gray", 16)
lines = field_value(report["total_lines"], "lines", "normal", 16)
print "{0:<{1}} {2} {3} {4} {5}".format(
clr.stringc(name, c.LOG_COLOR[report["state"]]),
pad_role_name_by, defaults, facts, files, lines) | python | def role(name, report, role_name_length):
"""
Print the role information.
"""
pad_role_name_by = 11 + role_name_length
defaults = field_value(report["total_defaults"], "defaults", "blue", 16)
facts = field_value(report["total_facts"], "facts", "purple", 16)
files = field_value(report["total_files"], "files", "dark gray", 16)
lines = field_value(report["total_lines"], "lines", "normal", 16)
print "{0:<{1}} {2} {3} {4} {5}".format(
clr.stringc(name, c.LOG_COLOR[report["state"]]),
pad_role_name_by, defaults, facts, files, lines) | [
"def",
"role",
"(",
"name",
",",
"report",
",",
"role_name_length",
")",
":",
"pad_role_name_by",
"=",
"11",
"+",
"role_name_length",
"defaults",
"=",
"field_value",
"(",
"report",
"[",
"\"total_defaults\"",
"]",
",",
"\"defaults\"",
",",
"\"blue\"",
",",
"16"... | Print the role information. | [
"Print",
"the",
"role",
"information",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L92-L105 | train | 34,843 |
nickjj/ansigenome | ansigenome/ui.py | field_value | def field_value(key, label, color, padding):
"""
Print a specific field's stats.
"""
if not clr.has_colors and padding > 0:
padding = 7
if color == "bright gray" or color == "dark gray":
bright_prefix = ""
else:
bright_prefix = "bright "
field = clr.stringc(key, "{0}{1}".format(bright_prefix, color))
field_label = clr.stringc(label, color)
return "{0:>{1}} {2}".format(field, padding, field_label) | python | def field_value(key, label, color, padding):
"""
Print a specific field's stats.
"""
if not clr.has_colors and padding > 0:
padding = 7
if color == "bright gray" or color == "dark gray":
bright_prefix = ""
else:
bright_prefix = "bright "
field = clr.stringc(key, "{0}{1}".format(bright_prefix, color))
field_label = clr.stringc(label, color)
return "{0:>{1}} {2}".format(field, padding, field_label) | [
"def",
"field_value",
"(",
"key",
",",
"label",
",",
"color",
",",
"padding",
")",
":",
"if",
"not",
"clr",
".",
"has_colors",
"and",
"padding",
">",
"0",
":",
"padding",
"=",
"7",
"if",
"color",
"==",
"\"bright gray\"",
"or",
"color",
"==",
"\"dark gr... | Print a specific field's stats. | [
"Print",
"a",
"specific",
"field",
"s",
"stats",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L108-L123 | train | 34,844 |
nickjj/ansigenome | ansigenome/ui.py | totals | def totals(report, total_roles, role_name_length):
"""
Print the totals for each role's stats.
"""
roles_len_string = len(str(total_roles))
roles_label_len = 6 # "r" "o" "l" "e" "s" " "
if clr.has_colors:
roles_count_offset = 22
else:
roles_count_offset = 13
roles_count_offset += role_name_length
# no idea honestly but it fixes the formatting
# it will probably break the formatting if you have 100+ roles
if roles_len_string > 1:
roles_count_offset -= 2
pad_roles_by = roles_count_offset + roles_len_string + roles_label_len
roles = field_value(total_roles, "roles", "normal", 0)
defaults = field_value(report["defaults"], "defaults", "blue", 16)
facts = field_value(report["facts"], "facts", "purple", 16)
files = field_value(report["files"], "files", "dark gray", 16)
lines = field_value(report["lines"], "lines", "normal", 16)
print "".join(clr.stringc("-", "black") * 79)
print "{0} {2:>{1}} {3} {4} {5}".format(
roles, pad_roles_by, defaults, facts, files, lines) | python | def totals(report, total_roles, role_name_length):
"""
Print the totals for each role's stats.
"""
roles_len_string = len(str(total_roles))
roles_label_len = 6 # "r" "o" "l" "e" "s" " "
if clr.has_colors:
roles_count_offset = 22
else:
roles_count_offset = 13
roles_count_offset += role_name_length
# no idea honestly but it fixes the formatting
# it will probably break the formatting if you have 100+ roles
if roles_len_string > 1:
roles_count_offset -= 2
pad_roles_by = roles_count_offset + roles_len_string + roles_label_len
roles = field_value(total_roles, "roles", "normal", 0)
defaults = field_value(report["defaults"], "defaults", "blue", 16)
facts = field_value(report["facts"], "facts", "purple", 16)
files = field_value(report["files"], "files", "dark gray", 16)
lines = field_value(report["lines"], "lines", "normal", 16)
print "".join(clr.stringc("-", "black") * 79)
print "{0} {2:>{1}} {3} {4} {5}".format(
roles, pad_roles_by, defaults, facts, files, lines) | [
"def",
"totals",
"(",
"report",
",",
"total_roles",
",",
"role_name_length",
")",
":",
"roles_len_string",
"=",
"len",
"(",
"str",
"(",
"total_roles",
")",
")",
"roles_label_len",
"=",
"6",
"# \"r\" \"o\" \"l\" \"e\" \"s\" \" \"",
"if",
"clr",
".",
"has_colors",
... | Print the totals for each role's stats. | [
"Print",
"the",
"totals",
"for",
"each",
"role",
"s",
"stats",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L126-L155 | train | 34,845 |
nickjj/ansigenome | ansigenome/ui.py | gen_totals | def gen_totals(report, file_type):
"""
Print the gen totals.
"""
label = clr.stringc(file_type + " files ", "bright purple")
ok = field_value(report["ok_role"], "ok", c.LOG_COLOR["ok"], 0)
skipped = field_value(report["skipped_role"], "skipped",
c.LOG_COLOR["skipped"], 16)
changed = field_value(report["changed_role"], "changed",
c.LOG_COLOR["changed"], 16)
# missing_meta = field_value(report["missing_meta_role"],
# "missing meta(s)",
# c.LOG_COLOR["missing_meta"], 16)
# print "\n{0} {1} {2} {3}".format(ok, skipped, changed, missing_meta)
print "\n{0} {1} {2} {3}".format(label, ok, skipped, changed) | python | def gen_totals(report, file_type):
"""
Print the gen totals.
"""
label = clr.stringc(file_type + " files ", "bright purple")
ok = field_value(report["ok_role"], "ok", c.LOG_COLOR["ok"], 0)
skipped = field_value(report["skipped_role"], "skipped",
c.LOG_COLOR["skipped"], 16)
changed = field_value(report["changed_role"], "changed",
c.LOG_COLOR["changed"], 16)
# missing_meta = field_value(report["missing_meta_role"],
# "missing meta(s)",
# c.LOG_COLOR["missing_meta"], 16)
# print "\n{0} {1} {2} {3}".format(ok, skipped, changed, missing_meta)
print "\n{0} {1} {2} {3}".format(label, ok, skipped, changed) | [
"def",
"gen_totals",
"(",
"report",
",",
"file_type",
")",
":",
"label",
"=",
"clr",
".",
"stringc",
"(",
"file_type",
"+",
"\" files \"",
",",
"\"bright purple\"",
")",
"ok",
"=",
"field_value",
"(",
"report",
"[",
"\"ok_role\"",
"]",
",",
"\"ok\"",
","... | Print the gen totals. | [
"Print",
"the",
"gen",
"totals",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L158-L176 | train | 34,846 |
nickjj/ansigenome | ansigenome/ui.py | scan_totals | def scan_totals(report):
"""
Print the scan totals.
"""
ok = field_value(report["ok_role"], "ok", c.LOG_COLOR["ok"], 0)
missing_readme = field_value(report["missing_readme_role"],
"missing readme(s)",
c.LOG_COLOR["missing_readme"], 16)
missing_meta = field_value(report["missing_meta_role"],
"missing meta(s)",
c.LOG_COLOR["missing_meta"], 16)
print "\n{0} {1} {2}".format(ok, missing_readme, missing_meta) | python | def scan_totals(report):
"""
Print the scan totals.
"""
ok = field_value(report["ok_role"], "ok", c.LOG_COLOR["ok"], 0)
missing_readme = field_value(report["missing_readme_role"],
"missing readme(s)",
c.LOG_COLOR["missing_readme"], 16)
missing_meta = field_value(report["missing_meta_role"],
"missing meta(s)",
c.LOG_COLOR["missing_meta"], 16)
print "\n{0} {1} {2}".format(ok, missing_readme, missing_meta) | [
"def",
"scan_totals",
"(",
"report",
")",
":",
"ok",
"=",
"field_value",
"(",
"report",
"[",
"\"ok_role\"",
"]",
",",
"\"ok\"",
",",
"c",
".",
"LOG_COLOR",
"[",
"\"ok\"",
"]",
",",
"0",
")",
"missing_readme",
"=",
"field_value",
"(",
"report",
"[",
"\"... | Print the scan totals. | [
"Print",
"the",
"scan",
"totals",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/ui.py#L179-L192 | train | 34,847 |
nickjj/ansigenome | ansigenome/color.py | has_colors | def has_colors(stream):
"""
Determine if the terminal supports ansi colors.
"""
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
return False | python | def has_colors(stream):
"""
Determine if the terminal supports ansi colors.
"""
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
return False | [
"def",
"has_colors",
"(",
"stream",
")",
":",
"if",
"not",
"hasattr",
"(",
"stream",
",",
"\"isatty\"",
")",
":",
"return",
"False",
"if",
"not",
"stream",
".",
"isatty",
"(",
")",
":",
"return",
"False",
"# auto color only on TTYs",
"try",
":",
"import",
... | Determine if the terminal supports ansi colors. | [
"Determine",
"if",
"the",
"terminal",
"supports",
"ansi",
"colors",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/color.py#L4-L17 | train | 34,848 |
nickjj/ansigenome | ansigenome/color.py | stringc | def stringc(text, color):
"""
Return a string with terminal colors.
"""
if has_colors:
text = str(text)
return "\033["+codeCodes[color]+"m"+text+"\033[0m"
else:
return text | python | def stringc(text, color):
"""
Return a string with terminal colors.
"""
if has_colors:
text = str(text)
return "\033["+codeCodes[color]+"m"+text+"\033[0m"
else:
return text | [
"def",
"stringc",
"(",
"text",
",",
"color",
")",
":",
"if",
"has_colors",
":",
"text",
"=",
"str",
"(",
"text",
")",
"return",
"\"\\033[\"",
"+",
"codeCodes",
"[",
"color",
"]",
"+",
"\"m\"",
"+",
"text",
"+",
"\"\\033[0m\"",
"else",
":",
"return",
... | Return a string with terminal colors. | [
"Return",
"a",
"string",
"with",
"terminal",
"colors",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/color.py#L47-L56 | train | 34,849 |
nickjj/ansigenome | ansigenome/run.py | Run.execute_command | def execute_command(self):
"""
Execute the shell command.
"""
stderr = ""
role_count = 0
for role in utils.roles_dict(self.roles_path):
self.command = self.command.replace("%role_name", role)
(_, err) = utils.capture_shell("cd {0} && {1}".
format(os.path.join(
self.roles_path, role),
self.command))
stderr = err
role_count += 1
utils.exit_if_no_roles(role_count, self.roles_path)
if len(stderr) > 0:
ui.error(c.MESSAGES["run_error"], stderr[:-1])
else:
if not self.config["options_quiet"]:
ui.ok(c.MESSAGES["run_success"].replace(
"%role_count", str(role_count)), self.options.command) | python | def execute_command(self):
"""
Execute the shell command.
"""
stderr = ""
role_count = 0
for role in utils.roles_dict(self.roles_path):
self.command = self.command.replace("%role_name", role)
(_, err) = utils.capture_shell("cd {0} && {1}".
format(os.path.join(
self.roles_path, role),
self.command))
stderr = err
role_count += 1
utils.exit_if_no_roles(role_count, self.roles_path)
if len(stderr) > 0:
ui.error(c.MESSAGES["run_error"], stderr[:-1])
else:
if not self.config["options_quiet"]:
ui.ok(c.MESSAGES["run_success"].replace(
"%role_count", str(role_count)), self.options.command) | [
"def",
"execute_command",
"(",
"self",
")",
":",
"stderr",
"=",
"\"\"",
"role_count",
"=",
"0",
"for",
"role",
"in",
"utils",
".",
"roles_dict",
"(",
"self",
".",
"roles_path",
")",
":",
"self",
".",
"command",
"=",
"self",
".",
"command",
".",
"replac... | Execute the shell command. | [
"Execute",
"the",
"shell",
"command",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/run.py#L17-L40 | train | 34,850 |
nickjj/ansigenome | ansigenome/utils.py | mkdir_p | def mkdir_p(path):
"""
Emulate the behavior of mkdir -p.
"""
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
ui.error(c.MESSAGES["path_unmakable"], err)
sys.exit(1) | python | def mkdir_p(path):
"""
Emulate the behavior of mkdir -p.
"""
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
ui.error(c.MESSAGES["path_unmakable"], err)
sys.exit(1) | [
"def",
"mkdir_p",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")"... | Emulate the behavior of mkdir -p. | [
"Emulate",
"the",
"behavior",
"of",
"mkdir",
"-",
"p",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L35-L46 | train | 34,851 |
nickjj/ansigenome | ansigenome/utils.py | string_to_file | def string_to_file(path, input):
"""
Write a file from a given string.
"""
mkdir_p(os.path.dirname(path))
with codecs.open(path, "w+", "UTF-8") as file:
file.write(input) | python | def string_to_file(path, input):
"""
Write a file from a given string.
"""
mkdir_p(os.path.dirname(path))
with codecs.open(path, "w+", "UTF-8") as file:
file.write(input) | [
"def",
"string_to_file",
"(",
"path",
",",
"input",
")",
":",
"mkdir_p",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
"with",
"codecs",
".",
"open",
"(",
"path",
",",
"\"w+\"",
",",
"\"UTF-8\"",
")",
"as",
"file",
":",
"file",
"."... | Write a file from a given string. | [
"Write",
"a",
"file",
"from",
"a",
"given",
"string",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L49-L56 | train | 34,852 |
nickjj/ansigenome | ansigenome/utils.py | file_to_string | def file_to_string(path):
"""
Return the contents of a file when given a path.
"""
if not os.path.exists(path):
ui.error(c.MESSAGES["path_missing"], path)
sys.exit(1)
with codecs.open(path, "r", "UTF-8") as contents:
return contents.read() | python | def file_to_string(path):
"""
Return the contents of a file when given a path.
"""
if not os.path.exists(path):
ui.error(c.MESSAGES["path_missing"], path)
sys.exit(1)
with codecs.open(path, "r", "UTF-8") as contents:
return contents.read() | [
"def",
"file_to_string",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"ui",
".",
"error",
"(",
"c",
".",
"MESSAGES",
"[",
"\"path_missing\"",
"]",
",",
"path",
")",
"sys",
".",
"exit",
"(",
"1",
")"... | Return the contents of a file when given a path. | [
"Return",
"the",
"contents",
"of",
"a",
"file",
"when",
"given",
"a",
"path",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L59-L68 | train | 34,853 |
nickjj/ansigenome | ansigenome/utils.py | file_to_list | def file_to_list(path):
"""
Return the contents of a file as a list when given a path.
"""
if not os.path.exists(path):
ui.error(c.MESSAGES["path_missing"], path)
sys.exit(1)
with codecs.open(path, "r", "UTF-8") as contents:
lines = contents.read().splitlines()
return lines | python | def file_to_list(path):
"""
Return the contents of a file as a list when given a path.
"""
if not os.path.exists(path):
ui.error(c.MESSAGES["path_missing"], path)
sys.exit(1)
with codecs.open(path, "r", "UTF-8") as contents:
lines = contents.read().splitlines()
return lines | [
"def",
"file_to_list",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"ui",
".",
"error",
"(",
"c",
".",
"MESSAGES",
"[",
"\"path_missing\"",
"]",
",",
"path",
")",
"sys",
".",
"exit",
"(",
"1",
")",
... | Return the contents of a file as a list when given a path. | [
"Return",
"the",
"contents",
"of",
"a",
"file",
"as",
"a",
"list",
"when",
"given",
"a",
"path",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L71-L82 | train | 34,854 |
nickjj/ansigenome | ansigenome/utils.py | url_to_string | def url_to_string(url):
"""
Return the contents of a web site url as a string.
"""
try:
page = urllib2.urlopen(url)
except (urllib2.HTTPError, urllib2.URLError) as err:
ui.error(c.MESSAGES["url_unreachable"], err)
sys.exit(1)
return page | python | def url_to_string(url):
"""
Return the contents of a web site url as a string.
"""
try:
page = urllib2.urlopen(url)
except (urllib2.HTTPError, urllib2.URLError) as err:
ui.error(c.MESSAGES["url_unreachable"], err)
sys.exit(1)
return page | [
"def",
"url_to_string",
"(",
"url",
")",
":",
"try",
":",
"page",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"except",
"(",
"urllib2",
".",
"HTTPError",
",",
"urllib2",
".",
"URLError",
")",
"as",
"err",
":",
"ui",
".",
"error",
"(",
"c",
"."... | Return the contents of a web site url as a string. | [
"Return",
"the",
"contents",
"of",
"a",
"web",
"site",
"url",
"as",
"a",
"string",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L92-L102 | train | 34,855 |
nickjj/ansigenome | ansigenome/utils.py | template | def template(path, extend_path, out):
"""
Return a jinja2 template instance with extends support.
"""
files = []
# add the "extender" template when it exists
if len(extend_path) > 0:
# determine the base readme path
base_path = os.path.dirname(extend_path)
new_base_path = os.path.join(base_path, "README.{0}.j2".format(out))
if os.path.exists(new_base_path):
path = new_base_path
if os.path.exists(extend_path):
files = [path, extend_path]
else:
ui.error(c.MESSAGES["template_extender_missing"])
ui.error(extend_path)
sys.exit(1)
else:
files = [path]
try:
# Use the subclassed relative environment class
env = RelEnvironment(trim_blocks=True)
# Add a unique dict filter, by key.
# DEPRECATION WARNING: This is only used for backwards compatibility,
# please use the unique filter instead.
def unique_dict(items, key):
return {v[key]: v for v in items}.values()
env.filters["unique_dict"] = unique_dict
def unique(a):
# Don’t use the following commented out optimization which is used
# in ansible/lib/ansible/plugins/filter/mathstuff.py in Ansigenome
# as it resorts the role dependencies:
# if isinstance(a,collections.Hashable):
# c = set(a)
c = []
for x in a:
if x not in c:
c.append(x)
return c
env.filters["unique"] = unique
# create a dictionary of templates
templates = dict(
(name, codecs.open(name, "rb", 'UTF-8').read())
for name in files)
env.loader = DictLoader(templates)
# return the final result (the last template in the list)
return env.get_template(files[len(files) - 1])
except Exception as err:
ui.error(c.MESSAGES["template_error"], err)
sys.exit(1) | python | def template(path, extend_path, out):
"""
Return a jinja2 template instance with extends support.
"""
files = []
# add the "extender" template when it exists
if len(extend_path) > 0:
# determine the base readme path
base_path = os.path.dirname(extend_path)
new_base_path = os.path.join(base_path, "README.{0}.j2".format(out))
if os.path.exists(new_base_path):
path = new_base_path
if os.path.exists(extend_path):
files = [path, extend_path]
else:
ui.error(c.MESSAGES["template_extender_missing"])
ui.error(extend_path)
sys.exit(1)
else:
files = [path]
try:
# Use the subclassed relative environment class
env = RelEnvironment(trim_blocks=True)
# Add a unique dict filter, by key.
# DEPRECATION WARNING: This is only used for backwards compatibility,
# please use the unique filter instead.
def unique_dict(items, key):
return {v[key]: v for v in items}.values()
env.filters["unique_dict"] = unique_dict
def unique(a):
# Don’t use the following commented out optimization which is used
# in ansible/lib/ansible/plugins/filter/mathstuff.py in Ansigenome
# as it resorts the role dependencies:
# if isinstance(a,collections.Hashable):
# c = set(a)
c = []
for x in a:
if x not in c:
c.append(x)
return c
env.filters["unique"] = unique
# create a dictionary of templates
templates = dict(
(name, codecs.open(name, "rb", 'UTF-8').read())
for name in files)
env.loader = DictLoader(templates)
# return the final result (the last template in the list)
return env.get_template(files[len(files) - 1])
except Exception as err:
ui.error(c.MESSAGES["template_error"], err)
sys.exit(1) | [
"def",
"template",
"(",
"path",
",",
"extend_path",
",",
"out",
")",
":",
"files",
"=",
"[",
"]",
"# add the \"extender\" template when it exists",
"if",
"len",
"(",
"extend_path",
")",
">",
"0",
":",
"# determine the base readme path",
"base_path",
"=",
"os",
"... | Return a jinja2 template instance with extends support. | [
"Return",
"a",
"jinja2",
"template",
"instance",
"with",
"extends",
"support",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L105-L167 | train | 34,856 |
nickjj/ansigenome | ansigenome/utils.py | files_in_path | def files_in_path(path):
"""
Return a list of all files in a path but exclude git folders.
"""
aggregated_files = []
for dir_, _, files in os.walk(path):
for file in files:
relative_dir = os.path.relpath(dir_, path)
if ".git" not in relative_dir:
relative_file = os.path.join(relative_dir, file)
aggregated_files.append(relative_file)
return aggregated_files | python | def files_in_path(path):
"""
Return a list of all files in a path but exclude git folders.
"""
aggregated_files = []
for dir_, _, files in os.walk(path):
for file in files:
relative_dir = os.path.relpath(dir_, path)
if ".git" not in relative_dir:
relative_file = os.path.join(relative_dir, file)
aggregated_files.append(relative_file)
return aggregated_files | [
"def",
"files_in_path",
"(",
"path",
")",
":",
"aggregated_files",
"=",
"[",
"]",
"for",
"dir_",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"file",
"in",
"files",
":",
"relative_dir",
"=",
"os",
".",
"path",
".",... | Return a list of all files in a path but exclude git folders. | [
"Return",
"a",
"list",
"of",
"all",
"files",
"in",
"a",
"path",
"but",
"exclude",
"git",
"folders",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L170-L184 | train | 34,857 |
nickjj/ansigenome | ansigenome/utils.py | exit_if_path_not_found | def exit_if_path_not_found(path):
"""
Exit if the path is not found.
"""
if not os.path.exists(path):
ui.error(c.MESSAGES["path_missing"], path)
sys.exit(1) | python | def exit_if_path_not_found(path):
"""
Exit if the path is not found.
"""
if not os.path.exists(path):
ui.error(c.MESSAGES["path_missing"], path)
sys.exit(1) | [
"def",
"exit_if_path_not_found",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"ui",
".",
"error",
"(",
"c",
".",
"MESSAGES",
"[",
"\"path_missing\"",
"]",
",",
"path",
")",
"sys",
".",
"exit",
"(",
"1... | Exit if the path is not found. | [
"Exit",
"if",
"the",
"path",
"is",
"not",
"found",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L187-L193 | train | 34,858 |
nickjj/ansigenome | ansigenome/utils.py | yaml_load | def yaml_load(path, input="", err_quit=False):
"""
Return a yaml dict from a file or string with error handling.
"""
try:
if len(input) > 0:
return yaml.safe_load(input)
elif len(path) > 0:
return yaml.safe_load(file_to_string(path))
except Exception as err:
file = os.path.basename(path)
ui.error("",
c.MESSAGES["yaml_error"].replace("%file", file), err,
"")
if err_quit:
sys.exit(1)
return False | python | def yaml_load(path, input="", err_quit=False):
"""
Return a yaml dict from a file or string with error handling.
"""
try:
if len(input) > 0:
return yaml.safe_load(input)
elif len(path) > 0:
return yaml.safe_load(file_to_string(path))
except Exception as err:
file = os.path.basename(path)
ui.error("",
c.MESSAGES["yaml_error"].replace("%file", file), err,
"")
if err_quit:
sys.exit(1)
return False | [
"def",
"yaml_load",
"(",
"path",
",",
"input",
"=",
"\"\"",
",",
"err_quit",
"=",
"False",
")",
":",
"try",
":",
"if",
"len",
"(",
"input",
")",
">",
"0",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"input",
")",
"elif",
"len",
"(",
"path",
")"... | Return a yaml dict from a file or string with error handling. | [
"Return",
"a",
"yaml",
"dict",
"from",
"a",
"file",
"or",
"string",
"with",
"error",
"handling",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L209-L227 | train | 34,859 |
nickjj/ansigenome | ansigenome/utils.py | to_nice_yaml | def to_nice_yaml(yaml_input, indentation=2):
"""
Return condensed yaml into human readable yaml.
"""
return yaml.safe_dump(yaml_input, indent=indentation,
allow_unicode=True, default_flow_style=False) | python | def to_nice_yaml(yaml_input, indentation=2):
"""
Return condensed yaml into human readable yaml.
"""
return yaml.safe_dump(yaml_input, indent=indentation,
allow_unicode=True, default_flow_style=False) | [
"def",
"to_nice_yaml",
"(",
"yaml_input",
",",
"indentation",
"=",
"2",
")",
":",
"return",
"yaml",
".",
"safe_dump",
"(",
"yaml_input",
",",
"indent",
"=",
"indentation",
",",
"allow_unicode",
"=",
"True",
",",
"default_flow_style",
"=",
"False",
")"
] | Return condensed yaml into human readable yaml. | [
"Return",
"condensed",
"yaml",
"into",
"human",
"readable",
"yaml",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L230-L235 | train | 34,860 |
nickjj/ansigenome | ansigenome/utils.py | keys_in_dict | def keys_in_dict(d, parent_key, keys):
"""
Create a list of keys from a dict recursively.
"""
for key, value in d.iteritems():
if isinstance(value, dict):
keys_in_dict(value, key, keys)
else:
if parent_key:
prefix = parent_key + "."
else:
prefix = ""
keys.append(prefix + key)
return keys | python | def keys_in_dict(d, parent_key, keys):
"""
Create a list of keys from a dict recursively.
"""
for key, value in d.iteritems():
if isinstance(value, dict):
keys_in_dict(value, key, keys)
else:
if parent_key:
prefix = parent_key + "."
else:
prefix = ""
keys.append(prefix + key)
return keys | [
"def",
"keys_in_dict",
"(",
"d",
",",
"parent_key",
",",
"keys",
")",
":",
"for",
"key",
",",
"value",
"in",
"d",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"keys_in_dict",
"(",
"value",
",",
"key",
",... | Create a list of keys from a dict recursively. | [
"Create",
"a",
"list",
"of",
"keys",
"from",
"a",
"dict",
"recursively",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L258-L273 | train | 34,861 |
nickjj/ansigenome | ansigenome/utils.py | swap_yaml_string | def swap_yaml_string(file_path, swaps):
"""
Swap a string in a yaml file without touching the existing formatting.
"""
original_file = file_to_string(file_path)
new_file = original_file
changed = False
for item in swaps:
match = re.compile(r'(?<={0}: )(["\']?)(.*)\1'.format(item[0]),
re.MULTILINE)
new_file = re.sub(match, item[1], new_file)
if new_file != original_file:
changed = True
string_to_file(file_path, new_file)
return (new_file, changed) | python | def swap_yaml_string(file_path, swaps):
"""
Swap a string in a yaml file without touching the existing formatting.
"""
original_file = file_to_string(file_path)
new_file = original_file
changed = False
for item in swaps:
match = re.compile(r'(?<={0}: )(["\']?)(.*)\1'.format(item[0]),
re.MULTILINE)
new_file = re.sub(match, item[1], new_file)
if new_file != original_file:
changed = True
string_to_file(file_path, new_file)
return (new_file, changed) | [
"def",
"swap_yaml_string",
"(",
"file_path",
",",
"swaps",
")",
":",
"original_file",
"=",
"file_to_string",
"(",
"file_path",
")",
"new_file",
"=",
"original_file",
"changed",
"=",
"False",
"for",
"item",
"in",
"swaps",
":",
"match",
"=",
"re",
".",
"compil... | Swap a string in a yaml file without touching the existing formatting. | [
"Swap",
"a",
"string",
"in",
"a",
"yaml",
"file",
"without",
"touching",
"the",
"existing",
"formatting",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L276-L295 | train | 34,862 |
nickjj/ansigenome | ansigenome/utils.py | exit_if_no_roles | def exit_if_no_roles(roles_count, roles_path):
"""
Exit if there were no roles found.
"""
if roles_count == 0:
ui.warn(c.MESSAGES["empty_roles_path"], roles_path)
sys.exit() | python | def exit_if_no_roles(roles_count, roles_path):
"""
Exit if there were no roles found.
"""
if roles_count == 0:
ui.warn(c.MESSAGES["empty_roles_path"], roles_path)
sys.exit() | [
"def",
"exit_if_no_roles",
"(",
"roles_count",
",",
"roles_path",
")",
":",
"if",
"roles_count",
"==",
"0",
":",
"ui",
".",
"warn",
"(",
"c",
".",
"MESSAGES",
"[",
"\"empty_roles_path\"",
"]",
",",
"roles_path",
")",
"sys",
".",
"exit",
"(",
")"
] | Exit if there were no roles found. | [
"Exit",
"if",
"there",
"were",
"no",
"roles",
"found",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L303-L309 | train | 34,863 |
nickjj/ansigenome | ansigenome/utils.py | roles_dict | def roles_dict(path, repo_prefix="", repo_sub_dir=""):
"""
Return a dict of role names and repo paths.
"""
exit_if_path_not_found(path)
aggregated_roles = {}
roles = os.walk(path).next()[1]
# First scan all directories
for role in roles:
for sub_role in roles_dict(path + "/" + role, repo_prefix="",
repo_sub_dir=role + "/"):
aggregated_roles[role + "/" + sub_role] = role + "/" + sub_role
# Then format them
for role in roles:
if is_role(os.path.join(path, role)):
if isinstance(role, basestring):
role_repo = "{0}{1}".format(repo_prefix, role_name(role))
aggregated_roles[role] = role_repo
return aggregated_roles | python | def roles_dict(path, repo_prefix="", repo_sub_dir=""):
"""
Return a dict of role names and repo paths.
"""
exit_if_path_not_found(path)
aggregated_roles = {}
roles = os.walk(path).next()[1]
# First scan all directories
for role in roles:
for sub_role in roles_dict(path + "/" + role, repo_prefix="",
repo_sub_dir=role + "/"):
aggregated_roles[role + "/" + sub_role] = role + "/" + sub_role
# Then format them
for role in roles:
if is_role(os.path.join(path, role)):
if isinstance(role, basestring):
role_repo = "{0}{1}".format(repo_prefix, role_name(role))
aggregated_roles[role] = role_repo
return aggregated_roles | [
"def",
"roles_dict",
"(",
"path",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"\"\"",
")",
":",
"exit_if_path_not_found",
"(",
"path",
")",
"aggregated_roles",
"=",
"{",
"}",
"roles",
"=",
"os",
".",
"walk",
"(",
"path",
")",
".",
"next",
... | Return a dict of role names and repo paths. | [
"Return",
"a",
"dict",
"of",
"role",
"names",
"and",
"repo",
"paths",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L312-L336 | train | 34,864 |
nickjj/ansigenome | ansigenome/utils.py | is_role | def is_role(path):
"""
Determine if a path is an ansible role.
"""
seems_legit = False
for folder in c.ANSIBLE_FOLDERS:
if os.path.exists(os.path.join(path, folder)):
seems_legit = True
return seems_legit | python | def is_role(path):
"""
Determine if a path is an ansible role.
"""
seems_legit = False
for folder in c.ANSIBLE_FOLDERS:
if os.path.exists(os.path.join(path, folder)):
seems_legit = True
return seems_legit | [
"def",
"is_role",
"(",
"path",
")",
":",
"seems_legit",
"=",
"False",
"for",
"folder",
"in",
"c",
".",
"ANSIBLE_FOLDERS",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder",
")",
")",
":",
... | Determine if a path is an ansible role. | [
"Determine",
"if",
"a",
"path",
"is",
"an",
"ansible",
"role",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L349-L358 | train | 34,865 |
nickjj/ansigenome | ansigenome/utils.py | stripped_args | def stripped_args(args):
"""
Return the stripped version of the arguments.
"""
stripped_args = []
for arg in args:
stripped_args.append(arg.strip())
return stripped_args | python | def stripped_args(args):
"""
Return the stripped version of the arguments.
"""
stripped_args = []
for arg in args:
stripped_args.append(arg.strip())
return stripped_args | [
"def",
"stripped_args",
"(",
"args",
")",
":",
"stripped_args",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"stripped_args",
".",
"append",
"(",
"arg",
".",
"strip",
"(",
")",
")",
"return",
"stripped_args"
] | Return the stripped version of the arguments. | [
"Return",
"the",
"stripped",
"version",
"of",
"the",
"arguments",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L361-L369 | train | 34,866 |
nickjj/ansigenome | ansigenome/utils.py | normalize_role | def normalize_role(role, config):
"""
Normalize a role name.
"""
if role.startswith(config["scm_repo_prefix"]):
role_name = role.replace(config["scm_repo_prefix"], "")
else:
if "." in role:
galaxy_prefix = "{0}.".format(config["scm_user"])
role_name = role.replace(galaxy_prefix, "")
elif "-" in role:
role_name = role.replace("-", "_")
else:
role_name = role
return role_name | python | def normalize_role(role, config):
"""
Normalize a role name.
"""
if role.startswith(config["scm_repo_prefix"]):
role_name = role.replace(config["scm_repo_prefix"], "")
else:
if "." in role:
galaxy_prefix = "{0}.".format(config["scm_user"])
role_name = role.replace(galaxy_prefix, "")
elif "-" in role:
role_name = role.replace("-", "_")
else:
role_name = role
return role_name | [
"def",
"normalize_role",
"(",
"role",
",",
"config",
")",
":",
"if",
"role",
".",
"startswith",
"(",
"config",
"[",
"\"scm_repo_prefix\"",
"]",
")",
":",
"role_name",
"=",
"role",
".",
"replace",
"(",
"config",
"[",
"\"scm_repo_prefix\"",
"]",
",",
"\"\"",... | Normalize a role name. | [
"Normalize",
"a",
"role",
"name",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L372-L387 | train | 34,867 |
nickjj/ansigenome | ansigenome/utils.py | create_meta_main | def create_meta_main(create_path, config, role, categories):
"""
Create a meta template.
"""
meta_file = c.DEFAULT_META_FILE.replace(
"%author_name", config["author_name"])
meta_file = meta_file.replace(
"%author_company", config["author_company"])
meta_file = meta_file.replace("%license_type", config["license_type"])
meta_file = meta_file.replace("%role_name", role)
# Normalize the category so %categories always gets replaced.
if not categories:
categories = ""
meta_file = meta_file.replace("%categories", categories)
string_to_file(create_path, meta_file) | python | def create_meta_main(create_path, config, role, categories):
"""
Create a meta template.
"""
meta_file = c.DEFAULT_META_FILE.replace(
"%author_name", config["author_name"])
meta_file = meta_file.replace(
"%author_company", config["author_company"])
meta_file = meta_file.replace("%license_type", config["license_type"])
meta_file = meta_file.replace("%role_name", role)
# Normalize the category so %categories always gets replaced.
if not categories:
categories = ""
meta_file = meta_file.replace("%categories", categories)
string_to_file(create_path, meta_file) | [
"def",
"create_meta_main",
"(",
"create_path",
",",
"config",
",",
"role",
",",
"categories",
")",
":",
"meta_file",
"=",
"c",
".",
"DEFAULT_META_FILE",
".",
"replace",
"(",
"\"%author_name\"",
",",
"config",
"[",
"\"author_name\"",
"]",
")",
"meta_file",
"=",... | Create a meta template. | [
"Create",
"a",
"meta",
"template",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L390-L407 | train | 34,868 |
nickjj/ansigenome | ansigenome/utils.py | get_version | def get_version(path, default="master"):
"""
Return the version from a VERSION file
"""
version = default
if os.path.exists(path):
version_contents = file_to_string(path)
if version_contents:
version = version_contents.strip()
return version | python | def get_version(path, default="master"):
"""
Return the version from a VERSION file
"""
version = default
if os.path.exists(path):
version_contents = file_to_string(path)
if version_contents:
version = version_contents.strip()
return version | [
"def",
"get_version",
"(",
"path",
",",
"default",
"=",
"\"master\"",
")",
":",
"version",
"=",
"default",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"version_contents",
"=",
"file_to_string",
"(",
"path",
")",
"if",
"version_contents",... | Return the version from a VERSION file | [
"Return",
"the",
"version",
"from",
"a",
"VERSION",
"file"
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L410-L420 | train | 34,869 |
nickjj/ansigenome | ansigenome/utils.py | write_config | def write_config(path, config):
"""
Write the config with a little post-converting formatting.
"""
config_as_string = to_nice_yaml(config)
config_as_string = "---\n" + config_as_string
string_to_file(path, config_as_string) | python | def write_config(path, config):
"""
Write the config with a little post-converting formatting.
"""
config_as_string = to_nice_yaml(config)
config_as_string = "---\n" + config_as_string
string_to_file(path, config_as_string) | [
"def",
"write_config",
"(",
"path",
",",
"config",
")",
":",
"config_as_string",
"=",
"to_nice_yaml",
"(",
"config",
")",
"config_as_string",
"=",
"\"---\\n\"",
"+",
"config_as_string",
"string_to_file",
"(",
"path",
",",
"config_as_string",
")"
] | Write the config with a little post-converting formatting. | [
"Write",
"the",
"config",
"with",
"a",
"little",
"post",
"-",
"converting",
"formatting",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/utils.py#L423-L431 | train | 34,870 |
nickjj/ansigenome | ansigenome/scan.py | Scan.limit_roles | def limit_roles(self):
"""
Limit the roles being scanned.
"""
new_roles = {}
roles = self.options.limit.split(",")
for key, value in self.roles.iteritems():
for role in roles:
role = role.strip()
if key == role:
new_roles[key] = value
self.roles = new_roles | python | def limit_roles(self):
"""
Limit the roles being scanned.
"""
new_roles = {}
roles = self.options.limit.split(",")
for key, value in self.roles.iteritems():
for role in roles:
role = role.strip()
if key == role:
new_roles[key] = value
self.roles = new_roles | [
"def",
"limit_roles",
"(",
"self",
")",
":",
"new_roles",
"=",
"{",
"}",
"roles",
"=",
"self",
".",
"options",
".",
"limit",
".",
"split",
"(",
"\",\"",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"roles",
".",
"iteritems",
"(",
")",
":",
... | Limit the roles being scanned. | [
"Limit",
"the",
"roles",
"being",
"scanned",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L88-L101 | train | 34,871 |
nickjj/ansigenome | ansigenome/scan.py | Scan.scan_roles | def scan_roles(self):
"""
Iterate over each role and report its stats.
"""
for key, value in sorted(self.roles.iteritems()):
self.paths["role"] = os.path.join(self.roles_path, key)
self.paths["meta"] = os.path.join(self.paths["role"], "meta",
"main.yml")
self.paths["readme"] = os.path.join(self.paths["role"],
"README.{0}"
.format(self.readme_format))
self.paths["defaults"] = os.path.join(self.paths["role"],
"defaults", "main.yml")
self.report["roles"][key] = self.report_role(key)
# we are writing a readme file which means the state of the role
# needs to be updated before it gets output by the ui
if self.gendoc:
if self.valid_meta(key):
self.make_meta_dict_consistent()
self.set_readme_template_vars(key, value)
self.write_readme(key)
# only load the meta file when generating meta files
elif self.genmeta:
self.make_or_augment_meta(key)
if self.valid_meta(key):
self.make_meta_dict_consistent()
self.write_meta(key)
else:
self.update_scan_report(key)
if not self.config["options_quiet"] and not self.export:
ui.role(key,
self.report["roles"][key],
self.report["stats"]["longest_role_name_length"])
self.tally_role_columns()
# below this point is only UI output, so we can return
if self.config["options_quiet"] or self.export:
return
ui.totals(self.report["totals"],
len(self.report["roles"].keys()),
self.report["stats"]["longest_role_name_length"])
if self.gendoc:
ui.gen_totals(self.report["state"], "readme")
elif self.genmeta:
ui.gen_totals(self.report["state"], "meta")
else:
ui.scan_totals(self.report["state"]) | python | def scan_roles(self):
"""
Iterate over each role and report its stats.
"""
for key, value in sorted(self.roles.iteritems()):
self.paths["role"] = os.path.join(self.roles_path, key)
self.paths["meta"] = os.path.join(self.paths["role"], "meta",
"main.yml")
self.paths["readme"] = os.path.join(self.paths["role"],
"README.{0}"
.format(self.readme_format))
self.paths["defaults"] = os.path.join(self.paths["role"],
"defaults", "main.yml")
self.report["roles"][key] = self.report_role(key)
# we are writing a readme file which means the state of the role
# needs to be updated before it gets output by the ui
if self.gendoc:
if self.valid_meta(key):
self.make_meta_dict_consistent()
self.set_readme_template_vars(key, value)
self.write_readme(key)
# only load the meta file when generating meta files
elif self.genmeta:
self.make_or_augment_meta(key)
if self.valid_meta(key):
self.make_meta_dict_consistent()
self.write_meta(key)
else:
self.update_scan_report(key)
if not self.config["options_quiet"] and not self.export:
ui.role(key,
self.report["roles"][key],
self.report["stats"]["longest_role_name_length"])
self.tally_role_columns()
# below this point is only UI output, so we can return
if self.config["options_quiet"] or self.export:
return
ui.totals(self.report["totals"],
len(self.report["roles"].keys()),
self.report["stats"]["longest_role_name_length"])
if self.gendoc:
ui.gen_totals(self.report["state"], "readme")
elif self.genmeta:
ui.gen_totals(self.report["state"], "meta")
else:
ui.scan_totals(self.report["state"]) | [
"def",
"scan_roles",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"roles",
".",
"iteritems",
"(",
")",
")",
":",
"self",
".",
"paths",
"[",
"\"role\"",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",... | Iterate over each role and report its stats. | [
"Iterate",
"over",
"each",
"role",
"and",
"report",
"its",
"stats",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L103-L155 | train | 34,872 |
nickjj/ansigenome | ansigenome/scan.py | Scan.export_roles | def export_roles(self):
"""
Export the roles to one of the export types.
"""
# prepare the report by removing unnecessary fields
del self.report["state"]
del self.report["stats"]
for role in self.report["roles"]:
del self.report["roles"][role]["state"]
defaults_path = os.path.join(self.roles_path, role,
"defaults", "main.yml")
if os.path.exists(defaults_path):
defaults = self.report["roles"][role]["defaults"]
self.report["roles"][role]["defaults"] = \
utils.yaml_load("", defaults)
Export(self.roles_path, self.report, self.config, self.options) | python | def export_roles(self):
"""
Export the roles to one of the export types.
"""
# prepare the report by removing unnecessary fields
del self.report["state"]
del self.report["stats"]
for role in self.report["roles"]:
del self.report["roles"][role]["state"]
defaults_path = os.path.join(self.roles_path, role,
"defaults", "main.yml")
if os.path.exists(defaults_path):
defaults = self.report["roles"][role]["defaults"]
self.report["roles"][role]["defaults"] = \
utils.yaml_load("", defaults)
Export(self.roles_path, self.report, self.config, self.options) | [
"def",
"export_roles",
"(",
"self",
")",
":",
"# prepare the report by removing unnecessary fields",
"del",
"self",
".",
"report",
"[",
"\"state\"",
"]",
"del",
"self",
".",
"report",
"[",
"\"stats\"",
"]",
"for",
"role",
"in",
"self",
".",
"report",
"[",
"\"r... | Export the roles to one of the export types. | [
"Export",
"the",
"roles",
"to",
"one",
"of",
"the",
"export",
"types",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L157-L174 | train | 34,873 |
nickjj/ansigenome | ansigenome/scan.py | Scan.report_role | def report_role(self, role):
"""
Return the fields gathered.
"""
self.yaml_files = []
fields = {
"state": "skipped",
"total_files": self.gather_files(),
"total_lines": self.gather_lines(),
"total_facts": self.gather_facts(),
"total_defaults": self.gather_defaults(),
"facts": self.facts,
"defaults": self.defaults,
"meta": self.gather_meta(),
"readme": self.gather_readme(),
"dependencies": self.dependencies,
"total_dependencies": len(self.dependencies)
}
return fields | python | def report_role(self, role):
"""
Return the fields gathered.
"""
self.yaml_files = []
fields = {
"state": "skipped",
"total_files": self.gather_files(),
"total_lines": self.gather_lines(),
"total_facts": self.gather_facts(),
"total_defaults": self.gather_defaults(),
"facts": self.facts,
"defaults": self.defaults,
"meta": self.gather_meta(),
"readme": self.gather_readme(),
"dependencies": self.dependencies,
"total_dependencies": len(self.dependencies)
}
return fields | [
"def",
"report_role",
"(",
"self",
",",
"role",
")",
":",
"self",
".",
"yaml_files",
"=",
"[",
"]",
"fields",
"=",
"{",
"\"state\"",
":",
"\"skipped\"",
",",
"\"total_files\"",
":",
"self",
".",
"gather_files",
"(",
")",
",",
"\"total_lines\"",
":",
"sel... | Return the fields gathered. | [
"Return",
"the",
"fields",
"gathered",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L176-L196 | train | 34,874 |
nickjj/ansigenome | ansigenome/scan.py | Scan.gather_meta | def gather_meta(self):
"""
Return the meta file.
"""
if not os.path.exists(self.paths["meta"]):
return ""
meta_dict = utils.yaml_load(self.paths["meta"])
# gather the dependencies
if meta_dict and "dependencies" in meta_dict:
# create a simple list of each role that is a dependency
dep_list = []
for dependency in meta_dict["dependencies"]:
if type(dependency) is dict:
dep_list.append(dependency["role"])
else:
dep_list.append(dependency)
# unique set of dependencies
meta_dict["dependencies"] = list(set(dep_list))
self.dependencies = meta_dict["dependencies"]
else:
self.dependencies = []
return utils.file_to_string(self.paths["meta"]) | python | def gather_meta(self):
"""
Return the meta file.
"""
if not os.path.exists(self.paths["meta"]):
return ""
meta_dict = utils.yaml_load(self.paths["meta"])
# gather the dependencies
if meta_dict and "dependencies" in meta_dict:
# create a simple list of each role that is a dependency
dep_list = []
for dependency in meta_dict["dependencies"]:
if type(dependency) is dict:
dep_list.append(dependency["role"])
else:
dep_list.append(dependency)
# unique set of dependencies
meta_dict["dependencies"] = list(set(dep_list))
self.dependencies = meta_dict["dependencies"]
else:
self.dependencies = []
return utils.file_to_string(self.paths["meta"]) | [
"def",
"gather_meta",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
")",
":",
"return",
"\"\"",
"meta_dict",
"=",
"utils",
".",
"yaml_load",
"(",
"self",
".",
"paths",
"[",
"\... | Return the meta file. | [
"Return",
"the",
"meta",
"file",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L198-L225 | train | 34,875 |
nickjj/ansigenome | ansigenome/scan.py | Scan.gather_readme | def gather_readme(self):
"""
Return the readme file.
"""
if not os.path.exists(self.paths["readme"]):
return ""
return utils.file_to_string(self.paths["readme"]) | python | def gather_readme(self):
"""
Return the readme file.
"""
if not os.path.exists(self.paths["readme"]):
return ""
return utils.file_to_string(self.paths["readme"]) | [
"def",
"gather_readme",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
"[",
"\"readme\"",
"]",
")",
":",
"return",
"\"\"",
"return",
"utils",
".",
"file_to_string",
"(",
"self",
".",
"paths",
"[",
"\"... | Return the readme file. | [
"Return",
"the",
"readme",
"file",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L227-L234 | train | 34,876 |
nickjj/ansigenome | ansigenome/scan.py | Scan.gather_defaults | def gather_defaults(self):
"""
Return the number of default variables.
"""
total_defaults = 0
defaults_lines = []
if not os.path.exists(self.paths["defaults"]):
# reset the defaults if no defaults were found
self.defaults = ""
return 0
file = open(self.paths["defaults"], "r")
for line in file:
if len(line) > 0:
first_char = line[0]
else:
first_char = ""
defaults_lines.append(line)
if (first_char != "#" and first_char != "-" and
first_char != " " and
first_char != "\r" and
first_char != "\n" and
first_char != "\t"):
total_defaults += 1
file.close()
self.defaults = "".join(defaults_lines)
return total_defaults | python | def gather_defaults(self):
"""
Return the number of default variables.
"""
total_defaults = 0
defaults_lines = []
if not os.path.exists(self.paths["defaults"]):
# reset the defaults if no defaults were found
self.defaults = ""
return 0
file = open(self.paths["defaults"], "r")
for line in file:
if len(line) > 0:
first_char = line[0]
else:
first_char = ""
defaults_lines.append(line)
if (first_char != "#" and first_char != "-" and
first_char != " " and
first_char != "\r" and
first_char != "\n" and
first_char != "\t"):
total_defaults += 1
file.close()
self.defaults = "".join(defaults_lines)
return total_defaults | [
"def",
"gather_defaults",
"(",
"self",
")",
":",
"total_defaults",
"=",
"0",
"defaults_lines",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
"[",
"\"defaults\"",
"]",
")",
":",
"# reset the defaults if no defaults w... | Return the number of default variables. | [
"Return",
"the",
"number",
"of",
"default",
"variables",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L236-L267 | train | 34,877 |
nickjj/ansigenome | ansigenome/scan.py | Scan.gather_facts | def gather_facts(self):
"""
Return the number of facts.
"""
facts = []
for file in self.yaml_files:
facts += self.gather_facts_list(file)
unique_facts = list(set(facts))
self.facts = unique_facts
return len(unique_facts) | python | def gather_facts(self):
"""
Return the number of facts.
"""
facts = []
for file in self.yaml_files:
facts += self.gather_facts_list(file)
unique_facts = list(set(facts))
self.facts = unique_facts
return len(unique_facts) | [
"def",
"gather_facts",
"(",
"self",
")",
":",
"facts",
"=",
"[",
"]",
"for",
"file",
"in",
"self",
".",
"yaml_files",
":",
"facts",
"+=",
"self",
".",
"gather_facts_list",
"(",
"file",
")",
"unique_facts",
"=",
"list",
"(",
"set",
"(",
"facts",
")",
... | Return the number of facts. | [
"Return",
"the",
"number",
"of",
"facts",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L269-L281 | train | 34,878 |
nickjj/ansigenome | ansigenome/scan.py | Scan.gather_facts_list | def gather_facts_list(self, file):
"""
Return a list of facts.
"""
facts = []
contents = utils.file_to_string(os.path.join(self.paths["role"],
file))
contents = re.sub(r"\s+", "", contents)
matches = self.regex_facts.findall(contents)
for match in matches:
facts.append(match.split(":")[1])
return facts | python | def gather_facts_list(self, file):
"""
Return a list of facts.
"""
facts = []
contents = utils.file_to_string(os.path.join(self.paths["role"],
file))
contents = re.sub(r"\s+", "", contents)
matches = self.regex_facts.findall(contents)
for match in matches:
facts.append(match.split(":")[1])
return facts | [
"def",
"gather_facts_list",
"(",
"self",
",",
"file",
")",
":",
"facts",
"=",
"[",
"]",
"contents",
"=",
"utils",
".",
"file_to_string",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"paths",
"[",
"\"role\"",
"]",
",",
"file",
")",
")",
"c... | Return a list of facts. | [
"Return",
"a",
"list",
"of",
"facts",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L283-L297 | train | 34,879 |
nickjj/ansigenome | ansigenome/scan.py | Scan.gather_files | def gather_files(self):
"""
Return the number of files.
"""
self.all_files = utils.files_in_path(self.paths["role"])
return len(self.all_files) | python | def gather_files(self):
"""
Return the number of files.
"""
self.all_files = utils.files_in_path(self.paths["role"])
return len(self.all_files) | [
"def",
"gather_files",
"(",
"self",
")",
":",
"self",
".",
"all_files",
"=",
"utils",
".",
"files_in_path",
"(",
"self",
".",
"paths",
"[",
"\"role\"",
"]",
")",
"return",
"len",
"(",
"self",
".",
"all_files",
")"
] | Return the number of files. | [
"Return",
"the",
"number",
"of",
"files",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L299-L305 | train | 34,880 |
nickjj/ansigenome | ansigenome/scan.py | Scan.gather_lines | def gather_lines(self):
"""
Return the number of lines.
"""
total_lines = 0
for file in self.all_files:
full_path = os.path.join(self.paths["role"], file)
with open(full_path, "r") as f:
for line in f:
total_lines += 1
if full_path.endswith(".yml"):
self.yaml_files.append(full_path)
return total_lines | python | def gather_lines(self):
"""
Return the number of lines.
"""
total_lines = 0
for file in self.all_files:
full_path = os.path.join(self.paths["role"], file)
with open(full_path, "r") as f:
for line in f:
total_lines += 1
if full_path.endswith(".yml"):
self.yaml_files.append(full_path)
return total_lines | [
"def",
"gather_lines",
"(",
"self",
")",
":",
"total_lines",
"=",
"0",
"for",
"file",
"in",
"self",
".",
"all_files",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"paths",
"[",
"\"role\"",
"]",
",",
"file",
")",
"with",
... | Return the number of lines. | [
"Return",
"the",
"number",
"of",
"lines",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L307-L322 | train | 34,881 |
nickjj/ansigenome | ansigenome/scan.py | Scan.tally_role_columns | def tally_role_columns(self):
"""
Sum up all of the stat columns.
"""
totals = self.report["totals"]
roles = self.report["roles"]
totals["dependencies"] = sum(roles[item]
["total_dependencies"] for item in roles)
totals["defaults"] = sum(roles[item]
["total_defaults"] for item in roles)
totals["facts"] = sum(roles[item]["total_facts"] for item in roles)
totals["files"] = sum(roles[item]["total_files"] for item in roles)
totals["lines"] = sum(roles[item]["total_lines"] for item in roles) | python | def tally_role_columns(self):
"""
Sum up all of the stat columns.
"""
totals = self.report["totals"]
roles = self.report["roles"]
totals["dependencies"] = sum(roles[item]
["total_dependencies"] for item in roles)
totals["defaults"] = sum(roles[item]
["total_defaults"] for item in roles)
totals["facts"] = sum(roles[item]["total_facts"] for item in roles)
totals["files"] = sum(roles[item]["total_files"] for item in roles)
totals["lines"] = sum(roles[item]["total_lines"] for item in roles) | [
"def",
"tally_role_columns",
"(",
"self",
")",
":",
"totals",
"=",
"self",
".",
"report",
"[",
"\"totals\"",
"]",
"roles",
"=",
"self",
".",
"report",
"[",
"\"roles\"",
"]",
"totals",
"[",
"\"dependencies\"",
"]",
"=",
"sum",
"(",
"roles",
"[",
"item",
... | Sum up all of the stat columns. | [
"Sum",
"up",
"all",
"of",
"the",
"stat",
"columns",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L324-L337 | train | 34,882 |
nickjj/ansigenome | ansigenome/scan.py | Scan.valid_meta | def valid_meta(self, role):
"""
Return whether or not the meta file being read is valid.
"""
if os.path.exists(self.paths["meta"]):
self.meta_dict = utils.yaml_load(self.paths["meta"])
else:
self.report["state"]["missing_meta_role"] += 1
self.report["roles"][role]["state"] = "missing_meta"
return False
is_valid = True
# utils.yaml_load returns False when the file is invalid
if isinstance(self.meta_dict, bool):
is_valid = False
sys.exit(1)
return is_valid | python | def valid_meta(self, role):
"""
Return whether or not the meta file being read is valid.
"""
if os.path.exists(self.paths["meta"]):
self.meta_dict = utils.yaml_load(self.paths["meta"])
else:
self.report["state"]["missing_meta_role"] += 1
self.report["roles"][role]["state"] = "missing_meta"
return False
is_valid = True
# utils.yaml_load returns False when the file is invalid
if isinstance(self.meta_dict, bool):
is_valid = False
sys.exit(1)
return is_valid | [
"def",
"valid_meta",
"(",
"self",
",",
"role",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
")",
":",
"self",
".",
"meta_dict",
"=",
"utils",
".",
"yaml_load",
"(",
"self",
".",
"paths",
"[",
... | Return whether or not the meta file being read is valid. | [
"Return",
"whether",
"or",
"not",
"the",
"meta",
"file",
"being",
"read",
"is",
"valid",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L339-L358 | train | 34,883 |
nickjj/ansigenome | ansigenome/scan.py | Scan.make_or_augment_meta | def make_or_augment_meta(self, role):
"""
Create or augment a meta file.
"""
if not os.path.exists(self.paths["meta"]):
utils.create_meta_main(self.paths["meta"], self.config, role, "")
self.report["state"]["ok_role"] += 1
self.report["roles"][role]["state"] = "ok"
# swap values in place to use the config values
swaps = [
("author", self.config["author_name"]),
("company", self.config["author_company"]),
("license", self.config["license_type"]),
]
(new_meta, _) = utils.swap_yaml_string(self.paths["meta"], swaps)
# normalize the --- at the top of the file by removing it first
new_meta = new_meta.replace("---", "")
new_meta = new_meta.lstrip()
# augment missing main keys
augments = [
("ansigenome_info", "{}"),
("galaxy_info", "{}"),
("dependencies", "[]"),
]
new_meta = self.augment_main_keys(augments, new_meta)
# re-attach the ---
new_meta = "---\n\n" + new_meta
travis_path = os.path.join(self.paths["role"], ".travis.yml")
if os.path.exists(travis_path):
new_meta = new_meta.replace("travis: False", "travis: True")
utils.string_to_file(self.paths["meta"], new_meta) | python | def make_or_augment_meta(self, role):
"""
Create or augment a meta file.
"""
if not os.path.exists(self.paths["meta"]):
utils.create_meta_main(self.paths["meta"], self.config, role, "")
self.report["state"]["ok_role"] += 1
self.report["roles"][role]["state"] = "ok"
# swap values in place to use the config values
swaps = [
("author", self.config["author_name"]),
("company", self.config["author_company"]),
("license", self.config["license_type"]),
]
(new_meta, _) = utils.swap_yaml_string(self.paths["meta"], swaps)
# normalize the --- at the top of the file by removing it first
new_meta = new_meta.replace("---", "")
new_meta = new_meta.lstrip()
# augment missing main keys
augments = [
("ansigenome_info", "{}"),
("galaxy_info", "{}"),
("dependencies", "[]"),
]
new_meta = self.augment_main_keys(augments, new_meta)
# re-attach the ---
new_meta = "---\n\n" + new_meta
travis_path = os.path.join(self.paths["role"], ".travis.yml")
if os.path.exists(travis_path):
new_meta = new_meta.replace("travis: False", "travis: True")
utils.string_to_file(self.paths["meta"], new_meta) | [
"def",
"make_or_augment_meta",
"(",
"self",
",",
"role",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
")",
":",
"utils",
".",
"create_meta_main",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
... | Create or augment a meta file. | [
"Create",
"or",
"augment",
"a",
"meta",
"file",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L360-L398 | train | 34,884 |
nickjj/ansigenome | ansigenome/scan.py | Scan.write_readme | def write_readme(self, role):
"""
Write out a new readme file.
"""
j2_out = self.readme_template.render(self.readme_template_vars)
self.update_gen_report(role, "readme", j2_out) | python | def write_readme(self, role):
"""
Write out a new readme file.
"""
j2_out = self.readme_template.render(self.readme_template_vars)
self.update_gen_report(role, "readme", j2_out) | [
"def",
"write_readme",
"(",
"self",
",",
"role",
")",
":",
"j2_out",
"=",
"self",
".",
"readme_template",
".",
"render",
"(",
"self",
".",
"readme_template_vars",
")",
"self",
".",
"update_gen_report",
"(",
"role",
",",
"\"readme\"",
",",
"j2_out",
")"
] | Write out a new readme file. | [
"Write",
"out",
"a",
"new",
"readme",
"file",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L431-L437 | train | 34,885 |
nickjj/ansigenome | ansigenome/scan.py | Scan.write_meta | def write_meta(self, role):
"""
Write out a new meta file.
"""
meta_file = utils.file_to_string(self.paths["meta"])
self.update_gen_report(role, "meta", meta_file) | python | def write_meta(self, role):
"""
Write out a new meta file.
"""
meta_file = utils.file_to_string(self.paths["meta"])
self.update_gen_report(role, "meta", meta_file) | [
"def",
"write_meta",
"(",
"self",
",",
"role",
")",
":",
"meta_file",
"=",
"utils",
".",
"file_to_string",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
")",
"self",
".",
"update_gen_report",
"(",
"role",
",",
"\"meta\"",
",",
"meta_file",
")"
] | Write out a new meta file. | [
"Write",
"out",
"a",
"new",
"meta",
"file",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L439-L445 | train | 34,886 |
nickjj/ansigenome | ansigenome/scan.py | Scan.update_scan_report | def update_scan_report(self, role):
"""
Update the role state and adjust the scan totals.
"""
state = self.report["state"]
# ensure the missing meta state is colored up and the ok count is good
if self.gendoc:
if self.report["roles"][role]["state"] == "missing_meta":
return
if os.path.exists(self.paths["readme"]):
state["ok_role"] += 1
self.report["roles"][role]["state"] = "ok"
else:
state["missing_readme_role"] += 1
self.report["roles"][role]["state"] = "missing_readme" | python | def update_scan_report(self, role):
"""
Update the role state and adjust the scan totals.
"""
state = self.report["state"]
# ensure the missing meta state is colored up and the ok count is good
if self.gendoc:
if self.report["roles"][role]["state"] == "missing_meta":
return
if os.path.exists(self.paths["readme"]):
state["ok_role"] += 1
self.report["roles"][role]["state"] = "ok"
else:
state["missing_readme_role"] += 1
self.report["roles"][role]["state"] = "missing_readme" | [
"def",
"update_scan_report",
"(",
"self",
",",
"role",
")",
":",
"state",
"=",
"self",
".",
"report",
"[",
"\"state\"",
"]",
"# ensure the missing meta state is colored up and the ok count is good",
"if",
"self",
".",
"gendoc",
":",
"if",
"self",
".",
"report",
"[... | Update the role state and adjust the scan totals. | [
"Update",
"the",
"role",
"state",
"and",
"adjust",
"the",
"scan",
"totals",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L447-L463 | train | 34,887 |
nickjj/ansigenome | ansigenome/scan.py | Scan.update_gen_report | def update_gen_report(self, role, file, original):
"""
Update the role state and adjust the gen totals.
"""
state = self.report["state"]
if not os.path.exists(self.paths[file]):
state["ok_role"] += 1
self.report["roles"][role]["state"] = "ok"
elif (self.report["roles"][role][file] != original and
self.report["roles"][role]["state"] != "ok"):
state["changed_role"] += 1
self.report["roles"][role]["state"] = "changed"
elif self.report["roles"][role][file] == original:
state["skipped_role"] += 1
self.report["roles"][role]["state"] = "skipped"
return
utils.string_to_file(self.paths[file], original) | python | def update_gen_report(self, role, file, original):
"""
Update the role state and adjust the gen totals.
"""
state = self.report["state"]
if not os.path.exists(self.paths[file]):
state["ok_role"] += 1
self.report["roles"][role]["state"] = "ok"
elif (self.report["roles"][role][file] != original and
self.report["roles"][role]["state"] != "ok"):
state["changed_role"] += 1
self.report["roles"][role]["state"] = "changed"
elif self.report["roles"][role][file] == original:
state["skipped_role"] += 1
self.report["roles"][role]["state"] = "skipped"
return
utils.string_to_file(self.paths[file], original) | [
"def",
"update_gen_report",
"(",
"self",
",",
"role",
",",
"file",
",",
"original",
")",
":",
"state",
"=",
"self",
".",
"report",
"[",
"\"state\"",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
"[",
"file",
"]",
")... | Update the role state and adjust the gen totals. | [
"Update",
"the",
"role",
"state",
"and",
"adjust",
"the",
"gen",
"totals",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L465-L483 | train | 34,888 |
nickjj/ansigenome | ansigenome/scan.py | Scan.make_meta_dict_consistent | def make_meta_dict_consistent(self):
"""
Remove the possibility of the main keys being undefined.
"""
if self.meta_dict is None:
self.meta_dict = {}
if "galaxy_info" not in self.meta_dict:
self.meta_dict["galaxy_info"] = {}
if "dependencies" not in self.meta_dict:
self.meta_dict["dependencies"] = []
if "ansigenome_info" not in self.meta_dict:
self.meta_dict["ansigenome_info"] = {} | python | def make_meta_dict_consistent(self):
"""
Remove the possibility of the main keys being undefined.
"""
if self.meta_dict is None:
self.meta_dict = {}
if "galaxy_info" not in self.meta_dict:
self.meta_dict["galaxy_info"] = {}
if "dependencies" not in self.meta_dict:
self.meta_dict["dependencies"] = []
if "ansigenome_info" not in self.meta_dict:
self.meta_dict["ansigenome_info"] = {} | [
"def",
"make_meta_dict_consistent",
"(",
"self",
")",
":",
"if",
"self",
".",
"meta_dict",
"is",
"None",
":",
"self",
".",
"meta_dict",
"=",
"{",
"}",
"if",
"\"galaxy_info\"",
"not",
"in",
"self",
".",
"meta_dict",
":",
"self",
".",
"meta_dict",
"[",
"\"... | Remove the possibility of the main keys being undefined. | [
"Remove",
"the",
"possibility",
"of",
"the",
"main",
"keys",
"being",
"undefined",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L485-L499 | train | 34,889 |
nickjj/ansigenome | ansigenome/scan.py | Scan.set_readme_template_vars | def set_readme_template_vars(self, role, repo_name):
"""
Set the readme template variables.
"""
# normalize and expose a bunch of fields to the template
authors = []
author = {
"name": self.config["author_name"],
"company": self.config["author_company"],
"url": self.config["author_url"],
"email": self.config["author_email"],
"twitter": self.config["author_twitter"],
}
scm = {
"host": self.config["scm_host"],
"repo_prefix": self.config["scm_repo_prefix"],
"type": self.config["scm_type"],
"user": self.config["scm_user"],
}
license = {
"type": self.config["license_type"],
"url": self.config["license_url"],
}
role_name = utils.normalize_role(role, self.config)
normalized_role = {
"name": role_name,
"galaxy_name": "{0}.{1}".format(self.config["scm_user"],
role_name),
"slug": "{0}{1}".format(self.config["scm_repo_prefix"],
role_name),
}
if "authors" in self.meta_dict["ansigenome_info"]:
authors = self.meta_dict["ansigenome_info"]["authors"]
else:
authors = [author]
if "github" in self.config["scm_host"]:
self.config["author_github"] = "{0}/{1}".format(
self.config["scm_host"],
self.config["scm_user"])
self.readme_template_vars = {
"authors": authors,
"scm": scm,
"role": normalized_role,
"license": license,
"galaxy_info": self.meta_dict["galaxy_info"],
"dependencies": self.meta_dict["dependencies"],
"ansigenome_info": self.meta_dict["ansigenome_info"]
}
# add the defaults and facts
r_defaults = self.report["roles"][role]["defaults"]
self.readme_template_vars["ansigenome_info"]["defaults"] = r_defaults
facts = "\n".join(self.report["roles"][role]["facts"])
self.readme_template_vars["ansigenome_info"]["facts"] = facts | python | def set_readme_template_vars(self, role, repo_name):
"""
Set the readme template variables.
"""
# normalize and expose a bunch of fields to the template
authors = []
author = {
"name": self.config["author_name"],
"company": self.config["author_company"],
"url": self.config["author_url"],
"email": self.config["author_email"],
"twitter": self.config["author_twitter"],
}
scm = {
"host": self.config["scm_host"],
"repo_prefix": self.config["scm_repo_prefix"],
"type": self.config["scm_type"],
"user": self.config["scm_user"],
}
license = {
"type": self.config["license_type"],
"url": self.config["license_url"],
}
role_name = utils.normalize_role(role, self.config)
normalized_role = {
"name": role_name,
"galaxy_name": "{0}.{1}".format(self.config["scm_user"],
role_name),
"slug": "{0}{1}".format(self.config["scm_repo_prefix"],
role_name),
}
if "authors" in self.meta_dict["ansigenome_info"]:
authors = self.meta_dict["ansigenome_info"]["authors"]
else:
authors = [author]
if "github" in self.config["scm_host"]:
self.config["author_github"] = "{0}/{1}".format(
self.config["scm_host"],
self.config["scm_user"])
self.readme_template_vars = {
"authors": authors,
"scm": scm,
"role": normalized_role,
"license": license,
"galaxy_info": self.meta_dict["galaxy_info"],
"dependencies": self.meta_dict["dependencies"],
"ansigenome_info": self.meta_dict["ansigenome_info"]
}
# add the defaults and facts
r_defaults = self.report["roles"][role]["defaults"]
self.readme_template_vars["ansigenome_info"]["defaults"] = r_defaults
facts = "\n".join(self.report["roles"][role]["facts"])
self.readme_template_vars["ansigenome_info"]["facts"] = facts | [
"def",
"set_readme_template_vars",
"(",
"self",
",",
"role",
",",
"repo_name",
")",
":",
"# normalize and expose a bunch of fields to the template",
"authors",
"=",
"[",
"]",
"author",
"=",
"{",
"\"name\"",
":",
"self",
".",
"config",
"[",
"\"author_name\"",
"]",
... | Set the readme template variables. | [
"Set",
"the",
"readme",
"template",
"variables",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/scan.py#L501-L561 | train | 34,890 |
nickjj/ansigenome | ansigenome/init.py | Init.exit_if_path_exists | def exit_if_path_exists(self):
"""
Exit early if the path cannot be found.
"""
if os.path.exists(self.output_path):
ui.error(c.MESSAGES["path_exists"], self.output_path)
sys.exit(1) | python | def exit_if_path_exists(self):
"""
Exit early if the path cannot be found.
"""
if os.path.exists(self.output_path):
ui.error(c.MESSAGES["path_exists"], self.output_path)
sys.exit(1) | [
"def",
"exit_if_path_exists",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"output_path",
")",
":",
"ui",
".",
"error",
"(",
"c",
".",
"MESSAGES",
"[",
"\"path_exists\"",
"]",
",",
"self",
".",
"output_path",
")",
... | Exit early if the path cannot be found. | [
"Exit",
"early",
"if",
"the",
"path",
"cannot",
"be",
"found",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/init.py#L62-L68 | train | 34,891 |
nickjj/ansigenome | ansigenome/init.py | Init.create_skeleton | def create_skeleton(self):
"""
Create the role's directory and file structure.
"""
utils.string_to_file(os.path.join(self.output_path, "VERSION"),
"master\n")
for folder in c.ANSIBLE_FOLDERS:
create_folder_path = os.path.join(self.output_path, folder)
utils.mkdir_p(create_folder_path)
mainyml_template = default_mainyml_template.replace(
"%role_name", self.role_name)
mainyml_template = mainyml_template.replace(
"%values", folder)
out_path = os.path.join(create_folder_path, "main.yml")
if folder not in ("templates", "meta", "tests", "files"):
utils.string_to_file(out_path, mainyml_template)
if folder == "meta":
utils.create_meta_main(out_path,
self.config, self.role_name,
self.options.galaxy_categories) | python | def create_skeleton(self):
"""
Create the role's directory and file structure.
"""
utils.string_to_file(os.path.join(self.output_path, "VERSION"),
"master\n")
for folder in c.ANSIBLE_FOLDERS:
create_folder_path = os.path.join(self.output_path, folder)
utils.mkdir_p(create_folder_path)
mainyml_template = default_mainyml_template.replace(
"%role_name", self.role_name)
mainyml_template = mainyml_template.replace(
"%values", folder)
out_path = os.path.join(create_folder_path, "main.yml")
if folder not in ("templates", "meta", "tests", "files"):
utils.string_to_file(out_path, mainyml_template)
if folder == "meta":
utils.create_meta_main(out_path,
self.config, self.role_name,
self.options.galaxy_categories) | [
"def",
"create_skeleton",
"(",
"self",
")",
":",
"utils",
".",
"string_to_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"output_path",
",",
"\"VERSION\"",
")",
",",
"\"master\\n\"",
")",
"for",
"folder",
"in",
"c",
".",
"ANSIBLE_FOLDERS",
... | Create the role's directory and file structure. | [
"Create",
"the",
"role",
"s",
"directory",
"and",
"file",
"structure",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/init.py#L70-L94 | train | 34,892 |
nickjj/ansigenome | ansigenome/init.py | Init.create_travis_config | def create_travis_config(self):
"""
Create a travis test setup.
"""
test_runner = self.config["options_test_runner"]
role_url = "{0}".format(os.path.join(self.config["scm_host"],
self.config["scm_user"],
self.config["scm_repo_prefix"] +
self.normalized_role))
travisyml_template = default_travisyml_template.replace(
"%test_runner", test_runner)
travisyml_template = travisyml_template.replace(
"%basename", test_runner.split("/")[-1])
travisyml_template = travisyml_template.replace(
"%role_url", role_url)
utils.string_to_file(os.path.join(self.output_path, ".travis.yml"),
travisyml_template) | python | def create_travis_config(self):
"""
Create a travis test setup.
"""
test_runner = self.config["options_test_runner"]
role_url = "{0}".format(os.path.join(self.config["scm_host"],
self.config["scm_user"],
self.config["scm_repo_prefix"] +
self.normalized_role))
travisyml_template = default_travisyml_template.replace(
"%test_runner", test_runner)
travisyml_template = travisyml_template.replace(
"%basename", test_runner.split("/")[-1])
travisyml_template = travisyml_template.replace(
"%role_url", role_url)
utils.string_to_file(os.path.join(self.output_path, ".travis.yml"),
travisyml_template) | [
"def",
"create_travis_config",
"(",
"self",
")",
":",
"test_runner",
"=",
"self",
".",
"config",
"[",
"\"options_test_runner\"",
"]",
"role_url",
"=",
"\"{0}\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"config",
"[",
"\"scm_ho... | Create a travis test setup. | [
"Create",
"a",
"travis",
"test",
"setup",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/init.py#L96-L115 | train | 34,893 |
nickjj/ansigenome | ansigenome/export.py | Export.set_format | def set_format(self, format):
"""
Pick the correct default format.
"""
if self.options.format:
self.format = self.options.format
else:
self.format = \
self.config["default_format_" + format] | python | def set_format(self, format):
"""
Pick the correct default format.
"""
if self.options.format:
self.format = self.options.format
else:
self.format = \
self.config["default_format_" + format] | [
"def",
"set_format",
"(",
"self",
",",
"format",
")",
":",
"if",
"self",
".",
"options",
".",
"format",
":",
"self",
".",
"format",
"=",
"self",
".",
"options",
".",
"format",
"else",
":",
"self",
".",
"format",
"=",
"self",
".",
"config",
"[",
"\"... | Pick the correct default format. | [
"Pick",
"the",
"correct",
"default",
"format",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L61-L69 | train | 34,894 |
nickjj/ansigenome | ansigenome/export.py | Export.validate_format | def validate_format(self, allowed_formats):
"""
Validate the allowed formats for a specific type.
"""
if self.format in allowed_formats:
return
ui.error("Export type '{0}' does not accept '{1}' format, only: "
"{2}".format(self.type, self.format, allowed_formats))
sys.exit(1) | python | def validate_format(self, allowed_formats):
"""
Validate the allowed formats for a specific type.
"""
if self.format in allowed_formats:
return
ui.error("Export type '{0}' does not accept '{1}' format, only: "
"{2}".format(self.type, self.format, allowed_formats))
sys.exit(1) | [
"def",
"validate_format",
"(",
"self",
",",
"allowed_formats",
")",
":",
"if",
"self",
".",
"format",
"in",
"allowed_formats",
":",
"return",
"ui",
".",
"error",
"(",
"\"Export type '{0}' does not accept '{1}' format, only: \"",
"\"{2}\"",
".",
"format",
"(",
"self"... | Validate the allowed formats for a specific type. | [
"Validate",
"the",
"allowed",
"formats",
"for",
"a",
"specific",
"type",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L71-L80 | train | 34,895 |
nickjj/ansigenome | ansigenome/export.py | Export.graph_dot | def graph_dot(self):
"""
Export a graph of the data in dot format.
"""
default_graphviz_template = """
digraph role_dependencies {
size="%size"
dpi=%dpi
ratio="fill"
landscape=false
rankdir="BT";
node [shape = "box",
style = "rounded,filled",
fillcolor = "lightgrey",
fontsize = 20];
edge [style = "dashed",
dir = "forward",
penwidth = 1.5];
%roles_list
%dependencies
}
"""
roles_list = ""
edges = ""
# remove the darkest and brightest colors, still have 100+ colors
adjusted_colors = c.X11_COLORS[125:-325]
random.shuffle(adjusted_colors)
backup_colors = adjusted_colors[:]
for role, fields in sorted(self.report["roles"].iteritems()):
name = utils.normalize_role(role, self.config)
color_length = len(adjusted_colors) - 1
# reset the colors if we run out
if color_length == 0:
adjusted_colors = backup_colors[:]
color_length = len(adjusted_colors) - 1
random_index = random.randint(1, color_length)
roles_list += " role_{0} [label = \"{1}\"]\n" \
.format(re.sub(r'[.-/]', '_', name), name)
edge = '\n edge [color = "{0}"];\n' \
.format(adjusted_colors[random_index])
del adjusted_colors[random_index]
if fields["dependencies"]:
dependencies = ""
for dependency in sorted(fields["dependencies"]):
dependency_name = utils.role_name(dependency)
dependencies += " role_{0} -> role_{1}\n".format(
re.sub(r'[.-/]', '_', name),
re.sub(r'[.-/]', '_',
utils.normalize_role(dependency_name,
self.config)
)
)
edges += "{0}{1}\n".format(edge, dependencies)
graphviz_template = default_graphviz_template.replace("%roles_list",
roles_list)
graphviz_template = graphviz_template.replace("%dependencies",
edges)
graphviz_template = graphviz_template.replace("%size",
self.size)
graphviz_template = graphviz_template.replace("%dpi",
str(self.dpi))
if self.out_file:
utils.string_to_file(self.out_file, graphviz_template)
else:
print graphviz_template | python | def graph_dot(self):
"""
Export a graph of the data in dot format.
"""
default_graphviz_template = """
digraph role_dependencies {
size="%size"
dpi=%dpi
ratio="fill"
landscape=false
rankdir="BT";
node [shape = "box",
style = "rounded,filled",
fillcolor = "lightgrey",
fontsize = 20];
edge [style = "dashed",
dir = "forward",
penwidth = 1.5];
%roles_list
%dependencies
}
"""
roles_list = ""
edges = ""
# remove the darkest and brightest colors, still have 100+ colors
adjusted_colors = c.X11_COLORS[125:-325]
random.shuffle(adjusted_colors)
backup_colors = adjusted_colors[:]
for role, fields in sorted(self.report["roles"].iteritems()):
name = utils.normalize_role(role, self.config)
color_length = len(adjusted_colors) - 1
# reset the colors if we run out
if color_length == 0:
adjusted_colors = backup_colors[:]
color_length = len(adjusted_colors) - 1
random_index = random.randint(1, color_length)
roles_list += " role_{0} [label = \"{1}\"]\n" \
.format(re.sub(r'[.-/]', '_', name), name)
edge = '\n edge [color = "{0}"];\n' \
.format(adjusted_colors[random_index])
del adjusted_colors[random_index]
if fields["dependencies"]:
dependencies = ""
for dependency in sorted(fields["dependencies"]):
dependency_name = utils.role_name(dependency)
dependencies += " role_{0} -> role_{1}\n".format(
re.sub(r'[.-/]', '_', name),
re.sub(r'[.-/]', '_',
utils.normalize_role(dependency_name,
self.config)
)
)
edges += "{0}{1}\n".format(edge, dependencies)
graphviz_template = default_graphviz_template.replace("%roles_list",
roles_list)
graphviz_template = graphviz_template.replace("%dependencies",
edges)
graphviz_template = graphviz_template.replace("%size",
self.size)
graphviz_template = graphviz_template.replace("%dpi",
str(self.dpi))
if self.out_file:
utils.string_to_file(self.out_file, graphviz_template)
else:
print graphviz_template | [
"def",
"graph_dot",
"(",
"self",
")",
":",
"default_graphviz_template",
"=",
"\"\"\"\ndigraph role_dependencies {\n size=\"%size\"\n dpi=%dpi\n ratio=\"fill\"\n landscape=false\n rankdir=\"BT\";\n\n node [shape = \"box\",\n style = \"rounded,fil... | Export a graph of the data in dot format. | [
"Export",
"a",
"graph",
"of",
"the",
"data",
"in",
"dot",
"format",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L82-L161 | train | 34,896 |
nickjj/ansigenome | ansigenome/export.py | Export.exit_if_missing_graphviz | def exit_if_missing_graphviz(self):
"""
Detect the presence of the dot utility to make a png graph.
"""
(out, err) = utils.capture_shell("which dot")
if "dot" not in out:
ui.error(c.MESSAGES["dot_missing"]) | python | def exit_if_missing_graphviz(self):
"""
Detect the presence of the dot utility to make a png graph.
"""
(out, err) = utils.capture_shell("which dot")
if "dot" not in out:
ui.error(c.MESSAGES["dot_missing"]) | [
"def",
"exit_if_missing_graphviz",
"(",
"self",
")",
":",
"(",
"out",
",",
"err",
")",
"=",
"utils",
".",
"capture_shell",
"(",
"\"which dot\"",
")",
"if",
"\"dot\"",
"not",
"in",
"out",
":",
"ui",
".",
"error",
"(",
"c",
".",
"MESSAGES",
"[",
"\"dot_m... | Detect the presence of the dot utility to make a png graph. | [
"Detect",
"the",
"presence",
"of",
"the",
"dot",
"utility",
"to",
"make",
"a",
"png",
"graph",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L182-L189 | train | 34,897 |
nickjj/ansigenome | ansigenome/export.py | Export.reqs_txt | def reqs_txt(self):
"""
Export a requirements file in txt format.
"""
role_lines = ""
for role in sorted(self.report["roles"]):
name = utils.normalize_role(role, self.config)
galaxy_name = "{0}.{1}".format(self.config["scm_user"], name)
version_path = os.path.join(self.roles_path, role, "VERSION")
version = utils.get_version(version_path)
role_lines += "{0},{1}\n".format(galaxy_name, version)
if self.out_file:
utils.string_to_file(self.out_file, role_lines)
else:
print role_lines | python | def reqs_txt(self):
"""
Export a requirements file in txt format.
"""
role_lines = ""
for role in sorted(self.report["roles"]):
name = utils.normalize_role(role, self.config)
galaxy_name = "{0}.{1}".format(self.config["scm_user"], name)
version_path = os.path.join(self.roles_path, role, "VERSION")
version = utils.get_version(version_path)
role_lines += "{0},{1}\n".format(galaxy_name, version)
if self.out_file:
utils.string_to_file(self.out_file, role_lines)
else:
print role_lines | [
"def",
"reqs_txt",
"(",
"self",
")",
":",
"role_lines",
"=",
"\"\"",
"for",
"role",
"in",
"sorted",
"(",
"self",
".",
"report",
"[",
"\"roles\"",
"]",
")",
":",
"name",
"=",
"utils",
".",
"normalize_role",
"(",
"role",
",",
"self",
".",
"config",
")"... | Export a requirements file in txt format. | [
"Export",
"a",
"requirements",
"file",
"in",
"txt",
"format",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L191-L208 | train | 34,898 |
nickjj/ansigenome | ansigenome/export.py | Export.reqs_yml | def reqs_yml(self):
"""
Export a requirements file in yml format.
"""
default_yml_item = """
- src: '%src'
name: '%name'
scm: '%scm'
version: '%version'
"""
role_lines = "---\n"
for role in sorted(self.report["roles"]):
name = utils.normalize_role(role, self.config)
galaxy_name = "{0}.{1}".format(self.config["scm_user"], name)
yml_item = default_yml_item
if self.config["scm_host"]:
yml_item = yml_item.replace("%name",
"{0}".format(galaxy_name))
if self.config["scm_repo_prefix"]:
role = self.config["scm_repo_prefix"] + name
src = os.path.join(self.config["scm_host"],
self.config["scm_user"], role)
else:
src = galaxy_name
yml_item = yml_item.replace(" name: '%name'\n", "")
yml_item = yml_item.replace(" scm: '%scm'\n", "")
yml_item = yml_item.replace("%src", src)
if self.config["scm_type"]:
yml_item = yml_item.replace("%scm", self.config["scm_type"])
else:
yml_item = yml_item.replace(" scm: '%scm'\n", "")
version_path = os.path.join(self.roles_path, role, "VERSION")
version = utils.get_version(version_path)
yml_item = yml_item.replace("%version", version)
role_lines += "{0}".format(yml_item)
if self.out_file:
utils.string_to_file(self.out_file, role_lines)
else:
print role_lines | python | def reqs_yml(self):
"""
Export a requirements file in yml format.
"""
default_yml_item = """
- src: '%src'
name: '%name'
scm: '%scm'
version: '%version'
"""
role_lines = "---\n"
for role in sorted(self.report["roles"]):
name = utils.normalize_role(role, self.config)
galaxy_name = "{0}.{1}".format(self.config["scm_user"], name)
yml_item = default_yml_item
if self.config["scm_host"]:
yml_item = yml_item.replace("%name",
"{0}".format(galaxy_name))
if self.config["scm_repo_prefix"]:
role = self.config["scm_repo_prefix"] + name
src = os.path.join(self.config["scm_host"],
self.config["scm_user"], role)
else:
src = galaxy_name
yml_item = yml_item.replace(" name: '%name'\n", "")
yml_item = yml_item.replace(" scm: '%scm'\n", "")
yml_item = yml_item.replace("%src", src)
if self.config["scm_type"]:
yml_item = yml_item.replace("%scm", self.config["scm_type"])
else:
yml_item = yml_item.replace(" scm: '%scm'\n", "")
version_path = os.path.join(self.roles_path, role, "VERSION")
version = utils.get_version(version_path)
yml_item = yml_item.replace("%version", version)
role_lines += "{0}".format(yml_item)
if self.out_file:
utils.string_to_file(self.out_file, role_lines)
else:
print role_lines | [
"def",
"reqs_yml",
"(",
"self",
")",
":",
"default_yml_item",
"=",
"\"\"\"\n- src: '%src'\n name: '%name'\n scm: '%scm'\n version: '%version'\n\"\"\"",
"role_lines",
"=",
"\"---\\n\"",
"for",
"role",
"in",
"sorted",
"(",
"self",
".",
"report",
"[",
"\"roles\""... | Export a requirements file in yml format. | [
"Export",
"a",
"requirements",
"file",
"in",
"yml",
"format",
"."
] | 70cd98d7a23d36c56f4e713ea820cfb4c485c81c | https://github.com/nickjj/ansigenome/blob/70cd98d7a23d36c56f4e713ea820cfb4c485c81c/ansigenome/export.py#L210-L256 | train | 34,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.