partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
set_name_lists
Set three globally available lists of names.
pantheon/names.py
def set_name_lists(ethnicity=None): """Set three globally available lists of names.""" if not ethnicity: ethnicity = random.choice(get_ethnicities()) print("Loading names from: " + ethnicity) filename = names_dir + ethnicity + '.json' try: with open(filename, 'r') as injson: dat...
def set_name_lists(ethnicity=None): """Set three globally available lists of names.""" if not ethnicity: ethnicity = random.choice(get_ethnicities()) print("Loading names from: " + ethnicity) filename = names_dir + ethnicity + '.json' try: with open(filename, 'r') as injson: dat...
[ "Set", "three", "globally", "available", "lists", "of", "names", "." ]
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/names.py#L14-L36
[ "def", "set_name_lists", "(", "ethnicity", "=", "None", ")", ":", "if", "not", "ethnicity", ":", "ethnicity", "=", "random", ".", "choice", "(", "get_ethnicities", "(", ")", ")", "print", "(", "\"Loading names from: \"", "+", "ethnicity", ")", "filename", "=...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.set_chromosomes
This model uses the XY sex-determination system. Sex != gender. Assign either XX or XY randomly with a 50/50 chance of each, unless <chromosomes> are passed as an argument.
pantheon/gods.py
def set_chromosomes(self, chromosomes=None): """This model uses the XY sex-determination system. Sex != gender. Assign either XX or XY randomly with a 50/50 chance of each, unless <chromosomes> are passed as an argument. """ if chromosomes and chromosomes in valid_chromosomes: ...
def set_chromosomes(self, chromosomes=None): """This model uses the XY sex-determination system. Sex != gender. Assign either XX or XY randomly with a 50/50 chance of each, unless <chromosomes> are passed as an argument. """ if chromosomes and chromosomes in valid_chromosomes: ...
[ "This", "model", "uses", "the", "XY", "sex", "-", "determination", "system", ".", "Sex", "!", "=", "gender", ".", "Assign", "either", "XX", "or", "XY", "randomly", "with", "a", "50", "/", "50", "chance", "of", "each", "unless", "<chromosomes", ">", "ar...
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L49-L57
[ "def", "set_chromosomes", "(", "self", ",", "chromosomes", "=", "None", ")", ":", "if", "chromosomes", "and", "chromosomes", "in", "valid_chromosomes", ":", "self", ".", "chromosomes", "=", "chromosomes", "else", ":", "self", ".", "chromosomes", "=", "random",...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.set_gender
This model recognizes that sex chromosomes don't always line up with gender. Assign M, F, or NB according to the probabilities in p_gender.
pantheon/gods.py
def set_gender(self, gender=None): """This model recognizes that sex chromosomes don't always line up with gender. Assign M, F, or NB according to the probabilities in p_gender. """ if gender and gender in genders: self.gender = gender else: if not self.ch...
def set_gender(self, gender=None): """This model recognizes that sex chromosomes don't always line up with gender. Assign M, F, or NB according to the probabilities in p_gender. """ if gender and gender in genders: self.gender = gender else: if not self.ch...
[ "This", "model", "recognizes", "that", "sex", "chromosomes", "don", "t", "always", "line", "up", "with", "gender", ".", "Assign", "M", "F", "or", "NB", "according", "to", "the", "probabilities", "in", "p_gender", "." ]
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L60-L68
[ "def", "set_gender", "(", "self", ",", "gender", "=", "None", ")", ":", "if", "gender", "and", "gender", "in", "genders", ":", "self", ".", "gender", "=", "gender", "else", ":", "if", "not", "self", ".", "chromosomes", ":", "self", ".", "set_chromosome...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.set_inherited_traits
Accept either strings or Gods as inputs.
pantheon/gods.py
def set_inherited_traits(self, egg_donor, sperm_donor): """Accept either strings or Gods as inputs.""" if type(egg_donor) == str: self.reproduce_asexually(egg_donor, sperm_donor) else: self.reproduce_sexually(egg_donor, sperm_donor)
def set_inherited_traits(self, egg_donor, sperm_donor): """Accept either strings or Gods as inputs.""" if type(egg_donor) == str: self.reproduce_asexually(egg_donor, sperm_donor) else: self.reproduce_sexually(egg_donor, sperm_donor)
[ "Accept", "either", "strings", "or", "Gods", "as", "inputs", "." ]
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L71-L76
[ "def", "set_inherited_traits", "(", "self", ",", "egg_donor", ",", "sperm_donor", ")", ":", "if", "type", "(", "egg_donor", ")", "==", "str", ":", "self", ".", "reproduce_asexually", "(", "egg_donor", ",", "sperm_donor", ")", "else", ":", "self", ".", "rep...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.reproduce_asexually
Produce two gametes, an egg and a sperm, from the input strings. Combine them to produce a genome a la sexual reproduction.
pantheon/gods.py
def reproduce_asexually(self, egg_word, sperm_word): """Produce two gametes, an egg and a sperm, from the input strings. Combine them to produce a genome a la sexual reproduction. """ egg = self.generate_gamete(egg_word) sperm = self.generate_gamete(sperm_word) self.geno...
def reproduce_asexually(self, egg_word, sperm_word): """Produce two gametes, an egg and a sperm, from the input strings. Combine them to produce a genome a la sexual reproduction. """ egg = self.generate_gamete(egg_word) sperm = self.generate_gamete(sperm_word) self.geno...
[ "Produce", "two", "gametes", "an", "egg", "and", "a", "sperm", "from", "the", "input", "strings", ".", "Combine", "them", "to", "produce", "a", "genome", "a", "la", "sexual", "reproduction", "." ]
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L79-L88
[ "def", "reproduce_asexually", "(", "self", ",", "egg_word", ",", "sperm_word", ")", ":", "egg", "=", "self", ".", "generate_gamete", "(", "egg_word", ")", "sperm", "=", "self", ".", "generate_gamete", "(", "sperm_word", ")", "self", ".", "genome", "=", "li...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.reproduce_sexually
Produce two gametes, an egg and a sperm, from input Gods. Combine them to produce a genome a la sexual reproduction. Assign divinity according to probabilities in p_divinity. The more divine the parents, the more divine their offspring.
pantheon/gods.py
def reproduce_sexually(self, egg_donor, sperm_donor): """Produce two gametes, an egg and a sperm, from input Gods. Combine them to produce a genome a la sexual reproduction. Assign divinity according to probabilities in p_divinity. The more divine the parents, the more divine their offsp...
def reproduce_sexually(self, egg_donor, sperm_donor): """Produce two gametes, an egg and a sperm, from input Gods. Combine them to produce a genome a la sexual reproduction. Assign divinity according to probabilities in p_divinity. The more divine the parents, the more divine their offsp...
[ "Produce", "two", "gametes", "an", "egg", "and", "a", "sperm", "from", "input", "Gods", ".", "Combine", "them", "to", "produce", "a", "genome", "a", "la", "sexual", "reproduction", ".", "Assign", "divinity", "according", "to", "probabilities", "in", "p_divin...
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L91-L106
[ "def", "reproduce_sexually", "(", "self", ",", "egg_donor", ",", "sperm_donor", ")", ":", "egg_word", "=", "random", ".", "choice", "(", "egg_donor", ".", "genome", ")", "egg", "=", "self", ".", "generate_gamete", "(", "egg_word", ")", "sperm_word", "=", "...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.set_name
Pick a random name from the lists loaded with the model. For Gods that identify as neither M nor F, the model attempts to retrieve an androgynous name. Note: not all of the scraped name lists contain androgynous names.
pantheon/gods.py
def set_name(self): """Pick a random name from the lists loaded with the model. For Gods that identify as neither M nor F, the model attempts to retrieve an androgynous name. Note: not all of the scraped name lists contain androgynous names. """ if not self.gender: self.set_gende...
def set_name(self): """Pick a random name from the lists loaded with the model. For Gods that identify as neither M nor F, the model attempts to retrieve an androgynous name. Note: not all of the scraped name lists contain androgynous names. """ if not self.gender: self.set_gende...
[ "Pick", "a", "random", "name", "from", "the", "lists", "loaded", "with", "the", "model", ".", "For", "Gods", "that", "identify", "as", "neither", "M", "nor", "F", "the", "model", "attempts", "to", "retrieve", "an", "androgynous", "name", ".", "Note", ":"...
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L109-L128
[ "def", "set_name", "(", "self", ")", ":", "if", "not", "self", ".", "gender", ":", "self", ".", "set_gender", "(", ")", "name", "=", "''", "if", "self", ".", "gender", "==", "female", ":", "name", "=", "names", ".", "female_names", ".", "pop", "(",...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.set_epithet
Divine an appropriate epithet for this God. (See what I did there?)
pantheon/gods.py
def set_epithet(self): """Divine an appropriate epithet for this God. (See what I did there?)""" if self.divinity == human: obsession = random.choice(self.genome) if self.gender == female: self.epithet = 'ordinary woman' elif self.gender == male: ...
def set_epithet(self): """Divine an appropriate epithet for this God. (See what I did there?)""" if self.divinity == human: obsession = random.choice(self.genome) if self.gender == female: self.epithet = 'ordinary woman' elif self.gender == male: ...
[ "Divine", "an", "appropriate", "epithet", "for", "this", "God", ".", "(", "See", "what", "I", "did", "there?", ")" ]
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L131-L167
[ "def", "set_epithet", "(", "self", ")", ":", "if", "self", ".", "divinity", "==", "human", ":", "obsession", "=", "random", ".", "choice", "(", "self", ".", "genome", ")", "if", "self", ".", "gender", "==", "female", ":", "self", ".", "epithet", "=",...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.generate_gamete
Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens by searching the list of tokens for words that are related to the given egg_or_sperm_word.
pantheon/gods.py
def generate_gamete(self, egg_or_sperm_word): """Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens by searching the list of tokens for words that are related to the given egg_or_sperm_word. """ p_rate_of_mutation = [0.9, 0.1] should_use_mutant_pool = ...
def generate_gamete(self, egg_or_sperm_word): """Extract 23 'chromosomes' aka words from 'gene pool' aka list of tokens by searching the list of tokens for words that are related to the given egg_or_sperm_word. """ p_rate_of_mutation = [0.9, 0.1] should_use_mutant_pool = ...
[ "Extract", "23", "chromosomes", "aka", "words", "from", "gene", "pool", "aka", "list", "of", "tokens", "by", "searching", "the", "list", "of", "tokens", "for", "words", "that", "are", "related", "to", "the", "given", "egg_or_sperm_word", "." ]
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L170-L182
[ "def", "generate_gamete", "(", "self", ",", "egg_or_sperm_word", ")", ":", "p_rate_of_mutation", "=", "[", "0.9", ",", "0.1", "]", "should_use_mutant_pool", "=", "(", "npchoice", "(", "[", "0", ",", "1", "]", ",", "1", ",", "p", "=", "p_rate_of_mutation", ...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
God.print_parents
Print parents' names and epithets.
pantheon/gods.py
def print_parents(self): """Print parents' names and epithets.""" if self.gender == female: title = 'Daughter' elif self.gender == male: title = 'Son' else: title = 'Child' p1 = self.parents[0] p2 = self.parents[1] template = ...
def print_parents(self): """Print parents' names and epithets.""" if self.gender == female: title = 'Daughter' elif self.gender == male: title = 'Son' else: title = 'Child' p1 = self.parents[0] p2 = self.parents[1] template = ...
[ "Print", "parents", "names", "and", "epithets", "." ]
carawarner/pantheon
python
https://github.com/carawarner/pantheon/blob/7e8718f4397eaa389fb3d5dc04fa01c7cb556512/pantheon/gods.py#L185-L199
[ "def", "print_parents", "(", "self", ")", ":", "if", "self", ".", "gender", "==", "female", ":", "title", "=", "'Daughter'", "elif", "self", ".", "gender", "==", "male", ":", "title", "=", "'Son'", "else", ":", "title", "=", "'Child'", "p1", "=", "se...
7e8718f4397eaa389fb3d5dc04fa01c7cb556512
valid
Stage.instance
Returns all the information regarding a specific stage run See the `Go stage instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-stage-instance Args: counter (int): The stage instance to fetch. If falsey returns the latest stage instance from :me...
gocd/api/stage.py
def instance(self, counter=None, pipeline_counter=None): """Returns all the information regarding a specific stage run See the `Go stage instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-stage-instance Args: counter (int): The stage instance to fet...
def instance(self, counter=None, pipeline_counter=None): """Returns all the information regarding a specific stage run See the `Go stage instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-stage-instance Args: counter (int): The stage instance to fet...
[ "Returns", "all", "the", "information", "regarding", "a", "specific", "stage", "run" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/stage.py#L52-L91
[ "def", "instance", "(", "self", ",", "counter", "=", "None", ",", "pipeline_counter", "=", "None", ")", ":", "pipeline_counter", "=", "pipeline_counter", "or", "self", ".", "pipeline_counter", "pipeline_instance", "=", "None", "if", "not", "pipeline_counter", ":...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Response.is_json
Returns: bool: True if `content_type` is `application/json`
gocd/api/response.py
def is_json(self): """ Returns: bool: True if `content_type` is `application/json` """ return (self.content_type.startswith('application/json') or re.match(r'application/vnd.go.cd.v(\d+)\+json', self.content_type))
def is_json(self): """ Returns: bool: True if `content_type` is `application/json` """ return (self.content_type.startswith('application/json') or re.match(r'application/vnd.go.cd.v(\d+)\+json', self.content_type))
[ "Returns", ":", "bool", ":", "True", "if", "content_type", "is", "application", "/", "json" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/response.py#L62-L68
[ "def", "is_json", "(", "self", ")", ":", "return", "(", "self", ".", "content_type", ".", "startswith", "(", "'application/json'", ")", "or", "re", ".", "match", "(", "r'application/vnd.go.cd.v(\\d+)\\+json'", ",", "self", ".", "content_type", ")", ")" ]
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Response.payload
Returns: `str` when not json. `dict` when json.
gocd/api/response.py
def payload(self): """ Returns: `str` when not json. `dict` when json. """ if self.is_json: if not self._body_parsed: if hasattr(self._body, 'decode'): body = self._body.decode('utf-8') else: ...
def payload(self): """ Returns: `str` when not json. `dict` when json. """ if self.is_json: if not self._body_parsed: if hasattr(self._body, 'decode'): body = self._body.decode('utf-8') else: ...
[ "Returns", ":", "str", "when", "not", "json", ".", "dict", "when", "json", "." ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/response.py#L91-L108
[ "def", "payload", "(", "self", ")", ":", "if", "self", ".", "is_json", ":", "if", "not", "self", ".", "_body_parsed", ":", "if", "hasattr", "(", "self", ".", "_body", ",", "'decode'", ")", ":", "body", "=", "self", ".", "_body", ".", "decode", "(",...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Server.request
Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present this request will become a POST request. headers (dict,...
gocd/server.py
def request(self, path, data=None, headers=None, method=None): """Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present thi...
def request(self, path, data=None, headers=None, method=None): """Performs a HTTP request to the Go server Args: path (str): The full path on the Go server to request. This includes any query string attributes. data (str, dict, bool, optional): If any data is present thi...
[ "Performs", "a", "HTTP", "request", "to", "the", "Go", "server" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/server.py#L135-L158
[ "def", "request", "(", "self", ",", "path", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "method", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "data", "=", "data", ".", "encode", "(", "'utf-8'", ")...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Server.add_logged_in_session
Make the request appear to be coming from a browser This is to interact with older parts of Go that doesn't have a proper API call to be made. What will be done: 1. If no response passed in a call to `go/api/pipelines.xml` is made to get a valid session 2. `JSESSIONID` will ...
gocd/server.py
def add_logged_in_session(self, response=None): """Make the request appear to be coming from a browser This is to interact with older parts of Go that doesn't have a proper API call to be made. What will be done: 1. If no response passed in a call to `go/api/pipelines.xml` is ...
def add_logged_in_session(self, response=None): """Make the request appear to be coming from a browser This is to interact with older parts of Go that doesn't have a proper API call to be made. What will be done: 1. If no response passed in a call to `go/api/pipelines.xml` is ...
[ "Make", "the", "request", "appear", "to", "be", "coming", "from", "a", "browser" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/server.py#L160-L200
[ "def", "add_logged_in_session", "(", "self", ",", "response", "=", "None", ")", ":", "if", "not", "response", ":", "response", "=", "self", ".", "get", "(", "'go/api/pipelines.xml'", ")", "self", ".", "_set_session_cookie", "(", "response", ")", "if", "not",...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Server.stage
Returns an instance of :class:`Stage` Args: pipeline_name (str): Name of the pipeline the stage belongs to stage_name (str): Name of the stage to act on pipeline_counter (int): The pipeline instance the stage is for. Returns: Stage: an instantiated :class:...
gocd/server.py
def stage(self, pipeline_name, stage_name, pipeline_counter=None): """Returns an instance of :class:`Stage` Args: pipeline_name (str): Name of the pipeline the stage belongs to stage_name (str): Name of the stage to act on pipeline_counter (int): The pipeline instanc...
def stage(self, pipeline_name, stage_name, pipeline_counter=None): """Returns an instance of :class:`Stage` Args: pipeline_name (str): Name of the pipeline the stage belongs to stage_name (str): Name of the stage to act on pipeline_counter (int): The pipeline instanc...
[ "Returns", "an", "instance", "of", ":", "class", ":", "Stage" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/server.py#L229-L240
[ "def", "stage", "(", "self", ",", "pipeline_name", ",", "stage_name", ",", "pipeline_counter", "=", "None", ")", ":", "return", "Stage", "(", "self", ",", "pipeline_name", ",", "stage_name", ",", "pipeline_counter", "=", "pipeline_counter", ")" ]
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
flatten
Return a dict as a list of lists. >>> flatten({"a": "b"}) [['a', 'b']] >>> flatten({"a": [1, 2, 3]}) [['a', [1, 2, 3]]] >>> flatten({"a": {"b": "c"}}) [['a', 'b', 'c']] >>> flatten({"a": {"b": {"c": "e"}}}) [['a', 'b', 'c', 'e']] >>> flatten({"a": {"b": "c", "d": "e"}}) [['a', '...
gocd/vendor/multidimensional_urlencode/urlencoder.py
def flatten(d): """Return a dict as a list of lists. >>> flatten({"a": "b"}) [['a', 'b']] >>> flatten({"a": [1, 2, 3]}) [['a', [1, 2, 3]]] >>> flatten({"a": {"b": "c"}}) [['a', 'b', 'c']] >>> flatten({"a": {"b": {"c": "e"}}}) [['a', 'b', 'c', 'e']] >>> flatten({"a": {"b": "c", "...
def flatten(d): """Return a dict as a list of lists. >>> flatten({"a": "b"}) [['a', 'b']] >>> flatten({"a": [1, 2, 3]}) [['a', [1, 2, 3]]] >>> flatten({"a": {"b": "c"}}) [['a', 'b', 'c']] >>> flatten({"a": {"b": {"c": "e"}}}) [['a', 'b', 'c', 'e']] >>> flatten({"a": {"b": "c", "...
[ "Return", "a", "dict", "as", "a", "list", "of", "lists", "." ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/vendor/multidimensional_urlencode/urlencoder.py#L9-L39
[ "def", "flatten", "(", "d", ")", ":", "if", "not", "isinstance", "(", "d", ",", "dict", ")", ":", "return", "[", "[", "d", "]", "]", "returned", "=", "[", "]", "for", "key", ",", "value", "in", "d", ".", "items", "(", ")", ":", "# Each key, val...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Pipeline.instance
Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. If falsey returns the latest pipeline in...
gocd/api/pipeline.py
def instance(self, counter=None): """Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. ...
def instance(self, counter=None): """Returns all the information regarding a specific pipeline run See the `Go pipeline instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-pipeline-instance Args: counter (int): The pipeline instance to fetch. ...
[ "Returns", "all", "the", "information", "regarding", "a", "specific", "pipeline", "run" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L99-L120
[ "def", "instance", "(", "self", ",", "counter", "=", "None", ")", ":", "if", "not", "counter", ":", "history", "=", "self", ".", "history", "(", ")", "if", "not", "history", ":", "return", "history", "else", ":", "return", "Response", ".", "_from_json"...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Pipeline.schedule
Schedule a pipeline run Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`. Args: variables (dict, optional): Variables to set/override secure_variables (dict, optional): Secure variables to set/override materials (dict, optional): Material revisions to be used...
gocd/api/pipeline.py
def schedule(self, variables=None, secure_variables=None, materials=None, return_new_instance=False, backoff_time=1.0): """Schedule a pipeline run Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`. Args: variables (dict, optional): Variables to set/overri...
def schedule(self, variables=None, secure_variables=None, materials=None, return_new_instance=False, backoff_time=1.0): """Schedule a pipeline run Aliased as :meth:`run`, :meth:`schedule`, and :meth:`trigger`. Args: variables (dict, optional): Variables to set/overri...
[ "Schedule", "a", "pipeline", "run" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L122-L185
[ "def", "schedule", "(", "self", ",", "variables", "=", "None", ",", "secure_variables", "=", "None", ",", "materials", "=", "None", ",", "return_new_instance", "=", "False", ",", "backoff_time", "=", "1.0", ")", ":", "scheduling_args", "=", "dict", "(", "v...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Pipeline.artifact
Helper to instantiate an :class:`gocd.api.artifact.Artifact` object Args: counter (int): The pipeline counter to get the artifact for stage: Stage name job: Job name stage_counter: Defaults to 1 Returns: Artifact: :class:`gocd.api.artifact.Artifact` ob...
gocd/api/pipeline.py
def artifact(self, counter, stage, job, stage_counter=1): """Helper to instantiate an :class:`gocd.api.artifact.Artifact` object Args: counter (int): The pipeline counter to get the artifact for stage: Stage name job: Job name stage_counter: Defaults to 1 ...
def artifact(self, counter, stage, job, stage_counter=1): """Helper to instantiate an :class:`gocd.api.artifact.Artifact` object Args: counter (int): The pipeline counter to get the artifact for stage: Stage name job: Job name stage_counter: Defaults to 1 ...
[ "Helper", "to", "instantiate", "an", ":", "class", ":", "gocd", ".", "api", ".", "artifact", ".", "Artifact", "object" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L192-L204
[ "def", "artifact", "(", "self", ",", "counter", ",", "stage", ",", "job", ",", "stage_counter", "=", "1", ")", ":", "return", "Artifact", "(", "self", ".", "server", ",", "self", ".", "name", ",", "counter", ",", "stage", ",", "job", ",", "stage_coun...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Pipeline.console_output
Yields the output and metadata from all jobs in the pipeline Args: instance: The result of a :meth:`instance` call, if not supplied the latest of the pipeline will be used. Yields: tuple: (metadata (dict), output (str)). metadata contains: - pipel...
gocd/api/pipeline.py
def console_output(self, instance=None): """Yields the output and metadata from all jobs in the pipeline Args: instance: The result of a :meth:`instance` call, if not supplied the latest of the pipeline will be used. Yields: tuple: (metadata (dict), output (str)...
def console_output(self, instance=None): """Yields the output and metadata from all jobs in the pipeline Args: instance: The result of a :meth:`instance` call, if not supplied the latest of the pipeline will be used. Yields: tuple: (metadata (dict), output (str)...
[ "Yields", "the", "output", "and", "metadata", "from", "all", "jobs", "in", "the", "pipeline" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L208-L252
[ "def", "console_output", "(", "self", ",", "instance", "=", "None", ")", ":", "if", "instance", "is", "None", ":", "instance", "=", "self", ".", "instance", "(", ")", "for", "stage", "in", "instance", "[", "'stages'", "]", ":", "for", "job", "in", "s...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Pipeline.stage
Helper to instantiate a :class:`gocd.api.stage.Stage` object Args: name: The name of the stage pipeline_counter: Returns:
gocd/api/pipeline.py
def stage(self, name, pipeline_counter=None): """Helper to instantiate a :class:`gocd.api.stage.Stage` object Args: name: The name of the stage pipeline_counter: Returns: """ return Stage( self.server, pipeline_name=self.name, ...
def stage(self, name, pipeline_counter=None): """Helper to instantiate a :class:`gocd.api.stage.Stage` object Args: name: The name of the stage pipeline_counter: Returns: """ return Stage( self.server, pipeline_name=self.name, ...
[ "Helper", "to", "instantiate", "a", ":", "class", ":", "gocd", ".", "api", ".", "stage", ".", "Stage", "object" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L254-L269
[ "def", "stage", "(", "self", ",", "name", ",", "pipeline_counter", "=", "None", ")", ":", "return", "Stage", "(", "self", ".", "server", ",", "pipeline_name", "=", "self", ".", "name", ",", "stage_name", "=", "name", ",", "pipeline_counter", "=", "pipeli...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
TemplateConfig.edit
Update template config for specified template name. .. __: https://api.go.cd/current/#edit-template-config Returns: Response: :class:`gocd.api.response.Response` object
gocd/api/template_config.py
def edit(self, config, etag): """Update template config for specified template name. .. __: https://api.go.cd/current/#edit-template-config Returns: Response: :class:`gocd.api.response.Response` object """ data = self._json_encode(config) headers = self._defa...
def edit(self, config, etag): """Update template config for specified template name. .. __: https://api.go.cd/current/#edit-template-config Returns: Response: :class:`gocd.api.response.Response` object """ data = self._json_encode(config) headers = self._defa...
[ "Update", "template", "config", "for", "specified", "template", "name", "." ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/template_config.py#L37-L56
[ "def", "edit", "(", "self", ",", "config", ",", "etag", ")", ":", "data", "=", "self", ".", "_json_encode", "(", "config", ")", "headers", "=", "self", ".", "_default_headers", "(", ")", "if", "etag", "is", "not", "None", ":", "headers", "[", "\"If-M...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
TemplateConfig.create
Create template config for specified template name. .. __: https://api.go.cd/current/#create-template-config Returns: Response: :class:`gocd.api.response.Response` object
gocd/api/template_config.py
def create(self, config): """Create template config for specified template name. .. __: https://api.go.cd/current/#create-template-config Returns: Response: :class:`gocd.api.response.Response` object """ assert config["name"] == self.name, "Given config is not for th...
def create(self, config): """Create template config for specified template name. .. __: https://api.go.cd/current/#create-template-config Returns: Response: :class:`gocd.api.response.Response` object """ assert config["name"] == self.name, "Given config is not for th...
[ "Create", "template", "config", "for", "specified", "template", "name", "." ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/template_config.py#L58-L75
[ "def", "create", "(", "self", ",", "config", ")", ":", "assert", "config", "[", "\"name\"", "]", "==", "self", ".", "name", ",", "\"Given config is not for this template\"", "data", "=", "self", ".", "_json_encode", "(", "config", ")", "headers", "=", "self"...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
TemplateConfig.delete
Delete template config for specified template name. .. __: https://api.go.cd/current/#delete-a-template Returns: Response: :class:`gocd.api.response.Response` object
gocd/api/template_config.py
def delete(self): """Delete template config for specified template name. .. __: https://api.go.cd/current/#delete-a-template Returns: Response: :class:`gocd.api.response.Response` object """ headers = self._default_headers() return self._request(self.name, ...
def delete(self): """Delete template config for specified template name. .. __: https://api.go.cd/current/#delete-a-template Returns: Response: :class:`gocd.api.response.Response` object """ headers = self._default_headers() return self._request(self.name, ...
[ "Delete", "template", "config", "for", "specified", "template", "name", "." ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/template_config.py#L77-L92
[ "def", "delete", "(", "self", ")", ":", "headers", "=", "self", ".", "_default_headers", "(", ")", "return", "self", ".", "_request", "(", "self", ".", "name", ",", "ok_status", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "headers", "...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
PipelineGroups.pipelines
Returns a set of all pipelines from the last response Returns: set: Response success: all the pipelines available in the response Response failure: an empty set
gocd/api/pipeline_groups.py
def pipelines(self): """Returns a set of all pipelines from the last response Returns: set: Response success: all the pipelines available in the response Response failure: an empty set """ if not self.response: return set() elif self._pipelin...
def pipelines(self): """Returns a set of all pipelines from the last response Returns: set: Response success: all the pipelines available in the response Response failure: an empty set """ if not self.response: return set() elif self._pipelin...
[ "Returns", "a", "set", "of", "all", "pipelines", "from", "the", "last", "response" ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline_groups.py#L40-L55
[ "def", "pipelines", "(", "self", ")", ":", "if", "not", "self", ".", "response", ":", "return", "set", "(", ")", "elif", "self", ".", "_pipelines", "is", "None", "and", "self", ".", "response", ":", "self", ".", "_pipelines", "=", "set", "(", ")", ...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
Artifact.get_directory
Gets an artifact directory by its path. See the `Go artifact directory documentation`__ for example responses. .. __: http://api.go.cd/current/#get-artifact-directory .. note:: Getting a directory relies on Go creating a zip file of the directory in question. Because of th...
gocd/api/artifact.py
def get_directory(self, path_to_directory, timeout=30, backoff=0.4, max_wait=4): """Gets an artifact directory by its path. See the `Go artifact directory documentation`__ for example responses. .. __: http://api.go.cd/current/#get-artifact-directory .. note:: Getting a dire...
def get_directory(self, path_to_directory, timeout=30, backoff=0.4, max_wait=4): """Gets an artifact directory by its path. See the `Go artifact directory documentation`__ for example responses. .. __: http://api.go.cd/current/#get-artifact-directory .. note:: Getting a dire...
[ "Gets", "an", "artifact", "directory", "by", "its", "path", "." ]
gaqzi/py-gocd
python
https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/artifact.py#L65-L119
[ "def", "get_directory", "(", "self", ",", "path_to_directory", ",", "timeout", "=", "30", ",", "backoff", "=", "0.4", ",", "max_wait", "=", "4", ")", ":", "response", "=", "None", "started_at", "=", "None", "time_elapsed", "=", "0", "i", "=", "0", "whi...
6fe5b62dea51e665c11a343aba5fc98e130c5c63
valid
DelayQueue.ask
Return the wait time in seconds required to retrieve the item currently at the head of the queue. Note that there is no guarantee that a call to `get()` will succeed even if `ask()` returns 0. By the time the calling thread reacts, other threads may have caused a different ...
delayqueue/core.py
def ask(self): """ Return the wait time in seconds required to retrieve the item currently at the head of the queue. Note that there is no guarantee that a call to `get()` will succeed even if `ask()` returns 0. By the time the calling thread reacts, other thread...
def ask(self): """ Return the wait time in seconds required to retrieve the item currently at the head of the queue. Note that there is no guarantee that a call to `get()` will succeed even if `ask()` returns 0. By the time the calling thread reacts, other thread...
[ "Return", "the", "wait", "time", "in", "seconds", "required", "to", "retrieve", "the", "item", "currently", "at", "the", "head", "of", "the", "queue", ".", "Note", "that", "there", "is", "no", "guarantee", "that", "a", "call", "to", "get", "()", "will", ...
aisthesis/delayqueue
python
https://github.com/aisthesis/delayqueue/blob/9f357d22e966a5cf252bae5446d92efa7b07e83d/delayqueue/core.py#L46-L63
[ "def", "ask", "(", "self", ")", ":", "with", "self", ".", "mutex", ":", "if", "not", "len", "(", "self", ".", "queue", ")", ":", "raise", "Empty", "utcnow", "=", "dt", ".", "datetime", ".", "utcnow", "(", ")", "if", "self", ".", "queue", "[", "...
9f357d22e966a5cf252bae5446d92efa7b07e83d
valid
p_transition
transition : START_KWD KEY NULL_KWD FLOAT transition : KEY KEY NULL_KWD FLOAT transition : KEY END_KWD NULL_KWD FLOAT transition : START_KWD KEY KEY FLOAT transition : KEY KEY KEY FLOAT transition : KEY END_KWD KEY FLOAT transition : START_KWD KEY NULL_KWD INTEGER transition : KEY KEY NULL_K...
marionette_tg/dsl.py
def p_transition(p): """ transition : START_KWD KEY NULL_KWD FLOAT transition : KEY KEY NULL_KWD FLOAT transition : KEY END_KWD NULL_KWD FLOAT transition : START_KWD KEY KEY FLOAT transition : KEY KEY KEY FLOAT transition : KEY END_KWD KEY FLOAT transition : START_KWD KEY NULL_KWD INTEGE...
def p_transition(p): """ transition : START_KWD KEY NULL_KWD FLOAT transition : KEY KEY NULL_KWD FLOAT transition : KEY END_KWD NULL_KWD FLOAT transition : START_KWD KEY KEY FLOAT transition : KEY KEY KEY FLOAT transition : KEY END_KWD KEY FLOAT transition : START_KWD KEY NULL_KWD INTEGE...
[ "transition", ":", "START_KWD", "KEY", "NULL_KWD", "FLOAT", "transition", ":", "KEY", "KEY", "NULL_KWD", "FLOAT", "transition", ":", "KEY", "END_KWD", "NULL_KWD", "FLOAT", "transition", ":", "START_KWD", "KEY", "KEY", "FLOAT", "transition", ":", "KEY", "KEY", ...
marionette-tg/marionette
python
https://github.com/marionette-tg/marionette/blob/bb40a334a18c82728eec01c9b56330bcb91a28da/marionette_tg/dsl.py#L174-L199
[ "def", "p_transition", "(", "p", ")", ":", "p", "[", "3", "]", "=", "None", "if", "p", "[", "3", "]", "==", "'NULL'", "else", "p", "[", "3", "]", "if", "p", "[", "4", "]", "==", "'error'", ":", "p", "[", "0", "]", "=", "MarionetteTransition",...
bb40a334a18c82728eec01c9b56330bcb91a28da
valid
p_action_blocks
action_blocks : action_blocks action_block
marionette_tg/dsl.py
def p_action_blocks(p): """ action_blocks : action_blocks action_block """ if isinstance(p[1], list): if isinstance(p[1][0], list): p[0] = p[1][0] + [p[2]] else: p[0] = p[1] + p[2] else: p[0] = [p[1], p[2]]
def p_action_blocks(p): """ action_blocks : action_blocks action_block """ if isinstance(p[1], list): if isinstance(p[1][0], list): p[0] = p[1][0] + [p[2]] else: p[0] = p[1] + p[2] else: p[0] = [p[1], p[2]]
[ "action_blocks", ":", "action_blocks", "action_block" ]
marionette-tg/marionette
python
https://github.com/marionette-tg/marionette/blob/bb40a334a18c82728eec01c9b56330bcb91a28da/marionette_tg/dsl.py#L202-L212
[ "def", "p_action_blocks", "(", "p", ")", ":", "if", "isinstance", "(", "p", "[", "1", "]", ",", "list", ")", ":", "if", "isinstance", "(", "p", "[", "1", "]", "[", "0", "]", ",", "list", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "...
bb40a334a18c82728eec01c9b56330bcb91a28da
valid
p_action_block
action_block : ACTION_KWD KEY COLON actions
marionette_tg/dsl.py
def p_action_block(p): """ action_block : ACTION_KWD KEY COLON actions """ p[0] = [] for i in range(len(p[4])): p[0] += [marionette_tg.action.MarionetteAction(p[2], p[4][i][0], p[4][i][1], ...
def p_action_block(p): """ action_block : ACTION_KWD KEY COLON actions """ p[0] = [] for i in range(len(p[4])): p[0] += [marionette_tg.action.MarionetteAction(p[2], p[4][i][0], p[4][i][1], ...
[ "action_block", ":", "ACTION_KWD", "KEY", "COLON", "actions" ]
marionette-tg/marionette
python
https://github.com/marionette-tg/marionette/blob/bb40a334a18c82728eec01c9b56330bcb91a28da/marionette_tg/dsl.py#L222-L232
[ "def", "p_action_block", "(", "p", ")", ":", "p", "[", "0", "]", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "p", "[", "4", "]", ")", ")", ":", "p", "[", "0", "]", "+=", "[", "marionette_tg", ".", "action", ".", "MarionetteActi...
bb40a334a18c82728eec01c9b56330bcb91a28da
valid
p_action
action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_stri...
marionette_tg/dsl.py
def p_action(p): """ action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MAT...
def p_action(p): """ action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN action : CLIENT_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MATCH_INCOMING_KWD LPAREN p_string_arg RPAREN action : SERVER_KWD KEY DOT KEY LPAREN args RPAREN IF_KWD REGEX_MAT...
[ "action", ":", "CLIENT_KWD", "KEY", "DOT", "KEY", "LPAREN", "args", "RPAREN", "action", ":", "SERVER_KWD", "KEY", "DOT", "KEY", "LPAREN", "args", "RPAREN", "action", ":", "CLIENT_KWD", "KEY", "DOT", "KEY", "LPAREN", "args", "RPAREN", "IF_KWD", "REGEX_MATCH_INC...
marionette-tg/marionette
python
https://github.com/marionette-tg/marionette/blob/bb40a334a18c82728eec01c9b56330bcb91a28da/marionette_tg/dsl.py#L249-L259
[ "def", "p_action", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "8", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", ",", "p", "[", "2", "]", ",", "p", "[", "4", "]", ",", "p", "[", "6", "]", ",", "None", "]", "elif"...
bb40a334a18c82728eec01c9b56330bcb91a28da
valid
config_loader
Configuration loader. Adds support for loading templates from the Flask application's instance folder (``<instance_folder>/templates``).
invenio_app/factory.py
def config_loader(app, **kwargs_config): """Configuration loader. Adds support for loading templates from the Flask application's instance folder (``<instance_folder>/templates``). """ # This is the only place customize the Flask application right after # it has been created, but before all ext...
def config_loader(app, **kwargs_config): """Configuration loader. Adds support for loading templates from the Flask application's instance folder (``<instance_folder>/templates``). """ # This is the only place customize the Flask application right after # it has been created, but before all ext...
[ "Configuration", "loader", "." ]
inveniosoftware/invenio-app
python
https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/factory.py#L48-L71
[ "def", "config_loader", "(", "app", ",", "*", "*", "kwargs_config", ")", ":", "# This is the only place customize the Flask application right after", "# it has been created, but before all extensions etc are loaded.", "local_templates_path", "=", "os", ".", "path", ".", "join", ...
6ef600f28913a501c05d75ffbe203e941e229f49
valid
app_class
Create Flask application class. Invenio-Files-REST needs to patch the Werkzeug form parsing in order to support streaming large file uploads. This is done by subclassing the Flask application class.
invenio_app/factory.py
def app_class(): """Create Flask application class. Invenio-Files-REST needs to patch the Werkzeug form parsing in order to support streaming large file uploads. This is done by subclassing the Flask application class. """ try: pkg_resources.get_distribution('invenio-files-rest') ...
def app_class(): """Create Flask application class. Invenio-Files-REST needs to patch the Werkzeug form parsing in order to support streaming large file uploads. This is done by subclassing the Flask application class. """ try: pkg_resources.get_distribution('invenio-files-rest') ...
[ "Create", "Flask", "application", "class", "." ]
inveniosoftware/invenio-app
python
https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/factory.py#L74-L94
[ "def", "app_class", "(", ")", ":", "try", ":", "pkg_resources", ".", "get_distribution", "(", "'invenio-files-rest'", ")", "from", "invenio_files_rest", ".", "app", "import", "Flask", "as", "FlaskBase", "except", "pkg_resources", ".", "DistributionNotFound", ":", ...
6ef600f28913a501c05d75ffbe203e941e229f49
valid
InvenioApp.init_app
Initialize application object. :param app: An instance of :class:`~flask.Flask`.
invenio_app/ext.py
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ # Init the configuration self.init_config(app) # Enable Rate limiter self.limiter = Limiter(app, key_func=get_ipaddr) # Enable secur...
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ # Init the configuration self.init_config(app) # Enable Rate limiter self.limiter = Limiter(app, key_func=get_ipaddr) # Enable secur...
[ "Initialize", "application", "object", "." ]
inveniosoftware/invenio-app
python
https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/ext.py#L40-L86
[ "def", "init_app", "(", "self", ",", "app", ",", "*", "*", "kwargs", ")", ":", "# Init the configuration", "self", ".", "init_config", "(", "app", ")", "# Enable Rate limiter", "self", ".", "limiter", "=", "Limiter", "(", "app", ",", "key_func", "=", "get_...
6ef600f28913a501c05d75ffbe203e941e229f49
valid
InvenioApp.init_config
Initialize configuration. :param app: An instance of :class:`~flask.Flask`.
invenio_app/ext.py
def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ config_apps = ['APP_', 'RATELIMIT_'] flask_talisman_debug_mode = ["'unsafe-inline'"] for k in dir(config): if any([k.startswith(prefix) for prefix i...
def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ config_apps = ['APP_', 'RATELIMIT_'] flask_talisman_debug_mode = ["'unsafe-inline'"] for k in dir(config): if any([k.startswith(prefix) for prefix i...
[ "Initialize", "configuration", "." ]
inveniosoftware/invenio-app
python
https://github.com/inveniosoftware/invenio-app/blob/6ef600f28913a501c05d75ffbe203e941e229f49/invenio_app/ext.py#L88-L110
[ "def", "init_config", "(", "self", ",", "app", ")", ":", "config_apps", "=", "[", "'APP_'", ",", "'RATELIMIT_'", "]", "flask_talisman_debug_mode", "=", "[", "\"'unsafe-inline'\"", "]", "for", "k", "in", "dir", "(", "config", ")", ":", "if", "any", "(", "...
6ef600f28913a501c05d75ffbe203e941e229f49
valid
remove_leading
Remove leading needle string (if exists). >>> remove_leading('Test', 'TestThisAndThat') 'ThisAndThat' >>> remove_leading('Test', 'ArbitraryName') 'ArbitraryName'
spec/plugin.py
def remove_leading(needle, haystack): """Remove leading needle string (if exists). >>> remove_leading('Test', 'TestThisAndThat') 'ThisAndThat' >>> remove_leading('Test', 'ArbitraryName') 'ArbitraryName' """ if haystack[:len(needle)] == needle: return haystack[len(needle):] retur...
def remove_leading(needle, haystack): """Remove leading needle string (if exists). >>> remove_leading('Test', 'TestThisAndThat') 'ThisAndThat' >>> remove_leading('Test', 'ArbitraryName') 'ArbitraryName' """ if haystack[:len(needle)] == needle: return haystack[len(needle):] retur...
[ "Remove", "leading", "needle", "string", "(", "if", "exists", ")", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/plugin.py#L38-L48
[ "def", "remove_leading", "(", "needle", ",", "haystack", ")", ":", "if", "haystack", "[", ":", "len", "(", "needle", ")", "]", "==", "needle", ":", "return", "haystack", "[", "len", "(", "needle", ")", ":", "]", "return", "haystack" ]
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
remove_trailing
Remove trailing needle string (if exists). >>> remove_trailing('Test', 'ThisAndThatTest') 'ThisAndThat' >>> remove_trailing('Test', 'ArbitraryName') 'ArbitraryName'
spec/plugin.py
def remove_trailing(needle, haystack): """Remove trailing needle string (if exists). >>> remove_trailing('Test', 'ThisAndThatTest') 'ThisAndThat' >>> remove_trailing('Test', 'ArbitraryName') 'ArbitraryName' """ if haystack[-len(needle):] == needle: return haystack[:-len(needle)] ...
def remove_trailing(needle, haystack): """Remove trailing needle string (if exists). >>> remove_trailing('Test', 'ThisAndThatTest') 'ThisAndThat' >>> remove_trailing('Test', 'ArbitraryName') 'ArbitraryName' """ if haystack[-len(needle):] == needle: return haystack[:-len(needle)] ...
[ "Remove", "trailing", "needle", "string", "(", "if", "exists", ")", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/plugin.py#L51-L61
[ "def", "remove_trailing", "(", "needle", ",", "haystack", ")", ":", "if", "haystack", "[", "-", "len", "(", "needle", ")", ":", "]", "==", "needle", ":", "return", "haystack", "[", ":", "-", "len", "(", "needle", ")", "]", "return", "haystack" ]
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
camel2word
Covert name from CamelCase to "Normal case". >>> camel2word('CamelCase') 'Camel case' >>> camel2word('CaseWithSpec') 'Case with spec'
spec/plugin.py
def camel2word(string): """Covert name from CamelCase to "Normal case". >>> camel2word('CamelCase') 'Camel case' >>> camel2word('CaseWithSpec') 'Case with spec' """ def wordize(match): return ' ' + match.group(1).lower() return string[0] + re.sub(r'([A-Z])', wordize, string[1:]...
def camel2word(string): """Covert name from CamelCase to "Normal case". >>> camel2word('CamelCase') 'Camel case' >>> camel2word('CaseWithSpec') 'Case with spec' """ def wordize(match): return ' ' + match.group(1).lower() return string[0] + re.sub(r'([A-Z])', wordize, string[1:]...
[ "Covert", "name", "from", "CamelCase", "to", "Normal", "case", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/plugin.py#L68-L79
[ "def", "camel2word", "(", "string", ")", ":", "def", "wordize", "(", "match", ")", ":", "return", "' '", "+", "match", ".", "group", "(", "1", ")", ".", "lower", "(", ")", "return", "string", "[", "0", "]", "+", "re", ".", "sub", "(", "r'([A-Z])'...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
complete_english
>>> complete_english('dont do this') "don't do this" >>> complete_english('doesnt is matched as well') "doesn't is matched as well"
spec/plugin.py
def complete_english(string): """ >>> complete_english('dont do this') "don't do this" >>> complete_english('doesnt is matched as well') "doesn't is matched as well" """ for x, y in [("dont", "don't"), ("doesnt", "doesn't"), ("wont", "won't"), ...
def complete_english(string): """ >>> complete_english('dont do this') "don't do this" >>> complete_english('doesnt is matched as well') "doesn't is matched as well" """ for x, y in [("dont", "don't"), ("doesnt", "doesn't"), ("wont", "won't"), ...
[ ">>>", "complete_english", "(", "dont", "do", "this", ")", "don", "t", "do", "this", ">>>", "complete_english", "(", "doesnt", "is", "matched", "as", "well", ")", "doesn", "t", "is", "matched", "as", "well" ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/plugin.py#L82-L94
[ "def", "complete_english", "(", "string", ")", ":", "for", "x", ",", "y", "in", "[", "(", "\"dont\"", ",", "\"don't\"", ")", ",", "(", "\"doesnt\"", ",", "\"doesn't\"", ")", ",", "(", "\"wont\"", ",", "\"won't\"", ")", ",", "(", "\"wasnt\"", ",", "\"...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
SpecPlugin.format_seconds
Format a time in seconds.
spec/plugin.py
def format_seconds(self, n_seconds): """Format a time in seconds.""" func = self.ok if n_seconds >= 60: n_minutes, n_seconds = divmod(n_seconds, 60) return "%s minutes %s seconds" % ( func("%d" % n_minutes), func("%.3f" % n_...
def format_seconds(self, n_seconds): """Format a time in seconds.""" func = self.ok if n_seconds >= 60: n_minutes, n_seconds = divmod(n_seconds, 60) return "%s minutes %s seconds" % ( func("%d" % n_minutes), func("%.3f" % n_...
[ "Format", "a", "time", "in", "seconds", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/plugin.py#L503-L513
[ "def", "format_seconds", "(", "self", ",", "n_seconds", ")", ":", "func", "=", "self", ".", "ok", "if", "n_seconds", ">=", "60", ":", "n_minutes", ",", "n_seconds", "=", "divmod", "(", "n_seconds", ",", "60", ")", "return", "\"%s minutes %s seconds\"", "%"...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
ppdict
Indent representation of a dict
esiosdata/prettyprinting/__init__.py
def ppdict(dict_to_print, br='\n', html=False, key_align='l', sort_keys=True, key_preffix='', key_suffix='', value_prefix='', value_suffix='', left_margin=3, indent=2): """Indent representation of a dict""" if dict_to_print: if sort_keys: dic = dict_to_print.copy() key...
def ppdict(dict_to_print, br='\n', html=False, key_align='l', sort_keys=True, key_preffix='', key_suffix='', value_prefix='', value_suffix='', left_margin=3, indent=2): """Indent representation of a dict""" if dict_to_print: if sort_keys: dic = dict_to_print.copy() key...
[ "Indent", "representation", "of", "a", "dict" ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/prettyprinting/__init__.py#L106-L142
[ "def", "ppdict", "(", "dict_to_print", ",", "br", "=", "'\\n'", ",", "html", "=", "False", ",", "key_align", "=", "'l'", ",", "sort_keys", "=", "True", ",", "key_preffix", "=", "''", ",", "key_suffix", "=", "''", ",", "value_prefix", "=", "''", ",", ...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
eq_
Shadow of the Nose builtin which presents easier to read multiline output.
spec/__init__.py
def eq_(result, expected, msg=None): """ Shadow of the Nose builtin which presents easier to read multiline output. """ params = {'expected': expected, 'result': result} aka = """ --------------------------------- aka ----------------------------------------- Expected: %(expected)r Got: %(result)...
def eq_(result, expected, msg=None): """ Shadow of the Nose builtin which presents easier to read multiline output. """ params = {'expected': expected, 'result': result} aka = """ --------------------------------- aka ----------------------------------------- Expected: %(expected)r Got: %(result)...
[ "Shadow", "of", "the", "Nose", "builtin", "which", "presents", "easier", "to", "read", "multiline", "output", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/__init__.py#L32-L67
[ "def", "eq_", "(", "result", ",", "expected", ",", "msg", "=", "None", ")", ":", "params", "=", "{", "'expected'", ":", "expected", ",", "'result'", ":", "result", "}", "aka", "=", "\"\"\"\n\n--------------------------------- aka ------------------------------------...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
_assert_contains
Test for existence of ``needle`` regex within ``haystack``. Say ``escape`` to escape the ``needle`` if you aren't really using the regex feature & have special characters in it.
spec/__init__.py
def _assert_contains(haystack, needle, invert, escape=False): """ Test for existence of ``needle`` regex within ``haystack``. Say ``escape`` to escape the ``needle`` if you aren't really using the regex feature & have special characters in it. """ myneedle = re.escape(needle) if escape else nee...
def _assert_contains(haystack, needle, invert, escape=False): """ Test for existence of ``needle`` regex within ``haystack``. Say ``escape`` to escape the ``needle`` if you aren't really using the regex feature & have special characters in it. """ myneedle = re.escape(needle) if escape else nee...
[ "Test", "for", "existence", "of", "needle", "regex", "within", "haystack", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/__init__.py#L80-L94
[ "def", "_assert_contains", "(", "haystack", ",", "needle", ",", "invert", ",", "escape", "=", "False", ")", ":", "myneedle", "=", "re", ".", "escape", "(", "needle", ")", "if", "escape", "else", "needle", "matched", "=", "re", ".", "search", "(", "myne...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
parse_config_file
Find the .splunk_logger config file in the current directory, or in the user's home and parse it. The one in the current directory has precedence. :return: A tuple with: - project_id - access_token
splunk_logger/utils.py
def parse_config_file(): """ Find the .splunk_logger config file in the current directory, or in the user's home and parse it. The one in the current directory has precedence. :return: A tuple with: - project_id - access_token """ for filename in ('.splunk_lo...
def parse_config_file(): """ Find the .splunk_logger config file in the current directory, or in the user's home and parse it. The one in the current directory has precedence. :return: A tuple with: - project_id - access_token """ for filename in ('.splunk_lo...
[ "Find", "the", ".", "splunk_logger", "config", "file", "in", "the", "current", "directory", "or", "in", "the", "user", "s", "home", "and", "parse", "it", ".", "The", "one", "in", "the", "current", "directory", "has", "precedence", ".", ":", "return", ":"...
andresriancho/splunk-logger
python
https://github.com/andresriancho/splunk-logger/blob/448d5ba54464fc355786ffb64f11fd6367792381/splunk_logger/utils.py#L5-L24
[ "def", "parse_config_file", "(", ")", ":", "for", "filename", "in", "(", "'.splunk_logger'", ",", "os", ".", "path", ".", "expanduser", "(", "'~/.splunk_logger'", ")", ")", ":", "project_id", ",", "access_token", ",", "api_domain", "=", "_parse_config_file_impl"...
448d5ba54464fc355786ffb64f11fd6367792381
valid
_parse_config_file_impl
Format for the file is: credentials: project_id: ... access_token: ... api_domain: ... :param filename: The filename to parse :return: A tuple with: - project_id - access_token - api_domain
splunk_logger/utils.py
def _parse_config_file_impl(filename): """ Format for the file is: credentials: project_id: ... access_token: ... api_domain: ... :param filename: The filename to parse :return: A tuple with: - project_id - access_...
def _parse_config_file_impl(filename): """ Format for the file is: credentials: project_id: ... access_token: ... api_domain: ... :param filename: The filename to parse :return: A tuple with: - project_id - access_...
[ "Format", "for", "the", "file", "is", ":", "credentials", ":", "project_id", ":", "...", "access_token", ":", "...", "api_domain", ":", "...", ":", "param", "filename", ":", "The", "filename", "to", "parse", ":", "return", ":", "A", "tuple", "with", ":",...
andresriancho/splunk-logger
python
https://github.com/andresriancho/splunk-logger/blob/448d5ba54464fc355786ffb64f11fd6367792381/splunk_logger/utils.py#L27-L51
[ "def", "_parse_config_file_impl", "(", "filename", ")", ":", "try", ":", "doc", "=", "yaml", ".", "load", "(", "file", "(", "filename", ")", ".", "read", "(", ")", ")", "project_id", "=", "doc", "[", "\"credentials\"", "]", "[", "\"project_id\"", "]", ...
448d5ba54464fc355786ffb64f11fd6367792381
valid
dem_url_dia
Obtiene las urls de descarga de los datos de demanda energética de un día concreto.
esiosdata/importdemdata.py
def dem_url_dia(dt_day='2015-06-22'): """Obtiene las urls de descarga de los datos de demanda energética de un día concreto.""" def _url_tipo_dato(str_dia, k): url = SERVER + '/archives/{}/download_json?locale=es'.format(D_TIPOS_REQ_DEM[k]) if type(str_dia) is str: return url + '&da...
def dem_url_dia(dt_day='2015-06-22'): """Obtiene las urls de descarga de los datos de demanda energética de un día concreto.""" def _url_tipo_dato(str_dia, k): url = SERVER + '/archives/{}/download_json?locale=es'.format(D_TIPOS_REQ_DEM[k]) if type(str_dia) is str: return url + '&da...
[ "Obtiene", "las", "urls", "de", "descarga", "de", "los", "datos", "de", "demanda", "energética", "de", "un", "día", "concreto", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importdemdata.py#L39-L50
[ "def", "dem_url_dia", "(", "dt_day", "=", "'2015-06-22'", ")", ":", "def", "_url_tipo_dato", "(", "str_dia", ",", "k", ")", ":", "url", "=", "SERVER", "+", "'/archives/{}/download_json?locale=es'", ".", "format", "(", "D_TIPOS_REQ_DEM", "[", "k", "]", ")", "...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
dem_procesa_datos_dia
Procesa los datos descargados en JSON.
esiosdata/importdemdata.py
def dem_procesa_datos_dia(key_day, response): """Procesa los datos descargados en JSON.""" dfs_import, df_import, dfs_maxmin, hay_errores = [], None, [], 0 for r in response: tipo_datos, data = _extract_func_json_data(r) if tipo_datos is not None: if ('IND_MaxMin' in tipo_datos) ...
def dem_procesa_datos_dia(key_day, response): """Procesa los datos descargados en JSON.""" dfs_import, df_import, dfs_maxmin, hay_errores = [], None, [], 0 for r in response: tipo_datos, data = _extract_func_json_data(r) if tipo_datos is not None: if ('IND_MaxMin' in tipo_datos) ...
[ "Procesa", "los", "datos", "descargados", "en", "JSON", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importdemdata.py#L98-L128
[ "def", "dem_procesa_datos_dia", "(", "key_day", ",", "response", ")", ":", "dfs_import", ",", "df_import", ",", "dfs_maxmin", ",", "hay_errores", "=", "[", "]", ",", "None", ",", "[", "]", ",", "0", "for", "r", "in", "response", ":", "tipo_datos", ",", ...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
dem_data_dia
Obtiene datos de demanda energética en un día concreto o un intervalo, accediendo directamente a la web.
esiosdata/importdemdata.py
def dem_data_dia(str_dia='2015-10-10', str_dia_fin=None): """Obtiene datos de demanda energética en un día concreto o un intervalo, accediendo directamente a la web.""" params = {'date_fmt': DATE_FMT, 'usar_multithread': False, 'num_retries': 1, "timeout": 10, 'func_procesa_data_dia': dem_procesa_...
def dem_data_dia(str_dia='2015-10-10', str_dia_fin=None): """Obtiene datos de demanda energética en un día concreto o un intervalo, accediendo directamente a la web.""" params = {'date_fmt': DATE_FMT, 'usar_multithread': False, 'num_retries': 1, "timeout": 10, 'func_procesa_data_dia': dem_procesa_...
[ "Obtiene", "datos", "de", "demanda", "energética", "en", "un", "día", "concreto", "o", "un", "intervalo", "accediendo", "directamente", "a", "la", "web", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importdemdata.py#L131-L145
[ "def", "dem_data_dia", "(", "str_dia", "=", "'2015-10-10'", ",", "str_dia_fin", "=", "None", ")", ":", "params", "=", "{", "'date_fmt'", ":", "DATE_FMT", ",", "'usar_multithread'", ":", "False", ",", "'num_retries'", ":", "1", ",", "\"timeout\"", ":", "10", ...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
flag_inner_classes
Mutates any attributes on ``obj`` which are classes, with link to ``obj``. Adds a convenience accessor which instantiates ``obj`` and then calls its ``setup`` method. Recurses on those objects as well.
spec/utils.py
def flag_inner_classes(obj): """ Mutates any attributes on ``obj`` which are classes, with link to ``obj``. Adds a convenience accessor which instantiates ``obj`` and then calls its ``setup`` method. Recurses on those objects as well. """ for tup in class_members(obj): tup[1]._pare...
def flag_inner_classes(obj): """ Mutates any attributes on ``obj`` which are classes, with link to ``obj``. Adds a convenience accessor which instantiates ``obj`` and then calls its ``setup`` method. Recurses on those objects as well. """ for tup in class_members(obj): tup[1]._pare...
[ "Mutates", "any", "attributes", "on", "obj", "which", "are", "classes", "with", "link", "to", "obj", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/utils.py#L30-L43
[ "def", "flag_inner_classes", "(", "obj", ")", ":", "for", "tup", "in", "class_members", "(", "obj", ")", ":", "tup", "[", "1", "]", ".", "_parent", "=", "obj", "tup", "[", "1", "]", ".", "_parent_inst", "=", "None", "tup", "[", "1", "]", ".", "__...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
autohide
Automatically hide setup() and teardown() methods, recursively.
spec/utils.py
def autohide(obj): """ Automatically hide setup() and teardown() methods, recursively. """ # Members on obj for name, item in six.iteritems(vars(obj)): if callable(item) and name in ('setup', 'teardown'): item = hide(item) # Recurse into class members for name, subclass i...
def autohide(obj): """ Automatically hide setup() and teardown() methods, recursively. """ # Members on obj for name, item in six.iteritems(vars(obj)): if callable(item) and name in ('setup', 'teardown'): item = hide(item) # Recurse into class members for name, subclass i...
[ "Automatically", "hide", "setup", "()", "and", "teardown", "()", "methods", "recursively", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/utils.py#L45-L55
[ "def", "autohide", "(", "obj", ")", ":", "# Members on obj", "for", "name", ",", "item", "in", "six", ".", "iteritems", "(", "vars", "(", "obj", ")", ")", ":", "if", "callable", "(", "item", ")", "and", "name", "in", "(", "'setup'", ",", "'teardown'"...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
trap
Replace sys.std(out|err) with a wrapper during execution, restored after. In addition, a new combined-streams output (another wrapper) will appear at ``sys.stdall``. This stream will resemble what a user sees at a terminal, i.e. both out/err streams intermingled.
spec/trap.py
def trap(func): """ Replace sys.std(out|err) with a wrapper during execution, restored after. In addition, a new combined-streams output (another wrapper) will appear at ``sys.stdall``. This stream will resemble what a user sees at a terminal, i.e. both out/err streams intermingled. """ @wr...
def trap(func): """ Replace sys.std(out|err) with a wrapper during execution, restored after. In addition, a new combined-streams output (another wrapper) will appear at ``sys.stdall``. This stream will resemble what a user sees at a terminal, i.e. both out/err streams intermingled. """ @wr...
[ "Replace", "sys", ".", "std", "(", "out|err", ")", "with", "a", "wrapper", "during", "execution", "restored", "after", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/trap.py#L60-L81
[ "def", "trap", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Use another CarbonCopy even though we're not cc'ing; for our \"write", "# bytes, return strings on py3\" behavior. Meh.", "s...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
pvpc_url_dia
Obtiene la url de descarga de los datos de PVPC de un día concreto. Anteriormente era: 'http://www.esios.ree.es/Solicitar?fileName=pvpcdesglosehorario_' + str_dia + '&fileType=xml&idioma=es', pero ahora es en JSON y requiere token_auth en headers.
esiosdata/importpvpcdata.py
def pvpc_url_dia(dt_day): """Obtiene la url de descarga de los datos de PVPC de un día concreto. Anteriormente era: 'http://www.esios.ree.es/Solicitar?fileName=pvpcdesglosehorario_' + str_dia + '&fileType=xml&idioma=es', pero ahora es en JSON y requiere token_auth en headers. """ if type(dt_day) is...
def pvpc_url_dia(dt_day): """Obtiene la url de descarga de los datos de PVPC de un día concreto. Anteriormente era: 'http://www.esios.ree.es/Solicitar?fileName=pvpcdesglosehorario_' + str_dia + '&fileType=xml&idioma=es', pero ahora es en JSON y requiere token_auth en headers. """ if type(dt_day) is...
[ "Obtiene", "la", "url", "de", "descarga", "de", "los", "datos", "de", "PVPC", "de", "un", "día", "concreto", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importpvpcdata.py#L36-L45
[ "def", "pvpc_url_dia", "(", "dt_day", ")", ":", "if", "type", "(", "dt_day", ")", "is", "str", ":", "return", "SERVER", "+", "'/archives/70/download_json?locale=es'", "+", "'&date='", "+", "dt_day", "else", ":", "return", "SERVER", "+", "'/archives/70/download_j...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
pvpc_calc_tcu_cp_feu_d
Procesa TCU, CP, FEU diario. :param df: :param verbose: :param convert_kwh: :return:
esiosdata/importpvpcdata.py
def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True): """Procesa TCU, CP, FEU diario. :param df: :param verbose: :param convert_kwh: :return: """ if 'TCU' + TARIFAS[0] not in df.columns: # Pasa de €/MWh a €/kWh: if convert_kwh: cols_mwh = [c + t for c i...
def pvpc_calc_tcu_cp_feu_d(df, verbose=True, convert_kwh=True): """Procesa TCU, CP, FEU diario. :param df: :param verbose: :param convert_kwh: :return: """ if 'TCU' + TARIFAS[0] not in df.columns: # Pasa de €/MWh a €/kWh: if convert_kwh: cols_mwh = [c + t for c i...
[ "Procesa", "TCU", "CP", "FEU", "diario", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importpvpcdata.py#L48-L87
[ "def", "pvpc_calc_tcu_cp_feu_d", "(", "df", ",", "verbose", "=", "True", ",", "convert_kwh", "=", "True", ")", ":", "if", "'TCU'", "+", "TARIFAS", "[", "0", "]", "not", "in", "df", ".", "columns", ":", "# Pasa de €/MWh a €/kWh:", "if", "convert_kwh", ":", ...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
pvpc_procesa_datos_dia
Procesa la información JSON descargada y forma el dataframe de los datos de un día.
esiosdata/importpvpcdata.py
def pvpc_procesa_datos_dia(_, response, verbose=True): """Procesa la información JSON descargada y forma el dataframe de los datos de un día.""" try: d_data = response['PVPC'] df = _process_json_pvpc_hourly_data(pd.DataFrame(d_data)) return df, 0 except Exception as e: if ver...
def pvpc_procesa_datos_dia(_, response, verbose=True): """Procesa la información JSON descargada y forma el dataframe de los datos de un día.""" try: d_data = response['PVPC'] df = _process_json_pvpc_hourly_data(pd.DataFrame(d_data)) return df, 0 except Exception as e: if ver...
[ "Procesa", "la", "información", "JSON", "descargada", "y", "forma", "el", "dataframe", "de", "los", "datos", "de", "un", "día", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importpvpcdata.py#L106-L115
[ "def", "pvpc_procesa_datos_dia", "(", "_", ",", "response", ",", "verbose", "=", "True", ")", ":", "try", ":", "d_data", "=", "response", "[", "'PVPC'", "]", "df", "=", "_process_json_pvpc_hourly_data", "(", "pd", ".", "DataFrame", "(", "d_data", ")", ")",...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
pvpc_data_dia
Obtiene datos de PVPC en un día concreto o un intervalo, accediendo directamente a la web.
esiosdata/importpvpcdata.py
def pvpc_data_dia(str_dia, str_dia_fin=None): """Obtiene datos de PVPC en un día concreto o un intervalo, accediendo directamente a la web.""" params = {'date_fmt': DATE_FMT, 'usar_multithread': False, 'func_procesa_data_dia': pvpc_procesa_datos_dia, 'func_url_data_dia': pvpc_url_dia, ...
def pvpc_data_dia(str_dia, str_dia_fin=None): """Obtiene datos de PVPC en un día concreto o un intervalo, accediendo directamente a la web.""" params = {'date_fmt': DATE_FMT, 'usar_multithread': False, 'func_procesa_data_dia': pvpc_procesa_datos_dia, 'func_url_data_dia': pvpc_url_dia, ...
[ "Obtiene", "datos", "de", "PVPC", "en", "un", "día", "concreto", "o", "un", "intervalo", "accediendo", "directamente", "a", "la", "web", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/importpvpcdata.py#L118-L131
[ "def", "pvpc_data_dia", "(", "str_dia", ",", "str_dia_fin", "=", "None", ")", ":", "params", "=", "{", "'date_fmt'", ":", "DATE_FMT", ",", "'usar_multithread'", ":", "False", ",", "'func_procesa_data_dia'", ":", "pvpc_procesa_datos_dia", ",", "'func_url_data_dia'", ...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
SplunkLogger._compress
Compress the log message in order to send less bytes to the wire.
splunk_logger/splunk_logger.py
def _compress(self, input_str): """ Compress the log message in order to send less bytes to the wire. """ compressed_bits = cStringIO.StringIO() f = gzip.GzipFile(fileobj=compressed_bits, mode='wb') f.write(input_str) f.close() return com...
def _compress(self, input_str): """ Compress the log message in order to send less bytes to the wire. """ compressed_bits = cStringIO.StringIO() f = gzip.GzipFile(fileobj=compressed_bits, mode='wb') f.write(input_str) f.close() return com...
[ "Compress", "the", "log", "message", "in", "order", "to", "send", "less", "bytes", "to", "the", "wire", "." ]
andresriancho/splunk-logger
python
https://github.com/andresriancho/splunk-logger/blob/448d5ba54464fc355786ffb64f11fd6367792381/splunk_logger/splunk_logger.py#L68-L78
[ "def", "_compress", "(", "self", ",", "input_str", ")", ":", "compressed_bits", "=", "cStringIO", ".", "StringIO", "(", ")", "f", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "compressed_bits", ",", "mode", "=", "'wb'", ")", "f", ".", "write", "(...
448d5ba54464fc355786ffb64f11fd6367792381
valid
get_data_coeficientes_perfilado_2017
Extrae la información de las dos hojas del Excel proporcionado por REE con los perfiles iniciales para 2017. :param force_download: Descarga el fichero 'raw' del servidor, en vez de acudir a la copia local. :return: perfiles_2017, coefs_alpha_beta_gamma :rtype: tuple
esiosdata/perfilesconsumopvpc.py
def get_data_coeficientes_perfilado_2017(force_download=False): """Extrae la información de las dos hojas del Excel proporcionado por REE con los perfiles iniciales para 2017. :param force_download: Descarga el fichero 'raw' del servidor, en vez de acudir a la copia local. :return: perfiles_2017, coefs_...
def get_data_coeficientes_perfilado_2017(force_download=False): """Extrae la información de las dos hojas del Excel proporcionado por REE con los perfiles iniciales para 2017. :param force_download: Descarga el fichero 'raw' del servidor, en vez de acudir a la copia local. :return: perfiles_2017, coefs_...
[ "Extrae", "la", "información", "de", "las", "dos", "hojas", "del", "Excel", "proporcionado", "por", "REE", "con", "los", "perfiles", "iniciales", "para", "2017", ".", ":", "param", "force_download", ":", "Descarga", "el", "fichero", "raw", "del", "servidor", ...
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/perfilesconsumopvpc.py#L44-L72
[ "def", "get_data_coeficientes_perfilado_2017", "(", "force_download", "=", "False", ")", ":", "path_perfs", "=", "os", ".", "path", ".", "join", "(", "STORAGE_DIR", ",", "'perfiles_consumo_2017.h5'", ")", "if", "force_download", "or", "not", "os", ".", "path", "...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
get_data_perfiles_estimados_2017
Extrae perfiles estimados para 2017 con el formato de los CSV's mensuales con los perfiles definitivos. :param force_download: bool para forzar la descarga del excel de la web de REE. :return: perfiles_2017 :rtype: pd.Dataframe
esiosdata/perfilesconsumopvpc.py
def get_data_perfiles_estimados_2017(force_download=False): """Extrae perfiles estimados para 2017 con el formato de los CSV's mensuales con los perfiles definitivos. :param force_download: bool para forzar la descarga del excel de la web de REE. :return: perfiles_2017 :rtype: pd.Dataframe """ g...
def get_data_perfiles_estimados_2017(force_download=False): """Extrae perfiles estimados para 2017 con el formato de los CSV's mensuales con los perfiles definitivos. :param force_download: bool para forzar la descarga del excel de la web de REE. :return: perfiles_2017 :rtype: pd.Dataframe """ g...
[ "Extrae", "perfiles", "estimados", "para", "2017", "con", "el", "formato", "de", "los", "CSV", "s", "mensuales", "con", "los", "perfiles", "definitivos", ".", ":", "param", "force_download", ":", "bool", "para", "forzar", "la", "descarga", "del", "excel", "d...
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/perfilesconsumopvpc.py#L75-L90
[ "def", "get_data_perfiles_estimados_2017", "(", "force_download", "=", "False", ")", ":", "global", "DATA_PERFILES_2017", "if", "(", "DATA_PERFILES_2017", "is", "None", ")", "or", "force_download", ":", "perf_demref_2017", ",", "_", "=", "get_data_coeficientes_perfilado...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
main_cli
Actualiza la base de datos de PVPC/DEMANDA almacenados como dataframe en local, creando una nueva si no existe o hubiere algún problema. Los datos registrados se guardan en HDF5
esiosdata/__main__.py
def main_cli(): """ Actualiza la base de datos de PVPC/DEMANDA almacenados como dataframe en local, creando una nueva si no existe o hubiere algún problema. Los datos registrados se guardan en HDF5 """ def _get_parser_args(): p = argparse.ArgumentParser(description='Gestor de DB de PVPC/D...
def main_cli(): """ Actualiza la base de datos de PVPC/DEMANDA almacenados como dataframe en local, creando una nueva si no existe o hubiere algún problema. Los datos registrados se guardan en HDF5 """ def _get_parser_args(): p = argparse.ArgumentParser(description='Gestor de DB de PVPC/D...
[ "Actualiza", "la", "base", "de", "datos", "de", "PVPC", "/", "DEMANDA", "almacenados", "como", "dataframe", "en", "local", "creando", "una", "nueva", "si", "no", "existe", "o", "hubiere", "algún", "problema", ".", "Los", "datos", "registrados", "se", "guarda...
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/__main__.py#L26-L96
[ "def", "main_cli", "(", ")", ":", "def", "_get_parser_args", "(", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Gestor de DB de PVPC/DEMANDA (esios.ree.es)'", ")", "p", ".", "add_argument", "(", "'-d'", ",", "'--dem'", ",", ...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
SpecSelector.registerGoodClass
Internal bookkeeping to handle nested classes
spec/cli.py
def registerGoodClass(self, class_): """ Internal bookkeeping to handle nested classes """ # Class itself added to "good" list self._valid_classes.append(class_) # Recurse into any inner classes for name, cls in class_members(class_): if self.isValidCl...
def registerGoodClass(self, class_): """ Internal bookkeeping to handle nested classes """ # Class itself added to "good" list self._valid_classes.append(class_) # Recurse into any inner classes for name, cls in class_members(class_): if self.isValidCl...
[ "Internal", "bookkeeping", "to", "handle", "nested", "classes" ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/cli.py#L56-L65
[ "def", "registerGoodClass", "(", "self", ",", "class_", ")", ":", "# Class itself added to \"good\" list", "self", ".", "_valid_classes", ".", "append", "(", "class_", ")", "# Recurse into any inner classes", "for", "name", ",", "cls", "in", "class_members", "(", "c...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
SpecSelector.isValidClass
Needs to be its own method so it can be called from both wantClass and registerGoodClass.
spec/cli.py
def isValidClass(self, class_): """ Needs to be its own method so it can be called from both wantClass and registerGoodClass. """ module = inspect.getmodule(class_) valid = ( module in self._valid_modules or ( hasattr(module, '__fil...
def isValidClass(self, class_): """ Needs to be its own method so it can be called from both wantClass and registerGoodClass. """ module = inspect.getmodule(class_) valid = ( module in self._valid_modules or ( hasattr(module, '__fil...
[ "Needs", "to", "be", "its", "own", "method", "so", "it", "can", "be", "called", "from", "both", "wantClass", "and", "registerGoodClass", "." ]
bitprophet/spec
python
https://github.com/bitprophet/spec/blob/d9646c5daf8e479937f970d21ebe185ad936a35a/spec/cli.py#L67-L80
[ "def", "isValidClass", "(", "self", ",", "class_", ")", ":", "module", "=", "inspect", ".", "getmodule", "(", "class_", ")", "valid", "=", "(", "module", "in", "self", ".", "_valid_modules", "or", "(", "hasattr", "(", "module", ",", "'__file__'", ")", ...
d9646c5daf8e479937f970d21ebe185ad936a35a
valid
PVPC.procesa_data_dia
Procesa los datos descargados correspondientes a un día `key_dia`.
esiosdata/classdataesios.py
def procesa_data_dia(self, key_dia, datos_para_procesar): """Procesa los datos descargados correspondientes a un día `key_dia`.""" return pvpc_procesa_datos_dia(key_dia, datos_para_procesar, verbose=self.verbose)
def procesa_data_dia(self, key_dia, datos_para_procesar): """Procesa los datos descargados correspondientes a un día `key_dia`.""" return pvpc_procesa_datos_dia(key_dia, datos_para_procesar, verbose=self.verbose)
[ "Procesa", "los", "datos", "descargados", "correspondientes", "a", "un", "día", "key_dia", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/classdataesios.py#L59-L61
[ "def", "procesa_data_dia", "(", "self", ",", "key_dia", ",", "datos_para_procesar", ")", ":", "return", "pvpc_procesa_datos_dia", "(", "key_dia", ",", "datos_para_procesar", ",", "verbose", "=", "self", ".", "verbose", ")" ]
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
PVPC.get_resample_data
Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.
esiosdata/classdataesios.py
def get_resample_data(self): """Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.""" if self.data is not None: if self._pvpc_mean_daily is None: self._pvpc_mean_daily = self.data['data'].resample('D').mean() if self._pvpc_mean_monthly is...
def get_resample_data(self): """Obtiene los dataframes de los datos de PVPC con resampling diario y mensual.""" if self.data is not None: if self._pvpc_mean_daily is None: self._pvpc_mean_daily = self.data['data'].resample('D').mean() if self._pvpc_mean_monthly is...
[ "Obtiene", "los", "dataframes", "de", "los", "datos", "de", "PVPC", "con", "resampling", "diario", "y", "mensual", "." ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/classdataesios.py#L63-L70
[ "def", "get_resample_data", "(", "self", ")", ":", "if", "self", ".", "data", "is", "not", "None", ":", "if", "self", ".", "_pvpc_mean_daily", "is", "None", ":", "self", ".", "_pvpc_mean_daily", "=", "self", ".", "data", "[", "'data'", "]", ".", "resam...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
DatosREE.last_entry
Definición específica para filtrar por datos de demanda energética (pues los datos se extienden más allá del tiempo presente debido a las columnas de potencia prevista y programada. :param data_revisar: (OPC) Se puede pasar un dataframe específico :param key_revisar: (OPC) Normalmente, para uti...
esiosdata/classdataesios.py
def last_entry(self, data_revisar=None, key_revisar=None): """ Definición específica para filtrar por datos de demanda energética (pues los datos se extienden más allá del tiempo presente debido a las columnas de potencia prevista y programada. :param data_revisar: (OPC) Se puede pasar ...
def last_entry(self, data_revisar=None, key_revisar=None): """ Definición específica para filtrar por datos de demanda energética (pues los datos se extienden más allá del tiempo presente debido a las columnas de potencia prevista y programada. :param data_revisar: (OPC) Se puede pasar ...
[ "Definición", "específica", "para", "filtrar", "por", "datos", "de", "demanda", "energética", "(", "pues", "los", "datos", "se", "extienden", "más", "allá", "del", "tiempo", "presente", "debido", "a", "las", "columnas", "de", "potencia", "prevista", "y", "prog...
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/classdataesios.py#L125-L140
[ "def", "last_entry", "(", "self", ",", "data_revisar", "=", "None", ",", "key_revisar", "=", "None", ")", ":", "if", "data_revisar", "is", "None", "and", "key_revisar", "is", "None", ":", "data_revisar", "=", "self", ".", "data", "[", "self", ".", "maste...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
DatosREE.integridad_data
Definición específica para comprobar timezone y frecuencia de los datos, además de comprobar que el index de cada dataframe de la base de datos sea de fechas, único (sin duplicados) y creciente :param data_integr: :param key:
esiosdata/classdataesios.py
def integridad_data(self, data_integr=None, key=None): """ Definición específica para comprobar timezone y frecuencia de los datos, además de comprobar que el index de cada dataframe de la base de datos sea de fechas, único (sin duplicados) y creciente :param data_integr: :param ...
def integridad_data(self, data_integr=None, key=None): """ Definición específica para comprobar timezone y frecuencia de los datos, además de comprobar que el index de cada dataframe de la base de datos sea de fechas, único (sin duplicados) y creciente :param data_integr: :param ...
[ "Definición", "específica", "para", "comprobar", "timezone", "y", "frecuencia", "de", "los", "datos", "además", "de", "comprobar", "que", "el", "index", "de", "cada", "dataframe", "de", "la", "base", "de", "datos", "sea", "de", "fechas", "único", "(", "sin",...
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/classdataesios.py#L143-L155
[ "def", "integridad_data", "(", "self", ",", "data_integr", "=", "None", ",", "key", "=", "None", ")", ":", "if", "data_integr", "is", "None", "and", "key", "is", "None", "and", "all", "(", "k", "in", "self", ".", "data", ".", "keys", "(", ")", "for...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
DatosREE.busca_errores_data
Busca errores o inconsistencias en los datos adquiridos :return: Dataframe de errores encontrados
esiosdata/classdataesios.py
def busca_errores_data(self): """ Busca errores o inconsistencias en los datos adquiridos :return: Dataframe de errores encontrados """ data_busqueda = self.append_delta_index(TS_DATA_DEM, data_delta=self.data[self.masterkey].copy()) idx_desconex = (((data_busqueda.index ...
def busca_errores_data(self): """ Busca errores o inconsistencias en los datos adquiridos :return: Dataframe de errores encontrados """ data_busqueda = self.append_delta_index(TS_DATA_DEM, data_delta=self.data[self.masterkey].copy()) idx_desconex = (((data_busqueda.index ...
[ "Busca", "errores", "o", "inconsistencias", "en", "los", "datos", "adquiridos", ":", "return", ":", "Dataframe", "de", "errores", "encontrados" ]
azogue/esiosdata
python
https://github.com/azogue/esiosdata/blob/680c7918955bc6ceee5bded92b3a4485f5ea8151/esiosdata/classdataesios.py#L157-L179
[ "def", "busca_errores_data", "(", "self", ")", ":", "data_busqueda", "=", "self", ".", "append_delta_index", "(", "TS_DATA_DEM", ",", "data_delta", "=", "self", ".", "data", "[", "self", ".", "masterkey", "]", ".", "copy", "(", ")", ")", "idx_desconex", "=...
680c7918955bc6ceee5bded92b3a4485f5ea8151
valid
sanitize_path
Performs sanitation of the path after validating :param path: path to sanitize :return: path :raises: - InvalidPath if the path doesn't start with a slash
flask_journey/utils.py
def sanitize_path(path): """Performs sanitation of the path after validating :param path: path to sanitize :return: path :raises: - InvalidPath if the path doesn't start with a slash """ if path == '/': # Nothing to do, just return return path if path[:1] != '/': ...
def sanitize_path(path): """Performs sanitation of the path after validating :param path: path to sanitize :return: path :raises: - InvalidPath if the path doesn't start with a slash """ if path == '/': # Nothing to do, just return return path if path[:1] != '/': ...
[ "Performs", "sanitation", "of", "the", "path", "after", "validating" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/utils.py#L13-L32
[ "def", "sanitize_path", "(", "path", ")", ":", "if", "path", "==", "'/'", ":", "# Nothing to do, just return", "return", "path", "if", "path", "[", ":", "1", "]", "!=", "'/'", ":", "raise", "InvalidPath", "(", "'The path must start with a slash'", ")", "# Dedu...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
_validate_schema
Ensures the passed schema instance is compatible :param obj: object to validate :return: obj :raises: - IncompatibleSchema if the passed schema is of an incompatible type
flask_journey/utils.py
def _validate_schema(obj): """Ensures the passed schema instance is compatible :param obj: object to validate :return: obj :raises: - IncompatibleSchema if the passed schema is of an incompatible type """ if obj is not None and not isinstance(obj, Schema): raise IncompatibleSch...
def _validate_schema(obj): """Ensures the passed schema instance is compatible :param obj: object to validate :return: obj :raises: - IncompatibleSchema if the passed schema is of an incompatible type """ if obj is not None and not isinstance(obj, Schema): raise IncompatibleSch...
[ "Ensures", "the", "passed", "schema", "instance", "is", "compatible" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/utils.py#L35-L47
[ "def", "_validate_schema", "(", "obj", ")", ":", "if", "obj", "is", "not", "None", "and", "not", "isinstance", "(", "obj", ",", "Schema", ")", ":", "raise", "IncompatibleSchema", "(", "'Schema must be of type {0}'", ".", "format", "(", "Schema", ")", ")", ...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
route
Journey route decorator Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow. :param bp: :class:`flask.Blueprint` object :param args: args to pass along to `Blueprint.route` :param kwargs: - :strict_slashes: Enable / disable strict slashes (...
flask_journey/utils.py
def route(bp, *args, **kwargs): """Journey route decorator Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow. :param bp: :class:`flask.Blueprint` object :param args: args to pass along to `Blueprint.route` :param kwargs: - :strict_sla...
def route(bp, *args, **kwargs): """Journey route decorator Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow. :param bp: :class:`flask.Blueprint` object :param args: args to pass along to `Blueprint.route` :param kwargs: - :strict_sla...
[ "Journey", "route", "decorator" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/utils.py#L50-L107
[ "def", "route", "(", "bp", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'strict_slashes'", "]", "=", "kwargs", ".", "pop", "(", "'strict_slashes'", ",", "False", ")", "body", "=", "_validate_schema", "(", "kwargs", ".", "pop", ...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
BlueprintBundle.attach_bp
Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint`
flask_journey/blueprint_bundle.py
def attach_bp(self, bp, description=''): """Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint` """ ...
def attach_bp(self, bp, description=''): """Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint` """ ...
[ "Attaches", "a", "flask", ".", "Blueprint", "to", "the", "bundle" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/blueprint_bundle.py#L20-L32
[ "def", "attach_bp", "(", "self", ",", "bp", ",", "description", "=", "''", ")", ":", "if", "not", "isinstance", "(", "bp", ",", "Blueprint", ")", ":", "raise", "InvalidBlueprint", "(", "'Blueprints attached to the bundle must be of type {0}'", ".", "format", "("...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
DottedRule.move_dot
Returns the DottedRule that results from moving the dot.
purplex/grammar.py
def move_dot(self): """Returns the DottedRule that results from moving the dot.""" return self.__class__(self.production, self.pos + 1, self.lookahead)
def move_dot(self): """Returns the DottedRule that results from moving the dot.""" return self.__class__(self.production, self.pos + 1, self.lookahead)
[ "Returns", "the", "DottedRule", "that", "results", "from", "moving", "the", "dot", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L69-L71
[ "def", "move_dot", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "production", ",", "self", ".", "pos", "+", "1", ",", "self", ".", "lookahead", ")" ]
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Grammar.first
Computes the intermediate FIRST set using symbols.
purplex/grammar.py
def first(self, symbols): """Computes the intermediate FIRST set using symbols.""" ret = set() if EPSILON in symbols: return set([EPSILON]) for symbol in symbols: ret |= self._first[symbol] - set([EPSILON]) if EPSILON not in self._first[symbol]: ...
def first(self, symbols): """Computes the intermediate FIRST set using symbols.""" ret = set() if EPSILON in symbols: return set([EPSILON]) for symbol in symbols: ret |= self._first[symbol] - set([EPSILON]) if EPSILON not in self._first[symbol]: ...
[ "Computes", "the", "intermediate", "FIRST", "set", "using", "symbols", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L94-L108
[ "def", "first", "(", "self", ",", "symbols", ")", ":", "ret", "=", "set", "(", ")", "if", "EPSILON", "in", "symbols", ":", "return", "set", "(", "[", "EPSILON", "]", ")", "for", "symbol", "in", "symbols", ":", "ret", "|=", "self", ".", "_first", ...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Grammar._compute_first
Computes the FIRST set for every symbol in the grammar. Tenatively based on _compute_first in PLY.
purplex/grammar.py
def _compute_first(self): """Computes the FIRST set for every symbol in the grammar. Tenatively based on _compute_first in PLY. """ for terminal in self.terminals: self._first[terminal].add(terminal) self._first[END_OF_INPUT].add(END_OF_INPUT) while True: ...
def _compute_first(self): """Computes the FIRST set for every symbol in the grammar. Tenatively based on _compute_first in PLY. """ for terminal in self.terminals: self._first[terminal].add(terminal) self._first[END_OF_INPUT].add(END_OF_INPUT) while True: ...
[ "Computes", "the", "FIRST", "set", "for", "every", "symbol", "in", "the", "grammar", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L110-L130
[ "def", "_compute_first", "(", "self", ")", ":", "for", "terminal", "in", "self", ".", "terminals", ":", "self", ".", "_first", "[", "terminal", "]", ".", "add", "(", "terminal", ")", "self", ".", "_first", "[", "END_OF_INPUT", "]", ".", "add", "(", "...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Grammar._compute_follow
Computes the FOLLOW set for every non-terminal in the grammar. Tenatively based on _compute_follow in PLY.
purplex/grammar.py
def _compute_follow(self): """Computes the FOLLOW set for every non-terminal in the grammar. Tenatively based on _compute_follow in PLY. """ self._follow[self.start_symbol].add(END_OF_INPUT) while True: changed = False for nonterminal, productions in se...
def _compute_follow(self): """Computes the FOLLOW set for every non-terminal in the grammar. Tenatively based on _compute_follow in PLY. """ self._follow[self.start_symbol].add(END_OF_INPUT) while True: changed = False for nonterminal, productions in se...
[ "Computes", "the", "FOLLOW", "set", "for", "every", "non", "-", "terminal", "in", "the", "grammar", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L132-L158
[ "def", "_compute_follow", "(", "self", ")", ":", "self", ".", "_follow", "[", "self", ".", "start_symbol", "]", ".", "add", "(", "END_OF_INPUT", ")", "while", "True", ":", "changed", "=", "False", "for", "nonterminal", ",", "productions", "in", "self", "...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Grammar.initial_closure
Computes the initial closure using the START_foo production.
purplex/grammar.py
def initial_closure(self): """Computes the initial closure using the START_foo production.""" first_rule = DottedRule(self.start, 0, END_OF_INPUT) return self.closure([first_rule])
def initial_closure(self): """Computes the initial closure using the START_foo production.""" first_rule = DottedRule(self.start, 0, END_OF_INPUT) return self.closure([first_rule])
[ "Computes", "the", "initial", "closure", "using", "the", "START_foo", "production", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L160-L163
[ "def", "initial_closure", "(", "self", ")", ":", "first_rule", "=", "DottedRule", "(", "self", ".", "start", ",", "0", ",", "END_OF_INPUT", ")", "return", "self", ".", "closure", "(", "[", "first_rule", "]", ")" ]
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Grammar.goto
Computes the next closure for rules based on the symbol we got. Args: rules - an iterable of DottedRules symbol - a string denoting the symbol we've just seen Returns: frozenset of DottedRules
purplex/grammar.py
def goto(self, rules, symbol): """Computes the next closure for rules based on the symbol we got. Args: rules - an iterable of DottedRules symbol - a string denoting the symbol we've just seen Returns: frozenset of DottedRules """ return self.closure( ...
def goto(self, rules, symbol): """Computes the next closure for rules based on the symbol we got. Args: rules - an iterable of DottedRules symbol - a string denoting the symbol we've just seen Returns: frozenset of DottedRules """ return self.closure( ...
[ "Computes", "the", "next", "closure", "for", "rules", "based", "on", "the", "symbol", "we", "got", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L165-L177
[ "def", "goto", "(", "self", ",", "rules", ",", "symbol", ")", ":", "return", "self", ".", "closure", "(", "{", "rule", ".", "move_dot", "(", ")", "for", "rule", "in", "rules", "if", "not", "rule", ".", "at_end", "and", "rule", ".", "rhs", "[", "r...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Grammar.closure
Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules
purplex/grammar.py
def closure(self, rules): """Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules """ closure = set() todo = set(rules) while todo: rule = todo.pop()...
def closure(self, rules): """Fills out the entire closure based on some initial dotted rules. Args: rules - an iterable of DottedRules Returns: frozenset of DottedRules """ closure = set() todo = set(rules) while todo: rule = todo.pop()...
[ "Fills", "out", "the", "entire", "closure", "based", "on", "some", "initial", "dotted", "rules", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L179-L212
[ "def", "closure", "(", "self", ",", "rules", ")", ":", "closure", "=", "set", "(", ")", "todo", "=", "set", "(", "rules", ")", "while", "todo", ":", "rule", "=", "todo", ".", "pop", "(", ")", "closure", ".", "add", "(", "rule", ")", "# If the dot...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Grammar.closures
Computes all LR(1) closure sets for the grammar.
purplex/grammar.py
def closures(self): """Computes all LR(1) closure sets for the grammar.""" initial = self.initial_closure() closures = collections.OrderedDict() goto = collections.defaultdict(dict) todo = set([initial]) while todo: closure = todo.pop() closures[c...
def closures(self): """Computes all LR(1) closure sets for the grammar.""" initial = self.initial_closure() closures = collections.OrderedDict() goto = collections.defaultdict(dict) todo = set([initial]) while todo: closure = todo.pop() closures[c...
[ "Computes", "all", "LR", "(", "1", ")", "closure", "sets", "for", "the", "grammar", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L214-L239
[ "def", "closures", "(", "self", ")", ":", "initial", "=", "self", ".", "initial_closure", "(", ")", "closures", "=", "collections", ".", "OrderedDict", "(", ")", "goto", "=", "collections", ".", "defaultdict", "(", "dict", ")", "todo", "=", "set", "(", ...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
Journey.init_app
Initializes Journey extension :param app: App passed from constructor or directly to init_app :raises: - NoBundlesAttached if no bundles has been attached attached
flask_journey/journey.py
def init_app(self, app): """Initializes Journey extension :param app: App passed from constructor or directly to init_app :raises: - NoBundlesAttached if no bundles has been attached attached """ if len(self._attached_bundles) == 0: raise NoBundlesAttac...
def init_app(self, app): """Initializes Journey extension :param app: App passed from constructor or directly to init_app :raises: - NoBundlesAttached if no bundles has been attached attached """ if len(self._attached_bundles) == 0: raise NoBundlesAttac...
[ "Initializes", "Journey", "extension" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L38-L65
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "if", "len", "(", "self", ".", "_attached_bundles", ")", "==", "0", ":", "raise", "NoBundlesAttached", "(", "\"At least one bundle must be attached before initializing Journey\"", ")", "for", "bundle", "in", "s...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
Journey.routes_simple
Returns simple info about registered blueprints :return: Tuple containing endpoint, path and allowed methods for each route
flask_journey/journey.py
def routes_simple(self): """Returns simple info about registered blueprints :return: Tuple containing endpoint, path and allowed methods for each route """ routes = [] for bundle in self._registered_bundles: bundle_path = bundle['path'] for blueprint in...
def routes_simple(self): """Returns simple info about registered blueprints :return: Tuple containing endpoint, path and allowed methods for each route """ routes = [] for bundle in self._registered_bundles: bundle_path = bundle['path'] for blueprint in...
[ "Returns", "simple", "info", "about", "registered", "blueprints" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L77-L98
[ "def", "routes_simple", "(", "self", ")", ":", "routes", "=", "[", "]", "for", "bundle", "in", "self", ".", "_registered_bundles", ":", "bundle_path", "=", "bundle", "[", "'path'", "]", "for", "blueprint", "in", "bundle", "[", "'blueprints'", "]", ":", "...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
Journey._bundle_exists
Checks if a bundle exists at the provided path :param path: Bundle path :return: bool
flask_journey/journey.py
def _bundle_exists(self, path): """Checks if a bundle exists at the provided path :param path: Bundle path :return: bool """ for attached_bundle in self._attached_bundles: if path == attached_bundle.path: return True return False
def _bundle_exists(self, path): """Checks if a bundle exists at the provided path :param path: Bundle path :return: bool """ for attached_bundle in self._attached_bundles: if path == attached_bundle.path: return True return False
[ "Checks", "if", "a", "bundle", "exists", "at", "the", "provided", "path" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L100-L111
[ "def", "_bundle_exists", "(", "self", ",", "path", ")", ":", "for", "attached_bundle", "in", "self", ".", "_attached_bundles", ":", "if", "path", "==", "attached_bundle", ".", "path", ":", "return", "True", "return", "False" ]
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
Journey.attach_bundle
Attaches a bundle object :param bundle: :class:`flask_journey.BlueprintBundle` object :raises: - IncompatibleBundle if the bundle is not of type `BlueprintBundle` - ConflictingPath if a bundle already exists at bundle.path - MissingBlueprints if the bundle doesn't co...
flask_journey/journey.py
def attach_bundle(self, bundle): """Attaches a bundle object :param bundle: :class:`flask_journey.BlueprintBundle` object :raises: - IncompatibleBundle if the bundle is not of type `BlueprintBundle` - ConflictingPath if a bundle already exists at bundle.path ...
def attach_bundle(self, bundle): """Attaches a bundle object :param bundle: :class:`flask_journey.BlueprintBundle` object :raises: - IncompatibleBundle if the bundle is not of type `BlueprintBundle` - ConflictingPath if a bundle already exists at bundle.path ...
[ "Attaches", "a", "bundle", "object" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L113-L133
[ "def", "attach_bundle", "(", "self", ",", "bundle", ")", ":", "if", "not", "isinstance", "(", "bundle", ",", "BlueprintBundle", ")", ":", "raise", "IncompatibleBundle", "(", "'BlueprintBundle object passed to attach_bundle must be of type {0}'", ".", "format", "(", "B...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
Journey._register_blueprint
Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path :return: Dict with info about the blueprint
flask_journey/journey.py
def _register_blueprint(self, app, bp, bundle_path, child_path, description): """Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path ...
def _register_blueprint(self, app, bp, bundle_path, child_path, description): """Register and return info about the registered blueprint :param bp: :class:`flask.Blueprint` object :param bundle_path: the URL prefix of the bundle :param child_path: blueprint relative to the bundle path ...
[ "Register", "and", "return", "info", "about", "the", "registered", "blueprint" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L135-L154
[ "def", "_register_blueprint", "(", "self", ",", "app", ",", "bp", ",", "bundle_path", ",", "child_path", ",", "description", ")", ":", "base_path", "=", "sanitize_path", "(", "self", ".", "_journey_path", "+", "bundle_path", "+", "child_path", ")", "app", "....
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
Journey.get_blueprint_routes
Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path :param app: App instance to obtain rules from :param base_path: Base path to return detailed route info for :return: List of route detail dicts
flask_journey/journey.py
def get_blueprint_routes(app, base_path): """Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path :param app: App instance to obtain rules from :param base_path: Base path to return detailed route info for :return: List of route detail dicts...
def get_blueprint_routes(app, base_path): """Returns detailed information about registered blueprint routes matching the `BlueprintBundle` path :param app: App instance to obtain rules from :param base_path: Base path to return detailed route info for :return: List of route detail dicts...
[ "Returns", "detailed", "information", "about", "registered", "blueprint", "routes", "matching", "the", "BlueprintBundle", "path" ]
rbw/flask-journey
python
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L167-L186
[ "def", "get_blueprint_routes", "(", "app", ",", "base_path", ")", ":", "routes", "=", "[", "]", "for", "child", "in", "app", ".", "url_map", ".", "iter_rules", "(", ")", ":", "if", "child", ".", "rule", ".", "startswith", "(", "base_path", ")", ":", ...
6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285
valid
ParserBase.compute_precedence
Computes the precedence of terminal and production. The precedence of a terminal is it's level in the PRECEDENCE tuple. For a production, the precedence is the right-most terminal (if it exists). The default precedence is DEFAULT_PREC - (LEFT, 0). Returns: precedence - dict...
purplex/parse.py
def compute_precedence(terminals, productions, precedence_levels): """Computes the precedence of terminal and production. The precedence of a terminal is it's level in the PRECEDENCE tuple. For a production, the precedence is the right-most terminal (if it exists). The default precedenc...
def compute_precedence(terminals, productions, precedence_levels): """Computes the precedence of terminal and production. The precedence of a terminal is it's level in the PRECEDENCE tuple. For a production, the precedence is the right-most terminal (if it exists). The default precedenc...
[ "Computes", "the", "precedence", "of", "terminal", "and", "production", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/parse.py#L85-L117
[ "def", "compute_precedence", "(", "terminals", ",", "productions", ",", "precedence_levels", ")", ":", "precedence", "=", "collections", ".", "OrderedDict", "(", ")", "for", "terminal", "in", "terminals", ":", "precedence", "[", "terminal", "]", "=", "DEFAULT_PR...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
ParserBase.make_tables
Generates the ACTION and GOTO tables for the grammar. Returns: action - dict[state][lookahead] = (action, ...) goto - dict[state][just_reduced] = new_state
purplex/parse.py
def make_tables(grammar, precedence): """Generates the ACTION and GOTO tables for the grammar. Returns: action - dict[state][lookahead] = (action, ...) goto - dict[state][just_reduced] = new_state """ ACTION = {} GOTO = {} labels = {} d...
def make_tables(grammar, precedence): """Generates the ACTION and GOTO tables for the grammar. Returns: action - dict[state][lookahead] = (action, ...) goto - dict[state][just_reduced] = new_state """ ACTION = {} GOTO = {} labels = {} d...
[ "Generates", "the", "ACTION", "and", "GOTO", "tables", "for", "the", "grammar", "." ]
mtomwing/purplex
python
https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/parse.py#L120-L193
[ "def", "make_tables", "(", "grammar", ",", "precedence", ")", ":", "ACTION", "=", "{", "}", "GOTO", "=", "{", "}", "labels", "=", "{", "}", "def", "get_label", "(", "closure", ")", ":", "if", "closure", "not", "in", "labels", ":", "labels", "[", "c...
4072109e1d4395826983cd9d95ead2c1dfc1184e
valid
KB_AgentProgram
A generic logical knowledge-based agent program. [Fig. 7.1]
aima/logic.py
def KB_AgentProgram(KB): """A generic logical knowledge-based agent program. [Fig. 7.1]""" steps = itertools.count() def program(percept): t = steps.next() KB.tell(make_percept_sentence(percept, t)) action = KB.ask(make_action_query(t)) KB.tell(make_action_sentence(action, t...
def KB_AgentProgram(KB): """A generic logical knowledge-based agent program. [Fig. 7.1]""" steps = itertools.count() def program(percept): t = steps.next() KB.tell(make_percept_sentence(percept, t)) action = KB.ask(make_action_query(t)) KB.tell(make_action_sentence(action, t...
[ "A", "generic", "logical", "knowledge", "-", "based", "agent", "program", ".", "[", "Fig", ".", "7", ".", "1", "]" ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L92-L112
[ "def", "KB_AgentProgram", "(", "KB", ")", ":", "steps", "=", "itertools", ".", "count", "(", ")", "def", "program", "(", "percept", ")", ":", "t", "=", "steps", ".", "next", "(", ")", "KB", ".", "tell", "(", "make_percept_sentence", "(", "percept", "...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
expr
Create an Expr representing a logic expression by parsing the input string. Symbols and numbers are automatically converted to Exprs. In addition you can use alternative spellings of these operators: 'x ==> y' parses as (x >> y) # Implication 'x <== y' parses as (x << y) # Reverse impl...
aima/logic.py
def expr(s): """Create an Expr representing a logic expression by parsing the input string. Symbols and numbers are automatically converted to Exprs. In addition you can use alternative spellings of these operators: 'x ==> y' parses as (x >> y) # Implication 'x <== y' parses as (x << ...
def expr(s): """Create an Expr representing a logic expression by parsing the input string. Symbols and numbers are automatically converted to Exprs. In addition you can use alternative spellings of these operators: 'x ==> y' parses as (x >> y) # Implication 'x <== y' parses as (x << ...
[ "Create", "an", "Expr", "representing", "a", "logic", "expression", "by", "parsing", "the", "input", "string", ".", "Symbols", "and", "numbers", "are", "automatically", "converted", "to", "Exprs", ".", "In", "addition", "you", "can", "use", "alternative", "spe...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L220-L243
[ "def", "expr", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "Expr", ")", ":", "return", "s", "if", "isnumber", "(", "s", ")", ":", "return", "Expr", "(", "s", ")", "## Replace the alternative spellings of operators with canonical spellings", "s", "...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
variables
Return a set of the variables in expression s. >>> ppset(variables(F(x, A, y))) set([x, y]) >>> ppset(variables(F(G(x), z))) set([x, z]) >>> ppset(variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, z)'))) set([x, y, z])
aima/logic.py
def variables(s): """Return a set of the variables in expression s. >>> ppset(variables(F(x, A, y))) set([x, y]) >>> ppset(variables(F(G(x), z))) set([x, z]) >>> ppset(variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, z)'))) set([x, y, z]) """ result = set([]) def walk(s): ...
def variables(s): """Return a set of the variables in expression s. >>> ppset(variables(F(x, A, y))) set([x, y]) >>> ppset(variables(F(G(x), z))) set([x, z]) >>> ppset(variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, z)'))) set([x, y, z]) """ result = set([]) def walk(s): ...
[ "Return", "a", "set", "of", "the", "variables", "in", "expression", "s", ".", ">>>", "ppset", "(", "variables", "(", "F", "(", "x", "A", "y", ")))", "set", "(", "[", "x", "y", "]", ")", ">>>", "ppset", "(", "variables", "(", "F", "(", "G", "(",...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L258-L275
[ "def", "variables", "(", "s", ")", ":", "result", "=", "set", "(", "[", "]", ")", "def", "walk", "(", "s", ")", ":", "if", "is_variable", "(", "s", ")", ":", "result", ".", "add", "(", "s", ")", "else", ":", "for", "arg", "in", "s", ".", "a...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
is_definite_clause
returns True for exprs s of the form A & B & ... & C ==> D, where all literals are positive. In clause form, this is ~A | ~B | ... | ~C | D, where exactly one clause is positive. >>> is_definite_clause(expr('Farmer(Mac)')) True >>> is_definite_clause(expr('~Farmer(Mac)')) False >>> is_defin...
aima/logic.py
def is_definite_clause(s): """returns True for exprs s of the form A & B & ... & C ==> D, where all literals are positive. In clause form, this is ~A | ~B | ... | ~C | D, where exactly one clause is positive. >>> is_definite_clause(expr('Farmer(Mac)')) True >>> is_definite_clause(expr('~Farmer(...
def is_definite_clause(s): """returns True for exprs s of the form A & B & ... & C ==> D, where all literals are positive. In clause form, this is ~A | ~B | ... | ~C | D, where exactly one clause is positive. >>> is_definite_clause(expr('Farmer(Mac)')) True >>> is_definite_clause(expr('~Farmer(...
[ "returns", "True", "for", "exprs", "s", "of", "the", "form", "A", "&", "B", "&", "...", "&", "C", "==", ">", "D", "where", "all", "literals", "are", "positive", ".", "In", "clause", "form", "this", "is", "~A", "|", "~B", "|", "...", "|", "~C", ...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L277-L299
[ "def", "is_definite_clause", "(", "s", ")", ":", "if", "is_symbol", "(", "s", ".", "op", ")", ":", "return", "True", "elif", "s", ".", "op", "==", "'>>'", ":", "antecedent", ",", "consequent", "=", "s", ".", "args", "return", "(", "is_symbol", "(", ...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
parse_definite_clause
Return the antecedents and the consequent of a definite clause.
aima/logic.py
def parse_definite_clause(s): "Return the antecedents and the consequent of a definite clause." assert is_definite_clause(s) if is_symbol(s.op): return [], s else: antecedent, consequent = s.args return conjuncts(antecedent), consequent
def parse_definite_clause(s): "Return the antecedents and the consequent of a definite clause." assert is_definite_clause(s) if is_symbol(s.op): return [], s else: antecedent, consequent = s.args return conjuncts(antecedent), consequent
[ "Return", "the", "antecedents", "and", "the", "consequent", "of", "a", "definite", "clause", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L301-L308
[ "def", "parse_definite_clause", "(", "s", ")", ":", "assert", "is_definite_clause", "(", "s", ")", "if", "is_symbol", "(", "s", ".", "op", ")", ":", "return", "[", "]", ",", "s", "else", ":", "antecedent", ",", "consequent", "=", "s", ".", "args", "r...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
tt_entails
Does kb entail the sentence alpha? Use truth tables. For propositional kb's and sentences. [Fig. 7.10] >>> tt_entails(expr('P & Q'), expr('Q')) True
aima/logic.py
def tt_entails(kb, alpha): """Does kb entail the sentence alpha? Use truth tables. For propositional kb's and sentences. [Fig. 7.10] >>> tt_entails(expr('P & Q'), expr('Q')) True """ assert not variables(alpha) return tt_check_all(kb, alpha, prop_symbols(kb & alpha), {})
def tt_entails(kb, alpha): """Does kb entail the sentence alpha? Use truth tables. For propositional kb's and sentences. [Fig. 7.10] >>> tt_entails(expr('P & Q'), expr('Q')) True """ assert not variables(alpha) return tt_check_all(kb, alpha, prop_symbols(kb & alpha), {})
[ "Does", "kb", "entail", "the", "sentence", "alpha?", "Use", "truth", "tables", ".", "For", "propositional", "kb", "s", "and", "sentences", ".", "[", "Fig", ".", "7", ".", "10", "]", ">>>", "tt_entails", "(", "expr", "(", "P", "&", "Q", ")", "expr", ...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L316-L323
[ "def", "tt_entails", "(", "kb", ",", "alpha", ")", ":", "assert", "not", "variables", "(", "alpha", ")", "return", "tt_check_all", "(", "kb", ",", "alpha", ",", "prop_symbols", "(", "kb", "&", "alpha", ")", ",", "{", "}", ")" ]
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
tt_check_all
Auxiliary routine to implement tt_entails.
aima/logic.py
def tt_check_all(kb, alpha, symbols, model): "Auxiliary routine to implement tt_entails." if not symbols: if pl_true(kb, model): result = pl_true(alpha, model) assert result in (True, False) return result else: return True else: P, rest...
def tt_check_all(kb, alpha, symbols, model): "Auxiliary routine to implement tt_entails." if not symbols: if pl_true(kb, model): result = pl_true(alpha, model) assert result in (True, False) return result else: return True else: P, rest...
[ "Auxiliary", "routine", "to", "implement", "tt_entails", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L325-L337
[ "def", "tt_check_all", "(", "kb", ",", "alpha", ",", "symbols", ",", "model", ")", ":", "if", "not", "symbols", ":", "if", "pl_true", "(", "kb", ",", "model", ")", ":", "result", "=", "pl_true", "(", "alpha", ",", "model", ")", "assert", "result", ...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
prop_symbols
Return a list of all propositional symbols in x.
aima/logic.py
def prop_symbols(x): "Return a list of all propositional symbols in x." if not isinstance(x, Expr): return [] elif is_prop_symbol(x.op): return [x] else: return list(set(symbol for arg in x.args for symbol in prop_symbols(arg)))
def prop_symbols(x): "Return a list of all propositional symbols in x." if not isinstance(x, Expr): return [] elif is_prop_symbol(x.op): return [x] else: return list(set(symbol for arg in x.args for symbol in prop_symbols(arg)))
[ "Return", "a", "list", "of", "all", "propositional", "symbols", "in", "x", "." ]
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L339-L347
[ "def", "prop_symbols", "(", "x", ")", ":", "if", "not", "isinstance", "(", "x", ",", "Expr", ")", ":", "return", "[", "]", "elif", "is_prop_symbol", "(", "x", ".", "op", ")", ":", "return", "[", "x", "]", "else", ":", "return", "list", "(", "set"...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
pl_true
Return True if the propositional logic expression is true in the model, and False if it is false. If the model does not specify the value for every proposition, this may return None to indicate 'not obvious'; this may happen even when the expression is tautological.
aima/logic.py
def pl_true(exp, model={}): """Return True if the propositional logic expression is true in the model, and False if it is false. If the model does not specify the value for every proposition, this may return None to indicate 'not obvious'; this may happen even when the expression is tautological.""" ...
def pl_true(exp, model={}): """Return True if the propositional logic expression is true in the model, and False if it is false. If the model does not specify the value for every proposition, this may return None to indicate 'not obvious'; this may happen even when the expression is tautological.""" ...
[ "Return", "True", "if", "the", "propositional", "logic", "expression", "is", "true", "in", "the", "model", "and", "False", "if", "it", "is", "false", ".", "If", "the", "model", "does", "not", "specify", "the", "value", "for", "every", "proposition", "this"...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L357-L401
[ "def", "pl_true", "(", "exp", ",", "model", "=", "{", "}", ")", ":", "op", ",", "args", "=", "exp", ".", "op", ",", "exp", ".", "args", "if", "exp", "==", "TRUE", ":", "return", "True", "elif", "exp", "==", "FALSE", ":", "return", "False", "eli...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
to_cnf
Convert a propositional logical sentence s to conjunctive normal form. That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253] >>> to_cnf("~(B|C)") (~B & ~C) >>> to_cnf("B <=> (P1|P2)") ((~P1 | B) & (~P2 | B) & (P1 | P2 | ~B)) >>> to_cnf("a | (b & c) | d") ((b | a | d) & (c | a ...
aima/logic.py
def to_cnf(s): """Convert a propositional logical sentence s to conjunctive normal form. That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253] >>> to_cnf("~(B|C)") (~B & ~C) >>> to_cnf("B <=> (P1|P2)") ((~P1 | B) & (~P2 | B) & (P1 | P2 | ~B)) >>> to_cnf("a | (b & c) | d") ...
def to_cnf(s): """Convert a propositional logical sentence s to conjunctive normal form. That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253] >>> to_cnf("~(B|C)") (~B & ~C) >>> to_cnf("B <=> (P1|P2)") ((~P1 | B) & (~P2 | B) & (P1 | P2 | ~B)) >>> to_cnf("a | (b & c) | d") ...
[ "Convert", "a", "propositional", "logical", "sentence", "s", "to", "conjunctive", "normal", "form", ".", "That", "is", "to", "the", "form", "((", "A", "|", "~B", "|", "...", ")", "&", "(", "B", "|", "C", "|", "...", ")", "&", "...", ")", "[", "p"...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L407-L424
[ "def", "to_cnf", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", ":", "s", "=", "expr", "(", "s", ")", "s", "=", "eliminate_implications", "(", "s", ")", "# Steps 1, 2 from p. 253", "s", "=", "move_not_inwards", "(", "s", ")", "# S...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
eliminate_implications
Change >>, <<, and <=> into &, |, and ~. That is, return an Expr that is equivalent to s, but has only &, |, and ~ as logical operators. >>> eliminate_implications(A >> (~B << C)) ((~B | ~C) | ~A) >>> eliminate_implications(A ^ B) ((A & ~B) | (~A & B))
aima/logic.py
def eliminate_implications(s): """Change >>, <<, and <=> into &, |, and ~. That is, return an Expr that is equivalent to s, but has only &, |, and ~ as logical operators. >>> eliminate_implications(A >> (~B << C)) ((~B | ~C) | ~A) >>> eliminate_implications(A ^ B) ((A & ~B) | (~A & B)) """ ...
def eliminate_implications(s): """Change >>, <<, and <=> into &, |, and ~. That is, return an Expr that is equivalent to s, but has only &, |, and ~ as logical operators. >>> eliminate_implications(A >> (~B << C)) ((~B | ~C) | ~A) >>> eliminate_implications(A ^ B) ((A & ~B) | (~A & B)) """ ...
[ "Change", ">>", "<<", "and", "<", "=", ">", "into", "&", "|", "and", "~", ".", "That", "is", "return", "an", "Expr", "that", "is", "equivalent", "to", "s", "but", "has", "only", "&", "|", "and", "~", "as", "logical", "operators", ".", ">>>", "eli...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L426-L448
[ "def", "eliminate_implications", "(", "s", ")", ":", "if", "not", "s", ".", "args", "or", "is_symbol", "(", "s", ".", "op", ")", ":", "return", "s", "## (Atoms are unchanged.)", "args", "=", "map", "(", "eliminate_implications", ",", "s", ".", "args", ")...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
move_not_inwards
Rewrite sentence s by moving negation sign inward. >>> move_not_inwards(~(A | B)) (~A & ~B) >>> move_not_inwards(~(A & B)) (~A | ~B) >>> move_not_inwards(~(~(A | ~B) | ~~C)) ((A | ~B) & ~C)
aima/logic.py
def move_not_inwards(s): """Rewrite sentence s by moving negation sign inward. >>> move_not_inwards(~(A | B)) (~A & ~B) >>> move_not_inwards(~(A & B)) (~A | ~B) >>> move_not_inwards(~(~(A | ~B) | ~~C)) ((A | ~B) & ~C) """ if s.op == '~': NOT = lambda b: move_not_inwards(~b) ...
def move_not_inwards(s): """Rewrite sentence s by moving negation sign inward. >>> move_not_inwards(~(A | B)) (~A & ~B) >>> move_not_inwards(~(A & B)) (~A | ~B) >>> move_not_inwards(~(~(A | ~B) | ~~C)) ((A | ~B) & ~C) """ if s.op == '~': NOT = lambda b: move_not_inwards(~b) ...
[ "Rewrite", "sentence", "s", "by", "moving", "negation", "sign", "inward", ".", ">>>", "move_not_inwards", "(", "~", "(", "A", "|", "B", "))", "(", "~A", "&", "~B", ")", ">>>", "move_not_inwards", "(", "~", "(", "A", "&", "B", "))", "(", "~A", "|", ...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L450-L469
[ "def", "move_not_inwards", "(", "s", ")", ":", "if", "s", ".", "op", "==", "'~'", ":", "NOT", "=", "lambda", "b", ":", "move_not_inwards", "(", "~", "b", ")", "a", "=", "s", ".", "args", "[", "0", "]", "if", "a", ".", "op", "==", "'~'", ":", ...
3572b2fb92039b4a1abe384be8545560fbd3d470
valid
distribute_and_over_or
Given a sentence s consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C))
aima/logic.py
def distribute_and_over_or(s): """Given a sentence s consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C)) """ if s.op == '|': s = associate('|', s.args) if s.op != '|': ...
def distribute_and_over_or(s): """Given a sentence s consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. >>> distribute_and_over_or((A & B) | C) ((A | C) & (B | C)) """ if s.op == '|': s = associate('|', s.args) if s.op != '|': ...
[ "Given", "a", "sentence", "s", "consisting", "of", "conjunctions", "and", "disjunctions", "of", "literals", "return", "an", "equivalent", "sentence", "in", "CNF", ".", ">>>", "distribute_and_over_or", "((", "A", "&", "B", ")", "|", "C", ")", "((", "A", "|"...
hobson/aima
python
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/logic.py#L471-L495
[ "def", "distribute_and_over_or", "(", "s", ")", ":", "if", "s", ".", "op", "==", "'|'", ":", "s", "=", "associate", "(", "'|'", ",", "s", ".", "args", ")", "if", "s", ".", "op", "!=", "'|'", ":", "return", "distribute_and_over_or", "(", "s", ")", ...
3572b2fb92039b4a1abe384be8545560fbd3d470