repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
jic-dtool/dtoolcore
dtoolcore/compare.py
diff_identifiers
def diff_identifiers(a, b): """Return list of tuples where identifiers in datasets differ. Tuple structure: (identifier, present in a, present in b) :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples where identifiers in datasets differ """ a_ids = set(a.identifiers) b_ids = set(b.identifiers) difference = [] for i in a_ids.difference(b_ids): difference.append((i, True, False)) for i in b_ids.difference(a_ids): difference.append((i, False, True)) return difference
python
def diff_identifiers(a, b): """Return list of tuples where identifiers in datasets differ. Tuple structure: (identifier, present in a, present in b) :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples where identifiers in datasets differ """ a_ids = set(a.identifiers) b_ids = set(b.identifiers) difference = [] for i in a_ids.difference(b_ids): difference.append((i, True, False)) for i in b_ids.difference(a_ids): difference.append((i, False, True)) return difference
[ "def", "diff_identifiers", "(", "a", ",", "b", ")", ":", "a_ids", "=", "set", "(", "a", ".", "identifiers", ")", "b_ids", "=", "set", "(", "b", ".", "identifiers", ")", "difference", "=", "[", "]", "for", "i", "in", "a_ids", ".", "difference", "(",...
Return list of tuples where identifiers in datasets differ. Tuple structure: (identifier, present in a, present in b) :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples where identifiers in datasets differ
[ "Return", "list", "of", "tuples", "where", "identifiers", "in", "datasets", "differ", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/compare.py#L4-L25
jic-dtool/dtoolcore
dtoolcore/compare.py
diff_sizes
def diff_sizes(a, b, progressbar=None): """Return list of tuples where sizes differ. Tuple structure: (identifier, size in a, size in b) Assumes list of identifiers in a and b are identical. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples for all items with different sizes """ difference = [] for i in a.identifiers: a_size = a.item_properties(i)["size_in_bytes"] b_size = b.item_properties(i)["size_in_bytes"] if a_size != b_size: difference.append((i, a_size, b_size)) if progressbar: progressbar.update(1) return difference
python
def diff_sizes(a, b, progressbar=None): """Return list of tuples where sizes differ. Tuple structure: (identifier, size in a, size in b) Assumes list of identifiers in a and b are identical. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples for all items with different sizes """ difference = [] for i in a.identifiers: a_size = a.item_properties(i)["size_in_bytes"] b_size = b.item_properties(i)["size_in_bytes"] if a_size != b_size: difference.append((i, a_size, b_size)) if progressbar: progressbar.update(1) return difference
[ "def", "diff_sizes", "(", "a", ",", "b", ",", "progressbar", "=", "None", ")", ":", "difference", "=", "[", "]", "for", "i", "in", "a", ".", "identifiers", ":", "a_size", "=", "a", ".", "item_properties", "(", "i", ")", "[", "\"size_in_bytes\"", "]",...
Return list of tuples where sizes differ. Tuple structure: (identifier, size in a, size in b) Assumes list of identifiers in a and b are identical. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples for all items with different sizes
[ "Return", "list", "of", "tuples", "where", "sizes", "differ", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/compare.py#L28-L50
jic-dtool/dtoolcore
dtoolcore/compare.py
diff_content
def diff_content(a, reference, progressbar=None): """Return list of tuples where content differ. Tuple structure: (identifier, hash in a, hash in reference) Assumes list of identifiers in a and b are identical. Storage broker of reference used to generate hash for files in a. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples for all items with different content """ difference = [] for i in a.identifiers: fpath = a.item_content_abspath(i) calc_hash = reference._storage_broker.hasher(fpath) ref_hash = reference.item_properties(i)["hash"] if calc_hash != ref_hash: info = (i, calc_hash, ref_hash) difference.append(info) if progressbar: progressbar.update(1) return difference
python
def diff_content(a, reference, progressbar=None): """Return list of tuples where content differ. Tuple structure: (identifier, hash in a, hash in reference) Assumes list of identifiers in a and b are identical. Storage broker of reference used to generate hash for files in a. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples for all items with different content """ difference = [] for i in a.identifiers: fpath = a.item_content_abspath(i) calc_hash = reference._storage_broker.hasher(fpath) ref_hash = reference.item_properties(i)["hash"] if calc_hash != ref_hash: info = (i, calc_hash, ref_hash) difference.append(info) if progressbar: progressbar.update(1) return difference
[ "def", "diff_content", "(", "a", ",", "reference", ",", "progressbar", "=", "None", ")", ":", "difference", "=", "[", "]", "for", "i", "in", "a", ".", "identifiers", ":", "fpath", "=", "a", ".", "item_content_abspath", "(", "i", ")", "calc_hash", "=", ...
Return list of tuples where content differ. Tuple structure: (identifier, hash in a, hash in reference) Assumes list of identifiers in a and b are identical. Storage broker of reference used to generate hash for files in a. :param a: first :class:`dtoolcore.DataSet` :param b: second :class:`dtoolcore.DataSet` :returns: list of tuples for all items with different content
[ "Return", "list", "of", "tuples", "where", "content", "differ", "." ]
train
https://github.com/jic-dtool/dtoolcore/blob/eeb9a924dc8fcf543340653748a7877be1f98e0f/dtoolcore/compare.py#L53-L79
Locu/chronology
kronos/kronos/storage/memory/client.py
InMemoryStorage._insert
def _insert(self, namespace, stream, events, configuration): """ `stream` is the name of a stream and `events` is a list of (TimeUUID, event) to insert. Make room for the events to insert if necessary by deleting the oldest events. Then insert each event in time sorted order. """ max_items = configuration['max_items'] for _id, event in events: while len(self.db[namespace][stream]) >= max_items: self.db[namespace][stream].pop(0) bisect.insort(self.db[namespace][stream], Event(_id, event))
python
def _insert(self, namespace, stream, events, configuration): """ `stream` is the name of a stream and `events` is a list of (TimeUUID, event) to insert. Make room for the events to insert if necessary by deleting the oldest events. Then insert each event in time sorted order. """ max_items = configuration['max_items'] for _id, event in events: while len(self.db[namespace][stream]) >= max_items: self.db[namespace][stream].pop(0) bisect.insort(self.db[namespace][stream], Event(_id, event))
[ "def", "_insert", "(", "self", ",", "namespace", ",", "stream", ",", "events", ",", "configuration", ")", ":", "max_items", "=", "configuration", "[", "'max_items'", "]", "for", "_id", ",", "event", "in", "events", ":", "while", "len", "(", "self", ".", ...
`stream` is the name of a stream and `events` is a list of (TimeUUID, event) to insert. Make room for the events to insert if necessary by deleting the oldest events. Then insert each event in time sorted order.
[ "stream", "is", "the", "name", "of", "a", "stream", "and", "events", "is", "a", "list", "of", "(", "TimeUUID", "event", ")", "to", "insert", ".", "Make", "room", "for", "the", "events", "to", "insert", "if", "necessary", "by", "deleting", "the", "oldes...
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/memory/client.py#L48-L59
Locu/chronology
kronos/kronos/storage/memory/client.py
InMemoryStorage._delete
def _delete(self, namespace, stream, start_id, end_time, configuration): """ Delete events with id > `start_id` and end_time <= `end_time`. """ start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST)) stream_events = self.db[namespace][stream] # Find the interval our events belong to. lo = bisect.bisect_left(stream_events, start_id_event) if lo + 1 > len(stream_events): return 0, [] if stream_events[lo] == start_id_event: lo += 1 hi = bisect.bisect_right(stream_events, end_id_event) del stream_events[lo:hi] return max(0, hi - lo), []
python
def _delete(self, namespace, stream, start_id, end_time, configuration): """ Delete events with id > `start_id` and end_time <= `end_time`. """ start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST)) stream_events = self.db[namespace][stream] # Find the interval our events belong to. lo = bisect.bisect_left(stream_events, start_id_event) if lo + 1 > len(stream_events): return 0, [] if stream_events[lo] == start_id_event: lo += 1 hi = bisect.bisect_right(stream_events, end_id_event) del stream_events[lo:hi] return max(0, hi - lo), []
[ "def", "_delete", "(", "self", ",", "namespace", ",", "stream", ",", "start_id", ",", "end_time", ",", "configuration", ")", ":", "start_id_event", "=", "Event", "(", "start_id", ")", "end_id_event", "=", "Event", "(", "uuid_from_kronos_time", "(", "end_time",...
Delete events with id > `start_id` and end_time <= `end_time`.
[ "Delete", "events", "with", "id", ">", "start_id", "and", "end_time", "<", "=", "end_time", "." ]
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/memory/client.py#L61-L79
Locu/chronology
kronos/kronos/storage/memory/client.py
InMemoryStorage._retrieve
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration): """ Yield events from stream starting after the event with id `start_id` until and including events with timestamp `end_time`. """ start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST)) stream_events = self.db[namespace][stream] # Find the interval our events belong to. lo = bisect.bisect_left(stream_events, start_id_event) if lo + 1 > len(stream_events): return if stream_events[lo] == start_id_event: lo += 1 hi = bisect.bisect_right(stream_events, end_id_event) if order == ResultOrder.DESCENDING: index_it = xrange(hi - 1, lo - 1, -1) else: index_it = xrange(lo, hi) for i in index_it: if limit <= 0: break limit -= 1 yield marshal.dumps(stream_events[i])
python
def _retrieve(self, namespace, stream, start_id, end_time, order, limit, configuration): """ Yield events from stream starting after the event with id `start_id` until and including events with timestamp `end_time`. """ start_id_event = Event(start_id) end_id_event = Event(uuid_from_kronos_time(end_time, _type=UUIDType.HIGHEST)) stream_events = self.db[namespace][stream] # Find the interval our events belong to. lo = bisect.bisect_left(stream_events, start_id_event) if lo + 1 > len(stream_events): return if stream_events[lo] == start_id_event: lo += 1 hi = bisect.bisect_right(stream_events, end_id_event) if order == ResultOrder.DESCENDING: index_it = xrange(hi - 1, lo - 1, -1) else: index_it = xrange(lo, hi) for i in index_it: if limit <= 0: break limit -= 1 yield marshal.dumps(stream_events[i])
[ "def", "_retrieve", "(", "self", ",", "namespace", ",", "stream", ",", "start_id", ",", "end_time", ",", "order", ",", "limit", ",", "configuration", ")", ":", "start_id_event", "=", "Event", "(", "start_id", ")", "end_id_event", "=", "Event", "(", "uuid_f...
Yield events from stream starting after the event with id `start_id` until and including events with timestamp `end_time`.
[ "Yield", "events", "from", "stream", "starting", "after", "the", "event", "with", "id", "start_id", "until", "and", "including", "events", "with", "timestamp", "end_time", "." ]
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/memory/client.py#L81-L109
tlatsas/sphinx-serve
sphinx_serve/sphinx_serve.py
cli
def cli(): """Parse options from the command line""" parser = argparse.ArgumentParser(prog="sphinx-serve", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler="resolve", description=__doc__ ) parser.add_argument("-v", "--version", action="version", version="%(prog)s {0}".format(__version__) ) parser.add_argument("-h", "--host", action="store", default="0.0.0.0", help="Listen to the given hostname" ) parser.add_argument("-p", "--port", action="store", type=int, default=8081, help="Listen to given port" ) parser.add_argument("-b", "--build", action="store", default="_build", help="Build folder name" ) parser.add_argument("-s", "--single", action="store_true", help="Serve the single-html documentation version" ) return parser.parse_args()
python
def cli(): """Parse options from the command line""" parser = argparse.ArgumentParser(prog="sphinx-serve", formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler="resolve", description=__doc__ ) parser.add_argument("-v", "--version", action="version", version="%(prog)s {0}".format(__version__) ) parser.add_argument("-h", "--host", action="store", default="0.0.0.0", help="Listen to the given hostname" ) parser.add_argument("-p", "--port", action="store", type=int, default=8081, help="Listen to given port" ) parser.add_argument("-b", "--build", action="store", default="_build", help="Build folder name" ) parser.add_argument("-s", "--single", action="store_true", help="Serve the single-html documentation version" ) return parser.parse_args()
[ "def", "cli", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"sphinx-serve\"", ",", "formatter_class", "=", "argparse", ".", "ArgumentDefaultsHelpFormatter", ",", "conflict_handler", "=", "\"resolve\"", ",", "description", "="...
Parse options from the command line
[ "Parse", "options", "from", "the", "command", "line" ]
train
https://github.com/tlatsas/sphinx-serve/blob/f7659787f5375025e9bc0e72c4427f096ce6785d/sphinx_serve/sphinx_serve.py#L14-L45
tlatsas/sphinx-serve
sphinx_serve/sphinx_serve.py
find_build_dir
def find_build_dir(path, build="_build"): """try to guess the build folder's location""" path = os.path.abspath(os.path.expanduser(path)) contents = os.listdir(path) filtered_contents = [directory for directory in contents if os.path.isdir(os.path.join(path, directory))] if build in filtered_contents: return os.path.join(path, build) else: if path == os.path.realpath("/"): return None else: return find_build_dir("{0}/..".format(path), build)
python
def find_build_dir(path, build="_build"): """try to guess the build folder's location""" path = os.path.abspath(os.path.expanduser(path)) contents = os.listdir(path) filtered_contents = [directory for directory in contents if os.path.isdir(os.path.join(path, directory))] if build in filtered_contents: return os.path.join(path, build) else: if path == os.path.realpath("/"): return None else: return find_build_dir("{0}/..".format(path), build)
[ "def", "find_build_dir", "(", "path", ",", "build", "=", "\"_build\"", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "contents", "=", "os", ".", "listdir", "(", "path", "...
try to guess the build folder's location
[ "try", "to", "guess", "the", "build", "folder", "s", "location" ]
train
https://github.com/tlatsas/sphinx-serve/blob/f7659787f5375025e9bc0e72c4427f096ce6785d/sphinx_serve/sphinx_serve.py#L48-L61
Locu/chronology
kronos/kronos/storage/sqlite/client.py
flip_uuid_parts
def flip_uuid_parts(uuid): """ Flips high and low segments of the timestamp portion of a UUID string. This enables correct lexicographic sorting. Because it is a simple flip, this function works in both directions. """ flipped_uuid = uuid.split('-') flipped_uuid[0], flipped_uuid[2] = flipped_uuid[2], flipped_uuid[0] flipped_uuid = '-'.join(flipped_uuid) return flipped_uuid
python
def flip_uuid_parts(uuid): """ Flips high and low segments of the timestamp portion of a UUID string. This enables correct lexicographic sorting. Because it is a simple flip, this function works in both directions. """ flipped_uuid = uuid.split('-') flipped_uuid[0], flipped_uuid[2] = flipped_uuid[2], flipped_uuid[0] flipped_uuid = '-'.join(flipped_uuid) return flipped_uuid
[ "def", "flip_uuid_parts", "(", "uuid", ")", ":", "flipped_uuid", "=", "uuid", ".", "split", "(", "'-'", ")", "flipped_uuid", "[", "0", "]", ",", "flipped_uuid", "[", "2", "]", "=", "flipped_uuid", "[", "2", "]", ",", "flipped_uuid", "[", "0", "]", "f...
Flips high and low segments of the timestamp portion of a UUID string. This enables correct lexicographic sorting. Because it is a simple flip, this function works in both directions.
[ "Flips", "high", "and", "low", "segments", "of", "the", "timestamp", "portion", "of", "a", "UUID", "string", ".", "This", "enables", "correct", "lexicographic", "sorting", ".", "Because", "it", "is", "a", "simple", "flip", "this", "function", "works", "in", ...
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/kronos/kronos/storage/sqlite/client.py#L33-L42
ryanvarley/ExoData
exodata/example.py
genExampleStar
def genExampleStar(binaryLetter='', heirarchy=True): """ generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a system and link everything up """ starPar = StarParameters() starPar.addParam('age', '7.6') starPar.addParam('magB', '9.8') starPar.addParam('magH', '7.4') starPar.addParam('magI', '7.6') starPar.addParam('magJ', '7.5') starPar.addParam('magK', '7.3') starPar.addParam('magV', '9.0') starPar.addParam('mass', '0.98') starPar.addParam('metallicity', '0.43') starPar.addParam('name', 'Example Star {0}{1}'.format(ac._ExampleSystemCount, binaryLetter)) starPar.addParam('name', 'HD {0}{1}'.format(ac._ExampleSystemCount, binaryLetter)) starPar.addParam('radius', '0.95') starPar.addParam('spectraltype', 'G5') starPar.addParam('temperature', '5370') exampleStar = Star(starPar.params) exampleStar.flags.addFlag('Fake') if heirarchy: if binaryLetter: exampleBinary = genExampleBinary() exampleBinary._addChild(exampleStar) exampleStar.parent = exampleBinary else: exampleSystem = genExampleSystem() exampleSystem._addChild(exampleStar) exampleStar.parent = exampleSystem return exampleStar
python
def genExampleStar(binaryLetter='', heirarchy=True): """ generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a system and link everything up """ starPar = StarParameters() starPar.addParam('age', '7.6') starPar.addParam('magB', '9.8') starPar.addParam('magH', '7.4') starPar.addParam('magI', '7.6') starPar.addParam('magJ', '7.5') starPar.addParam('magK', '7.3') starPar.addParam('magV', '9.0') starPar.addParam('mass', '0.98') starPar.addParam('metallicity', '0.43') starPar.addParam('name', 'Example Star {0}{1}'.format(ac._ExampleSystemCount, binaryLetter)) starPar.addParam('name', 'HD {0}{1}'.format(ac._ExampleSystemCount, binaryLetter)) starPar.addParam('radius', '0.95') starPar.addParam('spectraltype', 'G5') starPar.addParam('temperature', '5370') exampleStar = Star(starPar.params) exampleStar.flags.addFlag('Fake') if heirarchy: if binaryLetter: exampleBinary = genExampleBinary() exampleBinary._addChild(exampleStar) exampleStar.parent = exampleBinary else: exampleSystem = genExampleSystem() exampleSystem._addChild(exampleStar) exampleStar.parent = exampleSystem return exampleStar
[ "def", "genExampleStar", "(", "binaryLetter", "=", "''", ",", "heirarchy", "=", "True", ")", ":", "starPar", "=", "StarParameters", "(", ")", "starPar", ".", "addParam", "(", "'age'", ",", "'7.6'", ")", "starPar", ".", "addParam", "(", "'magB'", ",", "'9...
generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a system and link everything up
[ "generates", "example", "star", "if", "binaryLetter", "is", "true", "creates", "a", "parent", "binary", "object", "if", "heirarchy", "is", "true", "will", "create", "a", "system", "and", "link", "everything", "up" ]
train
https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/example.py#L48-L82
ryanvarley/ExoData
exodata/example.py
genExamplePlanet
def genExamplePlanet(binaryLetter=''): """ Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return: """ planetPar = PlanetParameters() planetPar.addParam('discoverymethod', 'transit') planetPar.addParam('discoveryyear', '2001') planetPar.addParam('eccentricity', '0.09') planetPar.addParam('inclination', '89.2') planetPar.addParam('lastupdate', '12/12/08') planetPar.addParam('mass', '3.9') planetPar.addParam('name', 'Example Star {0}{1} b'.format(ac._ExampleSystemCount, binaryLetter)) planetPar.addParam('period', '111.2') planetPar.addParam('radius', '0.92') planetPar.addParam('semimajoraxis', '0.449') planetPar.addParam('temperature', '339.6') planetPar.addParam('transittime', '2454876.344') planetPar.addParam('separation', '330', {'unit': 'AU'}) examplePlanet = Planet(planetPar.params) examplePlanet.flags.addFlag('Fake') exampleStar = genExampleStar(binaryLetter=binaryLetter) exampleStar._addChild(examplePlanet) examplePlanet.parent = exampleStar return examplePlanet
python
def genExamplePlanet(binaryLetter=''): """ Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return: """ planetPar = PlanetParameters() planetPar.addParam('discoverymethod', 'transit') planetPar.addParam('discoveryyear', '2001') planetPar.addParam('eccentricity', '0.09') planetPar.addParam('inclination', '89.2') planetPar.addParam('lastupdate', '12/12/08') planetPar.addParam('mass', '3.9') planetPar.addParam('name', 'Example Star {0}{1} b'.format(ac._ExampleSystemCount, binaryLetter)) planetPar.addParam('period', '111.2') planetPar.addParam('radius', '0.92') planetPar.addParam('semimajoraxis', '0.449') planetPar.addParam('temperature', '339.6') planetPar.addParam('transittime', '2454876.344') planetPar.addParam('separation', '330', {'unit': 'AU'}) examplePlanet = Planet(planetPar.params) examplePlanet.flags.addFlag('Fake') exampleStar = genExampleStar(binaryLetter=binaryLetter) exampleStar._addChild(examplePlanet) examplePlanet.parent = exampleStar return examplePlanet
[ "def", "genExamplePlanet", "(", "binaryLetter", "=", "''", ")", ":", "planetPar", "=", "PlanetParameters", "(", ")", "planetPar", ".", "addParam", "(", "'discoverymethod'", ",", "'transit'", ")", "planetPar", ".", "addParam", "(", "'discoveryyear'", ",", "'2001'...
Creates a fake planet with some defaults :param `binaryLetter`: host star is part of a binary with letter binaryletter :return:
[ "Creates", "a", "fake", "planet", "with", "some", "defaults", ":", "param", "binaryLetter", ":", "host", "star", "is", "part", "of", "a", "binary", "with", "letter", "binaryletter", ":", "return", ":" ]
train
https://github.com/ryanvarley/ExoData/blob/e0d3652117214d2377a707d6778f93b7eb201a41/exodata/example.py#L85-L113
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
config_list
def config_list(backend): """ Print the current configuration """ click.secho('Print Configuration', fg='green') print str(backend.dki.get_config())
python
def config_list(backend): """ Print the current configuration """ click.secho('Print Configuration', fg='green') print str(backend.dki.get_config())
[ "def", "config_list", "(", "backend", ")", ":", "click", ".", "secho", "(", "'Print Configuration'", ",", "fg", "=", "'green'", ")", "print", "str", "(", "backend", ".", "dki", ".", "get_config", "(", ")", ")" ]
Print the current configuration
[ "Print", "the", "current", "configuration" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L251-L256
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
recipe_status
def recipe_status(backend): """ Compare local recipe to remote recipe for the current recipe. """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You are not in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder') recipe_name = DKRecipeDisk.find_recipe_name() click.secho("%s - Getting the status of Recipe '%s' in Kitchen '%s'\n\tversus directory '%s'" % ( get_datetime(), recipe_name, kitchen, recipe_dir), fg='green') check_and_print(DKCloudCommandRunner.recipe_status(backend.dki, kitchen, recipe_name, recipe_dir))
python
def recipe_status(backend): """ Compare local recipe to remote recipe for the current recipe. """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You are not in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder') recipe_name = DKRecipeDisk.find_recipe_name() click.secho("%s - Getting the status of Recipe '%s' in Kitchen '%s'\n\tversus directory '%s'" % ( get_datetime(), recipe_name, kitchen, recipe_dir), fg='green') check_and_print(DKCloudCommandRunner.recipe_status(backend.dki, kitchen, recipe_name, recipe_dir))
[ "def", "recipe_status", "(", "backend", ")", ":", "kitchen", "=", "DKCloudCommandRunner", ".", "which_kitchen_name", "(", ")", "if", "kitchen", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "'You are not in a Kitchen'", ")", "recipe_dir", "=", ...
Compare local recipe to remote recipe for the current recipe.
[ "Compare", "local", "recipe", "to", "remote", "recipe", "for", "the", "current", "recipe", "." ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L261-L274
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
recipe_conflicts
def recipe_conflicts(backend): """ See if there are any unresolved conflicts for this recipe. """ recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder.') recipe_name = DKRecipeDisk.find_recipe_name() click.secho("%s - Checking for conflicts on Recipe '%s'" % ( get_datetime(),recipe_name)) recipe_name = DKRecipeDisk.find_recipe_name() check_and_print(DKCloudCommandRunner.get_unresolved_conflicts(recipe_name, recipe_dir))
python
def recipe_conflicts(backend): """ See if there are any unresolved conflicts for this recipe. """ recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder.') recipe_name = DKRecipeDisk.find_recipe_name() click.secho("%s - Checking for conflicts on Recipe '%s'" % ( get_datetime(),recipe_name)) recipe_name = DKRecipeDisk.find_recipe_name() check_and_print(DKCloudCommandRunner.get_unresolved_conflicts(recipe_name, recipe_dir))
[ "def", "recipe_conflicts", "(", "backend", ")", ":", "recipe_dir", "=", "DKRecipeDisk", ".", "find_recipe_root_dir", "(", ")", "if", "recipe_dir", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "'You must be in a Recipe folder.'", ")", "recipe_name...
See if there are any unresolved conflicts for this recipe.
[ "See", "if", "there", "are", "any", "unresolved", "conflicts", "for", "this", "recipe", "." ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L279-L290
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
kitchen_list
def kitchen_list(backend): """ List all Kitchens """ click.echo(click.style('%s - Getting the list of kitchens' % get_datetime(), fg='green')) check_and_print(DKCloudCommandRunner.list_kitchen(backend.dki))
python
def kitchen_list(backend): """ List all Kitchens """ click.echo(click.style('%s - Getting the list of kitchens' % get_datetime(), fg='green')) check_and_print(DKCloudCommandRunner.list_kitchen(backend.dki))
[ "def", "kitchen_list", "(", "backend", ")", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "'%s - Getting the list of kitchens'", "%", "get_datetime", "(", ")", ",", "fg", "=", "'green'", ")", ")", "check_and_print", "(", "DKCloudCommandRunner", "...
List all Kitchens
[ "List", "all", "Kitchens" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L313-L318
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
kitchen_get
def kitchen_get(backend, kitchen_name, recipe): """ Get an existing Kitchen """ found_kitchen = DKKitchenDisk.find_kitchen_name() if found_kitchen is not None and len(found_kitchen) > 0: raise click.ClickException("You cannot get a kitchen into an existing kitchen directory structure.") if len(recipe) > 0: click.secho("%s - Getting kitchen '%s' and the recipes %s" % (get_datetime(), kitchen_name, str(recipe)), fg='green') else: click.secho("%s - Getting kitchen '%s'" % (get_datetime(), kitchen_name), fg='green') check_and_print(DKCloudCommandRunner.get_kitchen(backend.dki, kitchen_name, os.getcwd(), recipe))
python
def kitchen_get(backend, kitchen_name, recipe): """ Get an existing Kitchen """ found_kitchen = DKKitchenDisk.find_kitchen_name() if found_kitchen is not None and len(found_kitchen) > 0: raise click.ClickException("You cannot get a kitchen into an existing kitchen directory structure.") if len(recipe) > 0: click.secho("%s - Getting kitchen '%s' and the recipes %s" % (get_datetime(), kitchen_name, str(recipe)), fg='green') else: click.secho("%s - Getting kitchen '%s'" % (get_datetime(), kitchen_name), fg='green') check_and_print(DKCloudCommandRunner.get_kitchen(backend.dki, kitchen_name, os.getcwd(), recipe))
[ "def", "kitchen_get", "(", "backend", ",", "kitchen_name", ",", "recipe", ")", ":", "found_kitchen", "=", "DKKitchenDisk", ".", "find_kitchen_name", "(", ")", "if", "found_kitchen", "is", "not", "None", "and", "len", "(", "found_kitchen", ")", ">", "0", ":",...
Get an existing Kitchen
[ "Get", "an", "existing", "Kitchen" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L325-L338
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
kitchen_create
def kitchen_create(backend, parent, kitchen): """ Create a new kitchen """ click.secho('%s - Creating kitchen %s from parent kitchen %s' % (get_datetime(), kitchen, parent), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.create_kitchen(backend.dki, parent, kitchen)) else: raise click.ClickException('Cannot create a kitchen called %s' % master)
python
def kitchen_create(backend, parent, kitchen): """ Create a new kitchen """ click.secho('%s - Creating kitchen %s from parent kitchen %s' % (get_datetime(), kitchen, parent), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.create_kitchen(backend.dki, parent, kitchen)) else: raise click.ClickException('Cannot create a kitchen called %s' % master)
[ "def", "kitchen_create", "(", "backend", ",", "parent", ",", "kitchen", ")", ":", "click", ".", "secho", "(", "'%s - Creating kitchen %s from parent kitchen %s'", "%", "(", "get_datetime", "(", ")", ",", "kitchen", ",", "parent", ")", ",", "fg", "=", "'green'"...
Create a new kitchen
[ "Create", "a", "new", "kitchen" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L354-L363
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
kitchen_delete
def kitchen_delete(backend, kitchen): """ Provide the name of the kitchen to delete """ click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki, kitchen)) else: raise click.ClickException('Cannot delete the kitchen called %s' % master)
python
def kitchen_delete(backend, kitchen): """ Provide the name of the kitchen to delete """ click.secho('%s - Deleting kitchen %s' % (get_datetime(), kitchen), fg='green') master = 'master' if kitchen.lower() != master.lower(): check_and_print(DKCloudCommandRunner.delete_kitchen(backend.dki, kitchen)) else: raise click.ClickException('Cannot delete the kitchen called %s' % master)
[ "def", "kitchen_delete", "(", "backend", ",", "kitchen", ")", ":", "click", ".", "secho", "(", "'%s - Deleting kitchen %s'", "%", "(", "get_datetime", "(", ")", ",", "kitchen", ")", ",", "fg", "=", "'green'", ")", "master", "=", "'master'", "if", "kitchen"...
Provide the name of the kitchen to delete
[ "Provide", "the", "name", "of", "the", "kitchen", "to", "delete" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L369-L378
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
kitchen_config
def kitchen_config(backend, kitchen, add, get, unset, listall): """ Get and Set Kitchen variable overrides """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get, unset, listall))
python
def kitchen_config(backend, kitchen, add, get, unset, listall): """ Get and Set Kitchen variable overrides """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get, unset, listall))
[ "def", "kitchen_config", "(", "backend", ",", "kitchen", ",", "add", ",", "get", ",", "unset", ",", "listall", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":...
Get and Set Kitchen variable overrides
[ "Get", "and", "Set", "Kitchen", "variable", "overrides" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L390-L397
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
kitchen_merge
def kitchen_merge(backend, source_kitchen, target_kitchen): """ Merge two Kitchens """ click.secho('%s - Merging Kitchen %s into Kitchen %s' % (get_datetime(), source_kitchen, target_kitchen), fg='green') check_and_print(DKCloudCommandRunner.merge_kitchens_improved(backend.dki, source_kitchen, target_kitchen))
python
def kitchen_merge(backend, source_kitchen, target_kitchen): """ Merge two Kitchens """ click.secho('%s - Merging Kitchen %s into Kitchen %s' % (get_datetime(), source_kitchen, target_kitchen), fg='green') check_and_print(DKCloudCommandRunner.merge_kitchens_improved(backend.dki, source_kitchen, target_kitchen))
[ "def", "kitchen_merge", "(", "backend", ",", "source_kitchen", ",", "target_kitchen", ")", ":", "click", ".", "secho", "(", "'%s - Merging Kitchen %s into Kitchen %s'", "%", "(", "get_datetime", "(", ")", ",", "source_kitchen", ",", "target_kitchen", ")", ",", "fg...
Merge two Kitchens
[ "Merge", "two", "Kitchens" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L404-L409
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
recipe_list
def recipe_list(backend, kitchen): """ List the Recipes in a Kitchen """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Getting the list of Recipes for Kitchen '%s'" % (get_datetime(), use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.list_recipe(backend.dki, use_kitchen))
python
def recipe_list(backend, kitchen): """ List the Recipes in a Kitchen """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Getting the list of Recipes for Kitchen '%s'" % (get_datetime(), use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.list_recipe(backend.dki, use_kitchen))
[ "def", "recipe_list", "(", "backend", ",", "kitchen", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "err_str", ...
List the Recipes in a Kitchen
[ "List", "the", "Recipes", "in", "a", "Kitchen" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L418-L426
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
recipe_create
def recipe_create(backend, kitchen, name): """ Create a new Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Creating Recipe %s for Kitchen '%s'" % (get_datetime(), name, use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.recipe_create(backend.dki, use_kitchen,name))
python
def recipe_create(backend, kitchen, name): """ Create a new Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho("%s - Creating Recipe %s for Kitchen '%s'" % (get_datetime(), name, use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.recipe_create(backend.dki, use_kitchen,name))
[ "def", "recipe_create", "(", "backend", ",", "kitchen", ",", "name", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":", "raise", "click", ".", "ClickException", ...
Create a new Recipe
[ "Create", "a", "new", "Recipe" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L432-L440
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
recipe_get
def recipe_get(backend, recipe): """ Get the latest files for this recipe. """ recipe_root_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_root_dir is None: if recipe is None: raise click.ClickException("\nPlease change to a recipe folder or provide a recipe name arguement") # raise click.ClickException('You must be in a Recipe folder') kitchen_root_dir = DKKitchenDisk.is_kitchen_root_dir() if not kitchen_root_dir: raise click.ClickException("\nPlease change to a recipe folder or a kitchen root dir.") recipe_name = recipe start_dir = DKKitchenDisk.find_kitchen_root_dir() else: recipe_name = DKRecipeDisk.find_recipe_name() if recipe is not None: if recipe_name != recipe: raise click.ClickException("\nThe recipe name argument '%s' is inconsistent with the current directory '%s'" % (recipe, recipe_root_dir)) start_dir = recipe_root_dir kitchen_name = Backend.get_kitchen_name_soft() click.secho("%s - Getting the latest version of Recipe '%s' in Kitchen '%s'" % (get_datetime(), recipe_name, kitchen_name), fg='green') check_and_print(DKCloudCommandRunner.get_recipe(backend.dki, kitchen_name, recipe_name, start_dir))
python
def recipe_get(backend, recipe): """ Get the latest files for this recipe. """ recipe_root_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_root_dir is None: if recipe is None: raise click.ClickException("\nPlease change to a recipe folder or provide a recipe name arguement") # raise click.ClickException('You must be in a Recipe folder') kitchen_root_dir = DKKitchenDisk.is_kitchen_root_dir() if not kitchen_root_dir: raise click.ClickException("\nPlease change to a recipe folder or a kitchen root dir.") recipe_name = recipe start_dir = DKKitchenDisk.find_kitchen_root_dir() else: recipe_name = DKRecipeDisk.find_recipe_name() if recipe is not None: if recipe_name != recipe: raise click.ClickException("\nThe recipe name argument '%s' is inconsistent with the current directory '%s'" % (recipe, recipe_root_dir)) start_dir = recipe_root_dir kitchen_name = Backend.get_kitchen_name_soft() click.secho("%s - Getting the latest version of Recipe '%s' in Kitchen '%s'" % (get_datetime(), recipe_name, kitchen_name), fg='green') check_and_print(DKCloudCommandRunner.get_recipe(backend.dki, kitchen_name, recipe_name, start_dir))
[ "def", "recipe_get", "(", "backend", ",", "recipe", ")", ":", "recipe_root_dir", "=", "DKRecipeDisk", ".", "find_recipe_root_dir", "(", ")", "if", "recipe_root_dir", "is", "None", ":", "if", "recipe", "is", "None", ":", "raise", "click", ".", "ClickException",...
Get the latest files for this recipe.
[ "Get", "the", "latest", "files", "for", "this", "recipe", "." ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L445-L469
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
recipe_compile
def recipe_compile(backend, kitchen, recipe, variation): """ Apply variables to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') click.secho('%s - Get the Compiled OrderRun of Recipe %s.%s in Kitchen %s' % (get_datetime(), recipe, variation, use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.get_compiled_serving(backend.dki, use_kitchen, recipe, variation))
python
def recipe_compile(backend, kitchen, recipe, variation): """ Apply variables to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') click.secho('%s - Get the Compiled OrderRun of Recipe %s.%s in Kitchen %s' % (get_datetime(), recipe, variation, use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.get_compiled_serving(backend.dki, use_kitchen, recipe, variation))
[ "def", "recipe_compile", "(", "backend", ",", "kitchen", ",", "recipe", ",", "variation", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":", "raise", "click", "....
Apply variables to a Recipe
[ "Apply", "variables", "to", "a", "Recipe" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L498-L513
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
file_add
def file_add(backend, kitchen, recipe, message, filepath): """ Add a newly created file to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') click.secho('%s - Adding File (%s) to Recipe (%s) in kitchen(%s) with message (%s)' % (get_datetime(), filepath, recipe, use_kitchen, message), fg='green') check_and_print(DKCloudCommandRunner.add_file(backend.dki, use_kitchen, recipe, message, filepath))
python
def file_add(backend, kitchen, recipe, message, filepath): """ Add a newly created file to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') click.secho('%s - Adding File (%s) to Recipe (%s) in kitchen(%s) with message (%s)' % (get_datetime(), filepath, recipe, use_kitchen, message), fg='green') check_and_print(DKCloudCommandRunner.add_file(backend.dki, use_kitchen, recipe, message, filepath))
[ "def", "file_add", "(", "backend", ",", "kitchen", ",", "recipe", ",", "message", ",", "filepath", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":", "raise", ...
Add a newly created file to a Recipe
[ "Add", "a", "newly", "created", "file", "to", "a", "Recipe" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L525-L539
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
file_update_all
def file_update_all(backend, message, dryrun): """ Update all of the changed files for this Recipe """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You must be in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder') recipe = DKRecipeDisk.find_recipe_name() if dryrun: click.secho('%s - Display all changed files in Recipe (%s) in Kitchen(%s) with message (%s)' % (get_datetime(), recipe, kitchen, message), fg='green') else: click.secho('%s - Updating all changed files in Recipe (%s) in Kitchen(%s) with message (%s)' % (get_datetime(), recipe, kitchen, message), fg='green') check_and_print(DKCloudCommandRunner.update_all_files(backend.dki, kitchen, recipe, recipe_dir, message, dryrun))
python
def file_update_all(backend, message, dryrun): """ Update all of the changed files for this Recipe """ kitchen = DKCloudCommandRunner.which_kitchen_name() if kitchen is None: raise click.ClickException('You must be in a Kitchen') recipe_dir = DKRecipeDisk.find_recipe_root_dir() if recipe_dir is None: raise click.ClickException('You must be in a Recipe folder') recipe = DKRecipeDisk.find_recipe_name() if dryrun: click.secho('%s - Display all changed files in Recipe (%s) in Kitchen(%s) with message (%s)' % (get_datetime(), recipe, kitchen, message), fg='green') else: click.secho('%s - Updating all changed files in Recipe (%s) in Kitchen(%s) with message (%s)' % (get_datetime(), recipe, kitchen, message), fg='green') check_and_print(DKCloudCommandRunner.update_all_files(backend.dki, kitchen, recipe, recipe_dir, message, dryrun))
[ "def", "file_update_all", "(", "backend", ",", "message", ",", "dryrun", ")", ":", "kitchen", "=", "DKCloudCommandRunner", ".", "which_kitchen_name", "(", ")", "if", "kitchen", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "'You must be in a K...
Update all of the changed files for this Recipe
[ "Update", "all", "of", "the", "changed", "files", "for", "this", "Recipe" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L569-L587
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
file_resolve
def file_resolve(backend, filepath): """ Mark a conflicted file as resolved, so that a merge can be completed """ recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder.') click.secho("%s - Resolving conflicts" % get_datetime()) for file_to_resolve in filepath: if not os.path.exists(file_to_resolve): raise click.ClickException('%s does not exist' % file_to_resolve) check_and_print(DKCloudCommandRunner.resolve_conflict(file_to_resolve))
python
def file_resolve(backend, filepath): """ Mark a conflicted file as resolved, so that a merge can be completed """ recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder.') click.secho("%s - Resolving conflicts" % get_datetime()) for file_to_resolve in filepath: if not os.path.exists(file_to_resolve): raise click.ClickException('%s does not exist' % file_to_resolve) check_and_print(DKCloudCommandRunner.resolve_conflict(file_to_resolve))
[ "def", "file_resolve", "(", "backend", ",", "filepath", ")", ":", "recipe", "=", "DKRecipeDisk", ".", "find_recipe_name", "(", ")", "if", "recipe", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "'You must be in a recipe folder.'", ")", "click"...
Mark a conflicted file as resolved, so that a merge can be completed
[ "Mark", "a", "conflicted", "file", "as", "resolved", "so", "that", "a", "merge", "can", "be", "completed" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L616-L629
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
active_serving_watcher
def active_serving_watcher(backend, kitchen, period): """ Watches all cooking Recipes in a Kitchen Provide the kitchen name as an argument or be in a Kitchen folder. """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Watching Active OrderRun Changes in Kitchen %s' % (get_datetime(), use_kitchen), fg='green') DKCloudCommandRunner.watch_active_servings(backend.dki, use_kitchen, period) while True: try: DKCloudCommandRunner.join_active_serving_watcher_thread_join() if not DKCloudCommandRunner.watcher_running(): break except KeyboardInterrupt: print 'KeyboardInterrupt' exit_gracefully(None, None) exit(0)
python
def active_serving_watcher(backend, kitchen, period): """ Watches all cooking Recipes in a Kitchen Provide the kitchen name as an argument or be in a Kitchen folder. """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Watching Active OrderRun Changes in Kitchen %s' % (get_datetime(), use_kitchen), fg='green') DKCloudCommandRunner.watch_active_servings(backend.dki, use_kitchen, period) while True: try: DKCloudCommandRunner.join_active_serving_watcher_thread_join() if not DKCloudCommandRunner.watcher_running(): break except KeyboardInterrupt: print 'KeyboardInterrupt' exit_gracefully(None, None) exit(0)
[ "def", "active_serving_watcher", "(", "backend", ",", "kitchen", ",", "period", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":", "raise", "click", ".", "ClickExc...
Watches all cooking Recipes in a Kitchen Provide the kitchen name as an argument or be in a Kitchen folder.
[ "Watches", "all", "cooking", "Recipes", "in", "a", "Kitchen", "Provide", "the", "kitchen", "name", "as", "an", "argument", "or", "be", "in", "a", "Kitchen", "folder", "." ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L639-L657
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
order_run
def order_run(backend, kitchen, recipe, variation, node): """ Run an order: cook a recipe variation """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') msg = '%s - Create an Order:\n\tKitchen: %s\n\tRecipe: %s\n\tVariation: %s\n' % (get_datetime(), use_kitchen, recipe, variation) if node is not None: msg += '\tNode: %s\n' % node click.secho(msg, fg='green') check_and_print(DKCloudCommandRunner.create_order(backend.dki, use_kitchen, recipe, variation, node))
python
def order_run(backend, kitchen, recipe, variation, node): """ Run an order: cook a recipe variation """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) if recipe is None: recipe = DKRecipeDisk.find_recipe_name() if recipe is None: raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') msg = '%s - Create an Order:\n\tKitchen: %s\n\tRecipe: %s\n\tVariation: %s\n' % (get_datetime(), use_kitchen, recipe, variation) if node is not None: msg += '\tNode: %s\n' % node click.secho(msg, fg='green') check_and_print(DKCloudCommandRunner.create_order(backend.dki, use_kitchen, recipe, variation, node))
[ "def", "order_run", "(", "backend", ",", "kitchen", ",", "recipe", ",", "variation", ",", "node", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":", "raise", "...
Run an order: cook a recipe variation
[ "Run", "an", "order", ":", "cook", "a", "recipe", "variation" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L670-L687
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
order_delete
def order_delete(backend, kitchen, order_id): """ Delete one order or all orders in a kitchen """ use_kitchen = Backend.get_kitchen_name_soft(kitchen) print use_kitchen if use_kitchen is None and order_id is None: raise click.ClickException('You must specify either a kitchen or an order_id or be in a kitchen directory') if order_id is not None: click.secho('%s - Delete an Order using id %s' % (get_datetime(), order_id), fg='green') check_and_print(DKCloudCommandRunner.delete_one_order(backend.dki, order_id)) else: click.secho('%s - Delete all orders in Kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.delete_all_order(backend.dki, use_kitchen))
python
def order_delete(backend, kitchen, order_id): """ Delete one order or all orders in a kitchen """ use_kitchen = Backend.get_kitchen_name_soft(kitchen) print use_kitchen if use_kitchen is None and order_id is None: raise click.ClickException('You must specify either a kitchen or an order_id or be in a kitchen directory') if order_id is not None: click.secho('%s - Delete an Order using id %s' % (get_datetime(), order_id), fg='green') check_and_print(DKCloudCommandRunner.delete_one_order(backend.dki, order_id)) else: click.secho('%s - Delete all orders in Kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.delete_all_order(backend.dki, use_kitchen))
[ "def", "order_delete", "(", "backend", ",", "kitchen", ",", "order_id", ")", ":", "use_kitchen", "=", "Backend", ".", "get_kitchen_name_soft", "(", "kitchen", ")", "print", "use_kitchen", "if", "use_kitchen", "is", "None", "and", "order_id", "is", "None", ":",...
Delete one order or all orders in a kitchen
[ "Delete", "one", "order", "or", "all", "orders", "in", "a", "kitchen" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L694-L708
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
order_stop
def order_stop(backend, order_id): """ Stop an order - Turn off the serving generation ability of an order. Stop any running jobs. Keep all state around. """ if order_id is None: raise click.ClickException('invalid order id %s' % order_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_id), fg='green') check_and_print(DKCloudCommandRunner.stop_order(backend.dki, order_id))
python
def order_stop(backend, order_id): """ Stop an order - Turn off the serving generation ability of an order. Stop any running jobs. Keep all state around. """ if order_id is None: raise click.ClickException('invalid order id %s' % order_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_id), fg='green') check_and_print(DKCloudCommandRunner.stop_order(backend.dki, order_id))
[ "def", "order_stop", "(", "backend", ",", "order_id", ")", ":", "if", "order_id", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "'invalid order id %s'", "%", "order_id", ")", "click", ".", "secho", "(", "'%s - Stop order id %s'", "%", "(", ...
Stop an order - Turn off the serving generation ability of an order. Stop any running jobs. Keep all state around.
[ "Stop", "an", "order", "-", "Turn", "off", "the", "serving", "generation", "ability", "of", "an", "order", ".", "Stop", "any", "running", "jobs", ".", "Keep", "all", "state", "around", "." ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L714-L721
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
order_stop
def order_stop(backend, order_run_id): """ Stop the run of an order - Stop the running order and keep all state around. """ if order_run_id is None: raise click.ClickException('invalid order id %s' % order_run_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_run_id), fg='green') check_and_print(DKCloudCommandRunner.stop_orderrun(backend.dki, order_run_id.strip()))
python
def order_stop(backend, order_run_id): """ Stop the run of an order - Stop the running order and keep all state around. """ if order_run_id is None: raise click.ClickException('invalid order id %s' % order_run_id) click.secho('%s - Stop order id %s' % (get_datetime(), order_run_id), fg='green') check_and_print(DKCloudCommandRunner.stop_orderrun(backend.dki, order_run_id.strip()))
[ "def", "order_stop", "(", "backend", ",", "order_run_id", ")", ":", "if", "order_run_id", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "'invalid order id %s'", "%", "order_run_id", ")", "click", ".", "secho", "(", "'%s - Stop order id %s'", "...
Stop the run of an order - Stop the running order and keep all state around.
[ "Stop", "the", "run", "of", "an", "order", "-", "Stop", "the", "running", "order", "and", "keep", "all", "state", "around", "." ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L727-L735
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
orderrun_detail
def orderrun_detail(backend, kitchen, summary, nodestatus, runstatus, log, timing, test, all_things, order_id, order_run_id, disp_order_id, disp_order_run_id): """ Display information about an Order-Run """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) # if recipe is None: # recipe = DKRecipeDisk.find_reciper_name() # if recipe is None: # raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') pd = dict() if all_things: pd['summary'] = True pd['logs'] = True pd['timingresults'] = True pd['testresults'] = True # pd['state'] = True pd['status'] = True if summary: pd['summary'] = True if log: pd['logs'] = True if timing: pd['timingresults'] = True if test: pd['testresults'] = True if nodestatus: pd['status'] = True if runstatus: pd['runstatus'] = True if disp_order_id: pd['disp_order_id'] = True if disp_order_run_id: pd['disp_order_run_id'] = True # if the user does not specify anything to display, show the summary information if not runstatus and \ not all_things and \ not test and \ not timing and \ not log and \ not nodestatus and \ not summary and \ not disp_order_id and \ not disp_order_run_id: pd['summary'] = True if order_id is not None and order_run_id is not None: raise click.ClickException("Cannot specify both the Order Id and the OrderRun Id") if order_id is not None: pd[DKCloudCommandRunner.ORDER_ID] = order_id.strip() elif order_run_id is not None: pd[DKCloudCommandRunner.ORDER_RUN_ID] = order_run_id.strip() # don't print the green thing if it is just runstatus if not runstatus and not disp_order_id and not disp_order_run_id: click.secho('%s - Display Order-Run details from kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.orderrun_detail(backend.dki, use_kitchen, pd))
python
def orderrun_detail(backend, kitchen, summary, nodestatus, runstatus, log, timing, test, all_things, order_id, order_run_id, disp_order_id, disp_order_run_id): """ Display information about an Order-Run """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) # if recipe is None: # recipe = DKRecipeDisk.find_reciper_name() # if recipe is None: # raise click.ClickException('You must be in a recipe folder, or provide a recipe name.') pd = dict() if all_things: pd['summary'] = True pd['logs'] = True pd['timingresults'] = True pd['testresults'] = True # pd['state'] = True pd['status'] = True if summary: pd['summary'] = True if log: pd['logs'] = True if timing: pd['timingresults'] = True if test: pd['testresults'] = True if nodestatus: pd['status'] = True if runstatus: pd['runstatus'] = True if disp_order_id: pd['disp_order_id'] = True if disp_order_run_id: pd['disp_order_run_id'] = True # if the user does not specify anything to display, show the summary information if not runstatus and \ not all_things and \ not test and \ not timing and \ not log and \ not nodestatus and \ not summary and \ not disp_order_id and \ not disp_order_run_id: pd['summary'] = True if order_id is not None and order_run_id is not None: raise click.ClickException("Cannot specify both the Order Id and the OrderRun Id") if order_id is not None: pd[DKCloudCommandRunner.ORDER_ID] = order_id.strip() elif order_run_id is not None: pd[DKCloudCommandRunner.ORDER_RUN_ID] = order_run_id.strip() # don't print the green thing if it is just runstatus if not runstatus and not disp_order_id and not disp_order_run_id: click.secho('%s - Display Order-Run details from kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print(DKCloudCommandRunner.orderrun_detail(backend.dki, use_kitchen, pd))
[ "def", "orderrun_detail", "(", "backend", ",", "kitchen", ",", "summary", ",", "nodestatus", ",", "runstatus", ",", "log", ",", "timing", ",", "test", ",", "all_things", ",", "order_id", ",", "order_run_id", ",", "disp_order_id", ",", "disp_order_run_id", ")",...
Display information about an Order-Run
[ "Display", "information", "about", "an", "Order", "-", "Run" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L756-L816
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
delete_orderrun
def delete_orderrun(backend, orderrun_id): """ Delete the orderrun specified by the argument. """ click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green') check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip()))
python
def delete_orderrun(backend, orderrun_id): """ Delete the orderrun specified by the argument. """ click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green') check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip()))
[ "def", "delete_orderrun", "(", "backend", ",", "orderrun_id", ")", ":", "click", ".", "secho", "(", "'%s - Deleting orderrun %s'", "%", "(", "get_datetime", "(", ")", ",", "orderrun_id", ")", ",", "fg", "=", "'green'", ")", "check_and_print", "(", "DKCloudComm...
Delete the orderrun specified by the argument.
[ "Delete", "the", "orderrun", "specified", "by", "the", "argument", "." ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L822-L827
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
order_list
def order_list(backend, kitchen): """ Apply variables to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Get Order information for Kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print( DKCloudCommandRunner.list_order(backend.dki, use_kitchen))
python
def order_list(backend, kitchen): """ Apply variables to a Recipe """ err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen) if use_kitchen is None: raise click.ClickException(err_str) click.secho('%s - Get Order information for Kitchen %s' % (get_datetime(), use_kitchen), fg='green') check_and_print( DKCloudCommandRunner.list_order(backend.dki, use_kitchen))
[ "def", "order_list", "(", "backend", ",", "kitchen", ")", ":", "err_str", ",", "use_kitchen", "=", "Backend", ".", "get_kitchen_from_user", "(", "kitchen", ")", "if", "use_kitchen", "is", "None", ":", "raise", "click", ".", "ClickException", "(", "err_str", ...
Apply variables to a Recipe
[ "Apply", "variables", "to", "a", "Recipe" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L845-L857
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
secret_list
def secret_list(backend,path): """ List all Secrets """ click.echo(click.style('%s - Getting the list of secrets' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_list(backend.dki,path))
python
def secret_list(backend,path): """ List all Secrets """ click.echo(click.style('%s - Getting the list of secrets' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_list(backend.dki,path))
[ "def", "secret_list", "(", "backend", ",", "path", ")", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "'%s - Getting the list of secrets'", "%", "get_datetime", "(", ")", ",", "fg", "=", "'green'", ")", ")", "check_and_print", "(", "DKCloudComm...
List all Secrets
[ "List", "all", "Secrets" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L865-L871
DataKitchen/DKCloudCommand
DKCloudCommand/cli/__main__.py
secret_write
def secret_write(backend,entry): """ Write a secret """ path,value=entry.split('=') if value.startswith('@'): with open(value[1:]) as vfile: value = vfile.read() click.echo(click.style('%s - Writing secret' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_write(backend.dki,path,value))
python
def secret_write(backend,entry): """ Write a secret """ path,value=entry.split('=') if value.startswith('@'): with open(value[1:]) as vfile: value = vfile.read() click.echo(click.style('%s - Writing secret' % get_datetime(), fg='green')) check_and_print( DKCloudCommandRunner.secret_write(backend.dki,path,value))
[ "def", "secret_write", "(", "backend", ",", "entry", ")", ":", "path", ",", "value", "=", "entry", ".", "split", "(", "'='", ")", "if", "value", ".", "startswith", "(", "'@'", ")", ":", "with", "open", "(", "value", "[", "1", ":", "]", ")", "as",...
Write a secret
[ "Write", "a", "secret" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/cli/__main__.py#L876-L888
bitprophet/botox
botox/utils.py
puts
def puts(text, end="\n", flush=True, stream=sys.stdout): """ Print ``text`` to ``stream`` (default: ``sys.stdout``) and auto-flush. This is useful for fast loops where Python's default IO buffering would prevent "realtime" updating. Newlines may be disabled by setting ``end`` to the empty string (``''``). (This intentionally mirrors Python 3's ``print`` syntax.) You may disable output flushing by setting ``flush=False``. """ stream.write(str(text) + end) if flush: stream.flush()
python
def puts(text, end="\n", flush=True, stream=sys.stdout): """ Print ``text`` to ``stream`` (default: ``sys.stdout``) and auto-flush. This is useful for fast loops where Python's default IO buffering would prevent "realtime" updating. Newlines may be disabled by setting ``end`` to the empty string (``''``). (This intentionally mirrors Python 3's ``print`` syntax.) You may disable output flushing by setting ``flush=False``. """ stream.write(str(text) + end) if flush: stream.flush()
[ "def", "puts", "(", "text", ",", "end", "=", "\"\\n\"", ",", "flush", "=", "True", ",", "stream", "=", "sys", ".", "stdout", ")", ":", "stream", ".", "write", "(", "str", "(", "text", ")", "+", "end", ")", "if", "flush", ":", "stream", ".", "fl...
Print ``text`` to ``stream`` (default: ``sys.stdout``) and auto-flush. This is useful for fast loops where Python's default IO buffering would prevent "realtime" updating. Newlines may be disabled by setting ``end`` to the empty string (``''``). (This intentionally mirrors Python 3's ``print`` syntax.) You may disable output flushing by setting ``flush=False``.
[ "Print", "text", "to", "stream", "(", "default", ":", "sys", ".", "stdout", ")", "and", "auto", "-", "flush", "." ]
train
https://github.com/bitprophet/botox/blob/02c887a28bd2638273548cc7d1e6d6f1d4d38bf9/botox/utils.py#L5-L19
mbr/data
data/__init__.py
Data.stream
def stream(self): """Returns a stream object (:func:`file`, :class:`~io.BytesIO` or :class:`~StringIO.StringIO`) on the data.""" if not hasattr(self, '_stream'): if self.file is not None: self._stream = self.file elif self.filename is not None: self._stream = open(self.filename, 'rb') elif self.text is not None: self._stream = StringIO(self.text) elif self.data is not None: self._stream = BytesIO(self.data) else: raise ValueError('Broken Data, all None.') return self._stream
python
def stream(self): """Returns a stream object (:func:`file`, :class:`~io.BytesIO` or :class:`~StringIO.StringIO`) on the data.""" if not hasattr(self, '_stream'): if self.file is not None: self._stream = self.file elif self.filename is not None: self._stream = open(self.filename, 'rb') elif self.text is not None: self._stream = StringIO(self.text) elif self.data is not None: self._stream = BytesIO(self.data) else: raise ValueError('Broken Data, all None.') return self._stream
[ "def", "stream", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_stream'", ")", ":", "if", "self", ".", "file", "is", "not", "None", ":", "self", ".", "_stream", "=", "self", ".", "file", "elif", "self", ".", "filename", "is", ...
Returns a stream object (:func:`file`, :class:`~io.BytesIO` or :class:`~StringIO.StringIO`) on the data.
[ "Returns", "a", "stream", "object", "(", ":", "func", ":", "file", ":", "class", ":", "~io", ".", "BytesIO", "or", ":", "class", ":", "~StringIO", ".", "StringIO", ")", "on", "the", "data", "." ]
train
https://github.com/mbr/data/blob/f326938502defb4af93e97ed1212a71575641e77/data/__init__.py#L166-L181
mbr/data
data/__init__.py
Data.readlines
def readlines(self, *args, **kwargs): """Return list of all lines. Always returns list of unicode.""" return list(iter(partial(self.readline, *args, **kwargs), u''))
python
def readlines(self, *args, **kwargs): """Return list of all lines. Always returns list of unicode.""" return list(iter(partial(self.readline, *args, **kwargs), u''))
[ "def", "readlines", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "list", "(", "iter", "(", "partial", "(", "self", ".", "readline", ",", "*", "args", ",", "*", "*", "kwargs", ")", ",", "u''", ")", ")" ]
Return list of all lines. Always returns list of unicode.
[ "Return", "list", "of", "all", "lines", ".", "Always", "returns", "list", "of", "unicode", "." ]
train
https://github.com/mbr/data/blob/f326938502defb4af93e97ed1212a71575641e77/data/__init__.py#L199-L201
mbr/data
data/__init__.py
Data.save_to
def save_to(self, file): """Save data to file. Will copy by either writing out the data or using :func:`shutil.copyfileobj`. :param file: A file-like object (with a ``write`` method) or a filename.""" dest = file if hasattr(dest, 'write'): # writing to a file-like # only works when no unicode conversion is done if self.file is not None and\ getattr(self.file, 'encoding', None) is None: copyfileobj(self.file, dest) elif self.filename is not None: with open(self.filename, 'rb') as inp: copyfileobj(inp, dest) else: dest.write(self.__bytes__()) else: # we do not use filesystem io to make sure we have the same # permissions all around # copyfileobj() should be efficient enough # destination is a filename with open(dest, 'wb') as out: return self.save_to(out)
python
def save_to(self, file): """Save data to file. Will copy by either writing out the data or using :func:`shutil.copyfileobj`. :param file: A file-like object (with a ``write`` method) or a filename.""" dest = file if hasattr(dest, 'write'): # writing to a file-like # only works when no unicode conversion is done if self.file is not None and\ getattr(self.file, 'encoding', None) is None: copyfileobj(self.file, dest) elif self.filename is not None: with open(self.filename, 'rb') as inp: copyfileobj(inp, dest) else: dest.write(self.__bytes__()) else: # we do not use filesystem io to make sure we have the same # permissions all around # copyfileobj() should be efficient enough # destination is a filename with open(dest, 'wb') as out: return self.save_to(out)
[ "def", "save_to", "(", "self", ",", "file", ")", ":", "dest", "=", "file", "if", "hasattr", "(", "dest", ",", "'write'", ")", ":", "# writing to a file-like", "# only works when no unicode conversion is done", "if", "self", ".", "file", "is", "not", "None", "a...
Save data to file. Will copy by either writing out the data or using :func:`shutil.copyfileobj`. :param file: A file-like object (with a ``write`` method) or a filename.
[ "Save", "data", "to", "file", "." ]
train
https://github.com/mbr/data/blob/f326938502defb4af93e97ed1212a71575641e77/data/__init__.py#L203-L231
mbr/data
data/__init__.py
Data.temp_saved
def temp_saved(self, suffix='', prefix='tmp', dir=None): """Saves data to temporary file and returns the relevant instance of :func:`~tempfile.NamedTemporaryFile`. The resulting file is not deleted upon closing, but when the context manager exits. Other arguments are passed on to :func:`~tempfile.NamedTemporaryFile`. """ tmp = tempfile.NamedTemporaryFile( suffix=suffix, prefix=prefix, dir=dir, delete=False, ) try: self.save_to(tmp) tmp.flush() tmp.seek(0) yield tmp finally: try: os.unlink(tmp.name) except OSError as e: if e.errno != 2: reraise(e)
python
def temp_saved(self, suffix='', prefix='tmp', dir=None): """Saves data to temporary file and returns the relevant instance of :func:`~tempfile.NamedTemporaryFile`. The resulting file is not deleted upon closing, but when the context manager exits. Other arguments are passed on to :func:`~tempfile.NamedTemporaryFile`. """ tmp = tempfile.NamedTemporaryFile( suffix=suffix, prefix=prefix, dir=dir, delete=False, ) try: self.save_to(tmp) tmp.flush() tmp.seek(0) yield tmp finally: try: os.unlink(tmp.name) except OSError as e: if e.errno != 2: reraise(e)
[ "def", "temp_saved", "(", "self", ",", "suffix", "=", "''", ",", "prefix", "=", "'tmp'", ",", "dir", "=", "None", ")", ":", "tmp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "suffix", ",", "prefix", "=", "prefix", ",", "dir", "="...
Saves data to temporary file and returns the relevant instance of :func:`~tempfile.NamedTemporaryFile`. The resulting file is not deleted upon closing, but when the context manager exits. Other arguments are passed on to :func:`~tempfile.NamedTemporaryFile`.
[ "Saves", "data", "to", "temporary", "file", "and", "returns", "the", "relevant", "instance", "of", ":", "func", ":", "~tempfile", ".", "NamedTemporaryFile", ".", "The", "resulting", "file", "is", "not", "deleted", "upon", "closing", "but", "when", "the", "co...
train
https://github.com/mbr/data/blob/f326938502defb4af93e97ed1212a71575641e77/data/__init__.py#L234-L258
bovee/Aston
aston/tracefile/inficon.py
InficonHapsite._ions
def _ions(self, f): """ This is a generator that returns the mzs being measured during each time segment, one segment at a time. """ outside_pos = f.tell() doff = find_offset(f, 4 * b'\xff' + 'HapsSearch'.encode('ascii')) # actual end of prev section is 34 bytes before, but assume 1 rec f.seek(doff - 62) # seek backwards to find the FFFFFFFF header while True: f.seek(f.tell() - 8) if f.read(4) == 4 * b'\xff': break f.seek(f.tell() + 64) nsegments = struct.unpack('<I', f.read(4))[0] for _ in range(nsegments): # first 32 bytes are segment name, rest are something else? f.seek(f.tell() + 96) nions = struct.unpack('<I', f.read(4))[0] ions = [] for _ in range(nions): # TODO: check that itype is actually a SIM/full scan switch i1, i2, _, _, _, _, itype, _ = struct.unpack('<' + 8 * 'I', f.read(32)) if itype == 0: # SIM ions.append(i1 / 100.) else: # full scan # TODO: this might be a little hacky? # ideally we would need to know n for this, e.g.: # ions += np.linspace(i1 / 100, i2 / 100, n).tolist() ions += np.arange(i1 / 100., i2 / 100. + 1, 1).tolist() # save the file position and load the position # that we were at before we started this code inside_pos = f.tell() f.seek(outside_pos) yield ions outside_pos = f.tell() f.seek(inside_pos) f.seek(outside_pos)
python
def _ions(self, f): """ This is a generator that returns the mzs being measured during each time segment, one segment at a time. """ outside_pos = f.tell() doff = find_offset(f, 4 * b'\xff' + 'HapsSearch'.encode('ascii')) # actual end of prev section is 34 bytes before, but assume 1 rec f.seek(doff - 62) # seek backwards to find the FFFFFFFF header while True: f.seek(f.tell() - 8) if f.read(4) == 4 * b'\xff': break f.seek(f.tell() + 64) nsegments = struct.unpack('<I', f.read(4))[0] for _ in range(nsegments): # first 32 bytes are segment name, rest are something else? f.seek(f.tell() + 96) nions = struct.unpack('<I', f.read(4))[0] ions = [] for _ in range(nions): # TODO: check that itype is actually a SIM/full scan switch i1, i2, _, _, _, _, itype, _ = struct.unpack('<' + 8 * 'I', f.read(32)) if itype == 0: # SIM ions.append(i1 / 100.) else: # full scan # TODO: this might be a little hacky? # ideally we would need to know n for this, e.g.: # ions += np.linspace(i1 / 100, i2 / 100, n).tolist() ions += np.arange(i1 / 100., i2 / 100. + 1, 1).tolist() # save the file position and load the position # that we were at before we started this code inside_pos = f.tell() f.seek(outside_pos) yield ions outside_pos = f.tell() f.seek(inside_pos) f.seek(outside_pos)
[ "def", "_ions", "(", "self", ",", "f", ")", ":", "outside_pos", "=", "f", ".", "tell", "(", ")", "doff", "=", "find_offset", "(", "f", ",", "4", "*", "b'\\xff'", "+", "'HapsSearch'", ".", "encode", "(", "'ascii'", ")", ")", "# actual end of prev sectio...
This is a generator that returns the mzs being measured during each time segment, one segment at a time.
[ "This", "is", "a", "generator", "that", "returns", "the", "mzs", "being", "measured", "during", "each", "time", "segment", "one", "segment", "at", "a", "time", "." ]
train
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/tracefile/inficon.py#L12-L51
jnrbsn/daemonocle
daemonocle/core.py
Daemon._emit_message
def _emit_message(cls, message): """Print a message to STDOUT.""" sys.stdout.write(message) sys.stdout.flush()
python
def _emit_message(cls, message): """Print a message to STDOUT.""" sys.stdout.write(message) sys.stdout.flush()
[ "def", "_emit_message", "(", "cls", ",", "message", ")", ":", "sys", ".", "stdout", ".", "write", "(", "message", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Print a message to STDOUT.
[ "Print", "a", "message", "to", "STDOUT", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L51-L54
jnrbsn/daemonocle
daemonocle/core.py
Daemon._emit_error
def _emit_error(cls, message): """Print an error message to STDERR.""" sys.stderr.write('ERROR: {message}\n'.format(message=message)) sys.stderr.flush()
python
def _emit_error(cls, message): """Print an error message to STDERR.""" sys.stderr.write('ERROR: {message}\n'.format(message=message)) sys.stderr.flush()
[ "def", "_emit_error", "(", "cls", ",", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'ERROR: {message}\\n'", ".", "format", "(", "message", "=", "message", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
Print an error message to STDERR.
[ "Print", "an", "error", "message", "to", "STDERR", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L67-L70
jnrbsn/daemonocle
daemonocle/core.py
Daemon._emit_warning
def _emit_warning(cls, message): """Print an warning message to STDERR.""" sys.stderr.write('WARNING: {message}\n'.format(message=message)) sys.stderr.flush()
python
def _emit_warning(cls, message): """Print an warning message to STDERR.""" sys.stderr.write('WARNING: {message}\n'.format(message=message)) sys.stderr.flush()
[ "def", "_emit_warning", "(", "cls", ",", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'WARNING: {message}\\n'", ".", "format", "(", "message", "=", "message", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
Print an warning message to STDERR.
[ "Print", "an", "warning", "message", "to", "STDERR", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L73-L76
jnrbsn/daemonocle
daemonocle/core.py
Daemon._setup_piddir
def _setup_piddir(self): """Create the directory for the PID file if necessary.""" if self.pidfile is None: return piddir = os.path.dirname(self.pidfile) if not os.path.isdir(piddir): # Create the directory with sensible mode and ownership os.makedirs(piddir, 0o777 & ~self.umask) os.chown(piddir, self.uid, self.gid)
python
def _setup_piddir(self): """Create the directory for the PID file if necessary.""" if self.pidfile is None: return piddir = os.path.dirname(self.pidfile) if not os.path.isdir(piddir): # Create the directory with sensible mode and ownership os.makedirs(piddir, 0o777 & ~self.umask) os.chown(piddir, self.uid, self.gid)
[ "def", "_setup_piddir", "(", "self", ")", ":", "if", "self", ".", "pidfile", "is", "None", ":", "return", "piddir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "pidfile", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "piddir...
Create the directory for the PID file if necessary.
[ "Create", "the", "directory", "for", "the", "PID", "file", "if", "necessary", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L78-L86
jnrbsn/daemonocle
daemonocle/core.py
Daemon._read_pidfile
def _read_pidfile(self): """Read the PID file and check to make sure it's not stale.""" if self.pidfile is None: return None if not os.path.isfile(self.pidfile): return None # Read the PID file with open(self.pidfile, 'r') as fp: try: pid = int(fp.read()) except ValueError: self._emit_warning('Empty or broken pidfile {pidfile}; ' 'removing'.format(pidfile=self.pidfile)) pid = None if pid is not None and psutil.pid_exists(pid): return pid else: # Remove the stale PID file os.remove(self.pidfile) return None
python
def _read_pidfile(self): """Read the PID file and check to make sure it's not stale.""" if self.pidfile is None: return None if not os.path.isfile(self.pidfile): return None # Read the PID file with open(self.pidfile, 'r') as fp: try: pid = int(fp.read()) except ValueError: self._emit_warning('Empty or broken pidfile {pidfile}; ' 'removing'.format(pidfile=self.pidfile)) pid = None if pid is not None and psutil.pid_exists(pid): return pid else: # Remove the stale PID file os.remove(self.pidfile) return None
[ "def", "_read_pidfile", "(", "self", ")", ":", "if", "self", ".", "pidfile", "is", "None", ":", "return", "None", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "pidfile", ")", ":", "return", "None", "# Read the PID file", "with", "op...
Read the PID file and check to make sure it's not stale.
[ "Read", "the", "PID", "file", "and", "check", "to", "make", "sure", "it", "s", "not", "stale", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L88-L110
jnrbsn/daemonocle
daemonocle/core.py
Daemon._write_pidfile
def _write_pidfile(self): """Create, write to, and lock the PID file.""" flags = os.O_CREAT | os.O_RDWR try: # Some systems don't have os.O_EXLOCK flags = flags | os.O_EXLOCK except AttributeError: pass self._pid_fd = os.open(self.pidfile, flags, 0o666 & ~self.umask) os.write(self._pid_fd, str(os.getpid()).encode('utf-8'))
python
def _write_pidfile(self): """Create, write to, and lock the PID file.""" flags = os.O_CREAT | os.O_RDWR try: # Some systems don't have os.O_EXLOCK flags = flags | os.O_EXLOCK except AttributeError: pass self._pid_fd = os.open(self.pidfile, flags, 0o666 & ~self.umask) os.write(self._pid_fd, str(os.getpid()).encode('utf-8'))
[ "def", "_write_pidfile", "(", "self", ")", ":", "flags", "=", "os", ".", "O_CREAT", "|", "os", ".", "O_RDWR", "try", ":", "# Some systems don't have os.O_EXLOCK", "flags", "=", "flags", "|", "os", ".", "O_EXLOCK", "except", "AttributeError", ":", "pass", "se...
Create, write to, and lock the PID file.
[ "Create", "write", "to", "and", "lock", "the", "PID", "file", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L112-L121
jnrbsn/daemonocle
daemonocle/core.py
Daemon._close_pidfile
def _close_pidfile(self): """Closes and removes the PID file.""" if self._pid_fd is not None: os.close(self._pid_fd) try: os.remove(self.pidfile) except OSError as ex: if ex.errno != errno.ENOENT: raise
python
def _close_pidfile(self): """Closes and removes the PID file.""" if self._pid_fd is not None: os.close(self._pid_fd) try: os.remove(self.pidfile) except OSError as ex: if ex.errno != errno.ENOENT: raise
[ "def", "_close_pidfile", "(", "self", ")", ":", "if", "self", ".", "_pid_fd", "is", "not", "None", ":", "os", ".", "close", "(", "self", ".", "_pid_fd", ")", "try", ":", "os", ".", "remove", "(", "self", ".", "pidfile", ")", "except", "OSError", "a...
Closes and removes the PID file.
[ "Closes", "and", "removes", "the", "PID", "file", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L123-L131
jnrbsn/daemonocle
daemonocle/core.py
Daemon._prevent_core_dump
def _prevent_core_dump(cls): """Prevent the process from generating a core dump.""" try: # Try to get the current limit resource.getrlimit(resource.RLIMIT_CORE) except ValueError: # System doesn't support the RLIMIT_CORE resource limit return else: # Set the soft and hard limits for core dump size to zero resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
python
def _prevent_core_dump(cls): """Prevent the process from generating a core dump.""" try: # Try to get the current limit resource.getrlimit(resource.RLIMIT_CORE) except ValueError: # System doesn't support the RLIMIT_CORE resource limit return else: # Set the soft and hard limits for core dump size to zero resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
[ "def", "_prevent_core_dump", "(", "cls", ")", ":", "try", ":", "# Try to get the current limit", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_CORE", ")", "except", "ValueError", ":", "# System doesn't support the RLIMIT_CORE resource limit", "return", "else...
Prevent the process from generating a core dump.
[ "Prevent", "the", "process", "from", "generating", "a", "core", "dump", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L134-L144
jnrbsn/daemonocle
daemonocle/core.py
Daemon._setup_environment
def _setup_environment(self): """Setup the environment for the daemon.""" # Save the original working directory so that reload can launch # the new process with the same arguments as the original self._orig_workdir = os.getcwd() if self.chrootdir is not None: try: # Change the root directory os.chdir(self.chrootdir) os.chroot(self.chrootdir) except Exception as ex: raise DaemonError('Unable to change root directory ' '({error})'.format(error=str(ex))) # Prevent the process from generating a core dump self._prevent_core_dump() try: # Switch directories os.chdir(self.workdir) except Exception as ex: raise DaemonError('Unable to change working directory ' '({error})'.format(error=str(ex))) # Create the directory for the pid file if necessary self._setup_piddir() try: # Set file creation mask os.umask(self.umask) except Exception as ex: raise DaemonError('Unable to change file creation mask ' '({error})'.format(error=str(ex))) try: # Switch users os.setgid(self.gid) os.setuid(self.uid) except Exception as ex: raise DaemonError('Unable to setuid or setgid ' '({error})'.format(error=str(ex)))
python
def _setup_environment(self): """Setup the environment for the daemon.""" # Save the original working directory so that reload can launch # the new process with the same arguments as the original self._orig_workdir = os.getcwd() if self.chrootdir is not None: try: # Change the root directory os.chdir(self.chrootdir) os.chroot(self.chrootdir) except Exception as ex: raise DaemonError('Unable to change root directory ' '({error})'.format(error=str(ex))) # Prevent the process from generating a core dump self._prevent_core_dump() try: # Switch directories os.chdir(self.workdir) except Exception as ex: raise DaemonError('Unable to change working directory ' '({error})'.format(error=str(ex))) # Create the directory for the pid file if necessary self._setup_piddir() try: # Set file creation mask os.umask(self.umask) except Exception as ex: raise DaemonError('Unable to change file creation mask ' '({error})'.format(error=str(ex))) try: # Switch users os.setgid(self.gid) os.setuid(self.uid) except Exception as ex: raise DaemonError('Unable to setuid or setgid ' '({error})'.format(error=str(ex)))
[ "def", "_setup_environment", "(", "self", ")", ":", "# Save the original working directory so that reload can launch", "# the new process with the same arguments as the original", "self", ".", "_orig_workdir", "=", "os", ".", "getcwd", "(", ")", "if", "self", ".", "chrootdir"...
Setup the environment for the daemon.
[ "Setup", "the", "environment", "for", "the", "daemon", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L146-L187
jnrbsn/daemonocle
daemonocle/core.py
Daemon._reset_file_descriptors
def _reset_file_descriptors(self): """Close open file descriptors and redirect standard streams.""" if self.close_open_files: # Attempt to determine the max number of open files max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == resource.RLIM_INFINITY: # If the limit is infinity, use a more reasonable limit max_fds = 2048 else: # If we're not closing all open files, we at least need to # reset STDIN, STDOUT, and STDERR. max_fds = 3 for fd in range(max_fds): try: os.close(fd) except OSError: # The file descriptor probably wasn't open pass # Redirect STDIN, STDOUT, and STDERR to /dev/null devnull_fd = os.open(os.devnull, os.O_RDWR) os.dup2(devnull_fd, 0) os.dup2(devnull_fd, 1) os.dup2(devnull_fd, 2)
python
def _reset_file_descriptors(self): """Close open file descriptors and redirect standard streams.""" if self.close_open_files: # Attempt to determine the max number of open files max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == resource.RLIM_INFINITY: # If the limit is infinity, use a more reasonable limit max_fds = 2048 else: # If we're not closing all open files, we at least need to # reset STDIN, STDOUT, and STDERR. max_fds = 3 for fd in range(max_fds): try: os.close(fd) except OSError: # The file descriptor probably wasn't open pass # Redirect STDIN, STDOUT, and STDERR to /dev/null devnull_fd = os.open(os.devnull, os.O_RDWR) os.dup2(devnull_fd, 0) os.dup2(devnull_fd, 1) os.dup2(devnull_fd, 2)
[ "def", "_reset_file_descriptors", "(", "self", ")", ":", "if", "self", ".", "close_open_files", ":", "# Attempt to determine the max number of open files", "max_fds", "=", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "[", "1", "]", "if",...
Close open file descriptors and redirect standard streams.
[ "Close", "open", "file", "descriptors", "and", "redirect", "standard", "streams", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L189-L213
jnrbsn/daemonocle
daemonocle/core.py
Daemon._is_socket
def _is_socket(cls, stream): """Check if the given stream is a socket.""" try: fd = stream.fileno() except ValueError: # If it has no file descriptor, it's not a socket return False sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) try: # This will raise a socket.error if it's not a socket sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) except socket.error as ex: if ex.args[0] != errno.ENOTSOCK: # It must be a socket return True else: # If an exception wasn't raised, it's a socket return True
python
def _is_socket(cls, stream): """Check if the given stream is a socket.""" try: fd = stream.fileno() except ValueError: # If it has no file descriptor, it's not a socket return False sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_RAW) try: # This will raise a socket.error if it's not a socket sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) except socket.error as ex: if ex.args[0] != errno.ENOTSOCK: # It must be a socket return True else: # If an exception wasn't raised, it's a socket return True
[ "def", "_is_socket", "(", "cls", ",", "stream", ")", ":", "try", ":", "fd", "=", "stream", ".", "fileno", "(", ")", "except", "ValueError", ":", "# If it has no file descriptor, it's not a socket", "return", "False", "sock", "=", "socket", ".", "fromfd", "(", ...
Check if the given stream is a socket.
[ "Check", "if", "the", "given", "stream", "is", "a", "socket", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L216-L234
jnrbsn/daemonocle
daemonocle/core.py
Daemon._pid_is_alive
def _pid_is_alive(cls, pid, timeout): """Check if a PID is alive with a timeout.""" try: proc = psutil.Process(pid) except psutil.NoSuchProcess: return False try: proc.wait(timeout=timeout) except psutil.TimeoutExpired: return True return False
python
def _pid_is_alive(cls, pid, timeout): """Check if a PID is alive with a timeout.""" try: proc = psutil.Process(pid) except psutil.NoSuchProcess: return False try: proc.wait(timeout=timeout) except psutil.TimeoutExpired: return True return False
[ "def", "_pid_is_alive", "(", "cls", ",", "pid", ",", "timeout", ")", ":", "try", ":", "proc", "=", "psutil", ".", "Process", "(", "pid", ")", "except", "psutil", ".", "NoSuchProcess", ":", "return", "False", "try", ":", "proc", ".", "wait", "(", "tim...
Check if a PID is alive with a timeout.
[ "Check", "if", "a", "PID", "is", "alive", "with", "a", "timeout", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L237-L249
jnrbsn/daemonocle
daemonocle/core.py
Daemon._is_detach_necessary
def _is_detach_necessary(cls): """Check if detaching the process is even necessary.""" if os.getppid() == 1: # Process was started by init return False if cls._is_socket(sys.stdin): # If STDIN is a socket, the daemon was started by a super-server return False return True
python
def _is_detach_necessary(cls): """Check if detaching the process is even necessary.""" if os.getppid() == 1: # Process was started by init return False if cls._is_socket(sys.stdin): # If STDIN is a socket, the daemon was started by a super-server return False return True
[ "def", "_is_detach_necessary", "(", "cls", ")", ":", "if", "os", ".", "getppid", "(", ")", "==", "1", ":", "# Process was started by init", "return", "False", "if", "cls", ".", "_is_socket", "(", "sys", ".", "stdin", ")", ":", "# If STDIN is a socket, the daem...
Check if detaching the process is even necessary.
[ "Check", "if", "detaching", "the", "process", "is", "even", "necessary", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L252-L262
jnrbsn/daemonocle
daemonocle/core.py
Daemon._detach_process
def _detach_process(self): """Detach the process via the standard double-fork method with some extra magic.""" # First fork to return control to the shell pid = os.fork() if pid > 0: # Wait for the first child, because it's going to wait and # check to make sure the second child is actually running # before exiting os.waitpid(pid, 0) sys.exit(0) # Become a process group and session group leader os.setsid() # Fork again so the session group leader can exit and to ensure # we can never regain a controlling terminal pid = os.fork() if pid > 0: time.sleep(1) # After waiting one second, check to make sure the second # child hasn't become a zombie already status = os.waitpid(pid, os.WNOHANG) if status[0] == pid: # The child is already gone for some reason exitcode = status[1] % 255 self._emit_failed() self._emit_error('Child exited immediately with exit ' 'code {code}'.format(code=exitcode)) sys.exit(exitcode) else: self._emit_ok() sys.exit(0) self._reset_file_descriptors()
python
def _detach_process(self): """Detach the process via the standard double-fork method with some extra magic.""" # First fork to return control to the shell pid = os.fork() if pid > 0: # Wait for the first child, because it's going to wait and # check to make sure the second child is actually running # before exiting os.waitpid(pid, 0) sys.exit(0) # Become a process group and session group leader os.setsid() # Fork again so the session group leader can exit and to ensure # we can never regain a controlling terminal pid = os.fork() if pid > 0: time.sleep(1) # After waiting one second, check to make sure the second # child hasn't become a zombie already status = os.waitpid(pid, os.WNOHANG) if status[0] == pid: # The child is already gone for some reason exitcode = status[1] % 255 self._emit_failed() self._emit_error('Child exited immediately with exit ' 'code {code}'.format(code=exitcode)) sys.exit(exitcode) else: self._emit_ok() sys.exit(0) self._reset_file_descriptors()
[ "def", "_detach_process", "(", "self", ")", ":", "# First fork to return control to the shell", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", ">", "0", ":", "# Wait for the first child, because it's going to wait and", "# check to make sure the second child is actuall...
Detach the process via the standard double-fork method with some extra magic.
[ "Detach", "the", "process", "via", "the", "standard", "double", "-", "fork", "method", "with", "some", "extra", "magic", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L264-L298
jnrbsn/daemonocle
daemonocle/core.py
Daemon._orphan_this_process
def _orphan_this_process(cls, wait_for_parent=False): """Orphan the current process by forking and then waiting for the parent to exit.""" # The current PID will be the PPID of the forked child ppid = os.getpid() pid = os.fork() if pid > 0: # Exit parent sys.exit(0) if wait_for_parent and cls._pid_is_alive(ppid, timeout=1): raise DaemonError( 'Parent did not exit while trying to orphan process')
python
def _orphan_this_process(cls, wait_for_parent=False): """Orphan the current process by forking and then waiting for the parent to exit.""" # The current PID will be the PPID of the forked child ppid = os.getpid() pid = os.fork() if pid > 0: # Exit parent sys.exit(0) if wait_for_parent and cls._pid_is_alive(ppid, timeout=1): raise DaemonError( 'Parent did not exit while trying to orphan process')
[ "def", "_orphan_this_process", "(", "cls", ",", "wait_for_parent", "=", "False", ")", ":", "# The current PID will be the PPID of the forked child", "ppid", "=", "os", ".", "getpid", "(", ")", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", ">", "0", "...
Orphan the current process by forking and then waiting for the parent to exit.
[ "Orphan", "the", "current", "process", "by", "forking", "and", "then", "waiting", "for", "the", "parent", "to", "exit", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L301-L314
jnrbsn/daemonocle
daemonocle/core.py
Daemon._fork_and_supervise_child
def _fork_and_supervise_child(cls): """Fork a child and then watch the process group until there are no processes in it.""" pid = os.fork() if pid == 0: # Fork again but orphan the child this time so we'll have # the original parent and the second child which is orphaned # so we don't have to worry about it becoming a zombie cls._orphan_this_process() return # Since this process is not going to exit, we need to call # os.waitpid() so that the first child doesn't become a zombie os.waitpid(pid, 0) # Generate a list of PIDs to exclude when checking for processes # in the group (exclude all ancestors that are in the group) pgid = os.getpgrp() exclude_pids = set([0, os.getpid()]) proc = psutil.Process() while os.getpgid(proc.pid) == pgid: exclude_pids.add(proc.pid) proc = psutil.Process(proc.ppid()) while True: try: # Look for other processes in this process group group_procs = [] for proc in psutil.process_iter(): try: if (os.getpgid(proc.pid) == pgid and proc.pid not in exclude_pids): # We found a process in this process group group_procs.append(proc) except (psutil.NoSuchProcess, OSError): continue if group_procs: psutil.wait_procs(group_procs, timeout=1) else: # No processes were found in this process group # so we can exit cls._emit_message( 'All children are gone. Parent is exiting...\n') sys.exit(0) except KeyboardInterrupt: # Don't exit immediatedly on Ctrl-C, because we want to # wait for the child processes to finish cls._emit_message('\n') continue
python
def _fork_and_supervise_child(cls): """Fork a child and then watch the process group until there are no processes in it.""" pid = os.fork() if pid == 0: # Fork again but orphan the child this time so we'll have # the original parent and the second child which is orphaned # so we don't have to worry about it becoming a zombie cls._orphan_this_process() return # Since this process is not going to exit, we need to call # os.waitpid() so that the first child doesn't become a zombie os.waitpid(pid, 0) # Generate a list of PIDs to exclude when checking for processes # in the group (exclude all ancestors that are in the group) pgid = os.getpgrp() exclude_pids = set([0, os.getpid()]) proc = psutil.Process() while os.getpgid(proc.pid) == pgid: exclude_pids.add(proc.pid) proc = psutil.Process(proc.ppid()) while True: try: # Look for other processes in this process group group_procs = [] for proc in psutil.process_iter(): try: if (os.getpgid(proc.pid) == pgid and proc.pid not in exclude_pids): # We found a process in this process group group_procs.append(proc) except (psutil.NoSuchProcess, OSError): continue if group_procs: psutil.wait_procs(group_procs, timeout=1) else: # No processes were found in this process group # so we can exit cls._emit_message( 'All children are gone. Parent is exiting...\n') sys.exit(0) except KeyboardInterrupt: # Don't exit immediatedly on Ctrl-C, because we want to # wait for the child processes to finish cls._emit_message('\n') continue
[ "def", "_fork_and_supervise_child", "(", "cls", ")", ":", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", "==", "0", ":", "# Fork again but orphan the child this time so we'll have", "# the original parent and the second child which is orphaned", "# so we don't have to ...
Fork a child and then watch the process group until there are no processes in it.
[ "Fork", "a", "child", "and", "then", "watch", "the", "process", "group", "until", "there", "are", "no", "processes", "in", "it", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L317-L365
jnrbsn/daemonocle
daemonocle/core.py
Daemon._shutdown
def _shutdown(self, message=None, code=0): """Shutdown and cleanup everything.""" if self._shutdown_complete: # Make sure we don't accidentally re-run the all cleanup sys.exit(code) if self.shutdown_callback is not None: # Call the shutdown callback with a message suitable for # logging and the exit code self.shutdown_callback(message, code) if self.pidfile is not None: self._close_pidfile() self._shutdown_complete = True sys.exit(code)
python
def _shutdown(self, message=None, code=0): """Shutdown and cleanup everything.""" if self._shutdown_complete: # Make sure we don't accidentally re-run the all cleanup sys.exit(code) if self.shutdown_callback is not None: # Call the shutdown callback with a message suitable for # logging and the exit code self.shutdown_callback(message, code) if self.pidfile is not None: self._close_pidfile() self._shutdown_complete = True sys.exit(code)
[ "def", "_shutdown", "(", "self", ",", "message", "=", "None", ",", "code", "=", "0", ")", ":", "if", "self", ".", "_shutdown_complete", ":", "# Make sure we don't accidentally re-run the all cleanup", "sys", ".", "exit", "(", "code", ")", "if", "self", ".", ...
Shutdown and cleanup everything.
[ "Shutdown", "and", "cleanup", "everything", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L367-L382
jnrbsn/daemonocle
daemonocle/core.py
Daemon._handle_terminate
def _handle_terminate(self, signal_number, _): """Handle a signal to terminate.""" signal_names = { signal.SIGINT: 'SIGINT', signal.SIGQUIT: 'SIGQUIT', signal.SIGTERM: 'SIGTERM', } message = 'Terminated by {name} ({number})'.format( name=signal_names[signal_number], number=signal_number) self._shutdown(message, code=128+signal_number)
python
def _handle_terminate(self, signal_number, _): """Handle a signal to terminate.""" signal_names = { signal.SIGINT: 'SIGINT', signal.SIGQUIT: 'SIGQUIT', signal.SIGTERM: 'SIGTERM', } message = 'Terminated by {name} ({number})'.format( name=signal_names[signal_number], number=signal_number) self._shutdown(message, code=128+signal_number)
[ "def", "_handle_terminate", "(", "self", ",", "signal_number", ",", "_", ")", ":", "signal_names", "=", "{", "signal", ".", "SIGINT", ":", "'SIGINT'", ",", "signal", ".", "SIGQUIT", ":", "'SIGQUIT'", ",", "signal", ".", "SIGTERM", ":", "'SIGTERM'", ",", ...
Handle a signal to terminate.
[ "Handle", "a", "signal", "to", "terminate", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L384-L393
jnrbsn/daemonocle
daemonocle/core.py
Daemon._run
def _run(self): """Run the worker function with some custom exception handling.""" try: # Run the worker self.worker() except SystemExit as ex: # sys.exit() was called if isinstance(ex.code, int): if ex.code is not None and ex.code != 0: # A custom exit code was specified self._shutdown( 'Exiting with non-zero exit code {exitcode}'.format( exitcode=ex.code), ex.code) else: # A message was passed to sys.exit() self._shutdown( 'Exiting with message: {msg}'.format(msg=ex.code), 1) except Exception as ex: if self.detach: self._shutdown('Dying due to unhandled {cls}: {msg}'.format( cls=ex.__class__.__name__, msg=str(ex)), 127) else: # We're not detached so just raise the exception raise self._shutdown('Shutting down normally')
python
def _run(self): """Run the worker function with some custom exception handling.""" try: # Run the worker self.worker() except SystemExit as ex: # sys.exit() was called if isinstance(ex.code, int): if ex.code is not None and ex.code != 0: # A custom exit code was specified self._shutdown( 'Exiting with non-zero exit code {exitcode}'.format( exitcode=ex.code), ex.code) else: # A message was passed to sys.exit() self._shutdown( 'Exiting with message: {msg}'.format(msg=ex.code), 1) except Exception as ex: if self.detach: self._shutdown('Dying due to unhandled {cls}: {msg}'.format( cls=ex.__class__.__name__, msg=str(ex)), 127) else: # We're not detached so just raise the exception raise self._shutdown('Shutting down normally')
[ "def", "_run", "(", "self", ")", ":", "try", ":", "# Run the worker", "self", ".", "worker", "(", ")", "except", "SystemExit", "as", "ex", ":", "# sys.exit() was called", "if", "isinstance", "(", "ex", ".", "code", ",", "int", ")", ":", "if", "ex", "."...
Run the worker function with some custom exception handling.
[ "Run", "the", "worker", "function", "with", "some", "custom", "exception", "handling", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L395-L421
jnrbsn/daemonocle
daemonocle/core.py
Daemon.start
def start(self): """Start the daemon.""" if self.worker is None: raise DaemonError('No worker is defined for daemon') if os.environ.get('DAEMONOCLE_RELOAD'): # If this is actually a reload, we need to wait for the # existing daemon to exit first self._emit_message('Reloading {prog} ... '.format(prog=self.prog)) # Orhpan this process so the parent can exit self._orphan_this_process(wait_for_parent=True) pid = self._read_pidfile() if (pid is not None and self._pid_is_alive(pid, timeout=self.stop_timeout)): # The process didn't exit for some reason self._emit_failed() message = ('Previous process (PID {pid}) did NOT ' 'exit during reload').format(pid=pid) self._emit_error(message) self._shutdown(message, 1) # Check to see if the daemon is already running pid = self._read_pidfile() if pid is not None: # I don't think this should not be a fatal error self._emit_warning('{prog} already running with PID {pid}'.format( prog=self.prog, pid=pid)) return if not self.detach and not os.environ.get('DAEMONOCLE_RELOAD'): # This keeps the original parent process open so that we # maintain control of the tty self._fork_and_supervise_child() if not os.environ.get('DAEMONOCLE_RELOAD'): # A custom message is printed for reloading self._emit_message('Starting {prog} ... '.format(prog=self.prog)) self._setup_environment() if self.detach: self._detach_process() else: self._emit_ok() if self.pidfile is not None: self._write_pidfile() # Setup signal handlers signal.signal(signal.SIGINT, self._handle_terminate) signal.signal(signal.SIGQUIT, self._handle_terminate) signal.signal(signal.SIGTERM, self._handle_terminate) self._run()
python
def start(self): """Start the daemon.""" if self.worker is None: raise DaemonError('No worker is defined for daemon') if os.environ.get('DAEMONOCLE_RELOAD'): # If this is actually a reload, we need to wait for the # existing daemon to exit first self._emit_message('Reloading {prog} ... '.format(prog=self.prog)) # Orhpan this process so the parent can exit self._orphan_this_process(wait_for_parent=True) pid = self._read_pidfile() if (pid is not None and self._pid_is_alive(pid, timeout=self.stop_timeout)): # The process didn't exit for some reason self._emit_failed() message = ('Previous process (PID {pid}) did NOT ' 'exit during reload').format(pid=pid) self._emit_error(message) self._shutdown(message, 1) # Check to see if the daemon is already running pid = self._read_pidfile() if pid is not None: # I don't think this should not be a fatal error self._emit_warning('{prog} already running with PID {pid}'.format( prog=self.prog, pid=pid)) return if not self.detach and not os.environ.get('DAEMONOCLE_RELOAD'): # This keeps the original parent process open so that we # maintain control of the tty self._fork_and_supervise_child() if not os.environ.get('DAEMONOCLE_RELOAD'): # A custom message is printed for reloading self._emit_message('Starting {prog} ... '.format(prog=self.prog)) self._setup_environment() if self.detach: self._detach_process() else: self._emit_ok() if self.pidfile is not None: self._write_pidfile() # Setup signal handlers signal.signal(signal.SIGINT, self._handle_terminate) signal.signal(signal.SIGQUIT, self._handle_terminate) signal.signal(signal.SIGTERM, self._handle_terminate) self._run()
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "worker", "is", "None", ":", "raise", "DaemonError", "(", "'No worker is defined for daemon'", ")", "if", "os", ".", "environ", ".", "get", "(", "'DAEMONOCLE_RELOAD'", ")", ":", "# If this is actually a...
Start the daemon.
[ "Start", "the", "daemon", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L424-L477
jnrbsn/daemonocle
daemonocle/core.py
Daemon.stop
def stop(self): """Stop the daemon.""" if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: # I don't think this should be a fatal error self._emit_warning('{prog} is not running'.format(prog=self.prog)) return self._emit_message('Stopping {prog} ... '.format(prog=self.prog)) try: # Try to terminate the process os.kill(pid, signal.SIGTERM) except OSError as ex: self._emit_failed() self._emit_error(str(ex)) sys.exit(1) if self._pid_is_alive(pid, timeout=self.stop_timeout): # The process didn't terminate for some reason self._emit_failed() self._emit_error('Timed out while waiting for process (PID {pid}) ' 'to terminate'.format(pid=pid)) sys.exit(1) self._emit_ok()
python
def stop(self): """Stop the daemon.""" if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: # I don't think this should be a fatal error self._emit_warning('{prog} is not running'.format(prog=self.prog)) return self._emit_message('Stopping {prog} ... '.format(prog=self.prog)) try: # Try to terminate the process os.kill(pid, signal.SIGTERM) except OSError as ex: self._emit_failed() self._emit_error(str(ex)) sys.exit(1) if self._pid_is_alive(pid, timeout=self.stop_timeout): # The process didn't terminate for some reason self._emit_failed() self._emit_error('Timed out while waiting for process (PID {pid}) ' 'to terminate'.format(pid=pid)) sys.exit(1) self._emit_ok()
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "pidfile", "is", "None", ":", "raise", "DaemonError", "(", "'Cannot stop daemon without PID file'", ")", "pid", "=", "self", ".", "_read_pidfile", "(", ")", "if", "pid", "is", "None", ":", "# I don't...
Stop the daemon.
[ "Stop", "the", "daemon", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L480-L508
jnrbsn/daemonocle
daemonocle/core.py
Daemon.status
def status(self): """Get the status of the daemon.""" if self.pidfile is None: raise DaemonError('Cannot get status of daemon without PID file') pid = self._read_pidfile() if pid is None: self._emit_message( '{prog} -- not running\n'.format(prog=self.prog)) sys.exit(1) proc = psutil.Process(pid) # Default data data = { 'prog': self.prog, 'pid': pid, 'status': proc.status(), 'uptime': '0m', 'cpu': 0.0, 'memory': 0.0, } # Add up all the CPU and memory usage of all the # processes in the process group pgid = os.getpgid(pid) for gproc in psutil.process_iter(): try: if os.getpgid(gproc.pid) == pgid and gproc.pid != 0: data['cpu'] += gproc.cpu_percent(interval=0.1) data['memory'] += gproc.memory_percent() except (psutil.Error, OSError): continue # Calculate the uptime and format it in a human-readable but # also machine-parsable format try: uptime_mins = int(round((time.time() - proc.create_time()) / 60)) uptime_hours, uptime_mins = divmod(uptime_mins, 60) data['uptime'] = str(uptime_mins) + 'm' if uptime_hours: uptime_days, uptime_hours = divmod(uptime_hours, 24) data['uptime'] = str(uptime_hours) + 'h ' + data['uptime'] if uptime_days: data['uptime'] = str(uptime_days) + 'd ' + data['uptime'] except psutil.Error: pass template = ('{prog} -- pid: {pid}, status: {status}, ' 'uptime: {uptime}, %cpu: {cpu:.1f}, %mem: {memory:.1f}\n') self._emit_message(template.format(**data))
python
def status(self): """Get the status of the daemon.""" if self.pidfile is None: raise DaemonError('Cannot get status of daemon without PID file') pid = self._read_pidfile() if pid is None: self._emit_message( '{prog} -- not running\n'.format(prog=self.prog)) sys.exit(1) proc = psutil.Process(pid) # Default data data = { 'prog': self.prog, 'pid': pid, 'status': proc.status(), 'uptime': '0m', 'cpu': 0.0, 'memory': 0.0, } # Add up all the CPU and memory usage of all the # processes in the process group pgid = os.getpgid(pid) for gproc in psutil.process_iter(): try: if os.getpgid(gproc.pid) == pgid and gproc.pid != 0: data['cpu'] += gproc.cpu_percent(interval=0.1) data['memory'] += gproc.memory_percent() except (psutil.Error, OSError): continue # Calculate the uptime and format it in a human-readable but # also machine-parsable format try: uptime_mins = int(round((time.time() - proc.create_time()) / 60)) uptime_hours, uptime_mins = divmod(uptime_mins, 60) data['uptime'] = str(uptime_mins) + 'm' if uptime_hours: uptime_days, uptime_hours = divmod(uptime_hours, 24) data['uptime'] = str(uptime_hours) + 'h ' + data['uptime'] if uptime_days: data['uptime'] = str(uptime_days) + 'd ' + data['uptime'] except psutil.Error: pass template = ('{prog} -- pid: {pid}, status: {status}, ' 'uptime: {uptime}, %cpu: {cpu:.1f}, %mem: {memory:.1f}\n') self._emit_message(template.format(**data))
[ "def", "status", "(", "self", ")", ":", "if", "self", ".", "pidfile", "is", "None", ":", "raise", "DaemonError", "(", "'Cannot get status of daemon without PID file'", ")", "pid", "=", "self", ".", "_read_pidfile", "(", ")", "if", "pid", "is", "None", ":", ...
Get the status of the daemon.
[ "Get", "the", "status", "of", "the", "daemon", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L517-L566
jnrbsn/daemonocle
daemonocle/core.py
Daemon.list_actions
def list_actions(cls): """Get a list of exposed actions that are callable via the ``do_action()`` method.""" # Make sure these are always at the beginning of the list actions = ['start', 'stop', 'restart', 'status'] # Iterate over the instance attributes checking for actions that # have been exposed for func_name in dir(cls): func = getattr(cls, func_name) if (not hasattr(func, '__call__') or not getattr(func, '__daemonocle_exposed__', False)): # Not a function or not exposed continue action = func_name.replace('_', '-') if action not in actions: actions.append(action) return actions
python
def list_actions(cls): """Get a list of exposed actions that are callable via the ``do_action()`` method.""" # Make sure these are always at the beginning of the list actions = ['start', 'stop', 'restart', 'status'] # Iterate over the instance attributes checking for actions that # have been exposed for func_name in dir(cls): func = getattr(cls, func_name) if (not hasattr(func, '__call__') or not getattr(func, '__daemonocle_exposed__', False)): # Not a function or not exposed continue action = func_name.replace('_', '-') if action not in actions: actions.append(action) return actions
[ "def", "list_actions", "(", "cls", ")", ":", "# Make sure these are always at the beginning of the list", "actions", "=", "[", "'start'", ",", "'stop'", ",", "'restart'", ",", "'status'", "]", "# Iterate over the instance attributes checking for actions that", "# have been expo...
Get a list of exposed actions that are callable via the ``do_action()`` method.
[ "Get", "a", "list", "of", "exposed", "actions", "that", "are", "callable", "via", "the", "do_action", "()", "method", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L569-L586
jnrbsn/daemonocle
daemonocle/core.py
Daemon.get_action
def get_action(self, action): """Get a callable action.""" func_name = action.replace('-', '_') if not hasattr(self, func_name): # Function doesn't exist raise DaemonError( 'Invalid action "{action}"'.format(action=action)) func = getattr(self, func_name) if (not hasattr(func, '__call__') or getattr(func, '__daemonocle_exposed__', False) is not True): # Not a function or not exposed raise DaemonError( 'Invalid action "{action}"'.format(action=action)) return func
python
def get_action(self, action): """Get a callable action.""" func_name = action.replace('-', '_') if not hasattr(self, func_name): # Function doesn't exist raise DaemonError( 'Invalid action "{action}"'.format(action=action)) func = getattr(self, func_name) if (not hasattr(func, '__call__') or getattr(func, '__daemonocle_exposed__', False) is not True): # Not a function or not exposed raise DaemonError( 'Invalid action "{action}"'.format(action=action)) return func
[ "def", "get_action", "(", "self", ",", "action", ")", ":", "func_name", "=", "action", ".", "replace", "(", "'-'", ",", "'_'", ")", "if", "not", "hasattr", "(", "self", ",", "func_name", ")", ":", "# Function doesn't exist", "raise", "DaemonError", "(", ...
Get a callable action.
[ "Get", "a", "callable", "action", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L588-L603
jnrbsn/daemonocle
daemonocle/core.py
Daemon.reload
def reload(self): """Make the daemon reload itself.""" pid = self._read_pidfile() if pid is None or pid != os.getpid(): raise DaemonError( 'Daemon.reload() should only be called by the daemon process ' 'itself') # Copy the current environment new_environ = os.environ.copy() new_environ['DAEMONOCLE_RELOAD'] = 'true' # Start a new python process with the same arguments as this one subprocess.call( [sys.executable] + sys.argv, cwd=self._orig_workdir, env=new_environ) # Exit this process self._shutdown('Shutting down for reload')
python
def reload(self): """Make the daemon reload itself.""" pid = self._read_pidfile() if pid is None or pid != os.getpid(): raise DaemonError( 'Daemon.reload() should only be called by the daemon process ' 'itself') # Copy the current environment new_environ = os.environ.copy() new_environ['DAEMONOCLE_RELOAD'] = 'true' # Start a new python process with the same arguments as this one subprocess.call( [sys.executable] + sys.argv, cwd=self._orig_workdir, env=new_environ) # Exit this process self._shutdown('Shutting down for reload')
[ "def", "reload", "(", "self", ")", ":", "pid", "=", "self", ".", "_read_pidfile", "(", ")", "if", "pid", "is", "None", "or", "pid", "!=", "os", ".", "getpid", "(", ")", ":", "raise", "DaemonError", "(", "'Daemon.reload() should only be called by the daemon p...
Make the daemon reload itself.
[ "Make", "the", "daemon", "reload", "itself", "." ]
train
https://github.com/jnrbsn/daemonocle/blob/a1e09bc99608eab8dfe024c6741b7ecb7143f717/daemonocle/core.py#L610-L626
bovee/Aston
aston/trace/new_integrator.py
_get_windows
def _get_windows(peak_list): """ Given a list of peaks, bin them into windows. """ win_list = [] for t0, t1, hints in peak_list: p_w = (t0, t1) for w in win_list: if p_w[0] <= w[0][1] and p_w[1] >= w[0][0]: w[0] = (min(p_w[0], w[0][0]), max(p_w[1], w[0][1])) w[1].append((t0, t1, hints)) break else: win_list.append([p_w, [(t0, t1, hints)]]) return win_list
python
def _get_windows(peak_list): """ Given a list of peaks, bin them into windows. """ win_list = [] for t0, t1, hints in peak_list: p_w = (t0, t1) for w in win_list: if p_w[0] <= w[0][1] and p_w[1] >= w[0][0]: w[0] = (min(p_w[0], w[0][0]), max(p_w[1], w[0][1])) w[1].append((t0, t1, hints)) break else: win_list.append([p_w, [(t0, t1, hints)]]) return win_list
[ "def", "_get_windows", "(", "peak_list", ")", ":", "win_list", "=", "[", "]", "for", "t0", ",", "t1", ",", "hints", "in", "peak_list", ":", "p_w", "=", "(", "t0", ",", "t1", ")", "for", "w", "in", "win_list", ":", "if", "p_w", "[", "0", "]", "<...
Given a list of peaks, bin them into windows.
[ "Given", "a", "list", "of", "peaks", "bin", "them", "into", "windows", "." ]
train
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/new_integrator.py#L6-L20
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.add_file
def add_file(self, kitchen, recipe, message, api_file_key, file_contents): """ returns True for success or False for failure '/v2/recipe/create/<string:kitchenname>/<string:recipename>', methods=['PUT'] :param self: DKCloudAPI :param kitchen: basestring :param recipe: basestring -- kitchen name, basestring :param message: basestring message -- commit message, basestring :param api_file_key: -- file name and path to the file name, relative to the recipe root :param file_contents: -- character string of the recipe file to update :rtype: boolean """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parameter') return rc if api_file_key is None or isinstance(api_file_key, basestring) is False: rc.set(rc.DK_FAIL, 'issue with api_file_key parameter') return rc if file_contents is None or isinstance(file_contents, basestring) is False: rc.set(rc.DK_FAIL, 'issue with file_contents parameter') return rc pdict = dict() pdict[self.MESSAGE] = message pdict[self.FILEPATH] = api_file_key pdict[self.FILE] = file_contents url = '%s/v2/recipe/create/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe) try: response = requests.put(url, data=json.dumps(pdict), headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "add_file: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None) else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
python
def add_file(self, kitchen, recipe, message, api_file_key, file_contents): """ returns True for success or False for failure '/v2/recipe/create/<string:kitchenname>/<string:recipename>', methods=['PUT'] :param self: DKCloudAPI :param kitchen: basestring :param recipe: basestring -- kitchen name, basestring :param message: basestring message -- commit message, basestring :param api_file_key: -- file name and path to the file name, relative to the recipe root :param file_contents: -- character string of the recipe file to update :rtype: boolean """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parameter') return rc if api_file_key is None or isinstance(api_file_key, basestring) is False: rc.set(rc.DK_FAIL, 'issue with api_file_key parameter') return rc if file_contents is None or isinstance(file_contents, basestring) is False: rc.set(rc.DK_FAIL, 'issue with file_contents parameter') return rc pdict = dict() pdict[self.MESSAGE] = message pdict[self.FILEPATH] = api_file_key pdict[self.FILE] = file_contents url = '%s/v2/recipe/create/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe) try: response = requests.put(url, data=json.dumps(pdict), headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "add_file: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None) else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
[ "def", "add_file", "(", "self", ",", "kitchen", ",", "recipe", ",", "message", ",", "api_file_key", ",", "file_contents", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen", ",", "basestring", ...
returns True for success or False for failure '/v2/recipe/create/<string:kitchenname>/<string:recipename>', methods=['PUT'] :param self: DKCloudAPI :param kitchen: basestring :param recipe: basestring -- kitchen name, basestring :param message: basestring message -- commit message, basestring :param api_file_key: -- file name and path to the file name, relative to the recipe root :param file_contents: -- character string of the recipe file to update :rtype: boolean
[ "returns", "True", "for", "success", "or", "False", "for", "failure", "/", "v2", "/", "recipe", "/", "create", "/", "<string", ":", "kitchenname", ">", "/", "<string", ":", "recipename", ">", "methods", "=", "[", "PUT", "]", ":", "param", "self", ":", ...
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L657-L701
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.get_compiled_serving
def get_compiled_serving(self, kitchen, recipe_name, variation_name): """ get the compiled version of arecipe with variables applied for a specific variation in a kitchen returns a dictionary '/v2/servings/compiled/get/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['GET'] :param self: DKCloudAPI :param kitchen: basestring :param recipe_name: basestring -- kitchen name, basestring :param variation_name: basestring message -- name of variation, basestring :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc if recipe_name is None or isinstance(recipe_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe_name') return rc if variation_name is None or isinstance(variation_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with variation_name') return rc url = '%s/v2/servings/compiled/get/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe_name, variation_name) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: rc.set(rc.DK_FAIL, "get_compiled_serving: exception: %s" % str(c)) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None, rdict[rdict.keys()[0]]) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
python
def get_compiled_serving(self, kitchen, recipe_name, variation_name): """ get the compiled version of arecipe with variables applied for a specific variation in a kitchen returns a dictionary '/v2/servings/compiled/get/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['GET'] :param self: DKCloudAPI :param kitchen: basestring :param recipe_name: basestring -- kitchen name, basestring :param variation_name: basestring message -- name of variation, basestring :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc if recipe_name is None or isinstance(recipe_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe_name') return rc if variation_name is None or isinstance(variation_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with variation_name') return rc url = '%s/v2/servings/compiled/get/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe_name, variation_name) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: rc.set(rc.DK_FAIL, "get_compiled_serving: exception: %s" % str(c)) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None, rdict[rdict.keys()[0]]) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
[ "def", "get_compiled_serving", "(", "self", ",", "kitchen", ",", "recipe_name", ",", "variation_name", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen", ",", "basestring", ")", "is", "False", ...
get the compiled version of arecipe with variables applied for a specific variation in a kitchen returns a dictionary '/v2/servings/compiled/get/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['GET'] :param self: DKCloudAPI :param kitchen: basestring :param recipe_name: basestring -- kitchen name, basestring :param variation_name: basestring message -- name of variation, basestring :rtype: dict
[ "get", "the", "compiled", "version", "of", "arecipe", "with", "variables", "applied", "for", "a", "specific", "variation", "in", "a", "kitchen", "returns", "a", "dictionary", "/", "v2", "/", "servings", "/", "compiled", "/", "get", "/", "<string", ":", "ki...
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L740-L776
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.merge_kitchens_improved
def merge_kitchens_improved(self, from_kitchen, to_kitchen, resolved_conflicts=None): """ merges kitchens '/v2/kitchen/merge/<string:kitchenname>/<string:kitchenname>', methods=['POST'] :param resolved_conflicts: :param self: DKCloudAPI :param from_kitchen: string :param to_kitchen: string :rtype: dict """ rc = DKReturnCode() if from_kitchen is None or isinstance(from_kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with from kitchen') return rc if to_kitchen is None or isinstance(to_kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with to kitchen') return rc url = '%s/v2/kitchen/merge/%s/%s' % (self.get_url_for_direct_rest_call(), from_kitchen, to_kitchen) try: if resolved_conflicts is not None and len(resolved_conflicts) > 0: data = dict() data['resolved_conflicts'] = resolved_conflicts response = requests.post(url, data=json.dumps(data), headers=self._get_common_headers()) else: response = requests.post(url, headers=self._get_common_headers()) rdict = self._get_json(response) except (RequestException, ValueError, TypeError), c: rc.set("merge_kitchens: exception: %s" % str(c)) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None, rdict) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
python
def merge_kitchens_improved(self, from_kitchen, to_kitchen, resolved_conflicts=None): """ merges kitchens '/v2/kitchen/merge/<string:kitchenname>/<string:kitchenname>', methods=['POST'] :param resolved_conflicts: :param self: DKCloudAPI :param from_kitchen: string :param to_kitchen: string :rtype: dict """ rc = DKReturnCode() if from_kitchen is None or isinstance(from_kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with from kitchen') return rc if to_kitchen is None or isinstance(to_kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with to kitchen') return rc url = '%s/v2/kitchen/merge/%s/%s' % (self.get_url_for_direct_rest_call(), from_kitchen, to_kitchen) try: if resolved_conflicts is not None and len(resolved_conflicts) > 0: data = dict() data['resolved_conflicts'] = resolved_conflicts response = requests.post(url, data=json.dumps(data), headers=self._get_common_headers()) else: response = requests.post(url, headers=self._get_common_headers()) rdict = self._get_json(response) except (RequestException, ValueError, TypeError), c: rc.set("merge_kitchens: exception: %s" % str(c)) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None, rdict) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
[ "def", "merge_kitchens_improved", "(", "self", ",", "from_kitchen", ",", "to_kitchen", ",", "resolved_conflicts", "=", "None", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "from_kitchen", "is", "None", "or", "isinstance", "(", "from_kitchen", ",", "bas...
merges kitchens '/v2/kitchen/merge/<string:kitchenname>/<string:kitchenname>', methods=['POST'] :param resolved_conflicts: :param self: DKCloudAPI :param from_kitchen: string :param to_kitchen: string :rtype: dict
[ "merges", "kitchens", "/", "v2", "/", "kitchen", "/", "merge", "/", "<string", ":", "kitchenname", ">", "/", "<string", ":", "kitchenname", ">", "methods", "=", "[", "POST", "]", ":", "param", "resolved_conflicts", ":", ":", "param", "self", ":", "DKClou...
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L778-L813
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.merge_file
def merge_file(self, kitchen, recipe, file_path, file_contents, orig_head, last_file_sha): """ Returns the result of merging a local file with the latest version on the remote. This does not cause any side-effects on the server, and no actual merge is performed in the remote repo. /v2/file/merge/<string:kitchenname>/<string:recipename>/<path:filepath>, methods=['POST'] :param kitchen: name of the kitchen where this file lives :param recipe: name of the recipe that owns this file :param file_path: path to the file, relative to the recipe :param file_contents: contents of the file :param orig_head: sha of commit head of the branch when this file was obtained. :param last_file_sha: The sha of the file when it was obtained from the server. :return: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False or \ recipe is None or isinstance(recipe, basestring) is False or \ file_path is None or isinstance(file_path, basestring) is False or \ orig_head is None or isinstance(orig_head, basestring) is False or \ last_file_sha is None or isinstance(last_file_sha, basestring) is False or \ file_contents is None: rc.set(rc.DK_FAIL, 'One or more parameters is invalid. ') return rc params = dict() params['orig_head'] = orig_head params['last_file_sha'] = last_file_sha params['content'] = file_contents adjusted_file_path = file_path url = '%s/v2/file/merge/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe, adjusted_file_path) try: response = requests.post(url, data=json.dumps(params), headers=self._get_common_headers()) rdict = self._get_json(response) except (RequestException, ValueError, TypeError), c: print "merge_file: exception: %s" % str(c) return None if DKCloudAPI._valid_response(response) is True and rdict is not None and isinstance(rdict, dict) is True: rc.set(rc.DK_SUCCESS, None, rdict) return rc else: rc.set(rc.DK_FAIL, str(rdict)) return rc
python
def merge_file(self, kitchen, recipe, file_path, file_contents, orig_head, last_file_sha): """ Returns the result of merging a local file with the latest version on the remote. This does not cause any side-effects on the server, and no actual merge is performed in the remote repo. /v2/file/merge/<string:kitchenname>/<string:recipename>/<path:filepath>, methods=['POST'] :param kitchen: name of the kitchen where this file lives :param recipe: name of the recipe that owns this file :param file_path: path to the file, relative to the recipe :param file_contents: contents of the file :param orig_head: sha of commit head of the branch when this file was obtained. :param last_file_sha: The sha of the file when it was obtained from the server. :return: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False or \ recipe is None or isinstance(recipe, basestring) is False or \ file_path is None or isinstance(file_path, basestring) is False or \ orig_head is None or isinstance(orig_head, basestring) is False or \ last_file_sha is None or isinstance(last_file_sha, basestring) is False or \ file_contents is None: rc.set(rc.DK_FAIL, 'One or more parameters is invalid. ') return rc params = dict() params['orig_head'] = orig_head params['last_file_sha'] = last_file_sha params['content'] = file_contents adjusted_file_path = file_path url = '%s/v2/file/merge/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe, adjusted_file_path) try: response = requests.post(url, data=json.dumps(params), headers=self._get_common_headers()) rdict = self._get_json(response) except (RequestException, ValueError, TypeError), c: print "merge_file: exception: %s" % str(c) return None if DKCloudAPI._valid_response(response) is True and rdict is not None and isinstance(rdict, dict) is True: rc.set(rc.DK_SUCCESS, None, rdict) return rc else: rc.set(rc.DK_FAIL, str(rdict)) return rc
[ "def", "merge_file", "(", "self", ",", "kitchen", ",", "recipe", ",", "file_path", ",", "file_contents", ",", "orig_head", ",", "last_file_sha", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen...
Returns the result of merging a local file with the latest version on the remote. This does not cause any side-effects on the server, and no actual merge is performed in the remote repo. /v2/file/merge/<string:kitchenname>/<string:recipename>/<path:filepath>, methods=['POST'] :param kitchen: name of the kitchen where this file lives :param recipe: name of the recipe that owns this file :param file_path: path to the file, relative to the recipe :param file_contents: contents of the file :param orig_head: sha of commit head of the branch when this file was obtained. :param last_file_sha: The sha of the file when it was obtained from the server. :return: dict
[ "Returns", "the", "result", "of", "merging", "a", "local", "file", "with", "the", "latest", "version", "on", "the", "remote", ".", "This", "does", "not", "cause", "any", "side", "-", "effects", "on", "the", "server", "and", "no", "actual", "merge", "is",...
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L815-L855
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.recipe_status
def recipe_status(self, kitchen, recipe, local_dir=None): """ gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parameter') return rc url = '%s/v2/recipe/tree/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "get_recipe: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): # Now get the local sha. if local_dir is None: check_path = os.getcwd() else: if os.path.isdir(local_dir) is False: print 'Local path %s does not exist' % local_dir return None else: check_path = local_dir local_sha = get_directory_sha(check_path) remote_sha = rdict['recipes'][recipe] rv = compare_sha(remote_sha, local_sha) rc.set(rc.DK_SUCCESS, None, rv) else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
python
def recipe_status(self, kitchen, recipe, local_dir=None): """ gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parameter') return rc url = '%s/v2/recipe/tree/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "get_recipe: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): # Now get the local sha. if local_dir is None: check_path = os.getcwd() else: if os.path.isdir(local_dir) is False: print 'Local path %s does not exist' % local_dir return None else: check_path = local_dir local_sha = get_directory_sha(check_path) remote_sha = rdict['recipes'][recipe] rv = compare_sha(remote_sha, local_sha) rc.set(rc.DK_SUCCESS, None, rv) else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
[ "def", "recipe_status", "(", "self", ",", "kitchen", ",", "recipe", ",", "local_dir", "=", "None", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen", ",", "basestring", ")", "is", "False", ...
gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict
[ "gets", "the", "status", "of", "a", "recipe", ":", "param", "self", ":", "DKCloudAPI", ":", "param", "kitchen", ":", "string", ":", "param", "recipe", ":", "string", ":", "param", "local_dir", ":", "string", "--", ":", "rtype", ":", "dict" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L858-L901
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.recipe_tree
def recipe_tree(self, kitchen, recipe): """ gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parameter') return rc url = '%s/v2/recipe/tree/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "recipe_tree: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): remote_sha = rdict['recipes'][recipe] rc.set(rc.DK_SUCCESS, None, remote_sha) else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
python
def recipe_tree(self, kitchen, recipe): """ gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :rtype: dict """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc if recipe is None or isinstance(recipe, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe parameter') return rc url = '%s/v2/recipe/tree/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "recipe_tree: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): remote_sha = rdict['recipes'][recipe] rc.set(rc.DK_SUCCESS, None, remote_sha) else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
[ "def", "recipe_tree", "(", "self", ",", "kitchen", ",", "recipe", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen", ",", "basestring", ")", "is", "False", ":", "rc", ".", "set", "(", "rc...
gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :rtype: dict
[ "gets", "the", "status", "of", "a", "recipe", ":", "param", "self", ":", "DKCloudAPI", ":", "param", "kitchen", ":", "string", ":", "param", "recipe", ":", "string", ":", "rtype", ":", "dict" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L904-L935
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.create_order
def create_order(self, kitchen, recipe_name, variation_name, node_name=None): """ Full graph '/v2/order/create/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['PUT'] Single node '/v2/order/create/onenode/<string:kitchenname>/<string:recipename>/<string:variationname>/<string:nodename', methods=['PUT'] """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc if recipe_name is None or isinstance(recipe_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe_name') return rc if variation_name is None or isinstance(variation_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with variation_name') return rc if node_name is None: url = '%s/v2/order/create/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe_name, variation_name) else: url = '%s/v2/order/create/onenode/%s/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe_name, variation_name, node_name) try: response = requests.put(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError), c: s = "create_order: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None, rdict['serving_chronos_id']) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
python
def create_order(self, kitchen, recipe_name, variation_name, node_name=None): """ Full graph '/v2/order/create/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['PUT'] Single node '/v2/order/create/onenode/<string:kitchenname>/<string:recipename>/<string:variationname>/<string:nodename', methods=['PUT'] """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc if recipe_name is None or isinstance(recipe_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with recipe_name') return rc if variation_name is None or isinstance(variation_name, basestring) is False: rc.set(rc.DK_FAIL, 'issue with variation_name') return rc if node_name is None: url = '%s/v2/order/create/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe_name, variation_name) else: url = '%s/v2/order/create/onenode/%s/%s/%s/%s' % (self.get_url_for_direct_rest_call(), kitchen, recipe_name, variation_name, node_name) try: response = requests.put(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError), c: s = "create_order: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): rc.set(rc.DK_SUCCESS, None, rdict['serving_chronos_id']) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
[ "def", "create_order", "(", "self", ",", "kitchen", ",", "recipe_name", ",", "variation_name", ",", "node_name", "=", "None", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen", ",", "basestring...
Full graph '/v2/order/create/<string:kitchenname>/<string:recipename>/<string:variationname>', methods=['PUT'] Single node '/v2/order/create/onenode/<string:kitchenname>/<string:recipename>/<string:variationname>/<string:nodename', methods=['PUT']
[ "Full", "graph", "/", "v2", "/", "order", "/", "create", "/", "<string", ":", "kitchenname", ">", "/", "<string", ":", "recipename", ">", "/", "<string", ":", "variationname", ">", "methods", "=", "[", "PUT", "]" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L941-L984
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.orderrun_detail
def orderrun_detail(self, kitchen, pdict, return_all_data=False): """ api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST']) :param self: DKCloudAPI :param kitchen: string :param pdict: dict :param return_all_data: boolean :rtype: DKReturnCode """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc url = '%s/v2/order/details/%s' % (self.get_url_for_direct_rest_call(), kitchen) try: response = requests.post(url, data=json.dumps(pdict), headers=self._get_common_headers()) rdict = self._get_json(response) if False: import pickle pickle.dump(rdict, open("files/orderrun_detail.p", "wb")) pass except (RequestException, ValueError), c: s = "orderrun_detail: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): if return_all_data is False: rc.set(rc.DK_SUCCESS, None, rdict['servings']) else: rc.set(rc.DK_SUCCESS, None, rdict) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
python
def orderrun_detail(self, kitchen, pdict, return_all_data=False): """ api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST']) :param self: DKCloudAPI :param kitchen: string :param pdict: dict :param return_all_data: boolean :rtype: DKReturnCode """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen') return rc url = '%s/v2/order/details/%s' % (self.get_url_for_direct_rest_call(), kitchen) try: response = requests.post(url, data=json.dumps(pdict), headers=self._get_common_headers()) rdict = self._get_json(response) if False: import pickle pickle.dump(rdict, open("files/orderrun_detail.p", "wb")) pass except (RequestException, ValueError), c: s = "orderrun_detail: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if DKCloudAPI._valid_response(response): if return_all_data is False: rc.set(rc.DK_SUCCESS, None, rdict['servings']) else: rc.set(rc.DK_SUCCESS, None, rdict) return rc else: arc = DKAPIReturnCode(rdict, response) rc.set(rc.DK_FAIL, arc.get_message()) return rc
[ "def", "orderrun_detail", "(", "self", ",", "kitchen", ",", "pdict", ",", "return_all_data", "=", "False", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen", ",", "basestring", ")", "is", "Fa...
api.add_resource(OrderDetailsV2, '/v2/order/details/<string:kitchenname>', methods=['POST']) :param self: DKCloudAPI :param kitchen: string :param pdict: dict :param return_all_data: boolean :rtype: DKReturnCode
[ "api", ".", "add_resource", "(", "OrderDetailsV2", "/", "v2", "/", "order", "/", "details", "/", "<string", ":", "kitchenname", ">", "methods", "=", "[", "POST", "]", ")", ":", "param", "self", ":", "DKCloudAPI", ":", "param", "kitchen", ":", "string", ...
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L1021-L1057
DataKitchen/DKCloudCommand
DKCloudCommand/modules/DKCloudAPI.py
DKCloudAPI.list_order
def list_order(self, kitchen, save_to_file=None): """ List the orders for a kitchen or recipe """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc url = '%s/v2/order/status/%s' % (self.get_url_for_direct_rest_call(), kitchen) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "get_recipe: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if not DKCloudAPI._valid_response(response): arc = DKAPIReturnCode(rdict) rc.set(rc.DK_FAIL, arc.get_message()) else: if save_to_file is not None: import pickle pickle.dump(rdict, open(save_to_file, "wb")) rc.set(rc.DK_SUCCESS, None, rdict) return rc
python
def list_order(self, kitchen, save_to_file=None): """ List the orders for a kitchen or recipe """ rc = DKReturnCode() if kitchen is None or isinstance(kitchen, basestring) is False: rc.set(rc.DK_FAIL, 'issue with kitchen parameter') return rc url = '%s/v2/order/status/%s' % (self.get_url_for_direct_rest_call(), kitchen) try: response = requests.get(url, headers=self._get_common_headers()) rdict = self._get_json(response) pass except (RequestException, ValueError, TypeError), c: s = "get_recipe: exception: %s" % str(c) rc.set(rc.DK_FAIL, s) return rc if not DKCloudAPI._valid_response(response): arc = DKAPIReturnCode(rdict) rc.set(rc.DK_FAIL, arc.get_message()) else: if save_to_file is not None: import pickle pickle.dump(rdict, open(save_to_file, "wb")) rc.set(rc.DK_SUCCESS, None, rdict) return rc
[ "def", "list_order", "(", "self", ",", "kitchen", ",", "save_to_file", "=", "None", ")", ":", "rc", "=", "DKReturnCode", "(", ")", "if", "kitchen", "is", "None", "or", "isinstance", "(", "kitchen", ",", "basestring", ")", "is", "False", ":", "rc", ".",...
List the orders for a kitchen or recipe
[ "List", "the", "orders", "for", "a", "kitchen", "or", "recipe" ]
train
https://github.com/DataKitchen/DKCloudCommand/blob/1cf9cb08ab02f063eef6b5c4b327af142991daa3/DKCloudCommand/modules/DKCloudAPI.py#L1059-L1086
Locu/chronology
metis/metis/core/execute/utils.py
_date_trunc
def _date_trunc(value, timeframe): """ A date flooring function. Returns the closest datetime to the current one that aligns to timeframe. For example, _date_trunc('2014-08-13 05:00:00', DateTrunc.Unit.MONTH) will return a Kronos time representing 2014-08-01 00:00:00. """ if isinstance(value, types.StringTypes): value = parse(value) return_as_str = True else: value = kronos_time_to_datetime(value) return_as_str = False timeframes = { DateTrunc.Unit.SECOND: (lambda dt: dt - timedelta(microseconds=dt.microsecond)), DateTrunc.Unit.MINUTE: (lambda dt: dt - timedelta(seconds=dt.second, microseconds=dt.microsecond)), DateTrunc.Unit.HOUR: (lambda dt: dt - timedelta(minutes=dt.minute, seconds=dt.second, microseconds=dt.microsecond)), DateTrunc.Unit.DAY: lambda dt: dt.date(), DateTrunc.Unit.WEEK: lambda dt: dt.date() - timedelta(days=dt.weekday()), DateTrunc.Unit.MONTH: lambda dt: datetime(dt.year, dt.month, 1), DateTrunc.Unit.YEAR: lambda dt: datetime(dt.year, 1, 1) } value = timeframes[timeframe](value) if return_as_str: return value.isoformat() return datetime_to_kronos_time(value)
python
def _date_trunc(value, timeframe): """ A date flooring function. Returns the closest datetime to the current one that aligns to timeframe. For example, _date_trunc('2014-08-13 05:00:00', DateTrunc.Unit.MONTH) will return a Kronos time representing 2014-08-01 00:00:00. """ if isinstance(value, types.StringTypes): value = parse(value) return_as_str = True else: value = kronos_time_to_datetime(value) return_as_str = False timeframes = { DateTrunc.Unit.SECOND: (lambda dt: dt - timedelta(microseconds=dt.microsecond)), DateTrunc.Unit.MINUTE: (lambda dt: dt - timedelta(seconds=dt.second, microseconds=dt.microsecond)), DateTrunc.Unit.HOUR: (lambda dt: dt - timedelta(minutes=dt.minute, seconds=dt.second, microseconds=dt.microsecond)), DateTrunc.Unit.DAY: lambda dt: dt.date(), DateTrunc.Unit.WEEK: lambda dt: dt.date() - timedelta(days=dt.weekday()), DateTrunc.Unit.MONTH: lambda dt: datetime(dt.year, dt.month, 1), DateTrunc.Unit.YEAR: lambda dt: datetime(dt.year, 1, 1) } value = timeframes[timeframe](value) if return_as_str: return value.isoformat() return datetime_to_kronos_time(value)
[ "def", "_date_trunc", "(", "value", ",", "timeframe", ")", ":", "if", "isinstance", "(", "value", ",", "types", ".", "StringTypes", ")", ":", "value", "=", "parse", "(", "value", ")", "return_as_str", "=", "True", "else", ":", "value", "=", "kronos_time_...
A date flooring function. Returns the closest datetime to the current one that aligns to timeframe. For example, _date_trunc('2014-08-13 05:00:00', DateTrunc.Unit.MONTH) will return a Kronos time representing 2014-08-01 00:00:00.
[ "A", "date", "flooring", "function", "." ]
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/metis/metis/core/execute/utils.py#L54-L86
Locu/chronology
metis/metis/core/execute/utils.py
_date_part
def _date_part(value, part): """ Returns a portion of a datetime. Returns the portion of a datetime represented by timeframe. For example, _date_part('2014-08-13 05:00:00', DatePart.Unit.WEEK_DAY) will return 2, for Wednesday. """ if isinstance(value, types.StringTypes): value = parse(value) else: value = kronos_time_to_datetime(value) parts = { DatePart.Unit.SECOND: lambda dt: dt.second, DatePart.Unit.MINUTE: lambda dt: dt.minute, DatePart.Unit.HOUR: lambda dt: dt.hour, DatePart.Unit.DAY: lambda dt: dt.day, DatePart.Unit.MONTH: lambda dt: dt.month, DatePart.Unit.YEAR: lambda dt: dt.year, DatePart.Unit.WEEK_DAY: lambda dt: dt.weekday(), } result = parts[part](value) return result
python
def _date_part(value, part): """ Returns a portion of a datetime. Returns the portion of a datetime represented by timeframe. For example, _date_part('2014-08-13 05:00:00', DatePart.Unit.WEEK_DAY) will return 2, for Wednesday. """ if isinstance(value, types.StringTypes): value = parse(value) else: value = kronos_time_to_datetime(value) parts = { DatePart.Unit.SECOND: lambda dt: dt.second, DatePart.Unit.MINUTE: lambda dt: dt.minute, DatePart.Unit.HOUR: lambda dt: dt.hour, DatePart.Unit.DAY: lambda dt: dt.day, DatePart.Unit.MONTH: lambda dt: dt.month, DatePart.Unit.YEAR: lambda dt: dt.year, DatePart.Unit.WEEK_DAY: lambda dt: dt.weekday(), } result = parts[part](value) return result
[ "def", "_date_part", "(", "value", ",", "part", ")", ":", "if", "isinstance", "(", "value", ",", "types", ".", "StringTypes", ")", ":", "value", "=", "parse", "(", "value", ")", "else", ":", "value", "=", "kronos_time_to_datetime", "(", "value", ")", "...
Returns a portion of a datetime. Returns the portion of a datetime represented by timeframe. For example, _date_part('2014-08-13 05:00:00', DatePart.Unit.WEEK_DAY) will return 2, for Wednesday.
[ "Returns", "a", "portion", "of", "a", "datetime", "." ]
train
https://github.com/Locu/chronology/blob/0edf3ee3286c76e242cbf92436ffa9c836b428e2/metis/metis/core/execute/utils.py#L89-L111
ask/redish
redish/client.py
Client.List
def List(self, name, initial=None): """The list datatype. :param name: The name of the list. :keyword initial: Initial contents of the list. See :class:`redish.types.List`. """ return types.List(name, self.api, initial=initial)
python
def List(self, name, initial=None): """The list datatype. :param name: The name of the list. :keyword initial: Initial contents of the list. See :class:`redish.types.List`. """ return types.List(name, self.api, initial=initial)
[ "def", "List", "(", "self", ",", "name", ",", "initial", "=", "None", ")", ":", "return", "types", ".", "List", "(", "name", ",", "self", ".", "api", ",", "initial", "=", "initial", ")" ]
The list datatype. :param name: The name of the list. :keyword initial: Initial contents of the list. See :class:`redish.types.List`.
[ "The", "list", "datatype", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L45-L54
ask/redish
redish/client.py
Client.Set
def Set(self, name, initial=None): """The set datatype. :param name: The name of the set. :keyword initial: Initial members of the set. See :class:`redish.types.Set`. """ return types.Set(name, self.api, initial)
python
def Set(self, name, initial=None): """The set datatype. :param name: The name of the set. :keyword initial: Initial members of the set. See :class:`redish.types.Set`. """ return types.Set(name, self.api, initial)
[ "def", "Set", "(", "self", ",", "name", ",", "initial", "=", "None", ")", ":", "return", "types", ".", "Set", "(", "name", ",", "self", ".", "api", ",", "initial", ")" ]
The set datatype. :param name: The name of the set. :keyword initial: Initial members of the set. See :class:`redish.types.Set`.
[ "The", "set", "datatype", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L56-L65
ask/redish
redish/client.py
Client.SortedSet
def SortedSet(self, name, initial=None): """The sorted set datatype. :param name: The name of the sorted set. :param initial: Initial members of the set as an iterable of ``(element, score)`` tuples. See :class:`redish.types.SortedSet`. """ return types.SortedSet(name, self.api, initial)
python
def SortedSet(self, name, initial=None): """The sorted set datatype. :param name: The name of the sorted set. :param initial: Initial members of the set as an iterable of ``(element, score)`` tuples. See :class:`redish.types.SortedSet`. """ return types.SortedSet(name, self.api, initial)
[ "def", "SortedSet", "(", "self", ",", "name", ",", "initial", "=", "None", ")", ":", "return", "types", ".", "SortedSet", "(", "name", ",", "self", ".", "api", ",", "initial", ")" ]
The sorted set datatype. :param name: The name of the sorted set. :param initial: Initial members of the set as an iterable of ``(element, score)`` tuples. See :class:`redish.types.SortedSet`.
[ "The", "sorted", "set", "datatype", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L68-L78
ask/redish
redish/client.py
Client.Dict
def Dict(self, name, initial=None, **extra): """The dictionary datatype (Hash). :param name: The name of the dictionary. :keyword initial: Initial contents. :keyword \*\*extra: Initial contents as keyword arguments. The ``initial``, and ``**extra`` keyword arguments will be merged (keyword arguments has priority). See :class:`redish.types.Dict`. """ return types.Dict(name, self.api, initial=initial, **extra)
python
def Dict(self, name, initial=None, **extra): """The dictionary datatype (Hash). :param name: The name of the dictionary. :keyword initial: Initial contents. :keyword \*\*extra: Initial contents as keyword arguments. The ``initial``, and ``**extra`` keyword arguments will be merged (keyword arguments has priority). See :class:`redish.types.Dict`. """ return types.Dict(name, self.api, initial=initial, **extra)
[ "def", "Dict", "(", "self", ",", "name", ",", "initial", "=", "None", ",", "*", "*", "extra", ")", ":", "return", "types", ".", "Dict", "(", "name", ",", "self", ".", "api", ",", "initial", "=", "initial", ",", "*", "*", "extra", ")" ]
The dictionary datatype (Hash). :param name: The name of the dictionary. :keyword initial: Initial contents. :keyword \*\*extra: Initial contents as keyword arguments. The ``initial``, and ``**extra`` keyword arguments will be merged (keyword arguments has priority). See :class:`redish.types.Dict`.
[ "The", "dictionary", "datatype", "(", "Hash", ")", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L80-L93
ask/redish
redish/client.py
Client.Queue
def Queue(self, name, initial=None, maxsize=None): """The queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.Queue`. """ return types.Queue(name, self.api, initial=initial, maxsize=maxsize)
python
def Queue(self, name, initial=None, maxsize=None): """The queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.Queue`. """ return types.Queue(name, self.api, initial=initial, maxsize=maxsize)
[ "def", "Queue", "(", "self", ",", "name", ",", "initial", "=", "None", ",", "maxsize", "=", "None", ")", ":", "return", "types", ".", "Queue", "(", "name", ",", "self", ".", "api", ",", "initial", "=", "initial", ",", "maxsize", "=", "maxsize", ")"...
The queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.Queue`.
[ "The", "queue", "datatype", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L95-L104
ask/redish
redish/client.py
Client.LifoQueue
def LifoQueue(self, name, initial=None, maxsize=None): """The LIFO queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.LifoQueue`. """ return types.LifoQueue(name, self.api, initial=initial, maxsize=maxsize)
python
def LifoQueue(self, name, initial=None, maxsize=None): """The LIFO queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.LifoQueue`. """ return types.LifoQueue(name, self.api, initial=initial, maxsize=maxsize)
[ "def", "LifoQueue", "(", "self", ",", "name", ",", "initial", "=", "None", ",", "maxsize", "=", "None", ")", ":", "return", "types", ".", "LifoQueue", "(", "name", ",", "self", ".", "api", ",", "initial", "=", "initial", ",", "maxsize", "=", "maxsize...
The LIFO queue datatype. :param name: The name of the queue. :keyword initial: Initial items in the queue. See :class:`redish.types.LifoQueue`.
[ "The", "LIFO", "queue", "datatype", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L106-L116
ask/redish
redish/client.py
Client.update
def update(self, mapping): """Update database with the key/values from a :class:`dict`.""" return self.api.mset(dict((key, self.prepare_value(value)) for key, value in mapping.items()))
python
def update(self, mapping): """Update database with the key/values from a :class:`dict`.""" return self.api.mset(dict((key, self.prepare_value(value)) for key, value in mapping.items()))
[ "def", "update", "(", "self", ",", "mapping", ")", ":", "return", "self", ".", "api", ".", "mset", "(", "dict", "(", "(", "key", ",", "self", ".", "prepare_value", "(", "value", ")", ")", "for", "key", ",", "value", "in", "mapping", ".", "items", ...
Update database with the key/values from a :class:`dict`.
[ "Update", "database", "with", "the", "key", "/", "values", "from", "a", ":", "class", ":", "dict", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L130-L133
ask/redish
redish/client.py
Client.rename
def rename(self, old_name, new_name): """Rename key to a new name.""" try: self.api.rename(mkey(old_name), mkey(new_name)) except ResponseError, exc: if "no such key" in exc.args: raise KeyError(old_name) raise
python
def rename(self, old_name, new_name): """Rename key to a new name.""" try: self.api.rename(mkey(old_name), mkey(new_name)) except ResponseError, exc: if "no such key" in exc.args: raise KeyError(old_name) raise
[ "def", "rename", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "try", ":", "self", ".", "api", ".", "rename", "(", "mkey", "(", "old_name", ")", ",", "mkey", "(", "new_name", ")", ")", "except", "ResponseError", ",", "exc", ":", "if", "\...
Rename key to a new name.
[ "Rename", "key", "to", "a", "new", "name", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L135-L142
ask/redish
redish/client.py
Client.iteritems
def iteritems(self, pattern="*"): """An iterator over all the ``(key, value)`` items in the database, or where the keys matches ``pattern``.""" for key in self.keys(pattern): yield (key, self[key])
python
def iteritems(self, pattern="*"): """An iterator over all the ``(key, value)`` items in the database, or where the keys matches ``pattern``.""" for key in self.keys(pattern): yield (key, self[key])
[ "def", "iteritems", "(", "self", ",", "pattern", "=", "\"*\"", ")", ":", "for", "key", "in", "self", ".", "keys", "(", "pattern", ")", ":", "yield", "(", "key", ",", "self", "[", "key", "]", ")" ]
An iterator over all the ``(key, value)`` items in the database, or where the keys matches ``pattern``.
[ "An", "iterator", "over", "all", "the", "(", "key", "value", ")", "items", "in", "the", "database", "or", "where", "the", "keys", "matches", "pattern", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L154-L158
ask/redish
redish/client.py
Client.pop
def pop(self, name): """Get and remove key from database (atomic).""" name = mkey(name) temp = mkey((name, "__poptmp__")) self.rename(name, temp) value = self[temp] del(self[temp]) return value
python
def pop(self, name): """Get and remove key from database (atomic).""" name = mkey(name) temp = mkey((name, "__poptmp__")) self.rename(name, temp) value = self[temp] del(self[temp]) return value
[ "def", "pop", "(", "self", ",", "name", ")", ":", "name", "=", "mkey", "(", "name", ")", "temp", "=", "mkey", "(", "(", "name", ",", "\"__poptmp__\"", ")", ")", "self", ".", "rename", "(", "name", ",", "temp", ")", "value", "=", "self", "[", "t...
Get and remove key from database (atomic).
[ "Get", "and", "remove", "key", "from", "database", "(", "atomic", ")", "." ]
train
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L176-L183
timdiels/pytil
pytil/write.py
csv
def csv(file, *args, **kwargs): ''' Write CSV file. Parameters ---------- file : Path *args csv.DictWriter args (except the f arg) **kwargs csv.DictWriter args Examples -------- with write.csv(file) as writer: writer.writerow((1,2,3)) ''' with file.open('w', newline='') as f: yield DictWriter(f, *args, **kwargs)
python
def csv(file, *args, **kwargs): ''' Write CSV file. Parameters ---------- file : Path *args csv.DictWriter args (except the f arg) **kwargs csv.DictWriter args Examples -------- with write.csv(file) as writer: writer.writerow((1,2,3)) ''' with file.open('w', newline='') as f: yield DictWriter(f, *args, **kwargs)
[ "def", "csv", "(", "file", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "file", ".", "open", "(", "'w'", ",", "newline", "=", "''", ")", "as", "f", ":", "yield", "DictWriter", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs...
Write CSV file. Parameters ---------- file : Path *args csv.DictWriter args (except the f arg) **kwargs csv.DictWriter args Examples -------- with write.csv(file) as writer: writer.writerow((1,2,3))
[ "Write", "CSV", "file", "." ]
train
https://github.com/timdiels/pytil/blob/086a3f8d52caecdd9d1c9f66c8d8a6d38667b00b/pytil/write.py#L29-L47
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
State.todict
def todict(self): """Returns a dictionary fully representing the state of this object """ return {"f_key": hb_encode(self.f_key), "alpha_key": hb_encode(self.alpha_key), "chunks": self.chunks, "encrypted": self.encrypted, "iv": hb_encode(self.iv), "hmac": hb_encode(self.hmac)}
python
def todict(self): """Returns a dictionary fully representing the state of this object """ return {"f_key": hb_encode(self.f_key), "alpha_key": hb_encode(self.alpha_key), "chunks": self.chunks, "encrypted": self.encrypted, "iv": hb_encode(self.iv), "hmac": hb_encode(self.hmac)}
[ "def", "todict", "(", "self", ")", ":", "return", "{", "\"f_key\"", ":", "hb_encode", "(", "self", ".", "f_key", ")", ",", "\"alpha_key\"", ":", "hb_encode", "(", "self", ".", "alpha_key", ")", ",", "\"chunks\"", ":", "self", ".", "chunks", ",", "\"enc...
Returns a dictionary fully representing the state of this object
[ "Returns", "a", "dictionary", "fully", "representing", "the", "state", "of", "this", "object" ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L125-L133
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
State.fromdict
def fromdict(dict): """Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert """ return State(hb_decode(dict["f_key"]), hb_decode(dict["alpha_key"]), dict["chunks"], dict["encrypted"], hb_decode(dict["iv"]), hb_decode(dict["hmac"]))
python
def fromdict(dict): """Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert """ return State(hb_decode(dict["f_key"]), hb_decode(dict["alpha_key"]), dict["chunks"], dict["encrypted"], hb_decode(dict["iv"]), hb_decode(dict["hmac"]))
[ "def", "fromdict", "(", "dict", ")", ":", "return", "State", "(", "hb_decode", "(", "dict", "[", "\"f_key\"", "]", ")", ",", "hb_decode", "(", "dict", "[", "\"alpha_key\"", "]", ")", ",", "dict", "[", "\"chunks\"", "]", ",", "dict", "[", "\"encrypted\"...
Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert
[ "Takes", "a", "dictionary", "as", "an", "argument", "and", "returns", "a", "new", "State", "object", "from", "the", "dictionary", "." ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L136-L147
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
State.get_hmac
def get_hmac(self, key): """Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function """ h = HMAC.new(key, None, SHA256) h.update(self.iv) h.update(str(self.chunks).encode()) h.update(self.f_key) h.update(self.alpha_key) h.update(str(self.encrypted).encode()) return h.digest()
python
def get_hmac(self, key): """Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function """ h = HMAC.new(key, None, SHA256) h.update(self.iv) h.update(str(self.chunks).encode()) h.update(self.f_key) h.update(self.alpha_key) h.update(str(self.encrypted).encode()) return h.digest()
[ "def", "get_hmac", "(", "self", ",", "key", ")", ":", "h", "=", "HMAC", ".", "new", "(", "key", ",", "None", ",", "SHA256", ")", "h", ".", "update", "(", "self", ".", "iv", ")", "h", ".", "update", "(", "str", "(", "self", ".", "chunks", ")",...
Returns the keyed HMAC for authentication of this state data. :param key: the key for the keyed hash function
[ "Returns", "the", "keyed", "HMAC", "for", "authentication", "of", "this", "state", "data", "." ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L149-L160
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
State.encrypt
def encrypt(self, key): """This method encrypts and signs the state to make it unreadable by the server, since it contains information that would allow faking proof of storage. :param key: the key to encrypt and sign with """ if (self.encrypted): return # encrypt self.iv = Random.new().read(AES.block_size) aes = AES.new(key, AES.MODE_CFB, self.iv) self.f_key = aes.encrypt(self.f_key) self.alpha_key = aes.encrypt(self.alpha_key) self.encrypted = True # sign self.hmac = self.get_hmac(key)
python
def encrypt(self, key): """This method encrypts and signs the state to make it unreadable by the server, since it contains information that would allow faking proof of storage. :param key: the key to encrypt and sign with """ if (self.encrypted): return # encrypt self.iv = Random.new().read(AES.block_size) aes = AES.new(key, AES.MODE_CFB, self.iv) self.f_key = aes.encrypt(self.f_key) self.alpha_key = aes.encrypt(self.alpha_key) self.encrypted = True # sign self.hmac = self.get_hmac(key)
[ "def", "encrypt", "(", "self", ",", "key", ")", ":", "if", "(", "self", ".", "encrypted", ")", ":", "return", "# encrypt", "self", ".", "iv", "=", "Random", ".", "new", "(", ")", ".", "read", "(", "AES", ".", "block_size", ")", "aes", "=", "AES",...
This method encrypts and signs the state to make it unreadable by the server, since it contains information that would allow faking proof of storage. :param key: the key to encrypt and sign with
[ "This", "method", "encrypts", "and", "signs", "the", "state", "to", "make", "it", "unreadable", "by", "the", "server", "since", "it", "contains", "information", "that", "would", "allow", "faking", "proof", "of", "storage", "." ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L162-L178
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
State.decrypt
def decrypt(self, key): """This method checks the signature on the state and decrypts it. :param key: the key to decrypt and sign with """ # check signature if (self.get_hmac(key) != self.hmac): raise HeartbeatError("Signature invalid on state.") if (not self.encrypted): return # decrypt aes = AES.new(key, AES.MODE_CFB, self.iv) self.f_key = aes.decrypt(self.f_key) self.alpha_key = aes.decrypt(self.alpha_key) self.encrypted = False self.hmac = self.get_hmac(key)
python
def decrypt(self, key): """This method checks the signature on the state and decrypts it. :param key: the key to decrypt and sign with """ # check signature if (self.get_hmac(key) != self.hmac): raise HeartbeatError("Signature invalid on state.") if (not self.encrypted): return # decrypt aes = AES.new(key, AES.MODE_CFB, self.iv) self.f_key = aes.decrypt(self.f_key) self.alpha_key = aes.decrypt(self.alpha_key) self.encrypted = False self.hmac = self.get_hmac(key)
[ "def", "decrypt", "(", "self", ",", "key", ")", ":", "# check signature", "if", "(", "self", ".", "get_hmac", "(", "key", ")", "!=", "self", ".", "hmac", ")", ":", "raise", "HeartbeatError", "(", "\"Signature invalid on state.\"", ")", "if", "(", "not", ...
This method checks the signature on the state and decrypts it. :param key: the key to decrypt and sign with
[ "This", "method", "checks", "the", "signature", "on", "the", "state", "and", "decrypts", "it", "." ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L180-L195
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
Proof.fromdict
def fromdict(dict): """Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert """ self = Proof() self.mu = dict["mu"] self.sigma = dict["sigma"] return self
python
def fromdict(dict): """Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert """ self = Proof() self.mu = dict["mu"] self.sigma = dict["sigma"] return self
[ "def", "fromdict", "(", "dict", ")", ":", "self", "=", "Proof", "(", ")", "self", ".", "mu", "=", "dict", "[", "\"mu\"", "]", "self", ".", "sigma", "=", "dict", "[", "\"sigma\"", "]", "return", "self" ]
Takes a dictionary as an argument and returns a new Proof object from the dictionary. :param dict: the dictionary to convert
[ "Takes", "a", "dictionary", "as", "an", "argument", "and", "returns", "a", "new", "Proof", "object", "from", "the", "dictionary", "." ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L215-L224
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
PySwizzle.encode
def encode(self, file): """This function returns a (tag,state) tuple that is calculated for the given file. the state will be encrypted with `self.key` :param file: the file to encode """ tag = Tag() tag.sigma = list() state = State(Random.new().read(32), Random.new().read(32)) f = KeyedPRF(state.f_key, self.prime) alpha = KeyedPRF(state.alpha_key, self.prime) done = False chunk_id = 0 while (not done): sigma = f.eval(chunk_id) for j in range(0, self.sectors): buffer = file.read(self.sectorsize) if (len(buffer) > 0): sigma += alpha.eval(j) * number.bytes_to_long(buffer) if (len(buffer) != self.sectorsize): done = True break sigma %= self.prime tag.sigma.append(sigma) chunk_id += 1 state.chunks = chunk_id state.encrypt(self.key) return (tag, state)
python
def encode(self, file): """This function returns a (tag,state) tuple that is calculated for the given file. the state will be encrypted with `self.key` :param file: the file to encode """ tag = Tag() tag.sigma = list() state = State(Random.new().read(32), Random.new().read(32)) f = KeyedPRF(state.f_key, self.prime) alpha = KeyedPRF(state.alpha_key, self.prime) done = False chunk_id = 0 while (not done): sigma = f.eval(chunk_id) for j in range(0, self.sectors): buffer = file.read(self.sectorsize) if (len(buffer) > 0): sigma += alpha.eval(j) * number.bytes_to_long(buffer) if (len(buffer) != self.sectorsize): done = True break sigma %= self.prime tag.sigma.append(sigma) chunk_id += 1 state.chunks = chunk_id state.encrypt(self.key) return (tag, state)
[ "def", "encode", "(", "self", ",", "file", ")", ":", "tag", "=", "Tag", "(", ")", "tag", ".", "sigma", "=", "list", "(", ")", "state", "=", "State", "(", "Random", ".", "new", "(", ")", ".", "read", "(", "32", ")", ",", "Random", ".", "new", ...
This function returns a (tag,state) tuple that is calculated for the given file. the state will be encrypted with `self.key` :param file: the file to encode
[ "This", "function", "returns", "a", "(", "tag", "state", ")", "tuple", "that", "is", "calculated", "for", "the", "given", "file", ".", "the", "state", "will", "be", "encrypted", "with", "self", ".", "key" ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L279-L314
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
PySwizzle.gen_challenge
def gen_challenge(self, state): """This function generates a challenge for given state. It selects a random number and sets that as the challenge key. By default, v_max is set to the prime, and the number of chunks to challenge is the number of chunks in the file. (this doesn't guarantee that the whole file will be checked since some chunks could be selected twice and some selected none. :param state: the state to use. it can be encrypted, as it will have just been received from the server """ state.decrypt(self.key) chal = Challenge(state.chunks, self.prime, Random.new().read(32)) return chal
python
def gen_challenge(self, state): """This function generates a challenge for given state. It selects a random number and sets that as the challenge key. By default, v_max is set to the prime, and the number of chunks to challenge is the number of chunks in the file. (this doesn't guarantee that the whole file will be checked since some chunks could be selected twice and some selected none. :param state: the state to use. it can be encrypted, as it will have just been received from the server """ state.decrypt(self.key) chal = Challenge(state.chunks, self.prime, Random.new().read(32)) return chal
[ "def", "gen_challenge", "(", "self", ",", "state", ")", ":", "state", ".", "decrypt", "(", "self", ".", "key", ")", "chal", "=", "Challenge", "(", "state", ".", "chunks", ",", "self", ".", "prime", ",", "Random", ".", "new", "(", ")", ".", "read", ...
This function generates a challenge for given state. It selects a random number and sets that as the challenge key. By default, v_max is set to the prime, and the number of chunks to challenge is the number of chunks in the file. (this doesn't guarantee that the whole file will be checked since some chunks could be selected twice and some selected none. :param state: the state to use. it can be encrypted, as it will have just been received from the server
[ "This", "function", "generates", "a", "challenge", "for", "given", "state", ".", "It", "selects", "a", "random", "number", "and", "sets", "that", "as", "the", "challenge", "key", ".", "By", "default", "v_max", "is", "set", "to", "the", "prime", "and", "t...
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L316-L331
StorjOld/heartbeat
heartbeat/PySwizzle/PySwizzle.py
PySwizzle.prove
def prove(self, file, chal, tag): """This function returns a proof calculated from the file, the challenge, and the file tag :param file: this is a file like object that supports `read()`, `tell()` and `seek()` methods. :param chal: the challenge to use for proving :param tag: the file tag """ chunk_size = self.sectors * self.sectorsize index = KeyedPRF(chal.key, len(tag.sigma)) v = KeyedPRF(chal.key, chal.v_max) proof = Proof() proof.mu = [0] * self.sectors proof.sigma = 0 for i in range(0, chal.chunks): for j in range(0, self.sectors): pos = index.eval(i) * chunk_size + j * self.sectorsize file.seek(pos) buffer = file.read(self.sectorsize) if (len(buffer) > 0): proof.mu[j] += v.eval(i) * number.bytes_to_long(buffer) if (len(buffer) != self.sectorsize): break for j in range(0, self.sectors): proof.mu[j] %= self.prime for i in range(0, chal.chunks): proof.sigma += v.eval(i) * tag.sigma[index.eval(i)] proof.sigma %= self.prime return proof
python
def prove(self, file, chal, tag): """This function returns a proof calculated from the file, the challenge, and the file tag :param file: this is a file like object that supports `read()`, `tell()` and `seek()` methods. :param chal: the challenge to use for proving :param tag: the file tag """ chunk_size = self.sectors * self.sectorsize index = KeyedPRF(chal.key, len(tag.sigma)) v = KeyedPRF(chal.key, chal.v_max) proof = Proof() proof.mu = [0] * self.sectors proof.sigma = 0 for i in range(0, chal.chunks): for j in range(0, self.sectors): pos = index.eval(i) * chunk_size + j * self.sectorsize file.seek(pos) buffer = file.read(self.sectorsize) if (len(buffer) > 0): proof.mu[j] += v.eval(i) * number.bytes_to_long(buffer) if (len(buffer) != self.sectorsize): break for j in range(0, self.sectors): proof.mu[j] %= self.prime for i in range(0, chal.chunks): proof.sigma += v.eval(i) * tag.sigma[index.eval(i)] proof.sigma %= self.prime return proof
[ "def", "prove", "(", "self", ",", "file", ",", "chal", ",", "tag", ")", ":", "chunk_size", "=", "self", ".", "sectors", "*", "self", ".", "sectorsize", "index", "=", "KeyedPRF", "(", "chal", ".", "key", ",", "len", "(", "tag", ".", "sigma", ")", ...
This function returns a proof calculated from the file, the challenge, and the file tag :param file: this is a file like object that supports `read()`, `tell()` and `seek()` methods. :param chal: the challenge to use for proving :param tag: the file tag
[ "This", "function", "returns", "a", "proof", "calculated", "from", "the", "file", "the", "challenge", "and", "the", "file", "tag" ]
train
https://github.com/StorjOld/heartbeat/blob/4d54f2011f1e9f688073d4347bc51bb7bd682718/heartbeat/PySwizzle/PySwizzle.py#L333-L370