repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Yelp/threat_intel
threat_intel/opendns.py
_cached_by_domain
def _cached_by_domain(api_name): """A caching wrapper for functions that take a list of domains as parameters. Raises: ResponseError - if the response received from the endpoint is not valid. """ def wrapped(func): def decorated(self, domains): if not self._cache: return func(self, domains) all_responses = self._cache.bulk_lookup(api_name, domains) domains = list(set(domains) - set(all_responses)) if domains: response = func(self, domains) if not response: raise ResponseError("No response for uncached domains") for domain in response: self._cache.cache_value(api_name, domain, response[domain]) all_responses[domain] = response[domain] return all_responses return decorated return wrapped
python
def _cached_by_domain(api_name): """A caching wrapper for functions that take a list of domains as parameters. Raises: ResponseError - if the response received from the endpoint is not valid. """ def wrapped(func): def decorated(self, domains): if not self._cache: return func(self, domains) all_responses = self._cache.bulk_lookup(api_name, domains) domains = list(set(domains) - set(all_responses)) if domains: response = func(self, domains) if not response: raise ResponseError("No response for uncached domains") for domain in response: self._cache.cache_value(api_name, domain, response[domain]) all_responses[domain] = response[domain] return all_responses return decorated return wrapped
[ "def", "_cached_by_domain", "(", "api_name", ")", ":", "def", "wrapped", "(", "func", ")", ":", "def", "decorated", "(", "self", ",", "domains", ")", ":", "if", "not", "self", ".", "_cache", ":", "return", "func", "(", "self", ",", "domains", ")", "all_responses", "=", "self", ".", "_cache", ".", "bulk_lookup", "(", "api_name", ",", "domains", ")", "domains", "=", "list", "(", "set", "(", "domains", ")", "-", "set", "(", "all_responses", ")", ")", "if", "domains", ":", "response", "=", "func", "(", "self", ",", "domains", ")", "if", "not", "response", ":", "raise", "ResponseError", "(", "\"No response for uncached domains\"", ")", "for", "domain", "in", "response", ":", "self", ".", "_cache", ".", "cache_value", "(", "api_name", ",", "domain", ",", "response", "[", "domain", "]", ")", "all_responses", "[", "domain", "]", "=", "response", "[", "domain", "]", "return", "all_responses", "return", "decorated", "return", "wrapped" ]
A caching wrapper for functions that take a list of domains as parameters. Raises: ResponseError - if the response received from the endpoint is not valid.
[ "A", "caching", "wrapper", "for", "functions", "that", "take", "a", "list", "of", "domains", "as", "parameters", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L16-L45
train
234,100
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.domain_score
def domain_score(self, domains): """Calls domain scores endpoint. This method is deprecated since OpenDNS Investigate API endpoint is also deprecated. """ warn( 'OpenDNS Domain Scores endpoint is deprecated. Use ' 'InvestigateApi.categorization() instead', DeprecationWarning, ) url_path = 'domains/score/' return self._multi_post(url_path, domains)
python
def domain_score(self, domains): """Calls domain scores endpoint. This method is deprecated since OpenDNS Investigate API endpoint is also deprecated. """ warn( 'OpenDNS Domain Scores endpoint is deprecated. Use ' 'InvestigateApi.categorization() instead', DeprecationWarning, ) url_path = 'domains/score/' return self._multi_post(url_path, domains)
[ "def", "domain_score", "(", "self", ",", "domains", ")", ":", "warn", "(", "'OpenDNS Domain Scores endpoint is deprecated. Use '", "'InvestigateApi.categorization() instead'", ",", "DeprecationWarning", ",", ")", "url_path", "=", "'domains/score/'", "return", "self", ".", "_multi_post", "(", "url_path", ",", "domains", ")" ]
Calls domain scores endpoint. This method is deprecated since OpenDNS Investigate API endpoint is also deprecated.
[ "Calls", "domain", "scores", "endpoint", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L115-L126
train
234,101
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi._multi_get
def _multi_get(self, cache_api_name, fmt_url_path, url_params, query_params=None): """Makes multiple GETs to an OpenDNS endpoint. Args: cache_api_name: string api_name for caching fmt_url_path: format string for building URL paths url_params: An enumerable of strings used in building URLs query_params - None / dict / list of dicts containing query params Returns: A dict of {url_param: api_result} """ all_responses = {} if self._cache: all_responses = self._cache.bulk_lookup(cache_api_name, url_params) url_params = [key for key in url_params if key not in all_responses.keys()] if len(url_params): urls = self._to_urls(fmt_url_path, url_params) responses = self._requests.multi_get(urls, query_params) for url_param, response in zip(url_params, responses): if self._cache: self._cache.cache_value(cache_api_name, url_param, response) all_responses[url_param] = response return all_responses
python
def _multi_get(self, cache_api_name, fmt_url_path, url_params, query_params=None): """Makes multiple GETs to an OpenDNS endpoint. Args: cache_api_name: string api_name for caching fmt_url_path: format string for building URL paths url_params: An enumerable of strings used in building URLs query_params - None / dict / list of dicts containing query params Returns: A dict of {url_param: api_result} """ all_responses = {} if self._cache: all_responses = self._cache.bulk_lookup(cache_api_name, url_params) url_params = [key for key in url_params if key not in all_responses.keys()] if len(url_params): urls = self._to_urls(fmt_url_path, url_params) responses = self._requests.multi_get(urls, query_params) for url_param, response in zip(url_params, responses): if self._cache: self._cache.cache_value(cache_api_name, url_param, response) all_responses[url_param] = response return all_responses
[ "def", "_multi_get", "(", "self", ",", "cache_api_name", ",", "fmt_url_path", ",", "url_params", ",", "query_params", "=", "None", ")", ":", "all_responses", "=", "{", "}", "if", "self", ".", "_cache", ":", "all_responses", "=", "self", ".", "_cache", ".", "bulk_lookup", "(", "cache_api_name", ",", "url_params", ")", "url_params", "=", "[", "key", "for", "key", "in", "url_params", "if", "key", "not", "in", "all_responses", ".", "keys", "(", ")", "]", "if", "len", "(", "url_params", ")", ":", "urls", "=", "self", ".", "_to_urls", "(", "fmt_url_path", ",", "url_params", ")", "responses", "=", "self", ".", "_requests", ".", "multi_get", "(", "urls", ",", "query_params", ")", "for", "url_param", ",", "response", "in", "zip", "(", "url_params", ",", "responses", ")", ":", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "cache_value", "(", "cache_api_name", ",", "url_param", ",", "response", ")", "all_responses", "[", "url_param", "]", "=", "response", "return", "all_responses" ]
Makes multiple GETs to an OpenDNS endpoint. Args: cache_api_name: string api_name for caching fmt_url_path: format string for building URL paths url_params: An enumerable of strings used in building URLs query_params - None / dict / list of dicts containing query params Returns: A dict of {url_param: api_result}
[ "Makes", "multiple", "GETs", "to", "an", "OpenDNS", "endpoint", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L129-L154
train
234,102
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.security
def security(self, domains): """Calls security end point and adds an 'is_suspicious' key to each response. Args: domains: An enumerable of strings Returns: A dict of {domain: security_result} """ api_name = 'opendns-security' fmt_url_path = u'security/name/{0}.json' return self._multi_get(api_name, fmt_url_path, domains)
python
def security(self, domains): """Calls security end point and adds an 'is_suspicious' key to each response. Args: domains: An enumerable of strings Returns: A dict of {domain: security_result} """ api_name = 'opendns-security' fmt_url_path = u'security/name/{0}.json' return self._multi_get(api_name, fmt_url_path, domains)
[ "def", "security", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'opendns-security'", "fmt_url_path", "=", "u'security/name/{0}.json'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "domains", ")" ]
Calls security end point and adds an 'is_suspicious' key to each response. Args: domains: An enumerable of strings Returns: A dict of {domain: security_result}
[ "Calls", "security", "end", "point", "and", "adds", "an", "is_suspicious", "key", "to", "each", "response", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L156-L166
train
234,103
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.whois_emails
def whois_emails(self, emails): """Calls WHOIS Email end point Args: emails: An enumerable of string Emails Returns: A dict of {email: domain_result} """ api_name = 'opendns-whois-emails' fmt_url_path = u'whois/emails/{0}' return self._multi_get(api_name, fmt_url_path, emails)
python
def whois_emails(self, emails): """Calls WHOIS Email end point Args: emails: An enumerable of string Emails Returns: A dict of {email: domain_result} """ api_name = 'opendns-whois-emails' fmt_url_path = u'whois/emails/{0}' return self._multi_get(api_name, fmt_url_path, emails)
[ "def", "whois_emails", "(", "self", ",", "emails", ")", ":", "api_name", "=", "'opendns-whois-emails'", "fmt_url_path", "=", "u'whois/emails/{0}'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "emails", ")" ]
Calls WHOIS Email end point Args: emails: An enumerable of string Emails Returns: A dict of {email: domain_result}
[ "Calls", "WHOIS", "Email", "end", "point" ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L168-L178
train
234,104
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.whois_nameservers
def whois_nameservers(self, nameservers): """Calls WHOIS Nameserver end point Args: emails: An enumerable of nameservers Returns: A dict of {nameserver: domain_result} """ api_name = 'opendns-whois-nameservers' fmt_url_path = u'whois/nameservers/{0}' return self._multi_get(api_name, fmt_url_path, nameservers)
python
def whois_nameservers(self, nameservers): """Calls WHOIS Nameserver end point Args: emails: An enumerable of nameservers Returns: A dict of {nameserver: domain_result} """ api_name = 'opendns-whois-nameservers' fmt_url_path = u'whois/nameservers/{0}' return self._multi_get(api_name, fmt_url_path, nameservers)
[ "def", "whois_nameservers", "(", "self", ",", "nameservers", ")", ":", "api_name", "=", "'opendns-whois-nameservers'", "fmt_url_path", "=", "u'whois/nameservers/{0}'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "nameservers", ")" ]
Calls WHOIS Nameserver end point Args: emails: An enumerable of nameservers Returns: A dict of {nameserver: domain_result}
[ "Calls", "WHOIS", "Nameserver", "end", "point" ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L180-L190
train
234,105
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.whois_domains
def whois_domains(self, domains): """Calls WHOIS domain end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_result} """ api_name = 'opendns-whois-domain' fmt_url_path = u'whois/{0}' return self._multi_get(api_name, fmt_url_path, domains)
python
def whois_domains(self, domains): """Calls WHOIS domain end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_result} """ api_name = 'opendns-whois-domain' fmt_url_path = u'whois/{0}' return self._multi_get(api_name, fmt_url_path, domains)
[ "def", "whois_domains", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'opendns-whois-domain'", "fmt_url_path", "=", "u'whois/{0}'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "domains", ")" ]
Calls WHOIS domain end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_result}
[ "Calls", "WHOIS", "domain", "end", "point" ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L192-L202
train
234,106
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.whois_domains_history
def whois_domains_history(self, domains): """Calls WHOIS domain history end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_history_result} """ api_name = 'opendns-whois-domain-history' fmt_url_path = u'whois/{0}/history' return self._multi_get(api_name, fmt_url_path, domains)
python
def whois_domains_history(self, domains): """Calls WHOIS domain history end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_history_result} """ api_name = 'opendns-whois-domain-history' fmt_url_path = u'whois/{0}/history' return self._multi_get(api_name, fmt_url_path, domains)
[ "def", "whois_domains_history", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'opendns-whois-domain-history'", "fmt_url_path", "=", "u'whois/{0}/history'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "domains", ")" ]
Calls WHOIS domain history end point Args: domains: An enumerable of domains Returns: A dict of {domain: domain_history_result}
[ "Calls", "WHOIS", "domain", "history", "end", "point" ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L204-L214
train
234,107
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.domain_tag
def domain_tag(self, domains): """Get the data range when a domain is part of OpenDNS block list. Args: domains: an enumerable of strings domain names Returns: An enumerable of string with period, category, and url """ api_name = 'opendns-domain_tag' fmt_url_path = u'domains/{0}/latest_tags' return self._multi_get(api_name, fmt_url_path, domains)
python
def domain_tag(self, domains): """Get the data range when a domain is part of OpenDNS block list. Args: domains: an enumerable of strings domain names Returns: An enumerable of string with period, category, and url """ api_name = 'opendns-domain_tag' fmt_url_path = u'domains/{0}/latest_tags' return self._multi_get(api_name, fmt_url_path, domains)
[ "def", "domain_tag", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'opendns-domain_tag'", "fmt_url_path", "=", "u'domains/{0}/latest_tags'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "domains", ")" ]
Get the data range when a domain is part of OpenDNS block list. Args: domains: an enumerable of strings domain names Returns: An enumerable of string with period, category, and url
[ "Get", "the", "data", "range", "when", "a", "domain", "is", "part", "of", "OpenDNS", "block", "list", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L228-L238
train
234,108
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.rr_history
def rr_history(self, ips): """Get the domains related to input ips. Args: ips: an enumerable of strings as ips Returns: An enumerable of resource records and features """ api_name = 'opendns-rr_history' fmt_url_path = u'dnsdb/ip/a/{0}.json' return self._multi_get(api_name, fmt_url_path, ips)
python
def rr_history(self, ips): """Get the domains related to input ips. Args: ips: an enumerable of strings as ips Returns: An enumerable of resource records and features """ api_name = 'opendns-rr_history' fmt_url_path = u'dnsdb/ip/a/{0}.json' return self._multi_get(api_name, fmt_url_path, ips)
[ "def", "rr_history", "(", "self", ",", "ips", ")", ":", "api_name", "=", "'opendns-rr_history'", "fmt_url_path", "=", "u'dnsdb/ip/a/{0}.json'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "ips", ")" ]
Get the domains related to input ips. Args: ips: an enumerable of strings as ips Returns: An enumerable of resource records and features
[ "Get", "the", "domains", "related", "to", "input", "ips", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L253-L263
train
234,109
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.sample
def sample(self, hashes): """Get the information about a sample based on its hash. Args: hashes: an enumerable of strings as hashes Returns: An enumerable of arrays which contains the information about the original samples """ api_name = 'opendns-sample' fmt_url_path = u'sample/{0}' return self._multi_get(api_name, fmt_url_path, hashes)
python
def sample(self, hashes): """Get the information about a sample based on its hash. Args: hashes: an enumerable of strings as hashes Returns: An enumerable of arrays which contains the information about the original samples """ api_name = 'opendns-sample' fmt_url_path = u'sample/{0}' return self._multi_get(api_name, fmt_url_path, hashes)
[ "def", "sample", "(", "self", ",", "hashes", ")", ":", "api_name", "=", "'opendns-sample'", "fmt_url_path", "=", "u'sample/{0}'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "hashes", ")" ]
Get the information about a sample based on its hash. Args: hashes: an enumerable of strings as hashes Returns: An enumerable of arrays which contains the information about the original samples
[ "Get", "the", "information", "about", "a", "sample", "based", "on", "its", "hash", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L289-L300
train
234,110
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.search
def search(self, patterns, start=30, limit=1000, include_category=False): """Performs pattern searches against the Investigate database. Args: patterns: An enumerable of RegEx domain patterns to search for start: How far back results extend from in days (max is 30) limit: Number of results to show (max is 1000) include_category: Include OpenDNS security categories Returns: An enumerable of matching domain strings """ api_name = 'opendns-patterns' fmt_url_path = u'search/{0}' start = '-{0}days'.format(start) include_category = str(include_category).lower() query_params = { 'start': start, 'limit': limit, 'includecategory': include_category, } return self._multi_get(api_name, fmt_url_path, patterns, query_params)
python
def search(self, patterns, start=30, limit=1000, include_category=False): """Performs pattern searches against the Investigate database. Args: patterns: An enumerable of RegEx domain patterns to search for start: How far back results extend from in days (max is 30) limit: Number of results to show (max is 1000) include_category: Include OpenDNS security categories Returns: An enumerable of matching domain strings """ api_name = 'opendns-patterns' fmt_url_path = u'search/{0}' start = '-{0}days'.format(start) include_category = str(include_category).lower() query_params = { 'start': start, 'limit': limit, 'includecategory': include_category, } return self._multi_get(api_name, fmt_url_path, patterns, query_params)
[ "def", "search", "(", "self", ",", "patterns", ",", "start", "=", "30", ",", "limit", "=", "1000", ",", "include_category", "=", "False", ")", ":", "api_name", "=", "'opendns-patterns'", "fmt_url_path", "=", "u'search/{0}'", "start", "=", "'-{0}days'", ".", "format", "(", "start", ")", "include_category", "=", "str", "(", "include_category", ")", ".", "lower", "(", ")", "query_params", "=", "{", "'start'", ":", "start", ",", "'limit'", ":", "limit", ",", "'includecategory'", ":", "include_category", ",", "}", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "patterns", ",", "query_params", ")" ]
Performs pattern searches against the Investigate database. Args: patterns: An enumerable of RegEx domain patterns to search for start: How far back results extend from in days (max is 30) limit: Number of results to show (max is 1000) include_category: Include OpenDNS security categories Returns: An enumerable of matching domain strings
[ "Performs", "pattern", "searches", "against", "the", "Investigate", "database", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L302-L322
train
234,111
Yelp/threat_intel
threat_intel/opendns.py
InvestigateApi.risk_score
def risk_score(self, domains): """Performs Umbrella risk score analysis on the input domains Args: domains: an enumerable of domains Returns: An enumerable of associated domain risk scores """ api_name = 'opendns-risk_score' fmt_url_path = u'domains/risk-score/{0}' return self._multi_get(api_name, fmt_url_path, domains)
python
def risk_score(self, domains): """Performs Umbrella risk score analysis on the input domains Args: domains: an enumerable of domains Returns: An enumerable of associated domain risk scores """ api_name = 'opendns-risk_score' fmt_url_path = u'domains/risk-score/{0}' return self._multi_get(api_name, fmt_url_path, domains)
[ "def", "risk_score", "(", "self", ",", "domains", ")", ":", "api_name", "=", "'opendns-risk_score'", "fmt_url_path", "=", "u'domains/risk-score/{0}'", "return", "self", ".", "_multi_get", "(", "api_name", ",", "fmt_url_path", ",", "domains", ")" ]
Performs Umbrella risk score analysis on the input domains Args: domains: an enumerable of domains Returns: An enumerable of associated domain risk scores
[ "Performs", "Umbrella", "risk", "score", "analysis", "on", "the", "input", "domains" ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/opendns.py#L324-L334
train
234,112
Yelp/threat_intel
threat_intel/virustotal.py
VirusTotalApi._extract_all_responses
def _extract_all_responses(self, resources, api_endpoint, api_name): """ Aux function to extract all the API endpoint responses. Args: resources: list of string hashes. api_endpoint: endpoint path api_name: endpoint name Returns: A dict with the hash as key and the VT report as value. """ all_responses, resources = self._bulk_cache_lookup(api_name, resources) resource_chunks = self._prepare_resource_chunks(resources) response_chunks = self._request_reports("resource", resource_chunks, api_endpoint) self._extract_response_chunks(all_responses, response_chunks, api_name) return all_responses
python
def _extract_all_responses(self, resources, api_endpoint, api_name): """ Aux function to extract all the API endpoint responses. Args: resources: list of string hashes. api_endpoint: endpoint path api_name: endpoint name Returns: A dict with the hash as key and the VT report as value. """ all_responses, resources = self._bulk_cache_lookup(api_name, resources) resource_chunks = self._prepare_resource_chunks(resources) response_chunks = self._request_reports("resource", resource_chunks, api_endpoint) self._extract_response_chunks(all_responses, response_chunks, api_name) return all_responses
[ "def", "_extract_all_responses", "(", "self", ",", "resources", ",", "api_endpoint", ",", "api_name", ")", ":", "all_responses", ",", "resources", "=", "self", ".", "_bulk_cache_lookup", "(", "api_name", ",", "resources", ")", "resource_chunks", "=", "self", ".", "_prepare_resource_chunks", "(", "resources", ")", "response_chunks", "=", "self", ".", "_request_reports", "(", "\"resource\"", ",", "resource_chunks", ",", "api_endpoint", ")", "self", ".", "_extract_response_chunks", "(", "all_responses", ",", "response_chunks", ",", "api_name", ")", "return", "all_responses" ]
Aux function to extract all the API endpoint responses. Args: resources: list of string hashes. api_endpoint: endpoint path api_name: endpoint name Returns: A dict with the hash as key and the VT report as value.
[ "Aux", "function", "to", "extract", "all", "the", "API", "endpoint", "responses", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/virustotal.py#L52-L67
train
234,113
Yelp/threat_intel
threat_intel/virustotal.py
VirusTotalApi.get_url_distribution
def get_url_distribution(self, params=None): """Retrieves a live feed with the latest URLs submitted to VT. Args: resources: a dictionary with name and value for optional arguments Returns: A dict with the VT report. """ params = params or {} all_responses = {} api_name = 'virustotal-url-distribution' response_chunks = self._request_reports(list(params.keys()), list(params.values()), 'url/distribution') self._extract_response_chunks(all_responses, response_chunks, api_name) return all_responses
python
def get_url_distribution(self, params=None): """Retrieves a live feed with the latest URLs submitted to VT. Args: resources: a dictionary with name and value for optional arguments Returns: A dict with the VT report. """ params = params or {} all_responses = {} api_name = 'virustotal-url-distribution' response_chunks = self._request_reports(list(params.keys()), list(params.values()), 'url/distribution') self._extract_response_chunks(all_responses, response_chunks, api_name) return all_responses
[ "def", "get_url_distribution", "(", "self", ",", "params", "=", "None", ")", ":", "params", "=", "params", "or", "{", "}", "all_responses", "=", "{", "}", "api_name", "=", "'virustotal-url-distribution'", "response_chunks", "=", "self", ".", "_request_reports", "(", "list", "(", "params", ".", "keys", "(", ")", ")", ",", "list", "(", "params", ".", "values", "(", ")", ")", ",", "'url/distribution'", ")", "self", ".", "_extract_response_chunks", "(", "all_responses", ",", "response_chunks", ",", "api_name", ")", "return", "all_responses" ]
Retrieves a live feed with the latest URLs submitted to VT. Args: resources: a dictionary with name and value for optional arguments Returns: A dict with the VT report.
[ "Retrieves", "a", "live", "feed", "with", "the", "latest", "URLs", "submitted", "to", "VT", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/virustotal.py#L128-L143
train
234,114
Yelp/threat_intel
threat_intel/virustotal.py
VirusTotalApi.get_url_reports
def get_url_reports(self, resources): """Retrieves a scan report on a given URL. Args: resources: list of URLs. Returns: A dict with the URL as key and the VT report as value. """ api_name = 'virustotal-url-reports' (all_responses, resources) = self._bulk_cache_lookup(api_name, resources) resource_chunks = self._prepare_resource_chunks(resources, '\n') response_chunks = self._request_reports("resource", resource_chunks, 'url/report') self._extract_response_chunks(all_responses, response_chunks, api_name) return all_responses
python
def get_url_reports(self, resources): """Retrieves a scan report on a given URL. Args: resources: list of URLs. Returns: A dict with the URL as key and the VT report as value. """ api_name = 'virustotal-url-reports' (all_responses, resources) = self._bulk_cache_lookup(api_name, resources) resource_chunks = self._prepare_resource_chunks(resources, '\n') response_chunks = self._request_reports("resource", resource_chunks, 'url/report') self._extract_response_chunks(all_responses, response_chunks, api_name) return all_responses
[ "def", "get_url_reports", "(", "self", ",", "resources", ")", ":", "api_name", "=", "'virustotal-url-reports'", "(", "all_responses", ",", "resources", ")", "=", "self", ".", "_bulk_cache_lookup", "(", "api_name", ",", "resources", ")", "resource_chunks", "=", "self", ".", "_prepare_resource_chunks", "(", "resources", ",", "'\\n'", ")", "response_chunks", "=", "self", ".", "_request_reports", "(", "\"resource\"", ",", "resource_chunks", ",", "'url/report'", ")", "self", ".", "_extract_response_chunks", "(", "all_responses", ",", "response_chunks", ",", "api_name", ")", "return", "all_responses" ]
Retrieves a scan report on a given URL. Args: resources: list of URLs. Returns: A dict with the URL as key and the VT report as value.
[ "Retrieves", "a", "scan", "report", "on", "a", "given", "URL", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/virustotal.py#L167-L182
train
234,115
Yelp/threat_intel
threat_intel/virustotal.py
VirusTotalApi.get_ip_reports
def get_ip_reports(self, ips): """Retrieves the most recent VT info for a set of ips. Args: ips: list of IPs. Returns: A dict with the IP as key and the VT report as value. """ api_name = 'virustotal-ip-address-reports' (all_responses, ips) = self._bulk_cache_lookup(api_name, ips) responses = self._request_reports("ip", ips, 'ip-address/report') for ip, response in zip(ips, responses): if self._cache: self._cache.cache_value(api_name, ip, response) all_responses[ip] = response return all_responses
python
def get_ip_reports(self, ips): """Retrieves the most recent VT info for a set of ips. Args: ips: list of IPs. Returns: A dict with the IP as key and the VT report as value. """ api_name = 'virustotal-ip-address-reports' (all_responses, ips) = self._bulk_cache_lookup(api_name, ips) responses = self._request_reports("ip", ips, 'ip-address/report') for ip, response in zip(ips, responses): if self._cache: self._cache.cache_value(api_name, ip, response) all_responses[ip] = response return all_responses
[ "def", "get_ip_reports", "(", "self", ",", "ips", ")", ":", "api_name", "=", "'virustotal-ip-address-reports'", "(", "all_responses", ",", "ips", ")", "=", "self", ".", "_bulk_cache_lookup", "(", "api_name", ",", "ips", ")", "responses", "=", "self", ".", "_request_reports", "(", "\"ip\"", ",", "ips", ",", "'ip-address/report'", ")", "for", "ip", ",", "response", "in", "zip", "(", "ips", ",", "responses", ")", ":", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "cache_value", "(", "api_name", ",", "ip", ",", "response", ")", "all_responses", "[", "ip", "]", "=", "response", "return", "all_responses" ]
Retrieves the most recent VT info for a set of ips. Args: ips: list of IPs. Returns: A dict with the IP as key and the VT report as value.
[ "Retrieves", "the", "most", "recent", "VT", "info", "for", "a", "set", "of", "ips", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/virustotal.py#L185-L203
train
234,116
Yelp/threat_intel
threat_intel/virustotal.py
VirusTotalApi.get_file_clusters
def get_file_clusters(self, date): """Retrieves file similarity clusters for a given time frame. Args: date: the specific date for which we want the clustering details. Example: 'date': '2013-09-10' Returns: A dict with the VT report. """ api_name = 'virustotal-file-clusters' (all_responses, resources) = self._bulk_cache_lookup(api_name, date) response = self._request_reports("date", date, 'file/clusters') self._extract_response_chunks(all_responses, response, api_name) return all_responses
python
def get_file_clusters(self, date): """Retrieves file similarity clusters for a given time frame. Args: date: the specific date for which we want the clustering details. Example: 'date': '2013-09-10' Returns: A dict with the VT report. """ api_name = 'virustotal-file-clusters' (all_responses, resources) = self._bulk_cache_lookup(api_name, date) response = self._request_reports("date", date, 'file/clusters') self._extract_response_chunks(all_responses, response, api_name) return all_responses
[ "def", "get_file_clusters", "(", "self", ",", "date", ")", ":", "api_name", "=", "'virustotal-file-clusters'", "(", "all_responses", ",", "resources", ")", "=", "self", ".", "_bulk_cache_lookup", "(", "api_name", ",", "date", ")", "response", "=", "self", ".", "_request_reports", "(", "\"date\"", ",", "date", ",", "'file/clusters'", ")", "self", ".", "_extract_response_chunks", "(", "all_responses", ",", "response", ",", "api_name", ")", "return", "all_responses" ]
Retrieves file similarity clusters for a given time frame. Args: date: the specific date for which we want the clustering details. Example: 'date': '2013-09-10' Returns: A dict with the VT report.
[ "Retrieves", "file", "similarity", "clusters", "for", "a", "given", "time", "frame", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/virustotal.py#L227-L242
train
234,117
Yelp/threat_intel
threat_intel/virustotal.py
VirusTotalApi._prepare_resource_chunks
def _prepare_resource_chunks(self, resources, resource_delim=','): """As in some VirusTotal API methods the call can be made for multiple resources at once this method prepares a list of concatenated resources according to the maximum number of resources per requests. Args: resources: a list of the resources. resource_delim: a string used to separate the resources. Default value is a comma. Returns: A list of the concatenated resources. """ return [self._prepare_resource_chunk(resources, resource_delim, pos) for pos in range(0, len(resources), self._resources_per_req)]
python
def _prepare_resource_chunks(self, resources, resource_delim=','): """As in some VirusTotal API methods the call can be made for multiple resources at once this method prepares a list of concatenated resources according to the maximum number of resources per requests. Args: resources: a list of the resources. resource_delim: a string used to separate the resources. Default value is a comma. Returns: A list of the concatenated resources. """ return [self._prepare_resource_chunk(resources, resource_delim, pos) for pos in range(0, len(resources), self._resources_per_req)]
[ "def", "_prepare_resource_chunks", "(", "self", ",", "resources", ",", "resource_delim", "=", "','", ")", ":", "return", "[", "self", ".", "_prepare_resource_chunk", "(", "resources", ",", "resource_delim", ",", "pos", ")", "for", "pos", "in", "range", "(", "0", ",", "len", "(", "resources", ")", ",", "self", ".", "_resources_per_req", ")", "]" ]
As in some VirusTotal API methods the call can be made for multiple resources at once this method prepares a list of concatenated resources according to the maximum number of resources per requests. Args: resources: a list of the resources. resource_delim: a string used to separate the resources. Default value is a comma. Returns: A list of the concatenated resources.
[ "As", "in", "some", "VirusTotal", "API", "methods", "the", "call", "can", "be", "made", "for", "multiple", "resources", "at", "once", "this", "method", "prepares", "a", "list", "of", "concatenated", "resources", "according", "to", "the", "maximum", "number", "of", "resources", "per", "requests", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/virustotal.py#L263-L276
train
234,118
Yelp/threat_intel
threat_intel/virustotal.py
VirusTotalApi._extract_response_chunks
def _extract_response_chunks(self, all_responses, response_chunks, api_name): """Extracts and caches the responses from the response chunks in case of the responses for the requests containing multiple concatenated resources. Extracted responses are added to the already cached responses passed in the all_responses parameter. Args: all_responses: a list containing already cached responses. response_chunks: a list with response chunks. api_name: a string name of the API. """ for response_chunk in response_chunks: if not isinstance(response_chunk, list): response_chunk = [response_chunk] for response in response_chunk: if not response: continue if self._cache: self._cache.cache_value(api_name, response['resource'], response) all_responses[response['resource']] = response
python
def _extract_response_chunks(self, all_responses, response_chunks, api_name): """Extracts and caches the responses from the response chunks in case of the responses for the requests containing multiple concatenated resources. Extracted responses are added to the already cached responses passed in the all_responses parameter. Args: all_responses: a list containing already cached responses. response_chunks: a list with response chunks. api_name: a string name of the API. """ for response_chunk in response_chunks: if not isinstance(response_chunk, list): response_chunk = [response_chunk] for response in response_chunk: if not response: continue if self._cache: self._cache.cache_value(api_name, response['resource'], response) all_responses[response['resource']] = response
[ "def", "_extract_response_chunks", "(", "self", ",", "all_responses", ",", "response_chunks", ",", "api_name", ")", ":", "for", "response_chunk", "in", "response_chunks", ":", "if", "not", "isinstance", "(", "response_chunk", ",", "list", ")", ":", "response_chunk", "=", "[", "response_chunk", "]", "for", "response", "in", "response_chunk", ":", "if", "not", "response", ":", "continue", "if", "self", ".", "_cache", ":", "self", ".", "_cache", ".", "cache_value", "(", "api_name", ",", "response", "[", "'resource'", "]", ",", "response", ")", "all_responses", "[", "response", "[", "'resource'", "]", "]", "=", "response" ]
Extracts and caches the responses from the response chunks in case of the responses for the requests containing multiple concatenated resources. Extracted responses are added to the already cached responses passed in the all_responses parameter. Args: all_responses: a list containing already cached responses. response_chunks: a list with response chunks. api_name: a string name of the API.
[ "Extracts", "and", "caches", "the", "responses", "from", "the", "response", "chunks", "in", "case", "of", "the", "responses", "for", "the", "requests", "containing", "multiple", "concatenated", "resources", ".", "Extracted", "responses", "are", "added", "to", "the", "already", "cached", "responses", "passed", "in", "the", "all_responses", "parameter", "." ]
60eef841d7cca115ec7857aeb9c553b72b694851
https://github.com/Yelp/threat_intel/blob/60eef841d7cca115ec7857aeb9c553b72b694851/threat_intel/virustotal.py#L295-L315
train
234,119
divio/djangocms-text-ckeditor
djangocms_text_ckeditor/cms_plugins.py
TextPlugin.get_editor_widget
def get_editor_widget(self, request, plugins, plugin): """ Returns the Django form Widget to be used for the text area """ cancel_url_name = self.get_admin_url_name('delete_on_cancel') cancel_url = reverse('admin:%s' % cancel_url_name) render_plugin_url_name = self.get_admin_url_name('render_plugin') render_plugin_url = reverse('admin:%s' % render_plugin_url_name) action_token = self.get_action_token(request, plugin) # should we delete the text plugin when # the user cancels? delete_text_on_cancel = ( 'delete-on-cancel' in request.GET and # noqa not plugin.get_plugin_instance()[0] ) widget = TextEditorWidget( installed_plugins=plugins, pk=plugin.pk, placeholder=plugin.placeholder, plugin_language=plugin.language, configuration=self.ckeditor_configuration, render_plugin_url=render_plugin_url, cancel_url=cancel_url, action_token=action_token, delete_on_cancel=delete_text_on_cancel, ) return widget
python
def get_editor_widget(self, request, plugins, plugin): """ Returns the Django form Widget to be used for the text area """ cancel_url_name = self.get_admin_url_name('delete_on_cancel') cancel_url = reverse('admin:%s' % cancel_url_name) render_plugin_url_name = self.get_admin_url_name('render_plugin') render_plugin_url = reverse('admin:%s' % render_plugin_url_name) action_token = self.get_action_token(request, plugin) # should we delete the text plugin when # the user cancels? delete_text_on_cancel = ( 'delete-on-cancel' in request.GET and # noqa not plugin.get_plugin_instance()[0] ) widget = TextEditorWidget( installed_plugins=plugins, pk=plugin.pk, placeholder=plugin.placeholder, plugin_language=plugin.language, configuration=self.ckeditor_configuration, render_plugin_url=render_plugin_url, cancel_url=cancel_url, action_token=action_token, delete_on_cancel=delete_text_on_cancel, ) return widget
[ "def", "get_editor_widget", "(", "self", ",", "request", ",", "plugins", ",", "plugin", ")", ":", "cancel_url_name", "=", "self", ".", "get_admin_url_name", "(", "'delete_on_cancel'", ")", "cancel_url", "=", "reverse", "(", "'admin:%s'", "%", "cancel_url_name", ")", "render_plugin_url_name", "=", "self", ".", "get_admin_url_name", "(", "'render_plugin'", ")", "render_plugin_url", "=", "reverse", "(", "'admin:%s'", "%", "render_plugin_url_name", ")", "action_token", "=", "self", ".", "get_action_token", "(", "request", ",", "plugin", ")", "# should we delete the text plugin when", "# the user cancels?", "delete_text_on_cancel", "=", "(", "'delete-on-cancel'", "in", "request", ".", "GET", "and", "# noqa", "not", "plugin", ".", "get_plugin_instance", "(", ")", "[", "0", "]", ")", "widget", "=", "TextEditorWidget", "(", "installed_plugins", "=", "plugins", ",", "pk", "=", "plugin", ".", "pk", ",", "placeholder", "=", "plugin", ".", "placeholder", ",", "plugin_language", "=", "plugin", ".", "language", ",", "configuration", "=", "self", ".", "ckeditor_configuration", ",", "render_plugin_url", "=", "render_plugin_url", ",", "cancel_url", "=", "cancel_url", ",", "action_token", "=", "action_token", ",", "delete_on_cancel", "=", "delete_text_on_cancel", ",", ")", "return", "widget" ]
Returns the Django form Widget to be used for the text area
[ "Returns", "the", "Django", "form", "Widget", "to", "be", "used", "for", "the", "text", "area" ]
a6069096fdac80931fd328055d1d615d168c33df
https://github.com/divio/djangocms-text-ckeditor/blob/a6069096fdac80931fd328055d1d615d168c33df/djangocms_text_ckeditor/cms_plugins.py#L227-L257
train
234,120
divio/djangocms-text-ckeditor
djangocms_text_ckeditor/cms_plugins.py
TextPlugin.get_form_class
def get_form_class(self, request, plugins, plugin): """ Returns a subclass of Form to be used by this plugin """ widget = self.get_editor_widget( request=request, plugins=plugins, plugin=plugin, ) instance = plugin.get_plugin_instance()[0] if instance: context = RequestContext(request) context['request'] = request rendered_text = plugin_tags_to_admin_html( text=instance.body, context=context, ) else: rendered_text = None # We avoid mutating the Form declared above by subclassing class TextPluginForm(self.form): body = CharField(widget=widget, required=False) def __init__(self, *args, **kwargs): initial = kwargs.pop('initial', {}) if rendered_text: initial['body'] = rendered_text super(TextPluginForm, self).__init__(*args, initial=initial, **kwargs) return TextPluginForm
python
def get_form_class(self, request, plugins, plugin): """ Returns a subclass of Form to be used by this plugin """ widget = self.get_editor_widget( request=request, plugins=plugins, plugin=plugin, ) instance = plugin.get_plugin_instance()[0] if instance: context = RequestContext(request) context['request'] = request rendered_text = plugin_tags_to_admin_html( text=instance.body, context=context, ) else: rendered_text = None # We avoid mutating the Form declared above by subclassing class TextPluginForm(self.form): body = CharField(widget=widget, required=False) def __init__(self, *args, **kwargs): initial = kwargs.pop('initial', {}) if rendered_text: initial['body'] = rendered_text super(TextPluginForm, self).__init__(*args, initial=initial, **kwargs) return TextPluginForm
[ "def", "get_form_class", "(", "self", ",", "request", ",", "plugins", ",", "plugin", ")", ":", "widget", "=", "self", ".", "get_editor_widget", "(", "request", "=", "request", ",", "plugins", "=", "plugins", ",", "plugin", "=", "plugin", ",", ")", "instance", "=", "plugin", ".", "get_plugin_instance", "(", ")", "[", "0", "]", "if", "instance", ":", "context", "=", "RequestContext", "(", "request", ")", "context", "[", "'request'", "]", "=", "request", "rendered_text", "=", "plugin_tags_to_admin_html", "(", "text", "=", "instance", ".", "body", ",", "context", "=", "context", ",", ")", "else", ":", "rendered_text", "=", "None", "# We avoid mutating the Form declared above by subclassing", "class", "TextPluginForm", "(", "self", ".", "form", ")", ":", "body", "=", "CharField", "(", "widget", "=", "widget", ",", "required", "=", "False", ")", "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "initial", "=", "kwargs", ".", "pop", "(", "'initial'", ",", "{", "}", ")", "if", "rendered_text", ":", "initial", "[", "'body'", "]", "=", "rendered_text", "super", "(", "TextPluginForm", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "initial", "=", "initial", ",", "*", "*", "kwargs", ")", "return", "TextPluginForm" ]
Returns a subclass of Form to be used by this plugin
[ "Returns", "a", "subclass", "of", "Form", "to", "be", "used", "by", "this", "plugin" ]
a6069096fdac80931fd328055d1d615d168c33df
https://github.com/divio/djangocms-text-ckeditor/blob/a6069096fdac80931fd328055d1d615d168c33df/djangocms_text_ckeditor/cms_plugins.py#L259-L291
train
234,121
divio/djangocms-text-ckeditor
djangocms_text_ckeditor/utils.py
_plugin_tags_to_html
def _plugin_tags_to_html(text, output_func): """ Convert plugin object 'tags' into the form for public site. context is the template context to use, placeholder is the placeholder name """ plugins_by_id = get_plugins_from_text(text) def _render_tag(m): try: plugin_id = int(m.groupdict()['pk']) obj = plugins_by_id[plugin_id] except KeyError: # Object must have been deleted. It cannot be rendered to # end user so just remove it from the HTML altogether return u'' else: obj._render_meta.text_enabled = True return output_func(obj, m) return OBJ_ADMIN_RE.sub(_render_tag, text)
python
def _plugin_tags_to_html(text, output_func): """ Convert plugin object 'tags' into the form for public site. context is the template context to use, placeholder is the placeholder name """ plugins_by_id = get_plugins_from_text(text) def _render_tag(m): try: plugin_id = int(m.groupdict()['pk']) obj = plugins_by_id[plugin_id] except KeyError: # Object must have been deleted. It cannot be rendered to # end user so just remove it from the HTML altogether return u'' else: obj._render_meta.text_enabled = True return output_func(obj, m) return OBJ_ADMIN_RE.sub(_render_tag, text)
[ "def", "_plugin_tags_to_html", "(", "text", ",", "output_func", ")", ":", "plugins_by_id", "=", "get_plugins_from_text", "(", "text", ")", "def", "_render_tag", "(", "m", ")", ":", "try", ":", "plugin_id", "=", "int", "(", "m", ".", "groupdict", "(", ")", "[", "'pk'", "]", ")", "obj", "=", "plugins_by_id", "[", "plugin_id", "]", "except", "KeyError", ":", "# Object must have been deleted. It cannot be rendered to", "# end user so just remove it from the HTML altogether", "return", "u''", "else", ":", "obj", ".", "_render_meta", ".", "text_enabled", "=", "True", "return", "output_func", "(", "obj", ",", "m", ")", "return", "OBJ_ADMIN_RE", ".", "sub", "(", "_render_tag", ",", "text", ")" ]
Convert plugin object 'tags' into the form for public site. context is the template context to use, placeholder is the placeholder name
[ "Convert", "plugin", "object", "tags", "into", "the", "form", "for", "public", "site", "." ]
a6069096fdac80931fd328055d1d615d168c33df
https://github.com/divio/djangocms-text-ckeditor/blob/a6069096fdac80931fd328055d1d615d168c33df/djangocms_text_ckeditor/utils.py#L91-L110
train
234,122
divio/djangocms-text-ckeditor
djangocms_text_ckeditor/html.py
extract_images
def extract_images(data, plugin): """ extracts base64 encoded images from drag and drop actions in browser and saves those images as plugins """ if not settings.TEXT_SAVE_IMAGE_FUNCTION: return data tree_builder = html5lib.treebuilders.getTreeBuilder('dom') parser = html5lib.html5parser.HTMLParser(tree=tree_builder) dom = parser.parse(data) found = False for img in dom.getElementsByTagName('img'): src = img.getAttribute('src') if not src.startswith('data:'): # nothing to do continue width = img.getAttribute('width') height = img.getAttribute('height') # extract the image data data_re = re.compile(r'data:(?P<mime_type>[^"]*);(?P<encoding>[^"]*),(?P<data>[^"]*)') m = data_re.search(src) dr = m.groupdict() mime_type = dr['mime_type'] image_data = dr['data'] if mime_type.find(';'): mime_type = mime_type.split(';')[0] try: image_data = base64.b64decode(image_data) except Exception: image_data = base64.urlsafe_b64decode(image_data) try: image_type = mime_type.split('/')[1] except IndexError: # No image type specified -- will convert to jpg below if it's valid image data image_type = '' image = BytesIO(image_data) # genarate filename and normalize image format if image_type == 'jpg' or image_type == 'jpeg': file_ending = 'jpg' elif image_type == 'png': file_ending = 'png' elif image_type == 'gif': file_ending = 'gif' else: # any not "web-safe" image format we try to convert to jpg im = Image.open(image) new_image = BytesIO() file_ending = 'jpg' im.save(new_image, 'JPEG') new_image.seek(0) image = new_image filename = u'%s.%s' % (uuid.uuid4(), file_ending) # transform image into a cms plugin image_plugin = img_data_to_plugin( filename, image, parent_plugin=plugin, width=width, height=height ) # render the new html for the plugin new_img_html = plugin_to_tag(image_plugin) # replace the original image node with the newly created cms plugin html img.parentNode.replaceChild(parser.parseFragment(new_img_html).childNodes[0], img) found = True if found: return u''.join([y.toxml() for y in dom.getElementsByTagName('body')[0].childNodes]) else: return data
python
def extract_images(data, plugin): """ extracts base64 encoded images from drag and drop actions in browser and saves those images as plugins """ if not settings.TEXT_SAVE_IMAGE_FUNCTION: return data tree_builder = html5lib.treebuilders.getTreeBuilder('dom') parser = html5lib.html5parser.HTMLParser(tree=tree_builder) dom = parser.parse(data) found = False for img in dom.getElementsByTagName('img'): src = img.getAttribute('src') if not src.startswith('data:'): # nothing to do continue width = img.getAttribute('width') height = img.getAttribute('height') # extract the image data data_re = re.compile(r'data:(?P<mime_type>[^"]*);(?P<encoding>[^"]*),(?P<data>[^"]*)') m = data_re.search(src) dr = m.groupdict() mime_type = dr['mime_type'] image_data = dr['data'] if mime_type.find(';'): mime_type = mime_type.split(';')[0] try: image_data = base64.b64decode(image_data) except Exception: image_data = base64.urlsafe_b64decode(image_data) try: image_type = mime_type.split('/')[1] except IndexError: # No image type specified -- will convert to jpg below if it's valid image data image_type = '' image = BytesIO(image_data) # genarate filename and normalize image format if image_type == 'jpg' or image_type == 'jpeg': file_ending = 'jpg' elif image_type == 'png': file_ending = 'png' elif image_type == 'gif': file_ending = 'gif' else: # any not "web-safe" image format we try to convert to jpg im = Image.open(image) new_image = BytesIO() file_ending = 'jpg' im.save(new_image, 'JPEG') new_image.seek(0) image = new_image filename = u'%s.%s' % (uuid.uuid4(), file_ending) # transform image into a cms plugin image_plugin = img_data_to_plugin( filename, image, parent_plugin=plugin, width=width, height=height ) # render the new html for the plugin new_img_html = plugin_to_tag(image_plugin) # replace the original image node with the newly created cms plugin html img.parentNode.replaceChild(parser.parseFragment(new_img_html).childNodes[0], img) found = True if found: return u''.join([y.toxml() for y in dom.getElementsByTagName('body')[0].childNodes]) else: return data
[ "def", "extract_images", "(", "data", ",", "plugin", ")", ":", "if", "not", "settings", ".", "TEXT_SAVE_IMAGE_FUNCTION", ":", "return", "data", "tree_builder", "=", "html5lib", ".", "treebuilders", ".", "getTreeBuilder", "(", "'dom'", ")", "parser", "=", "html5lib", ".", "html5parser", ".", "HTMLParser", "(", "tree", "=", "tree_builder", ")", "dom", "=", "parser", ".", "parse", "(", "data", ")", "found", "=", "False", "for", "img", "in", "dom", ".", "getElementsByTagName", "(", "'img'", ")", ":", "src", "=", "img", ".", "getAttribute", "(", "'src'", ")", "if", "not", "src", ".", "startswith", "(", "'data:'", ")", ":", "# nothing to do", "continue", "width", "=", "img", ".", "getAttribute", "(", "'width'", ")", "height", "=", "img", ".", "getAttribute", "(", "'height'", ")", "# extract the image data", "data_re", "=", "re", ".", "compile", "(", "r'data:(?P<mime_type>[^\"]*);(?P<encoding>[^\"]*),(?P<data>[^\"]*)'", ")", "m", "=", "data_re", ".", "search", "(", "src", ")", "dr", "=", "m", ".", "groupdict", "(", ")", "mime_type", "=", "dr", "[", "'mime_type'", "]", "image_data", "=", "dr", "[", "'data'", "]", "if", "mime_type", ".", "find", "(", "';'", ")", ":", "mime_type", "=", "mime_type", ".", "split", "(", "';'", ")", "[", "0", "]", "try", ":", "image_data", "=", "base64", ".", "b64decode", "(", "image_data", ")", "except", "Exception", ":", "image_data", "=", "base64", ".", "urlsafe_b64decode", "(", "image_data", ")", "try", ":", "image_type", "=", "mime_type", ".", "split", "(", "'/'", ")", "[", "1", "]", "except", "IndexError", ":", "# No image type specified -- will convert to jpg below if it's valid image data", "image_type", "=", "''", "image", "=", "BytesIO", "(", "image_data", ")", "# genarate filename and normalize image format", "if", "image_type", "==", "'jpg'", "or", "image_type", "==", "'jpeg'", ":", "file_ending", "=", "'jpg'", "elif", "image_type", "==", "'png'", ":", "file_ending", "=", "'png'", "elif", "image_type", "==", "'gif'", ":", "file_ending", "=", "'gif'", "else", ":", "# any not \"web-safe\" image format we try to convert to jpg", "im", "=", "Image", ".", "open", "(", "image", ")", "new_image", "=", "BytesIO", "(", ")", "file_ending", "=", "'jpg'", "im", ".", "save", "(", "new_image", ",", "'JPEG'", ")", "new_image", ".", "seek", "(", "0", ")", "image", "=", "new_image", "filename", "=", "u'%s.%s'", "%", "(", "uuid", ".", "uuid4", "(", ")", ",", "file_ending", ")", "# transform image into a cms plugin", "image_plugin", "=", "img_data_to_plugin", "(", "filename", ",", "image", ",", "parent_plugin", "=", "plugin", ",", "width", "=", "width", ",", "height", "=", "height", ")", "# render the new html for the plugin", "new_img_html", "=", "plugin_to_tag", "(", "image_plugin", ")", "# replace the original image node with the newly created cms plugin html", "img", ".", "parentNode", ".", "replaceChild", "(", "parser", ".", "parseFragment", "(", "new_img_html", ")", ".", "childNodes", "[", "0", "]", ",", "img", ")", "found", "=", "True", "if", "found", ":", "return", "u''", ".", "join", "(", "[", "y", ".", "toxml", "(", ")", "for", "y", "in", "dom", ".", "getElementsByTagName", "(", "'body'", ")", "[", "0", "]", ".", "childNodes", "]", ")", "else", ":", "return", "data" ]
extracts base64 encoded images from drag and drop actions in browser and saves those images as plugins
[ "extracts", "base64", "encoded", "images", "from", "drag", "and", "drop", "actions", "in", "browser", "and", "saves", "those", "images", "as", "plugins" ]
a6069096fdac80931fd328055d1d615d168c33df
https://github.com/divio/djangocms-text-ckeditor/blob/a6069096fdac80931fd328055d1d615d168c33df/djangocms_text_ckeditor/html.py#L76-L140
train
234,123
edx/i18n-tools
i18n/config.py
Configuration.default_config_filename
def default_config_filename(root_dir=None): """ Returns the default name of the configuration file. """ root_dir = Path(root_dir) if root_dir else Path('.').abspath() locale_dir = root_dir / 'locale' if not os.path.exists(locale_dir): locale_dir = root_dir / 'conf' / 'locale' return locale_dir / BASE_CONFIG_FILENAME
python
def default_config_filename(root_dir=None): """ Returns the default name of the configuration file. """ root_dir = Path(root_dir) if root_dir else Path('.').abspath() locale_dir = root_dir / 'locale' if not os.path.exists(locale_dir): locale_dir = root_dir / 'conf' / 'locale' return locale_dir / BASE_CONFIG_FILENAME
[ "def", "default_config_filename", "(", "root_dir", "=", "None", ")", ":", "root_dir", "=", "Path", "(", "root_dir", ")", "if", "root_dir", "else", "Path", "(", "'.'", ")", ".", "abspath", "(", ")", "locale_dir", "=", "root_dir", "/", "'locale'", "if", "not", "os", ".", "path", ".", "exists", "(", "locale_dir", ")", ":", "locale_dir", "=", "root_dir", "/", "'conf'", "/", "'locale'", "return", "locale_dir", "/", "BASE_CONFIG_FILENAME" ]
Returns the default name of the configuration file.
[ "Returns", "the", "default", "name", "of", "the", "configuration", "file", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/config.py#L47-L55
train
234,124
edx/i18n-tools
i18n/config.py
Configuration.rtl_langs
def rtl_langs(self): """ Returns the set of translated RTL language codes present in self.locales. Ignores source locale. """ def is_rtl(lang): """ Returns True if lang is a RTL language args: lang (str): The language to be checked Returns: True if lang is an RTL language. """ # Base RTL langs are Arabic, Farsi, Hebrew, and Urdu base_rtl = ['ar', 'fa', 'he', 'ur'] # do this to capture both 'fa' and 'fa_IR' return any([lang.startswith(base_code) for base_code in base_rtl]) return sorted(set([lang for lang in self.translated_locales if is_rtl(lang)]))
python
def rtl_langs(self): """ Returns the set of translated RTL language codes present in self.locales. Ignores source locale. """ def is_rtl(lang): """ Returns True if lang is a RTL language args: lang (str): The language to be checked Returns: True if lang is an RTL language. """ # Base RTL langs are Arabic, Farsi, Hebrew, and Urdu base_rtl = ['ar', 'fa', 'he', 'ur'] # do this to capture both 'fa' and 'fa_IR' return any([lang.startswith(base_code) for base_code in base_rtl]) return sorted(set([lang for lang in self.translated_locales if is_rtl(lang)]))
[ "def", "rtl_langs", "(", "self", ")", ":", "def", "is_rtl", "(", "lang", ")", ":", "\"\"\"\n Returns True if lang is a RTL language\n\n args:\n lang (str): The language to be checked\n\n Returns:\n True if lang is an RTL language.\n \"\"\"", "# Base RTL langs are Arabic, Farsi, Hebrew, and Urdu", "base_rtl", "=", "[", "'ar'", ",", "'fa'", ",", "'he'", ",", "'ur'", "]", "# do this to capture both 'fa' and 'fa_IR'", "return", "any", "(", "[", "lang", ".", "startswith", "(", "base_code", ")", "for", "base_code", "in", "base_rtl", "]", ")", "return", "sorted", "(", "set", "(", "[", "lang", "for", "lang", "in", "self", ".", "translated_locales", "if", "is_rtl", "(", "lang", ")", "]", ")", ")" ]
Returns the set of translated RTL language codes present in self.locales. Ignores source locale.
[ "Returns", "the", "set", "of", "translated", "RTL", "language", "codes", "present", "in", "self", ".", "locales", ".", "Ignores", "source", "locale", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/config.py#L94-L115
train
234,125
edx/i18n-tools
i18n/branch_cleanup.py
BranchCleanup.clean_conf_folder
def clean_conf_folder(self, locale): """Remove the configuration directory for `locale`""" dirname = self.configuration.get_messages_dir(locale) dirname.removedirs_p()
python
def clean_conf_folder(self, locale): """Remove the configuration directory for `locale`""" dirname = self.configuration.get_messages_dir(locale) dirname.removedirs_p()
[ "def", "clean_conf_folder", "(", "self", ",", "locale", ")", ":", "dirname", "=", "self", ".", "configuration", ".", "get_messages_dir", "(", "locale", ")", "dirname", ".", "removedirs_p", "(", ")" ]
Remove the configuration directory for `locale`
[ "Remove", "the", "configuration", "directory", "for", "locale" ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/branch_cleanup.py#L27-L30
train
234,126
edx/i18n-tools
i18n/segment.py
segment_pofiles
def segment_pofiles(configuration, locale): """Segment all the pofiles for `locale`. Returns a set of filenames, all the segment files written. """ files_written = set() for filename, segments in configuration.segment.items(): filename = configuration.get_messages_dir(locale) / filename files_written.update(segment_pofile(filename, segments)) return files_written
python
def segment_pofiles(configuration, locale): """Segment all the pofiles for `locale`. Returns a set of filenames, all the segment files written. """ files_written = set() for filename, segments in configuration.segment.items(): filename = configuration.get_messages_dir(locale) / filename files_written.update(segment_pofile(filename, segments)) return files_written
[ "def", "segment_pofiles", "(", "configuration", ",", "locale", ")", ":", "files_written", "=", "set", "(", ")", "for", "filename", ",", "segments", "in", "configuration", ".", "segment", ".", "items", "(", ")", ":", "filename", "=", "configuration", ".", "get_messages_dir", "(", "locale", ")", "/", "filename", "files_written", ".", "update", "(", "segment_pofile", "(", "filename", ",", "segments", ")", ")", "return", "files_written" ]
Segment all the pofiles for `locale`. Returns a set of filenames, all the segment files written.
[ "Segment", "all", "the", "pofiles", "for", "locale", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/segment.py#L20-L30
train
234,127
edx/i18n-tools
i18n/segment.py
segment_pofile
def segment_pofile(filename, segments): """Segment a .po file using patterns in `segments`. The .po file at `filename` is read, and the occurrence locations of its messages are examined. `segments` is a dictionary: the keys are segment .po filenames, the values are lists of patterns:: { 'django-studio.po': [ 'cms/*', 'some-other-studio-place/*', ], 'django-weird.po': [ '*/weird_*.*', ], } If all a message's occurrences match the patterns for a segment, then that message is written to the new segmented .po file. Any message that matches no segments, or more than one, is written back to the original file. Arguments: filename (path.path): a path object referring to the original .po file. segments (dict): specification of the segments to create. Returns: a set of path objects, all the segment files written. """ reading_msg = "Reading {num} entries from {file}" writing_msg = "Writing {num} entries to {file}" source_po = polib.pofile(filename) LOG.info(reading_msg.format(file=filename, num=len(source_po))) # pylint: disable=logging-format-interpolation # A new pofile just like the source, but with no messages. We'll put # anything not segmented into this file. remaining_po = copy.deepcopy(source_po) remaining_po[:] = [] # Turn the segments dictionary into two structures: segment_patterns is a # list of (pattern, segmentfile) pairs. segment_po_files is a dict mapping # segment file names to pofile objects of their contents. segment_po_files = {filename: remaining_po} segment_patterns = [] for segmentfile, patterns in segments.items(): segment_po_files[segmentfile] = copy.deepcopy(remaining_po) segment_patterns.extend((pat, segmentfile) for pat in patterns) # Examine each message in the source file. If all of its occurrences match # a pattern for the same segment, it goes in that segment. Otherwise, it # goes in remaining. for msg in source_po: msg_segments = set() for occ_file, _ in msg.occurrences: for pat, segment_file in segment_patterns: if fnmatch.fnmatch(occ_file, pat): msg_segments.add(segment_file) break else: msg_segments.add(filename) assert msg_segments if len(msg_segments) == 1: # This message belongs in this segment. segment_file = msg_segments.pop() segment_po_files[segment_file].append(msg) else: # It's in more than one segment, so put it back in the main file. remaining_po.append(msg) # Write out the results. files_written = set() for segment_file, pofile in segment_po_files.items(): out_file = filename.dirname() / segment_file if not pofile: LOG.error("No messages to write to %s, did you run segment twice?", out_file) else: LOG.info(writing_msg.format(file=out_file, num=len(pofile))) # pylint: disable=logging-format-interpolation pofile.save(out_file) files_written.add(out_file) return files_written
python
def segment_pofile(filename, segments): """Segment a .po file using patterns in `segments`. The .po file at `filename` is read, and the occurrence locations of its messages are examined. `segments` is a dictionary: the keys are segment .po filenames, the values are lists of patterns:: { 'django-studio.po': [ 'cms/*', 'some-other-studio-place/*', ], 'django-weird.po': [ '*/weird_*.*', ], } If all a message's occurrences match the patterns for a segment, then that message is written to the new segmented .po file. Any message that matches no segments, or more than one, is written back to the original file. Arguments: filename (path.path): a path object referring to the original .po file. segments (dict): specification of the segments to create. Returns: a set of path objects, all the segment files written. """ reading_msg = "Reading {num} entries from {file}" writing_msg = "Writing {num} entries to {file}" source_po = polib.pofile(filename) LOG.info(reading_msg.format(file=filename, num=len(source_po))) # pylint: disable=logging-format-interpolation # A new pofile just like the source, but with no messages. We'll put # anything not segmented into this file. remaining_po = copy.deepcopy(source_po) remaining_po[:] = [] # Turn the segments dictionary into two structures: segment_patterns is a # list of (pattern, segmentfile) pairs. segment_po_files is a dict mapping # segment file names to pofile objects of their contents. segment_po_files = {filename: remaining_po} segment_patterns = [] for segmentfile, patterns in segments.items(): segment_po_files[segmentfile] = copy.deepcopy(remaining_po) segment_patterns.extend((pat, segmentfile) for pat in patterns) # Examine each message in the source file. If all of its occurrences match # a pattern for the same segment, it goes in that segment. Otherwise, it # goes in remaining. for msg in source_po: msg_segments = set() for occ_file, _ in msg.occurrences: for pat, segment_file in segment_patterns: if fnmatch.fnmatch(occ_file, pat): msg_segments.add(segment_file) break else: msg_segments.add(filename) assert msg_segments if len(msg_segments) == 1: # This message belongs in this segment. segment_file = msg_segments.pop() segment_po_files[segment_file].append(msg) else: # It's in more than one segment, so put it back in the main file. remaining_po.append(msg) # Write out the results. files_written = set() for segment_file, pofile in segment_po_files.items(): out_file = filename.dirname() / segment_file if not pofile: LOG.error("No messages to write to %s, did you run segment twice?", out_file) else: LOG.info(writing_msg.format(file=out_file, num=len(pofile))) # pylint: disable=logging-format-interpolation pofile.save(out_file) files_written.add(out_file) return files_written
[ "def", "segment_pofile", "(", "filename", ",", "segments", ")", ":", "reading_msg", "=", "\"Reading {num} entries from {file}\"", "writing_msg", "=", "\"Writing {num} entries to {file}\"", "source_po", "=", "polib", ".", "pofile", "(", "filename", ")", "LOG", ".", "info", "(", "reading_msg", ".", "format", "(", "file", "=", "filename", ",", "num", "=", "len", "(", "source_po", ")", ")", ")", "# pylint: disable=logging-format-interpolation", "# A new pofile just like the source, but with no messages. We'll put", "# anything not segmented into this file.", "remaining_po", "=", "copy", ".", "deepcopy", "(", "source_po", ")", "remaining_po", "[", ":", "]", "=", "[", "]", "# Turn the segments dictionary into two structures: segment_patterns is a", "# list of (pattern, segmentfile) pairs. segment_po_files is a dict mapping", "# segment file names to pofile objects of their contents.", "segment_po_files", "=", "{", "filename", ":", "remaining_po", "}", "segment_patterns", "=", "[", "]", "for", "segmentfile", ",", "patterns", "in", "segments", ".", "items", "(", ")", ":", "segment_po_files", "[", "segmentfile", "]", "=", "copy", ".", "deepcopy", "(", "remaining_po", ")", "segment_patterns", ".", "extend", "(", "(", "pat", ",", "segmentfile", ")", "for", "pat", "in", "patterns", ")", "# Examine each message in the source file. If all of its occurrences match", "# a pattern for the same segment, it goes in that segment. Otherwise, it", "# goes in remaining.", "for", "msg", "in", "source_po", ":", "msg_segments", "=", "set", "(", ")", "for", "occ_file", ",", "_", "in", "msg", ".", "occurrences", ":", "for", "pat", ",", "segment_file", "in", "segment_patterns", ":", "if", "fnmatch", ".", "fnmatch", "(", "occ_file", ",", "pat", ")", ":", "msg_segments", ".", "add", "(", "segment_file", ")", "break", "else", ":", "msg_segments", ".", "add", "(", "filename", ")", "assert", "msg_segments", "if", "len", "(", "msg_segments", ")", "==", "1", ":", "# This message belongs in this segment.", "segment_file", "=", "msg_segments", ".", "pop", "(", ")", "segment_po_files", "[", "segment_file", "]", ".", "append", "(", "msg", ")", "else", ":", "# It's in more than one segment, so put it back in the main file.", "remaining_po", ".", "append", "(", "msg", ")", "# Write out the results.", "files_written", "=", "set", "(", ")", "for", "segment_file", ",", "pofile", "in", "segment_po_files", ".", "items", "(", ")", ":", "out_file", "=", "filename", ".", "dirname", "(", ")", "/", "segment_file", "if", "not", "pofile", ":", "LOG", ".", "error", "(", "\"No messages to write to %s, did you run segment twice?\"", ",", "out_file", ")", "else", ":", "LOG", ".", "info", "(", "writing_msg", ".", "format", "(", "file", "=", "out_file", ",", "num", "=", "len", "(", "pofile", ")", ")", ")", "# pylint: disable=logging-format-interpolation", "pofile", ".", "save", "(", "out_file", ")", "files_written", ".", "add", "(", "out_file", ")", "return", "files_written" ]
Segment a .po file using patterns in `segments`. The .po file at `filename` is read, and the occurrence locations of its messages are examined. `segments` is a dictionary: the keys are segment .po filenames, the values are lists of patterns:: { 'django-studio.po': [ 'cms/*', 'some-other-studio-place/*', ], 'django-weird.po': [ '*/weird_*.*', ], } If all a message's occurrences match the patterns for a segment, then that message is written to the new segmented .po file. Any message that matches no segments, or more than one, is written back to the original file. Arguments: filename (path.path): a path object referring to the original .po file. segments (dict): specification of the segments to create. Returns: a set of path objects, all the segment files written.
[ "Segment", "a", ".", "po", "file", "using", "patterns", "in", "segments", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/segment.py#L33-L116
train
234,128
edx/i18n-tools
i18n/extract.py
fix_header
def fix_header(pofile): """ Replace default headers with edX headers """ # By default, django-admin.py makemessages creates this header: # # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. pofile.metadata_is_fuzzy = [] # remove [u'fuzzy'] header = pofile.header fixes = ( ('SOME DESCRIPTIVE TITLE', EDX_MARKER), ('Translations template for PROJECT.', EDX_MARKER), ('YEAR', str(datetime.utcnow().year)), ('ORGANIZATION', 'edX'), ("THE PACKAGE'S COPYRIGHT HOLDER", "EdX"), ( 'This file is distributed under the same license as the PROJECT project.', 'This file is distributed under the GNU AFFERO GENERAL PUBLIC LICENSE.' ), ( 'This file is distributed under the same license as the PACKAGE package.', 'This file is distributed under the GNU AFFERO GENERAL PUBLIC LICENSE.' ), ('FIRST AUTHOR <EMAIL@ADDRESS>', 'EdX Team <info@edx.org>'), ) for src, dest in fixes: header = header.replace(src, dest) pofile.header = header
python
def fix_header(pofile): """ Replace default headers with edX headers """ # By default, django-admin.py makemessages creates this header: # # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. pofile.metadata_is_fuzzy = [] # remove [u'fuzzy'] header = pofile.header fixes = ( ('SOME DESCRIPTIVE TITLE', EDX_MARKER), ('Translations template for PROJECT.', EDX_MARKER), ('YEAR', str(datetime.utcnow().year)), ('ORGANIZATION', 'edX'), ("THE PACKAGE'S COPYRIGHT HOLDER", "EdX"), ( 'This file is distributed under the same license as the PROJECT project.', 'This file is distributed under the GNU AFFERO GENERAL PUBLIC LICENSE.' ), ( 'This file is distributed under the same license as the PACKAGE package.', 'This file is distributed under the GNU AFFERO GENERAL PUBLIC LICENSE.' ), ('FIRST AUTHOR <EMAIL@ADDRESS>', 'EdX Team <info@edx.org>'), ) for src, dest in fixes: header = header.replace(src, dest) pofile.header = header
[ "def", "fix_header", "(", "pofile", ")", ":", "# By default, django-admin.py makemessages creates this header:", "#", "# SOME DESCRIPTIVE TITLE.", "# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER", "# This file is distributed under the same license as the PACKAGE package.", "# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.", "pofile", ".", "metadata_is_fuzzy", "=", "[", "]", "# remove [u'fuzzy']", "header", "=", "pofile", ".", "header", "fixes", "=", "(", "(", "'SOME DESCRIPTIVE TITLE'", ",", "EDX_MARKER", ")", ",", "(", "'Translations template for PROJECT.'", ",", "EDX_MARKER", ")", ",", "(", "'YEAR'", ",", "str", "(", "datetime", ".", "utcnow", "(", ")", ".", "year", ")", ")", ",", "(", "'ORGANIZATION'", ",", "'edX'", ")", ",", "(", "\"THE PACKAGE'S COPYRIGHT HOLDER\"", ",", "\"EdX\"", ")", ",", "(", "'This file is distributed under the same license as the PROJECT project.'", ",", "'This file is distributed under the GNU AFFERO GENERAL PUBLIC LICENSE.'", ")", ",", "(", "'This file is distributed under the same license as the PACKAGE package.'", ",", "'This file is distributed under the GNU AFFERO GENERAL PUBLIC LICENSE.'", ")", ",", "(", "'FIRST AUTHOR <EMAIL@ADDRESS>'", ",", "'EdX Team <info@edx.org>'", ")", ",", ")", "for", "src", ",", "dest", "in", "fixes", ":", "header", "=", "header", ".", "replace", "(", "src", ",", "dest", ")", "pofile", ".", "header", "=", "header" ]
Replace default headers with edX headers
[ "Replace", "default", "headers", "with", "edX", "headers" ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/extract.py#L184-L216
train
234,129
edx/i18n-tools
i18n/extract.py
strip_key_strings
def strip_key_strings(pofile): """ Removes all entries in PO which are key strings. These entries should appear only in messages.po, not in any other po files. """ newlist = [entry for entry in pofile if not is_key_string(entry.msgid)] del pofile[:] pofile += newlist
python
def strip_key_strings(pofile): """ Removes all entries in PO which are key strings. These entries should appear only in messages.po, not in any other po files. """ newlist = [entry for entry in pofile if not is_key_string(entry.msgid)] del pofile[:] pofile += newlist
[ "def", "strip_key_strings", "(", "pofile", ")", ":", "newlist", "=", "[", "entry", "for", "entry", "in", "pofile", "if", "not", "is_key_string", "(", "entry", ".", "msgid", ")", "]", "del", "pofile", "[", ":", "]", "pofile", "+=", "newlist" ]
Removes all entries in PO which are key strings. These entries should appear only in messages.po, not in any other po files.
[ "Removes", "all", "entries", "in", "PO", "which", "are", "key", "strings", ".", "These", "entries", "should", "appear", "only", "in", "messages", ".", "po", "not", "in", "any", "other", "po", "files", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/extract.py#L249-L256
train
234,130
edx/i18n-tools
i18n/extract.py
Extract.rename_source_file
def rename_source_file(self, src, dst): """ Rename a file in the source directory. """ try: os.rename(self.source_msgs_dir.joinpath(src), self.source_msgs_dir.joinpath(dst)) except OSError: pass
python
def rename_source_file(self, src, dst): """ Rename a file in the source directory. """ try: os.rename(self.source_msgs_dir.joinpath(src), self.source_msgs_dir.joinpath(dst)) except OSError: pass
[ "def", "rename_source_file", "(", "self", ",", "src", ",", "dst", ")", ":", "try", ":", "os", ".", "rename", "(", "self", ".", "source_msgs_dir", ".", "joinpath", "(", "src", ")", ",", "self", ".", "source_msgs_dir", ".", "joinpath", "(", "dst", ")", ")", "except", "OSError", ":", "pass" ]
Rename a file in the source directory.
[ "Rename", "a", "file", "in", "the", "source", "directory", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/extract.py#L55-L62
train
234,131
edx/i18n-tools
i18n/main.py
get_valid_commands
def get_valid_commands(): """ Returns valid commands. Returns: commands (list): List of valid commands """ modules = [m.basename().split('.')[0] for m in Path(__file__).dirname().files('*.py')] commands = [] for modname in modules: if modname == 'main': continue mod = importlib.import_module('i18n.%s' % modname) if hasattr(mod, 'main'): commands.append(modname) return commands
python
def get_valid_commands(): """ Returns valid commands. Returns: commands (list): List of valid commands """ modules = [m.basename().split('.')[0] for m in Path(__file__).dirname().files('*.py')] commands = [] for modname in modules: if modname == 'main': continue mod = importlib.import_module('i18n.%s' % modname) if hasattr(mod, 'main'): commands.append(modname) return commands
[ "def", "get_valid_commands", "(", ")", ":", "modules", "=", "[", "m", ".", "basename", "(", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "for", "m", "in", "Path", "(", "__file__", ")", ".", "dirname", "(", ")", ".", "files", "(", "'*.py'", ")", "]", "commands", "=", "[", "]", "for", "modname", "in", "modules", ":", "if", "modname", "==", "'main'", ":", "continue", "mod", "=", "importlib", ".", "import_module", "(", "'i18n.%s'", "%", "modname", ")", "if", "hasattr", "(", "mod", ",", "'main'", ")", ":", "commands", ".", "append", "(", "modname", ")", "return", "commands" ]
Returns valid commands. Returns: commands (list): List of valid commands
[ "Returns", "valid", "commands", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/main.py#L11-L26
train
234,132
edx/i18n-tools
i18n/main.py
error_message
def error_message(): """ Writes out error message specifying the valid commands. Returns: Failure code for system exit """ sys.stderr.write('valid commands:\n') for cmd in get_valid_commands(): sys.stderr.write('\t%s\n' % cmd) return -1
python
def error_message(): """ Writes out error message specifying the valid commands. Returns: Failure code for system exit """ sys.stderr.write('valid commands:\n') for cmd in get_valid_commands(): sys.stderr.write('\t%s\n' % cmd) return -1
[ "def", "error_message", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'valid commands:\\n'", ")", "for", "cmd", "in", "get_valid_commands", "(", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'\\t%s\\n'", "%", "cmd", ")", "return", "-", "1" ]
Writes out error message specifying the valid commands. Returns: Failure code for system exit
[ "Writes", "out", "error", "message", "specifying", "the", "valid", "commands", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/main.py#L29-L39
train
234,133
edx/i18n-tools
i18n/main.py
main
def main(): """ Executes the given command. Returns error_message if command is not valid. Returns: Output of the given command or error message if command is not valid. """ try: command = sys.argv[1] except IndexError: return error_message() try: module = importlib.import_module('i18n.%s' % command) module.main.args = sys.argv[2:] except (ImportError, AttributeError): return error_message() return module.main()
python
def main(): """ Executes the given command. Returns error_message if command is not valid. Returns: Output of the given command or error message if command is not valid. """ try: command = sys.argv[1] except IndexError: return error_message() try: module = importlib.import_module('i18n.%s' % command) module.main.args = sys.argv[2:] except (ImportError, AttributeError): return error_message() return module.main()
[ "def", "main", "(", ")", ":", "try", ":", "command", "=", "sys", ".", "argv", "[", "1", "]", "except", "IndexError", ":", "return", "error_message", "(", ")", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "'i18n.%s'", "%", "command", ")", "module", ".", "main", ".", "args", "=", "sys", ".", "argv", "[", "2", ":", "]", "except", "(", "ImportError", ",", "AttributeError", ")", ":", "return", "error_message", "(", ")", "return", "module", ".", "main", "(", ")" ]
Executes the given command. Returns error_message if command is not valid. Returns: Output of the given command or error message if command is not valid.
[ "Executes", "the", "given", "command", ".", "Returns", "error_message", "if", "command", "is", "not", "valid", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/main.py#L42-L60
train
234,134
edx/i18n-tools
i18n/validate.py
validate_po_files
def validate_po_files(configuration, locale_dir, root_dir=None, report_empty=False, check_all=False): """ Validate all of the po files found in the root directory that are not product of a merge. Returns a boolean indicating whether or not problems were found. """ found_problems = False # List of .po files that are the product of a merge (see generate.py). merged_files = configuration.generate_merge.keys() for dirpath, __, filenames in os.walk(root_dir if root_dir else locale_dir): for name in filenames: __, ext = os.path.splitext(name) filename = os.path.join(dirpath, name) # Validate only .po files that are not product of a merge (see generate.py) unless check_all is true. # If django-partial.po has a problem, then django.po will also, so don't report it. if ext.lower() == '.po' and (check_all or os.path.basename(filename) not in merged_files): # First validate the format of this file if msgfmt_check_po_file(locale_dir, filename): found_problems = True # Check that the translated strings are valid, and optionally # check for empty translations. But don't check English. if "/locale/en/" not in filename: problems = check_messages(filename, report_empty) if problems: report_problems(filename, problems) found_problems = True dup_filename = filename.replace('.po', '.dup') has_duplicates = os.path.exists(dup_filename) if has_duplicates: log.warning(" Duplicates found in %s, details in .dup file", dup_filename) found_problems = True if not (problems or has_duplicates): log.info(" No problems found in %s", filename) return found_problems
python
def validate_po_files(configuration, locale_dir, root_dir=None, report_empty=False, check_all=False): """ Validate all of the po files found in the root directory that are not product of a merge. Returns a boolean indicating whether or not problems were found. """ found_problems = False # List of .po files that are the product of a merge (see generate.py). merged_files = configuration.generate_merge.keys() for dirpath, __, filenames in os.walk(root_dir if root_dir else locale_dir): for name in filenames: __, ext = os.path.splitext(name) filename = os.path.join(dirpath, name) # Validate only .po files that are not product of a merge (see generate.py) unless check_all is true. # If django-partial.po has a problem, then django.po will also, so don't report it. if ext.lower() == '.po' and (check_all or os.path.basename(filename) not in merged_files): # First validate the format of this file if msgfmt_check_po_file(locale_dir, filename): found_problems = True # Check that the translated strings are valid, and optionally # check for empty translations. But don't check English. if "/locale/en/" not in filename: problems = check_messages(filename, report_empty) if problems: report_problems(filename, problems) found_problems = True dup_filename = filename.replace('.po', '.dup') has_duplicates = os.path.exists(dup_filename) if has_duplicates: log.warning(" Duplicates found in %s, details in .dup file", dup_filename) found_problems = True if not (problems or has_duplicates): log.info(" No problems found in %s", filename) return found_problems
[ "def", "validate_po_files", "(", "configuration", ",", "locale_dir", ",", "root_dir", "=", "None", ",", "report_empty", "=", "False", ",", "check_all", "=", "False", ")", ":", "found_problems", "=", "False", "# List of .po files that are the product of a merge (see generate.py).", "merged_files", "=", "configuration", ".", "generate_merge", ".", "keys", "(", ")", "for", "dirpath", ",", "__", ",", "filenames", "in", "os", ".", "walk", "(", "root_dir", "if", "root_dir", "else", "locale_dir", ")", ":", "for", "name", "in", "filenames", ":", "__", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "name", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "dirpath", ",", "name", ")", "# Validate only .po files that are not product of a merge (see generate.py) unless check_all is true.", "# If django-partial.po has a problem, then django.po will also, so don't report it.", "if", "ext", ".", "lower", "(", ")", "==", "'.po'", "and", "(", "check_all", "or", "os", ".", "path", ".", "basename", "(", "filename", ")", "not", "in", "merged_files", ")", ":", "# First validate the format of this file", "if", "msgfmt_check_po_file", "(", "locale_dir", ",", "filename", ")", ":", "found_problems", "=", "True", "# Check that the translated strings are valid, and optionally", "# check for empty translations. But don't check English.", "if", "\"/locale/en/\"", "not", "in", "filename", ":", "problems", "=", "check_messages", "(", "filename", ",", "report_empty", ")", "if", "problems", ":", "report_problems", "(", "filename", ",", "problems", ")", "found_problems", "=", "True", "dup_filename", "=", "filename", ".", "replace", "(", "'.po'", ",", "'.dup'", ")", "has_duplicates", "=", "os", ".", "path", ".", "exists", "(", "dup_filename", ")", "if", "has_duplicates", ":", "log", ".", "warning", "(", "\" Duplicates found in %s, details in .dup file\"", ",", "dup_filename", ")", "found_problems", "=", "True", "if", "not", "(", "problems", "or", "has_duplicates", ")", ":", "log", ".", "info", "(", "\" No problems found in %s\"", ",", "filename", ")", "return", "found_problems" ]
Validate all of the po files found in the root directory that are not product of a merge. Returns a boolean indicating whether or not problems were found.
[ "Validate", "all", "of", "the", "po", "files", "found", "in", "the", "root", "directory", "that", "are", "not", "product", "of", "a", "merge", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/validate.py#L22-L63
train
234,135
edx/i18n-tools
i18n/validate.py
msgfmt_check_po_file
def msgfmt_check_po_file(locale_dir, filename): """ Call GNU msgfmt -c on each .po file to validate its format. Any errors caught by msgfmt are logged to log. Returns a boolean indicating whether or not problems were found. """ found_problems = False # Use relative paths to make output less noisy. rfile = os.path.relpath(filename, locale_dir) out, err = call('msgfmt -c -o /dev/null {}'.format(rfile), working_directory=locale_dir) if err: log.info(u'\n' + out.decode('utf8')) log.warning(u'\n' + err.decode('utf8')) found_problems = True return found_problems
python
def msgfmt_check_po_file(locale_dir, filename): """ Call GNU msgfmt -c on each .po file to validate its format. Any errors caught by msgfmt are logged to log. Returns a boolean indicating whether or not problems were found. """ found_problems = False # Use relative paths to make output less noisy. rfile = os.path.relpath(filename, locale_dir) out, err = call('msgfmt -c -o /dev/null {}'.format(rfile), working_directory=locale_dir) if err: log.info(u'\n' + out.decode('utf8')) log.warning(u'\n' + err.decode('utf8')) found_problems = True return found_problems
[ "def", "msgfmt_check_po_file", "(", "locale_dir", ",", "filename", ")", ":", "found_problems", "=", "False", "# Use relative paths to make output less noisy.", "rfile", "=", "os", ".", "path", ".", "relpath", "(", "filename", ",", "locale_dir", ")", "out", ",", "err", "=", "call", "(", "'msgfmt -c -o /dev/null {}'", ".", "format", "(", "rfile", ")", ",", "working_directory", "=", "locale_dir", ")", "if", "err", ":", "log", ".", "info", "(", "u'\\n'", "+", "out", ".", "decode", "(", "'utf8'", ")", ")", "log", ".", "warning", "(", "u'\\n'", "+", "err", ".", "decode", "(", "'utf8'", ")", ")", "found_problems", "=", "True", "return", "found_problems" ]
Call GNU msgfmt -c on each .po file to validate its format. Any errors caught by msgfmt are logged to log. Returns a boolean indicating whether or not problems were found.
[ "Call", "GNU", "msgfmt", "-", "c", "on", "each", ".", "po", "file", "to", "validate", "its", "format", ".", "Any", "errors", "caught", "by", "msgfmt", "are", "logged", "to", "log", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/validate.py#L66-L83
train
234,136
edx/i18n-tools
i18n/validate.py
tags_in_string
def tags_in_string(msg): """ Return the set of tags in a message string. Tags includes HTML tags, data placeholders, etc. Skips tags that might change due to translations: HTML entities, <abbr>, and so on. """ def is_linguistic_tag(tag): """Is this tag one that can change with the language?""" if tag.startswith("&"): return True if any(x in tag for x in ["<abbr>", "<abbr ", "</abbr>"]): return True return False __, tags = Converter().detag_string(msg) return set(t for t in tags if not is_linguistic_tag(t))
python
def tags_in_string(msg): """ Return the set of tags in a message string. Tags includes HTML tags, data placeholders, etc. Skips tags that might change due to translations: HTML entities, <abbr>, and so on. """ def is_linguistic_tag(tag): """Is this tag one that can change with the language?""" if tag.startswith("&"): return True if any(x in tag for x in ["<abbr>", "<abbr ", "</abbr>"]): return True return False __, tags = Converter().detag_string(msg) return set(t for t in tags if not is_linguistic_tag(t))
[ "def", "tags_in_string", "(", "msg", ")", ":", "def", "is_linguistic_tag", "(", "tag", ")", ":", "\"\"\"Is this tag one that can change with the language?\"\"\"", "if", "tag", ".", "startswith", "(", "\"&\"", ")", ":", "return", "True", "if", "any", "(", "x", "in", "tag", "for", "x", "in", "[", "\"<abbr>\"", ",", "\"<abbr \"", ",", "\"</abbr>\"", "]", ")", ":", "return", "True", "return", "False", "__", ",", "tags", "=", "Converter", "(", ")", ".", "detag_string", "(", "msg", ")", "return", "set", "(", "t", "for", "t", "in", "tags", "if", "not", "is_linguistic_tag", "(", "t", ")", ")" ]
Return the set of tags in a message string. Tags includes HTML tags, data placeholders, etc. Skips tags that might change due to translations: HTML entities, <abbr>, and so on.
[ "Return", "the", "set", "of", "tags", "in", "a", "message", "string", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/validate.py#L86-L105
train
234,137
edx/i18n-tools
i18n/validate.py
astral
def astral(msg): """Does `msg` have characters outside the Basic Multilingual Plane?""" # Python2 narrow builds present astral characters as surrogate pairs. # By encoding as utf32, and decoding DWORDS, we can get at the real code # points. utf32 = msg.encode("utf32")[4:] # [4:] to drop the bom code_points = struct.unpack("%dI" % (len(utf32) / 4), utf32) return any(cp > 0xFFFF for cp in code_points)
python
def astral(msg): """Does `msg` have characters outside the Basic Multilingual Plane?""" # Python2 narrow builds present astral characters as surrogate pairs. # By encoding as utf32, and decoding DWORDS, we can get at the real code # points. utf32 = msg.encode("utf32")[4:] # [4:] to drop the bom code_points = struct.unpack("%dI" % (len(utf32) / 4), utf32) return any(cp > 0xFFFF for cp in code_points)
[ "def", "astral", "(", "msg", ")", ":", "# Python2 narrow builds present astral characters as surrogate pairs.", "# By encoding as utf32, and decoding DWORDS, we can get at the real code", "# points.", "utf32", "=", "msg", ".", "encode", "(", "\"utf32\"", ")", "[", "4", ":", "]", "# [4:] to drop the bom", "code_points", "=", "struct", ".", "unpack", "(", "\"%dI\"", "%", "(", "len", "(", "utf32", ")", "/", "4", ")", ",", "utf32", ")", "return", "any", "(", "cp", ">", "0xFFFF", "for", "cp", "in", "code_points", ")" ]
Does `msg` have characters outside the Basic Multilingual Plane?
[ "Does", "msg", "have", "characters", "outside", "the", "Basic", "Multilingual", "Plane?" ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/validate.py#L108-L115
train
234,138
edx/i18n-tools
i18n/validate.py
report_problems
def report_problems(filename, problems): """ Report on the problems found in `filename`. `problems` is a list of tuples as returned by `check_messages`. """ problem_file = filename.replace(".po", ".prob") id_filler = textwrap.TextWrapper(width=79, initial_indent=" msgid: ", subsequent_indent=" " * 9) tx_filler = textwrap.TextWrapper(width=79, initial_indent=" -----> ", subsequent_indent=" " * 9) with codecs.open(problem_file, "w", encoding="utf8") as prob_file: for problem in problems: desc, msgid = problem[:2] prob_file.write(u"{}\n{}\n".format(desc, id_filler.fill(msgid))) info = u"{}\n{}\n".format(desc, id_filler.fill(msgid)) for translation in problem[2:]: prob_file.write(u"{}\n".format(tx_filler.fill(translation))) info += u"{}\n".format(tx_filler.fill(translation)) log.info(info) prob_file.write(u"\n") log.error(" %s problems in %s, details in .prob file", len(problems), filename)
python
def report_problems(filename, problems): """ Report on the problems found in `filename`. `problems` is a list of tuples as returned by `check_messages`. """ problem_file = filename.replace(".po", ".prob") id_filler = textwrap.TextWrapper(width=79, initial_indent=" msgid: ", subsequent_indent=" " * 9) tx_filler = textwrap.TextWrapper(width=79, initial_indent=" -----> ", subsequent_indent=" " * 9) with codecs.open(problem_file, "w", encoding="utf8") as prob_file: for problem in problems: desc, msgid = problem[:2] prob_file.write(u"{}\n{}\n".format(desc, id_filler.fill(msgid))) info = u"{}\n{}\n".format(desc, id_filler.fill(msgid)) for translation in problem[2:]: prob_file.write(u"{}\n".format(tx_filler.fill(translation))) info += u"{}\n".format(tx_filler.fill(translation)) log.info(info) prob_file.write(u"\n") log.error(" %s problems in %s, details in .prob file", len(problems), filename)
[ "def", "report_problems", "(", "filename", ",", "problems", ")", ":", "problem_file", "=", "filename", ".", "replace", "(", "\".po\"", ",", "\".prob\"", ")", "id_filler", "=", "textwrap", ".", "TextWrapper", "(", "width", "=", "79", ",", "initial_indent", "=", "\" msgid: \"", ",", "subsequent_indent", "=", "\" \"", "*", "9", ")", "tx_filler", "=", "textwrap", ".", "TextWrapper", "(", "width", "=", "79", ",", "initial_indent", "=", "\" -----> \"", ",", "subsequent_indent", "=", "\" \"", "*", "9", ")", "with", "codecs", ".", "open", "(", "problem_file", ",", "\"w\"", ",", "encoding", "=", "\"utf8\"", ")", "as", "prob_file", ":", "for", "problem", "in", "problems", ":", "desc", ",", "msgid", "=", "problem", "[", ":", "2", "]", "prob_file", ".", "write", "(", "u\"{}\\n{}\\n\"", ".", "format", "(", "desc", ",", "id_filler", ".", "fill", "(", "msgid", ")", ")", ")", "info", "=", "u\"{}\\n{}\\n\"", ".", "format", "(", "desc", ",", "id_filler", ".", "fill", "(", "msgid", ")", ")", "for", "translation", "in", "problem", "[", "2", ":", "]", ":", "prob_file", ".", "write", "(", "u\"{}\\n\"", ".", "format", "(", "tx_filler", ".", "fill", "(", "translation", ")", ")", ")", "info", "+=", "u\"{}\\n\"", ".", "format", "(", "tx_filler", ".", "fill", "(", "translation", ")", ")", "log", ".", "info", "(", "info", ")", "prob_file", ".", "write", "(", "u\"\\n\"", ")", "log", ".", "error", "(", "\" %s problems in %s, details in .prob file\"", ",", "len", "(", "problems", ")", ",", "filename", ")" ]
Report on the problems found in `filename`. `problems` is a list of tuples as returned by `check_messages`.
[ "Report", "on", "the", "problems", "found", "in", "filename", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/validate.py#L182-L203
train
234,139
edx/i18n-tools
i18n/generate.py
merge
def merge(configuration, locale, target='django.po', sources=('django-partial.po',), fail_if_missing=True): """ For the given locale, merge the `sources` files to become the `target` file. Note that the target file might also be one of the sources. If fail_if_missing is true, and the files to be merged are missing, throw an Exception, otherwise return silently. If fail_if_missing is false, and the files to be merged are missing, just return silently. """ LOG.info('Merging %s locale %s', target, locale) locale_directory = configuration.get_messages_dir(locale) try: validate_files(locale_directory, sources) except Exception: # pylint: disable=broad-except if not fail_if_missing: return raise # merged file is merged.po merge_cmd = 'msgcat -o merged.po ' + ' '.join(sources) execute(merge_cmd, working_directory=locale_directory) # clean up redunancies in the metadata merged_filename = locale_directory.joinpath('merged.po') duplicate_entries = clean_pofile(merged_filename) # rename merged.po -> django.po (default) target_filename = locale_directory.joinpath(target) os.rename(merged_filename, target_filename) # Write duplicate messages to a file if duplicate_entries: dup_file = target_filename.replace(".po", ".dup") with codecs.open(dup_file, "w", encoding="utf8") as dfile: for (entry, translations) in duplicate_entries: dfile.write(u"{}\n".format(entry)) dfile.write(u"Translations found were:\n\t{}\n\n".format(translations)) LOG.warning(" %s duplicates in %s, details in .dup file", len(duplicate_entries), target_filename)
python
def merge(configuration, locale, target='django.po', sources=('django-partial.po',), fail_if_missing=True): """ For the given locale, merge the `sources` files to become the `target` file. Note that the target file might also be one of the sources. If fail_if_missing is true, and the files to be merged are missing, throw an Exception, otherwise return silently. If fail_if_missing is false, and the files to be merged are missing, just return silently. """ LOG.info('Merging %s locale %s', target, locale) locale_directory = configuration.get_messages_dir(locale) try: validate_files(locale_directory, sources) except Exception: # pylint: disable=broad-except if not fail_if_missing: return raise # merged file is merged.po merge_cmd = 'msgcat -o merged.po ' + ' '.join(sources) execute(merge_cmd, working_directory=locale_directory) # clean up redunancies in the metadata merged_filename = locale_directory.joinpath('merged.po') duplicate_entries = clean_pofile(merged_filename) # rename merged.po -> django.po (default) target_filename = locale_directory.joinpath(target) os.rename(merged_filename, target_filename) # Write duplicate messages to a file if duplicate_entries: dup_file = target_filename.replace(".po", ".dup") with codecs.open(dup_file, "w", encoding="utf8") as dfile: for (entry, translations) in duplicate_entries: dfile.write(u"{}\n".format(entry)) dfile.write(u"Translations found were:\n\t{}\n\n".format(translations)) LOG.warning(" %s duplicates in %s, details in .dup file", len(duplicate_entries), target_filename)
[ "def", "merge", "(", "configuration", ",", "locale", ",", "target", "=", "'django.po'", ",", "sources", "=", "(", "'django-partial.po'", ",", ")", ",", "fail_if_missing", "=", "True", ")", ":", "LOG", ".", "info", "(", "'Merging %s locale %s'", ",", "target", ",", "locale", ")", "locale_directory", "=", "configuration", ".", "get_messages_dir", "(", "locale", ")", "try", ":", "validate_files", "(", "locale_directory", ",", "sources", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "if", "not", "fail_if_missing", ":", "return", "raise", "# merged file is merged.po", "merge_cmd", "=", "'msgcat -o merged.po '", "+", "' '", ".", "join", "(", "sources", ")", "execute", "(", "merge_cmd", ",", "working_directory", "=", "locale_directory", ")", "# clean up redunancies in the metadata", "merged_filename", "=", "locale_directory", ".", "joinpath", "(", "'merged.po'", ")", "duplicate_entries", "=", "clean_pofile", "(", "merged_filename", ")", "# rename merged.po -> django.po (default)", "target_filename", "=", "locale_directory", ".", "joinpath", "(", "target", ")", "os", ".", "rename", "(", "merged_filename", ",", "target_filename", ")", "# Write duplicate messages to a file", "if", "duplicate_entries", ":", "dup_file", "=", "target_filename", ".", "replace", "(", "\".po\"", ",", "\".dup\"", ")", "with", "codecs", ".", "open", "(", "dup_file", ",", "\"w\"", ",", "encoding", "=", "\"utf8\"", ")", "as", "dfile", ":", "for", "(", "entry", ",", "translations", ")", "in", "duplicate_entries", ":", "dfile", ".", "write", "(", "u\"{}\\n\"", ".", "format", "(", "entry", ")", ")", "dfile", ".", "write", "(", "u\"Translations found were:\\n\\t{}\\n\\n\"", ".", "format", "(", "translations", ")", ")", "LOG", ".", "warning", "(", "\" %s duplicates in %s, details in .dup file\"", ",", "len", "(", "duplicate_entries", ")", ",", "target_filename", ")" ]
For the given locale, merge the `sources` files to become the `target` file. Note that the target file might also be one of the sources. If fail_if_missing is true, and the files to be merged are missing, throw an Exception, otherwise return silently. If fail_if_missing is false, and the files to be merged are missing, just return silently.
[ "For", "the", "given", "locale", "merge", "the", "sources", "files", "to", "become", "the", "target", "file", ".", "Note", "that", "the", "target", "file", "might", "also", "be", "one", "of", "the", "sources", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/generate.py#L32-L72
train
234,140
edx/i18n-tools
i18n/generate.py
merge_files
def merge_files(configuration, locale, fail_if_missing=True): """ Merge all the files in `locale`, as specified in config.yaml. """ for target, sources in configuration.generate_merge.items(): merge(configuration, locale, target, sources, fail_if_missing)
python
def merge_files(configuration, locale, fail_if_missing=True): """ Merge all the files in `locale`, as specified in config.yaml. """ for target, sources in configuration.generate_merge.items(): merge(configuration, locale, target, sources, fail_if_missing)
[ "def", "merge_files", "(", "configuration", ",", "locale", ",", "fail_if_missing", "=", "True", ")", ":", "for", "target", ",", "sources", "in", "configuration", ".", "generate_merge", ".", "items", "(", ")", ":", "merge", "(", "configuration", ",", "locale", ",", "target", ",", "sources", ",", "fail_if_missing", ")" ]
Merge all the files in `locale`, as specified in config.yaml.
[ "Merge", "all", "the", "files", "in", "locale", "as", "specified", "in", "config", ".", "yaml", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/generate.py#L75-L80
train
234,141
edx/i18n-tools
i18n/generate.py
clean_pofile
def clean_pofile(pofile_path): """ Clean various aspect of a .po file. Fixes: - Removes the fuzzy flag on metadata. - Removes occurrence line numbers so that the generated files don't generate a lot of line noise when they're committed. Returns a list of any duplicate entries found. """ # Reading in the .po file and saving it again fixes redundancies. pomsgs = pofile(pofile_path) # The msgcat tool marks the metadata as fuzzy, but it's ok as it is. pomsgs.metadata_is_fuzzy = False duplicate_entries = [] for entry in pomsgs: # Remove line numbers entry.occurrences = [(filename, None) for filename, __ in entry.occurrences] # Check for merge conflicts. Pick the first, and emit a warning. if 'fuzzy' in entry.flags: # Remove fuzzy from flags entry.flags = [f for f in entry.flags if f != 'fuzzy'] # Save a warning message dup_msg = 'Multiple translations found for single string.\n\tString "{0}"\n\tPresent in files {1}'.format( entry.msgid, [f for (f, __) in entry.occurrences] ) duplicate_entries.append((dup_msg, entry.msgstr)) # Pick the first entry for msgstr in DUPLICATE_ENTRY_PATTERN.split(entry.msgstr): # Ignore any empty strings that may result from the split call if msgstr: # Set the first one we find to be the right one. Strip to remove extraneous # new lines that exist. entry.msgstr = msgstr.strip() # Raise error if there's new lines starting or ending the id string. if entry.msgid.startswith('\n') or entry.msgid.endswith('\n'): raise ValueError( u'{} starts or ends with a new line character, which is not allowed. ' 'Please fix before continuing. Source string is found in {}'.format( entry.msgid, entry.occurrences ).encode('utf-8') ) break pomsgs.save() return duplicate_entries
python
def clean_pofile(pofile_path): """ Clean various aspect of a .po file. Fixes: - Removes the fuzzy flag on metadata. - Removes occurrence line numbers so that the generated files don't generate a lot of line noise when they're committed. Returns a list of any duplicate entries found. """ # Reading in the .po file and saving it again fixes redundancies. pomsgs = pofile(pofile_path) # The msgcat tool marks the metadata as fuzzy, but it's ok as it is. pomsgs.metadata_is_fuzzy = False duplicate_entries = [] for entry in pomsgs: # Remove line numbers entry.occurrences = [(filename, None) for filename, __ in entry.occurrences] # Check for merge conflicts. Pick the first, and emit a warning. if 'fuzzy' in entry.flags: # Remove fuzzy from flags entry.flags = [f for f in entry.flags if f != 'fuzzy'] # Save a warning message dup_msg = 'Multiple translations found for single string.\n\tString "{0}"\n\tPresent in files {1}'.format( entry.msgid, [f for (f, __) in entry.occurrences] ) duplicate_entries.append((dup_msg, entry.msgstr)) # Pick the first entry for msgstr in DUPLICATE_ENTRY_PATTERN.split(entry.msgstr): # Ignore any empty strings that may result from the split call if msgstr: # Set the first one we find to be the right one. Strip to remove extraneous # new lines that exist. entry.msgstr = msgstr.strip() # Raise error if there's new lines starting or ending the id string. if entry.msgid.startswith('\n') or entry.msgid.endswith('\n'): raise ValueError( u'{} starts or ends with a new line character, which is not allowed. ' 'Please fix before continuing. Source string is found in {}'.format( entry.msgid, entry.occurrences ).encode('utf-8') ) break pomsgs.save() return duplicate_entries
[ "def", "clean_pofile", "(", "pofile_path", ")", ":", "# Reading in the .po file and saving it again fixes redundancies.", "pomsgs", "=", "pofile", "(", "pofile_path", ")", "# The msgcat tool marks the metadata as fuzzy, but it's ok as it is.", "pomsgs", ".", "metadata_is_fuzzy", "=", "False", "duplicate_entries", "=", "[", "]", "for", "entry", "in", "pomsgs", ":", "# Remove line numbers", "entry", ".", "occurrences", "=", "[", "(", "filename", ",", "None", ")", "for", "filename", ",", "__", "in", "entry", ".", "occurrences", "]", "# Check for merge conflicts. Pick the first, and emit a warning.", "if", "'fuzzy'", "in", "entry", ".", "flags", ":", "# Remove fuzzy from flags", "entry", ".", "flags", "=", "[", "f", "for", "f", "in", "entry", ".", "flags", "if", "f", "!=", "'fuzzy'", "]", "# Save a warning message", "dup_msg", "=", "'Multiple translations found for single string.\\n\\tString \"{0}\"\\n\\tPresent in files {1}'", ".", "format", "(", "entry", ".", "msgid", ",", "[", "f", "for", "(", "f", ",", "__", ")", "in", "entry", ".", "occurrences", "]", ")", "duplicate_entries", ".", "append", "(", "(", "dup_msg", ",", "entry", ".", "msgstr", ")", ")", "# Pick the first entry", "for", "msgstr", "in", "DUPLICATE_ENTRY_PATTERN", ".", "split", "(", "entry", ".", "msgstr", ")", ":", "# Ignore any empty strings that may result from the split call", "if", "msgstr", ":", "# Set the first one we find to be the right one. Strip to remove extraneous", "# new lines that exist.", "entry", ".", "msgstr", "=", "msgstr", ".", "strip", "(", ")", "# Raise error if there's new lines starting or ending the id string.", "if", "entry", ".", "msgid", ".", "startswith", "(", "'\\n'", ")", "or", "entry", ".", "msgid", ".", "endswith", "(", "'\\n'", ")", ":", "raise", "ValueError", "(", "u'{} starts or ends with a new line character, which is not allowed. '", "'Please fix before continuing. Source string is found in {}'", ".", "format", "(", "entry", ".", "msgid", ",", "entry", ".", "occurrences", ")", ".", "encode", "(", "'utf-8'", ")", ")", "break", "pomsgs", ".", "save", "(", ")", "return", "duplicate_entries" ]
Clean various aspect of a .po file. Fixes: - Removes the fuzzy flag on metadata. - Removes occurrence line numbers so that the generated files don't generate a lot of line noise when they're committed. Returns a list of any duplicate entries found.
[ "Clean", "various", "aspect", "of", "a", ".", "po", "file", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/generate.py#L83-L135
train
234,142
edx/i18n-tools
i18n/dummy.py
new_filename
def new_filename(original_filename, new_locale): """Returns a filename derived from original_filename, using new_locale as the locale""" orig_file = Path(original_filename) new_file = orig_file.parent.parent.parent / new_locale / orig_file.parent.name / orig_file.name return new_file.abspath()
python
def new_filename(original_filename, new_locale): """Returns a filename derived from original_filename, using new_locale as the locale""" orig_file = Path(original_filename) new_file = orig_file.parent.parent.parent / new_locale / orig_file.parent.name / orig_file.name return new_file.abspath()
[ "def", "new_filename", "(", "original_filename", ",", "new_locale", ")", ":", "orig_file", "=", "Path", "(", "original_filename", ")", "new_file", "=", "orig_file", ".", "parent", ".", "parent", ".", "parent", "/", "new_locale", "/", "orig_file", ".", "parent", ".", "name", "/", "orig_file", ".", "name", "return", "new_file", ".", "abspath", "(", ")" ]
Returns a filename derived from original_filename, using new_locale as the locale
[ "Returns", "a", "filename", "derived", "from", "original_filename", "using", "new_locale", "as", "the", "locale" ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/dummy.py#L217-L221
train
234,143
edx/i18n-tools
i18n/dummy.py
DummyCommand.run
def run(self, args): """ Generate dummy strings for all source po files. """ configuration = self.configuration source_messages_dir = configuration.source_messages_dir for locale, converter in zip(configuration.dummy_locales, [Dummy(), Dummy2(), ArabicDummy()]): print('Processing source language files into dummy strings, locale "{}"'.format(locale)) for source_file in configuration.source_messages_dir.walkfiles('*.po'): if args.verbose: print(' ', source_file.relpath()) make_dummy(source_messages_dir.joinpath(source_file), locale, converter) if args.verbose: print()
python
def run(self, args): """ Generate dummy strings for all source po files. """ configuration = self.configuration source_messages_dir = configuration.source_messages_dir for locale, converter in zip(configuration.dummy_locales, [Dummy(), Dummy2(), ArabicDummy()]): print('Processing source language files into dummy strings, locale "{}"'.format(locale)) for source_file in configuration.source_messages_dir.walkfiles('*.po'): if args.verbose: print(' ', source_file.relpath()) make_dummy(source_messages_dir.joinpath(source_file), locale, converter) if args.verbose: print()
[ "def", "run", "(", "self", ",", "args", ")", ":", "configuration", "=", "self", ".", "configuration", "source_messages_dir", "=", "configuration", ".", "source_messages_dir", "for", "locale", ",", "converter", "in", "zip", "(", "configuration", ".", "dummy_locales", ",", "[", "Dummy", "(", ")", ",", "Dummy2", "(", ")", ",", "ArabicDummy", "(", ")", "]", ")", ":", "print", "(", "'Processing source language files into dummy strings, locale \"{}\"'", ".", "format", "(", "locale", ")", ")", "for", "source_file", "in", "configuration", ".", "source_messages_dir", ".", "walkfiles", "(", "'*.po'", ")", ":", "if", "args", ".", "verbose", ":", "print", "(", "' '", ",", "source_file", ".", "relpath", "(", ")", ")", "make_dummy", "(", "source_messages_dir", ".", "joinpath", "(", "source_file", ")", ",", "locale", ",", "converter", ")", "if", "args", ".", "verbose", ":", "print", "(", ")" ]
Generate dummy strings for all source po files.
[ "Generate", "dummy", "strings", "for", "all", "source", "po", "files", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/dummy.py#L235-L248
train
234,144
edx/i18n-tools
i18n/execute.py
execute
def execute(command, working_directory=config.BASE_DIR, stderr=sp.STDOUT): """ Executes shell command in a given working_directory. Command is a string to pass to the shell. Output is ignored. """ LOG.info("Executing in %s ...", working_directory) LOG.info(command) sp.check_call(command, cwd=working_directory, stderr=stderr, shell=True)
python
def execute(command, working_directory=config.BASE_DIR, stderr=sp.STDOUT): """ Executes shell command in a given working_directory. Command is a string to pass to the shell. Output is ignored. """ LOG.info("Executing in %s ...", working_directory) LOG.info(command) sp.check_call(command, cwd=working_directory, stderr=stderr, shell=True)
[ "def", "execute", "(", "command", ",", "working_directory", "=", "config", ".", "BASE_DIR", ",", "stderr", "=", "sp", ".", "STDOUT", ")", ":", "LOG", ".", "info", "(", "\"Executing in %s ...\"", ",", "working_directory", ")", "LOG", ".", "info", "(", "command", ")", "sp", ".", "check_call", "(", "command", ",", "cwd", "=", "working_directory", ",", "stderr", "=", "stderr", ",", "shell", "=", "True", ")" ]
Executes shell command in a given working_directory. Command is a string to pass to the shell. Output is ignored.
[ "Executes", "shell", "command", "in", "a", "given", "working_directory", ".", "Command", "is", "a", "string", "to", "pass", "to", "the", "shell", ".", "Output", "is", "ignored", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/execute.py#L13-L21
train
234,145
edx/i18n-tools
i18n/execute.py
remove_file
def remove_file(filename, verbose=True): """ Attempt to delete filename. log is boolean. If true, removal is logged. Log a warning if file does not exist. Logging filenames are relative to config.BASE_DIR to cut down on noise in output. """ if verbose: LOG.info('Deleting file %s', os.path.relpath(filename, config.BASE_DIR)) if not os.path.exists(filename): LOG.warning("File does not exist: %s", os.path.relpath(filename, config.BASE_DIR)) else: os.remove(filename)
python
def remove_file(filename, verbose=True): """ Attempt to delete filename. log is boolean. If true, removal is logged. Log a warning if file does not exist. Logging filenames are relative to config.BASE_DIR to cut down on noise in output. """ if verbose: LOG.info('Deleting file %s', os.path.relpath(filename, config.BASE_DIR)) if not os.path.exists(filename): LOG.warning("File does not exist: %s", os.path.relpath(filename, config.BASE_DIR)) else: os.remove(filename)
[ "def", "remove_file", "(", "filename", ",", "verbose", "=", "True", ")", ":", "if", "verbose", ":", "LOG", ".", "info", "(", "'Deleting file %s'", ",", "os", ".", "path", ".", "relpath", "(", "filename", ",", "config", ".", "BASE_DIR", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOG", ".", "warning", "(", "\"File does not exist: %s\"", ",", "os", ".", "path", ".", "relpath", "(", "filename", ",", "config", ".", "BASE_DIR", ")", ")", "else", ":", "os", ".", "remove", "(", "filename", ")" ]
Attempt to delete filename. log is boolean. If true, removal is logged. Log a warning if file does not exist. Logging filenames are relative to config.BASE_DIR to cut down on noise in output.
[ "Attempt", "to", "delete", "filename", ".", "log", "is", "boolean", ".", "If", "true", "removal", "is", "logged", ".", "Log", "a", "warning", "if", "file", "does", "not", "exist", ".", "Logging", "filenames", "are", "relative", "to", "config", ".", "BASE_DIR", "to", "cut", "down", "on", "noise", "in", "output", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/execute.py#L37-L49
train
234,146
edx/i18n-tools
i18n/transifex.py
push
def push(*resources): """ Push translation source English files to Transifex. Arguments name specific resources to push. Otherwise, push all the source files. """ cmd = 'tx push -s' if resources: for resource in resources: execute(cmd + ' -r {resource}'.format(resource=resource)) else: execute(cmd)
python
def push(*resources): """ Push translation source English files to Transifex. Arguments name specific resources to push. Otherwise, push all the source files. """ cmd = 'tx push -s' if resources: for resource in resources: execute(cmd + ' -r {resource}'.format(resource=resource)) else: execute(cmd)
[ "def", "push", "(", "*", "resources", ")", ":", "cmd", "=", "'tx push -s'", "if", "resources", ":", "for", "resource", "in", "resources", ":", "execute", "(", "cmd", "+", "' -r {resource}'", ".", "format", "(", "resource", "=", "resource", ")", ")", "else", ":", "execute", "(", "cmd", ")" ]
Push translation source English files to Transifex. Arguments name specific resources to push. Otherwise, push all the source files.
[ "Push", "translation", "source", "English", "files", "to", "Transifex", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L17-L29
train
234,147
edx/i18n-tools
i18n/transifex.py
pull_all_ltr
def pull_all_ltr(configuration): """ Pulls all translations - reviewed or not - for LTR languages """ print("Pulling all translated LTR languages from transifex...") for lang in configuration.ltr_langs: print('rm -rf conf/locale/' + lang) execute('rm -rf conf/locale/' + lang) execute('tx pull -l ' + lang) clean_translated_locales(configuration, langs=configuration.ltr_langs)
python
def pull_all_ltr(configuration): """ Pulls all translations - reviewed or not - for LTR languages """ print("Pulling all translated LTR languages from transifex...") for lang in configuration.ltr_langs: print('rm -rf conf/locale/' + lang) execute('rm -rf conf/locale/' + lang) execute('tx pull -l ' + lang) clean_translated_locales(configuration, langs=configuration.ltr_langs)
[ "def", "pull_all_ltr", "(", "configuration", ")", ":", "print", "(", "\"Pulling all translated LTR languages from transifex...\"", ")", "for", "lang", "in", "configuration", ".", "ltr_langs", ":", "print", "(", "'rm -rf conf/locale/'", "+", "lang", ")", "execute", "(", "'rm -rf conf/locale/'", "+", "lang", ")", "execute", "(", "'tx pull -l '", "+", "lang", ")", "clean_translated_locales", "(", "configuration", ",", "langs", "=", "configuration", ".", "ltr_langs", ")" ]
Pulls all translations - reviewed or not - for LTR languages
[ "Pulls", "all", "translations", "-", "reviewed", "or", "not", "-", "for", "LTR", "languages" ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L79-L88
train
234,148
edx/i18n-tools
i18n/transifex.py
pull_all_rtl
def pull_all_rtl(configuration): """ Pulls all translations - reviewed or not - for RTL languages """ print("Pulling all translated RTL languages from transifex...") for lang in configuration.rtl_langs: print('rm -rf conf/locale/' + lang) execute('rm -rf conf/locale/' + lang) execute('tx pull -l ' + lang) clean_translated_locales(configuration, langs=configuration.rtl_langs)
python
def pull_all_rtl(configuration): """ Pulls all translations - reviewed or not - for RTL languages """ print("Pulling all translated RTL languages from transifex...") for lang in configuration.rtl_langs: print('rm -rf conf/locale/' + lang) execute('rm -rf conf/locale/' + lang) execute('tx pull -l ' + lang) clean_translated_locales(configuration, langs=configuration.rtl_langs)
[ "def", "pull_all_rtl", "(", "configuration", ")", ":", "print", "(", "\"Pulling all translated RTL languages from transifex...\"", ")", "for", "lang", "in", "configuration", ".", "rtl_langs", ":", "print", "(", "'rm -rf conf/locale/'", "+", "lang", ")", "execute", "(", "'rm -rf conf/locale/'", "+", "lang", ")", "execute", "(", "'tx pull -l '", "+", "lang", ")", "clean_translated_locales", "(", "configuration", ",", "langs", "=", "configuration", ".", "rtl_langs", ")" ]
Pulls all translations - reviewed or not - for RTL languages
[ "Pulls", "all", "translations", "-", "reviewed", "or", "not", "-", "for", "RTL", "languages" ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L91-L100
train
234,149
edx/i18n-tools
i18n/transifex.py
clean_translated_locales
def clean_translated_locales(configuration, langs=None): """ Strips out the warning from all translated po files about being an English source file. """ if not langs: langs = configuration.translated_locales for locale in langs: clean_locale(configuration, locale)
python
def clean_translated_locales(configuration, langs=None): """ Strips out the warning from all translated po files about being an English source file. """ if not langs: langs = configuration.translated_locales for locale in langs: clean_locale(configuration, locale)
[ "def", "clean_translated_locales", "(", "configuration", ",", "langs", "=", "None", ")", ":", "if", "not", "langs", ":", "langs", "=", "configuration", ".", "translated_locales", "for", "locale", "in", "langs", ":", "clean_locale", "(", "configuration", ",", "locale", ")" ]
Strips out the warning from all translated po files about being an English source file.
[ "Strips", "out", "the", "warning", "from", "all", "translated", "po", "files", "about", "being", "an", "English", "source", "file", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L103-L111
train
234,150
edx/i18n-tools
i18n/transifex.py
clean_locale
def clean_locale(configuration, locale): """ Strips out the warning from all of a locale's translated po files about being an English source file. Iterates over machine-generated files. """ dirname = configuration.get_messages_dir(locale) if not dirname.exists(): # Happens when we have a supported locale that doesn't exist in Transifex return for filename in dirname.files('*.po'): clean_file(configuration, dirname.joinpath(filename))
python
def clean_locale(configuration, locale): """ Strips out the warning from all of a locale's translated po files about being an English source file. Iterates over machine-generated files. """ dirname = configuration.get_messages_dir(locale) if not dirname.exists(): # Happens when we have a supported locale that doesn't exist in Transifex return for filename in dirname.files('*.po'): clean_file(configuration, dirname.joinpath(filename))
[ "def", "clean_locale", "(", "configuration", ",", "locale", ")", ":", "dirname", "=", "configuration", ".", "get_messages_dir", "(", "locale", ")", "if", "not", "dirname", ".", "exists", "(", ")", ":", "# Happens when we have a supported locale that doesn't exist in Transifex", "return", "for", "filename", "in", "dirname", ".", "files", "(", "'*.po'", ")", ":", "clean_file", "(", "configuration", ",", "dirname", ".", "joinpath", "(", "filename", ")", ")" ]
Strips out the warning from all of a locale's translated po files about being an English source file. Iterates over machine-generated files.
[ "Strips", "out", "the", "warning", "from", "all", "of", "a", "locale", "s", "translated", "po", "files", "about", "being", "an", "English", "source", "file", ".", "Iterates", "over", "machine", "-", "generated", "files", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L114-L125
train
234,151
edx/i18n-tools
i18n/transifex.py
clean_file
def clean_file(configuration, filename): """ Strips out the warning from a translated po file about being an English source file. Replaces warning with a note about coming from Transifex. """ pofile = polib.pofile(filename) if pofile.header.find(EDX_MARKER) != -1: new_header = get_new_header(configuration, pofile) new = pofile.header.replace(EDX_MARKER, new_header) pofile.header = new pofile.save()
python
def clean_file(configuration, filename): """ Strips out the warning from a translated po file about being an English source file. Replaces warning with a note about coming from Transifex. """ pofile = polib.pofile(filename) if pofile.header.find(EDX_MARKER) != -1: new_header = get_new_header(configuration, pofile) new = pofile.header.replace(EDX_MARKER, new_header) pofile.header = new pofile.save()
[ "def", "clean_file", "(", "configuration", ",", "filename", ")", ":", "pofile", "=", "polib", ".", "pofile", "(", "filename", ")", "if", "pofile", ".", "header", ".", "find", "(", "EDX_MARKER", ")", "!=", "-", "1", ":", "new_header", "=", "get_new_header", "(", "configuration", ",", "pofile", ")", "new", "=", "pofile", ".", "header", ".", "replace", "(", "EDX_MARKER", ",", "new_header", ")", "pofile", ".", "header", "=", "new", "pofile", ".", "save", "(", ")" ]
Strips out the warning from a translated po file about being an English source file. Replaces warning with a note about coming from Transifex.
[ "Strips", "out", "the", "warning", "from", "a", "translated", "po", "file", "about", "being", "an", "English", "source", "file", ".", "Replaces", "warning", "with", "a", "note", "about", "coming", "from", "Transifex", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L128-L139
train
234,152
edx/i18n-tools
i18n/transifex.py
get_new_header
def get_new_header(configuration, pofile): """ Insert info about edX into the po file headers """ team = pofile.metadata.get('Language-Team', None) if not team: return TRANSIFEX_HEADER.format(configuration.TRANSIFEX_URL) return TRANSIFEX_HEADER.format(team)
python
def get_new_header(configuration, pofile): """ Insert info about edX into the po file headers """ team = pofile.metadata.get('Language-Team', None) if not team: return TRANSIFEX_HEADER.format(configuration.TRANSIFEX_URL) return TRANSIFEX_HEADER.format(team)
[ "def", "get_new_header", "(", "configuration", ",", "pofile", ")", ":", "team", "=", "pofile", ".", "metadata", ".", "get", "(", "'Language-Team'", ",", "None", ")", "if", "not", "team", ":", "return", "TRANSIFEX_HEADER", ".", "format", "(", "configuration", ".", "TRANSIFEX_URL", ")", "return", "TRANSIFEX_HEADER", ".", "format", "(", "team", ")" ]
Insert info about edX into the po file headers
[ "Insert", "info", "about", "edX", "into", "the", "po", "file", "headers" ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/transifex.py#L142-L149
train
234,153
edx/i18n-tools
i18n/converter.py
Converter.detag_string
def detag_string(self, string): """Extracts tags from string. returns (string, list) where string: string has tags replaced by indices (<BR>... => <0>, <1>, <2>, etc.) list: list of the removed tags ('<BR>', '<I>', '</I>') """ counter = itertools.count(0) count = lambda m: '<%s>' % next(counter) tags = self.tag_pattern.findall(string) tags = [''.join(tag) for tag in tags] (new, nfound) = self.tag_pattern.subn(count, string) if len(tags) != nfound: raise Exception('tags dont match:' + string) return (new, tags)
python
def detag_string(self, string): """Extracts tags from string. returns (string, list) where string: string has tags replaced by indices (<BR>... => <0>, <1>, <2>, etc.) list: list of the removed tags ('<BR>', '<I>', '</I>') """ counter = itertools.count(0) count = lambda m: '<%s>' % next(counter) tags = self.tag_pattern.findall(string) tags = [''.join(tag) for tag in tags] (new, nfound) = self.tag_pattern.subn(count, string) if len(tags) != nfound: raise Exception('tags dont match:' + string) return (new, tags)
[ "def", "detag_string", "(", "self", ",", "string", ")", ":", "counter", "=", "itertools", ".", "count", "(", "0", ")", "count", "=", "lambda", "m", ":", "'<%s>'", "%", "next", "(", "counter", ")", "tags", "=", "self", ".", "tag_pattern", ".", "findall", "(", "string", ")", "tags", "=", "[", "''", ".", "join", "(", "tag", ")", "for", "tag", "in", "tags", "]", "(", "new", ",", "nfound", ")", "=", "self", ".", "tag_pattern", ".", "subn", "(", "count", ",", "string", ")", "if", "len", "(", "tags", ")", "!=", "nfound", ":", "raise", "Exception", "(", "'tags dont match:'", "+", "string", ")", "return", "(", "new", ",", "tags", ")" ]
Extracts tags from string. returns (string, list) where string: string has tags replaced by indices (<BR>... => <0>, <1>, <2>, etc.) list: list of the removed tags ('<BR>', '<I>', '</I>')
[ "Extracts", "tags", "from", "string", "." ]
99b20c17d1a0ca07a8839f33e0e9068248a581e5
https://github.com/edx/i18n-tools/blob/99b20c17d1a0ca07a8839f33e0e9068248a581e5/i18n/converter.py#L51-L65
train
234,154
protream/iquery
iquery/utils.py
Args.options
def options(self): """Train tickets query options.""" arg = self.get(0) if arg.startswith('-') and not self.is_asking_for_help: return arg[1:] return ''.join(x for x in arg if x in 'dgktz')
python
def options(self): """Train tickets query options.""" arg = self.get(0) if arg.startswith('-') and not self.is_asking_for_help: return arg[1:] return ''.join(x for x in arg if x in 'dgktz')
[ "def", "options", "(", "self", ")", ":", "arg", "=", "self", ".", "get", "(", "0", ")", "if", "arg", ".", "startswith", "(", "'-'", ")", "and", "not", "self", ".", "is_asking_for_help", ":", "return", "arg", "[", "1", ":", "]", "return", "''", ".", "join", "(", "x", "for", "x", "in", "arg", "if", "x", "in", "'dgktz'", ")" ]
Train tickets query options.
[ "Train", "tickets", "query", "options", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/utils.py#L79-L84
train
234,155
protream/iquery
iquery/trains.py
TrainsCollection.trains
def trains(self): """Filter rows according to `headers`""" for row in self._rows: train_no = row.get('station_train_code') initial = train_no[0].lower() if not self._opts or initial in self._opts: train = [ # Column: '车次' train_no, # Column: '车站' '\n'.join([ colored.green(row.get('from_station_name')), colored.red(row.get('to_station_name')), ]), # Column: '时间' '\n'.join([ colored.green(row.get('start_time')), colored.red(row.get('arrive_time')), ]), # Column: '历时' self._get_duration(row), # Column: '商务' row.get('swz_num'), # Column: '一等' row.get('zy_num'), # Column: '二等' row.get('ze_num'), # Column: '软卧' row.get('rw_num'), # Column: '硬卧' row.get('yw_num'), # Column: '软座' row.get('rz_num'), # Column: '硬座' row.get('yz_num'), # Column: '无座' row.get('wz_num') ] yield train
python
def trains(self): """Filter rows according to `headers`""" for row in self._rows: train_no = row.get('station_train_code') initial = train_no[0].lower() if not self._opts or initial in self._opts: train = [ # Column: '车次' train_no, # Column: '车站' '\n'.join([ colored.green(row.get('from_station_name')), colored.red(row.get('to_station_name')), ]), # Column: '时间' '\n'.join([ colored.green(row.get('start_time')), colored.red(row.get('arrive_time')), ]), # Column: '历时' self._get_duration(row), # Column: '商务' row.get('swz_num'), # Column: '一等' row.get('zy_num'), # Column: '二等' row.get('ze_num'), # Column: '软卧' row.get('rw_num'), # Column: '硬卧' row.get('yw_num'), # Column: '软座' row.get('rz_num'), # Column: '硬座' row.get('yz_num'), # Column: '无座' row.get('wz_num') ] yield train
[ "def", "trains", "(", "self", ")", ":", "for", "row", "in", "self", ".", "_rows", ":", "train_no", "=", "row", ".", "get", "(", "'station_train_code'", ")", "initial", "=", "train_no", "[", "0", "]", ".", "lower", "(", ")", "if", "not", "self", ".", "_opts", "or", "initial", "in", "self", ".", "_opts", ":", "train", "=", "[", "# Column: '车次'", "train_no", ",", "# Column: '车站'", "'\\n'", ".", "join", "(", "[", "colored", ".", "green", "(", "row", ".", "get", "(", "'from_station_name'", ")", ")", ",", "colored", ".", "red", "(", "row", ".", "get", "(", "'to_station_name'", ")", ")", ",", "]", ")", ",", "# Column: '时间'", "'\\n'", ".", "join", "(", "[", "colored", ".", "green", "(", "row", ".", "get", "(", "'start_time'", ")", ")", ",", "colored", ".", "red", "(", "row", ".", "get", "(", "'arrive_time'", ")", ")", ",", "]", ")", ",", "# Column: '历时'", "self", ".", "_get_duration", "(", "row", ")", ",", "# Column: '商务'", "row", ".", "get", "(", "'swz_num'", ")", ",", "# Column: '一等'", "row", ".", "get", "(", "'zy_num'", ")", ",", "# Column: '二等'", "row", ".", "get", "(", "'ze_num'", ")", ",", "# Column: '软卧'", "row", ".", "get", "(", "'rw_num'", ")", ",", "# Column: '硬卧'", "row", ".", "get", "(", "'yw_num'", ")", ",", "# Column: '软座'", "row", ".", "get", "(", "'rz_num'", ")", ",", "# Column: '硬座'", "row", ".", "get", "(", "'yz_num'", ")", ",", "# Column: '无座'", "row", ".", "get", "(", "'wz_num'", ")", "]", "yield", "train" ]
Filter rows according to `headers`
[ "Filter", "rows", "according", "to", "headers" ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L63-L101
train
234,156
protream/iquery
iquery/trains.py
TrainsCollection.pretty_print
def pretty_print(self): """Use `PrettyTable` to perform formatted outprint.""" pt = PrettyTable() if len(self) == 0: pt._set_field_names(['Sorry,']) pt.add_row([TRAIN_NOT_FOUND]) else: pt._set_field_names(self.headers) for train in self.trains: pt.add_row(train) print(pt)
python
def pretty_print(self): """Use `PrettyTable` to perform formatted outprint.""" pt = PrettyTable() if len(self) == 0: pt._set_field_names(['Sorry,']) pt.add_row([TRAIN_NOT_FOUND]) else: pt._set_field_names(self.headers) for train in self.trains: pt.add_row(train) print(pt)
[ "def", "pretty_print", "(", "self", ")", ":", "pt", "=", "PrettyTable", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "pt", ".", "_set_field_names", "(", "[", "'Sorry,'", "]", ")", "pt", ".", "add_row", "(", "[", "TRAIN_NOT_FOUND", "]", ")", "else", ":", "pt", ".", "_set_field_names", "(", "self", ".", "headers", ")", "for", "train", "in", "self", ".", "trains", ":", "pt", ".", "add_row", "(", "train", ")", "print", "(", "pt", ")" ]
Use `PrettyTable` to perform formatted outprint.
[ "Use", "PrettyTable", "to", "perform", "formatted", "outprint", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L103-L113
train
234,157
protream/iquery
iquery/trains.py
TrainTicketsQuery._valid_date
def _valid_date(self): """Check and return a valid query date.""" date = self._parse_date(self.date) if not date: exit_after_echo(INVALID_DATE) try: date = datetime.strptime(date, '%Y%m%d') except ValueError: exit_after_echo(INVALID_DATE) # A valid query date should within 50 days. offset = date - datetime.today() if offset.days not in range(-1, 50): exit_after_echo(INVALID_DATE) return datetime.strftime(date, '%Y-%m-%d')
python
def _valid_date(self): """Check and return a valid query date.""" date = self._parse_date(self.date) if not date: exit_after_echo(INVALID_DATE) try: date = datetime.strptime(date, '%Y%m%d') except ValueError: exit_after_echo(INVALID_DATE) # A valid query date should within 50 days. offset = date - datetime.today() if offset.days not in range(-1, 50): exit_after_echo(INVALID_DATE) return datetime.strftime(date, '%Y-%m-%d')
[ "def", "_valid_date", "(", "self", ")", ":", "date", "=", "self", ".", "_parse_date", "(", "self", ".", "date", ")", "if", "not", "date", ":", "exit_after_echo", "(", "INVALID_DATE", ")", "try", ":", "date", "=", "datetime", ".", "strptime", "(", "date", ",", "'%Y%m%d'", ")", "except", "ValueError", ":", "exit_after_echo", "(", "INVALID_DATE", ")", "# A valid query date should within 50 days.", "offset", "=", "date", "-", "datetime", ".", "today", "(", ")", "if", "offset", ".", "days", "not", "in", "range", "(", "-", "1", ",", "50", ")", ":", "exit_after_echo", "(", "INVALID_DATE", ")", "return", "datetime", ".", "strftime", "(", "date", ",", "'%Y-%m-%d'", ")" ]
Check and return a valid query date.
[ "Check", "and", "return", "a", "valid", "query", "date", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L177-L194
train
234,158
protream/iquery
iquery/trains.py
TrainTicketsQuery._parse_date
def _parse_date(date): """Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string. """ result = ''.join(re.findall('\d', date)) l = len(result) # User only input month and day, eg 6-1, 6.26, 0626... if l in (2, 3, 4): year = str(datetime.today().year) return year + result # User input full format date, eg 201661, 2016-6-26, 20160626... if l in (6, 7, 8): return result return ''
python
def _parse_date(date): """Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string. """ result = ''.join(re.findall('\d', date)) l = len(result) # User only input month and day, eg 6-1, 6.26, 0626... if l in (2, 3, 4): year = str(datetime.today().year) return year + result # User input full format date, eg 201661, 2016-6-26, 20160626... if l in (6, 7, 8): return result return ''
[ "def", "_parse_date", "(", "date", ")", ":", "result", "=", "''", ".", "join", "(", "re", ".", "findall", "(", "'\\d'", ",", "date", ")", ")", "l", "=", "len", "(", "result", ")", "# User only input month and day, eg 6-1, 6.26, 0626...", "if", "l", "in", "(", "2", ",", "3", ",", "4", ")", ":", "year", "=", "str", "(", "datetime", ".", "today", "(", ")", ".", "year", ")", "return", "year", "+", "result", "# User input full format date, eg 201661, 2016-6-26, 20160626...", "if", "l", "in", "(", "6", ",", "7", ",", "8", ")", ":", "return", "result", "return", "''" ]
Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string.
[ "Parse", "from", "the", "user", "input", "date", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L197-L218
train
234,159
protream/iquery
iquery/trains.py
TrainTicketsQuery._build_params
def _build_params(self): """Have no idea why wrong params order can't get data. So, use `OrderedDict` here. """ d = OrderedDict() d['purpose_codes'] = 'ADULT' d['queryDate'] = self._valid_date d['from_station'] = self._from_station_telecode d['to_station'] = self._to_station_telecode return d
python
def _build_params(self): """Have no idea why wrong params order can't get data. So, use `OrderedDict` here. """ d = OrderedDict() d['purpose_codes'] = 'ADULT' d['queryDate'] = self._valid_date d['from_station'] = self._from_station_telecode d['to_station'] = self._to_station_telecode return d
[ "def", "_build_params", "(", "self", ")", ":", "d", "=", "OrderedDict", "(", ")", "d", "[", "'purpose_codes'", "]", "=", "'ADULT'", "d", "[", "'queryDate'", "]", "=", "self", ".", "_valid_date", "d", "[", "'from_station'", "]", "=", "self", ".", "_from_station_telecode", "d", "[", "'to_station'", "]", "=", "self", ".", "_to_station_telecode", "return", "d" ]
Have no idea why wrong params order can't get data. So, use `OrderedDict` here.
[ "Have", "no", "idea", "why", "wrong", "params", "order", "can", "t", "get", "data", ".", "So", "use", "OrderedDict", "here", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/trains.py#L220-L229
train
234,160
protream/iquery
iquery/showes.py
ShowTicketsQuery.date_range
def date_range(self): """Generate date range according to the `days` user input.""" try: days = int(self.days) except ValueError: exit_after_echo(QUERY_DAYS_INVALID) if days < 1: exit_after_echo(QUERY_DAYS_INVALID) start = datetime.today() end = start + timedelta(days=days) return ( datetime.strftime(start, '%Y-%m-%d'), datetime.strftime(end, '%Y-%m-%d') )
python
def date_range(self): """Generate date range according to the `days` user input.""" try: days = int(self.days) except ValueError: exit_after_echo(QUERY_DAYS_INVALID) if days < 1: exit_after_echo(QUERY_DAYS_INVALID) start = datetime.today() end = start + timedelta(days=days) return ( datetime.strftime(start, '%Y-%m-%d'), datetime.strftime(end, '%Y-%m-%d') )
[ "def", "date_range", "(", "self", ")", ":", "try", ":", "days", "=", "int", "(", "self", ".", "days", ")", "except", "ValueError", ":", "exit_after_echo", "(", "QUERY_DAYS_INVALID", ")", "if", "days", "<", "1", ":", "exit_after_echo", "(", "QUERY_DAYS_INVALID", ")", "start", "=", "datetime", ".", "today", "(", ")", "end", "=", "start", "+", "timedelta", "(", "days", "=", "days", ")", "return", "(", "datetime", ".", "strftime", "(", "start", ",", "'%Y-%m-%d'", ")", ",", "datetime", ".", "strftime", "(", "end", ",", "'%Y-%m-%d'", ")", ")" ]
Generate date range according to the `days` user input.
[ "Generate", "date", "range", "according", "to", "the", "days", "user", "input", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/showes.py#L121-L135
train
234,161
protream/iquery
iquery/hospitals.py
query
def query(params): """`params` is a city name or a city name + hospital name. CLI: 1. query all putian hospitals in a city: $ iquery -p 南京 +------+ | 南京 | +------+ |... | +------+ |... | +------+ ... 2. query if the hospital in the city is putian series, you can only input hospital's short name: $ iquery -p 南京 曙光 +------------+ |南京曙光医院| +------------+ | True | +------------+ """ r = requests_get(QUERY_URL, verify=True) return HospitalCollection(r.json(), params)
python
def query(params): """`params` is a city name or a city name + hospital name. CLI: 1. query all putian hospitals in a city: $ iquery -p 南京 +------+ | 南京 | +------+ |... | +------+ |... | +------+ ... 2. query if the hospital in the city is putian series, you can only input hospital's short name: $ iquery -p 南京 曙光 +------------+ |南京曙光医院| +------------+ | True | +------------+ """ r = requests_get(QUERY_URL, verify=True) return HospitalCollection(r.json(), params)
[ "def", "query", "(", "params", ")", ":", "r", "=", "requests_get", "(", "QUERY_URL", ",", "verify", "=", "True", ")", "return", "HospitalCollection", "(", "r", ".", "json", "(", ")", ",", "params", ")" ]
`params` is a city name or a city name + hospital name. CLI: 1. query all putian hospitals in a city: $ iquery -p 南京 +------+ | 南京 | +------+ |... | +------+ |... | +------+ ... 2. query if the hospital in the city is putian series, you can only input hospital's short name: $ iquery -p 南京 曙光 +------------+ |南京曙光医院| +------------+ | True | +------------+
[ "params", "is", "a", "city", "name", "or", "a", "city", "name", "+", "hospital", "name", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/hospitals.py#L67-L99
train
234,162
protream/iquery
iquery/core.py
cli
def cli(): """Various information query via command line. Usage: iquery -l <song> [singer] iquery (-m|电影) iquery (-c|彩票) iquery -p <city> iquery -p <city> <hospital> iquery <city> <show> [days] iquery [-dgktz] <from> <to> <date> Arguments: from 出发站 to 到达站 date 查询日期 song 歌曲名称 singer 歌手, 可选项 city 查询城市 show 演出的类型 days 查询近(几)天内的演出, 若省略, 默认15 city 城市名,加在-p后查询该城市所有莆田医院 hospital 医院名,加在city后检查该医院是否是莆田系 Options: -h, --help 显示该帮助菜单. -dgktz 动车,高铁,快速,特快,直达 -m 热映电影查询 -p 莆田系医院查询 -l 歌词查询 Show: 演唱会 音乐会 音乐剧 歌舞剧 儿童剧 话剧 歌剧 比赛 舞蹈 戏曲 相声 杂技 马戏 魔术 Go to https://github.com/protream/tickets for usage examples. """ if args.is_asking_for_help: exit_after_echo(cli.__doc__, color=None) elif args.is_querying_lottery: from .lottery import query result = query() elif args.is_querying_movie: from .movies import query result = query() elif args.is_querying_lyric: from .lyrics import query result = query(args.as_lyric_query_params) elif args.is_querying_show: from .showes import query result = query(args.as_show_query_params) elif args.is_querying_putian_hospital: from .hospitals import query result = query(args.as_hospital_query_params) elif args.is_querying_train: from .trains import query result = query(args.as_train_query_params) else: exit_after_echo(show_usage.__doc__, color=None) result.pretty_print()
python
def cli(): """Various information query via command line. Usage: iquery -l <song> [singer] iquery (-m|电影) iquery (-c|彩票) iquery -p <city> iquery -p <city> <hospital> iquery <city> <show> [days] iquery [-dgktz] <from> <to> <date> Arguments: from 出发站 to 到达站 date 查询日期 song 歌曲名称 singer 歌手, 可选项 city 查询城市 show 演出的类型 days 查询近(几)天内的演出, 若省略, 默认15 city 城市名,加在-p后查询该城市所有莆田医院 hospital 医院名,加在city后检查该医院是否是莆田系 Options: -h, --help 显示该帮助菜单. -dgktz 动车,高铁,快速,特快,直达 -m 热映电影查询 -p 莆田系医院查询 -l 歌词查询 Show: 演唱会 音乐会 音乐剧 歌舞剧 儿童剧 话剧 歌剧 比赛 舞蹈 戏曲 相声 杂技 马戏 魔术 Go to https://github.com/protream/tickets for usage examples. """ if args.is_asking_for_help: exit_after_echo(cli.__doc__, color=None) elif args.is_querying_lottery: from .lottery import query result = query() elif args.is_querying_movie: from .movies import query result = query() elif args.is_querying_lyric: from .lyrics import query result = query(args.as_lyric_query_params) elif args.is_querying_show: from .showes import query result = query(args.as_show_query_params) elif args.is_querying_putian_hospital: from .hospitals import query result = query(args.as_hospital_query_params) elif args.is_querying_train: from .trains import query result = query(args.as_train_query_params) else: exit_after_echo(show_usage.__doc__, color=None) result.pretty_print()
[ "def", "cli", "(", ")", ":", "if", "args", ".", "is_asking_for_help", ":", "exit_after_echo", "(", "cli", ".", "__doc__", ",", "color", "=", "None", ")", "elif", "args", ".", "is_querying_lottery", ":", "from", ".", "lottery", "import", "query", "result", "=", "query", "(", ")", "elif", "args", ".", "is_querying_movie", ":", "from", ".", "movies", "import", "query", "result", "=", "query", "(", ")", "elif", "args", ".", "is_querying_lyric", ":", "from", ".", "lyrics", "import", "query", "result", "=", "query", "(", "args", ".", "as_lyric_query_params", ")", "elif", "args", ".", "is_querying_show", ":", "from", ".", "showes", "import", "query", "result", "=", "query", "(", "args", ".", "as_show_query_params", ")", "elif", "args", ".", "is_querying_putian_hospital", ":", "from", ".", "hospitals", "import", "query", "result", "=", "query", "(", "args", ".", "as_hospital_query_params", ")", "elif", "args", ".", "is_querying_train", ":", "from", ".", "trains", "import", "query", "result", "=", "query", "(", "args", ".", "as_train_query_params", ")", "else", ":", "exit_after_echo", "(", "show_usage", ".", "__doc__", ",", "color", "=", "None", ")", "result", ".", "pretty_print", "(", ")" ]
Various information query via command line. Usage: iquery -l <song> [singer] iquery (-m|电影) iquery (-c|彩票) iquery -p <city> iquery -p <city> <hospital> iquery <city> <show> [days] iquery [-dgktz] <from> <to> <date> Arguments: from 出发站 to 到达站 date 查询日期 song 歌曲名称 singer 歌手, 可选项 city 查询城市 show 演出的类型 days 查询近(几)天内的演出, 若省略, 默认15 city 城市名,加在-p后查询该城市所有莆田医院 hospital 医院名,加在city后检查该医院是否是莆田系 Options: -h, --help 显示该帮助菜单. -dgktz 动车,高铁,快速,特快,直达 -m 热映电影查询 -p 莆田系医院查询 -l 歌词查询 Show: 演唱会 音乐会 音乐剧 歌舞剧 儿童剧 话剧 歌剧 比赛 舞蹈 戏曲 相声 杂技 马戏 魔术 Go to https://github.com/protream/tickets for usage examples.
[ "Various", "information", "query", "via", "command", "line", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/core.py#L44-L117
train
234,163
protream/iquery
iquery/movies.py
query
def query(): """Query hot movies infomation from douban.""" r = requests_get(QUERY_URL) try: rows = r.json()['subject_collection_items'] except (IndexError, TypeError): rows = [] return MoviesCollection(rows)
python
def query(): """Query hot movies infomation from douban.""" r = requests_get(QUERY_URL) try: rows = r.json()['subject_collection_items'] except (IndexError, TypeError): rows = [] return MoviesCollection(rows)
[ "def", "query", "(", ")", ":", "r", "=", "requests_get", "(", "QUERY_URL", ")", "try", ":", "rows", "=", "r", ".", "json", "(", ")", "[", "'subject_collection_items'", "]", "except", "(", "IndexError", ",", "TypeError", ")", ":", "rows", "=", "[", "]", "return", "MoviesCollection", "(", "rows", ")" ]
Query hot movies infomation from douban.
[ "Query", "hot", "movies", "infomation", "from", "douban", "." ]
7272e68af610f1dd63cf695209cfa44b75adc0e6
https://github.com/protream/iquery/blob/7272e68af610f1dd63cf695209cfa44b75adc0e6/iquery/movies.py#L93-L103
train
234,164
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_draft
def action_draft(self): """Set a change request as draft""" for rec in self: if not rec.state == 'cancelled': raise UserError( _('You need to cancel it before reopening.')) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can reopen Change Requests.')) rec.write({'state': 'draft'})
python
def action_draft(self): """Set a change request as draft""" for rec in self: if not rec.state == 'cancelled': raise UserError( _('You need to cancel it before reopening.')) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can reopen Change Requests.')) rec.write({'state': 'draft'})
[ "def", "action_draft", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "if", "not", "rec", ".", "state", "==", "'cancelled'", ":", "raise", "UserError", "(", "_", "(", "'You need to cancel it before reopening.'", ")", ")", "if", "not", "(", "rec", ".", "am_i_owner", "or", "rec", ".", "am_i_approver", ")", ":", "raise", "UserError", "(", "_", "(", "'You are not authorized to do this.\\r\\n'", "'Only owners or approvers can reopen Change Requests.'", ")", ")", "rec", ".", "write", "(", "{", "'state'", ":", "'draft'", "}", ")" ]
Set a change request as draft
[ "Set", "a", "change", "request", "as", "draft" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L54-L64
train
234,165
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_to_approve
def action_to_approve(self): """Set a change request as to approve""" template = self.env.ref( 'document_page_approval.email_template_new_draft_need_approval') approver_gid = self.env.ref( 'document_page_approval.group_document_approver_user') for rec in self: if rec.state != 'draft': raise UserError( _("Can't approve pages in '%s' state.") % rec.state) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can request approval.')) # request approval if rec.is_approval_required: rec.write({'state': 'to approve'}) guids = [g.id for g in rec.page_id.approver_group_ids] users = self.env['res.users'].search([ ('groups_id', 'in', guids), ('groups_id', 'in', approver_gid.id)]) rec.message_subscribe_users([u.id for u in users]) rec.message_post_with_template(template.id) else: # auto-approve if approval is not required rec.action_approve()
python
def action_to_approve(self): """Set a change request as to approve""" template = self.env.ref( 'document_page_approval.email_template_new_draft_need_approval') approver_gid = self.env.ref( 'document_page_approval.group_document_approver_user') for rec in self: if rec.state != 'draft': raise UserError( _("Can't approve pages in '%s' state.") % rec.state) if not (rec.am_i_owner or rec.am_i_approver): raise UserError( _('You are not authorized to do this.\r\n' 'Only owners or approvers can request approval.')) # request approval if rec.is_approval_required: rec.write({'state': 'to approve'}) guids = [g.id for g in rec.page_id.approver_group_ids] users = self.env['res.users'].search([ ('groups_id', 'in', guids), ('groups_id', 'in', approver_gid.id)]) rec.message_subscribe_users([u.id for u in users]) rec.message_post_with_template(template.id) else: # auto-approve if approval is not required rec.action_approve()
[ "def", "action_to_approve", "(", "self", ")", ":", "template", "=", "self", ".", "env", ".", "ref", "(", "'document_page_approval.email_template_new_draft_need_approval'", ")", "approver_gid", "=", "self", ".", "env", ".", "ref", "(", "'document_page_approval.group_document_approver_user'", ")", "for", "rec", "in", "self", ":", "if", "rec", ".", "state", "!=", "'draft'", ":", "raise", "UserError", "(", "_", "(", "\"Can't approve pages in '%s' state.\"", ")", "%", "rec", ".", "state", ")", "if", "not", "(", "rec", ".", "am_i_owner", "or", "rec", ".", "am_i_approver", ")", ":", "raise", "UserError", "(", "_", "(", "'You are not authorized to do this.\\r\\n'", "'Only owners or approvers can request approval.'", ")", ")", "# request approval", "if", "rec", ".", "is_approval_required", ":", "rec", ".", "write", "(", "{", "'state'", ":", "'to approve'", "}", ")", "guids", "=", "[", "g", ".", "id", "for", "g", "in", "rec", ".", "page_id", ".", "approver_group_ids", "]", "users", "=", "self", ".", "env", "[", "'res.users'", "]", ".", "search", "(", "[", "(", "'groups_id'", ",", "'in'", ",", "guids", ")", ",", "(", "'groups_id'", ",", "'in'", ",", "approver_gid", ".", "id", ")", "]", ")", "rec", ".", "message_subscribe_users", "(", "[", "u", ".", "id", "for", "u", "in", "users", "]", ")", "rec", ".", "message_post_with_template", "(", "template", ".", "id", ")", "else", ":", "# auto-approve if approval is not required", "rec", ".", "action_approve", "(", ")" ]
Set a change request as to approve
[ "Set", "a", "change", "request", "as", "to", "approve" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L67-L92
train
234,166
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_approve
def action_approve(self): """Set a change request as approved.""" for rec in self: if rec.state not in ['draft', 'to approve']: raise UserError( _("Can't approve page in '%s' state.") % rec.state) if not rec.am_i_approver: raise UserError(_( 'You are not authorized to do this.\r\n' 'Only approvers with these groups can approve this: ' ) % ', '.join( [g.display_name for g in rec.page_id.approver_group_ids])) # Update state rec.write({ 'state': 'approved', 'approved_date': fields.datetime.now(), 'approved_uid': self.env.uid, }) # Trigger computed field update rec.page_id._compute_history_head() # Notify state change rec.message_post( subtype='mt_comment', body=_( 'Change request has been approved by %s.' ) % (self.env.user.name) ) # Notify followers a new version is available rec.page_id.message_post( subtype='mt_comment', body=_( 'New version of the document %s approved.' ) % (rec.page_id.name) )
python
def action_approve(self): """Set a change request as approved.""" for rec in self: if rec.state not in ['draft', 'to approve']: raise UserError( _("Can't approve page in '%s' state.") % rec.state) if not rec.am_i_approver: raise UserError(_( 'You are not authorized to do this.\r\n' 'Only approvers with these groups can approve this: ' ) % ', '.join( [g.display_name for g in rec.page_id.approver_group_ids])) # Update state rec.write({ 'state': 'approved', 'approved_date': fields.datetime.now(), 'approved_uid': self.env.uid, }) # Trigger computed field update rec.page_id._compute_history_head() # Notify state change rec.message_post( subtype='mt_comment', body=_( 'Change request has been approved by %s.' ) % (self.env.user.name) ) # Notify followers a new version is available rec.page_id.message_post( subtype='mt_comment', body=_( 'New version of the document %s approved.' ) % (rec.page_id.name) )
[ "def", "action_approve", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "if", "rec", ".", "state", "not", "in", "[", "'draft'", ",", "'to approve'", "]", ":", "raise", "UserError", "(", "_", "(", "\"Can't approve page in '%s' state.\"", ")", "%", "rec", ".", "state", ")", "if", "not", "rec", ".", "am_i_approver", ":", "raise", "UserError", "(", "_", "(", "'You are not authorized to do this.\\r\\n'", "'Only approvers with these groups can approve this: '", ")", "%", "', '", ".", "join", "(", "[", "g", ".", "display_name", "for", "g", "in", "rec", ".", "page_id", ".", "approver_group_ids", "]", ")", ")", "# Update state", "rec", ".", "write", "(", "{", "'state'", ":", "'approved'", ",", "'approved_date'", ":", "fields", ".", "datetime", ".", "now", "(", ")", ",", "'approved_uid'", ":", "self", ".", "env", ".", "uid", ",", "}", ")", "# Trigger computed field update", "rec", ".", "page_id", ".", "_compute_history_head", "(", ")", "# Notify state change", "rec", ".", "message_post", "(", "subtype", "=", "'mt_comment'", ",", "body", "=", "_", "(", "'Change request has been approved by %s.'", ")", "%", "(", "self", ".", "env", ".", "user", ".", "name", ")", ")", "# Notify followers a new version is available", "rec", ".", "page_id", ".", "message_post", "(", "subtype", "=", "'mt_comment'", ",", "body", "=", "_", "(", "'New version of the document %s approved.'", ")", "%", "(", "rec", ".", "page_id", ".", "name", ")", ")" ]
Set a change request as approved.
[ "Set", "a", "change", "request", "as", "approved", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L95-L129
train
234,167
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory.action_cancel
def action_cancel(self): """Set a change request as cancelled.""" self.write({'state': 'cancelled'}) for rec in self: rec.message_post( subtype='mt_comment', body=_( 'Change request <b>%s</b> has been cancelled by %s.' ) % (rec.display_name, self.env.user.name) )
python
def action_cancel(self): """Set a change request as cancelled.""" self.write({'state': 'cancelled'}) for rec in self: rec.message_post( subtype='mt_comment', body=_( 'Change request <b>%s</b> has been cancelled by %s.' ) % (rec.display_name, self.env.user.name) )
[ "def", "action_cancel", "(", "self", ")", ":", "self", ".", "write", "(", "{", "'state'", ":", "'cancelled'", "}", ")", "for", "rec", "in", "self", ":", "rec", ".", "message_post", "(", "subtype", "=", "'mt_comment'", ",", "body", "=", "_", "(", "'Change request <b>%s</b> has been cancelled by %s.'", ")", "%", "(", "rec", ".", "display_name", ",", "self", ".", "env", ".", "user", ".", "name", ")", ")" ]
Set a change request as cancelled.
[ "Set", "a", "change", "request", "as", "cancelled", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L132-L141
train
234,168
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory._compute_am_i_owner
def _compute_am_i_owner(self): """Check if current user is the owner""" for rec in self: rec.am_i_owner = (rec.create_uid == self.env.user)
python
def _compute_am_i_owner(self): """Check if current user is the owner""" for rec in self: rec.am_i_owner = (rec.create_uid == self.env.user)
[ "def", "_compute_am_i_owner", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "rec", ".", "am_i_owner", "=", "(", "rec", ".", "create_uid", "==", "self", ".", "env", ".", "user", ")" ]
Check if current user is the owner
[ "Check", "if", "current", "user", "is", "the", "owner" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L150-L153
train
234,169
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory._compute_page_url
def _compute_page_url(self): """Compute the page url.""" for page in self: base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url', default='http://localhost:8069' ) page.page_url = ( '{}/web#db={}&id={}&view_type=form&' 'model=document.page.history').format( base_url, self.env.cr.dbname, page.id )
python
def _compute_page_url(self): """Compute the page url.""" for page in self: base_url = self.env['ir.config_parameter'].sudo().get_param( 'web.base.url', default='http://localhost:8069' ) page.page_url = ( '{}/web#db={}&id={}&view_type=form&' 'model=document.page.history').format( base_url, self.env.cr.dbname, page.id )
[ "def", "_compute_page_url", "(", "self", ")", ":", "for", "page", "in", "self", ":", "base_url", "=", "self", ".", "env", "[", "'ir.config_parameter'", "]", ".", "sudo", "(", ")", ".", "get_param", "(", "'web.base.url'", ",", "default", "=", "'http://localhost:8069'", ")", "page", ".", "page_url", "=", "(", "'{}/web#db={}&id={}&view_type=form&'", "'model=document.page.history'", ")", ".", "format", "(", "base_url", ",", "self", ".", "env", ".", "cr", ".", "dbname", ",", "page", ".", "id", ")" ]
Compute the page url.
[ "Compute", "the", "page", "url", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L156-L170
train
234,170
OCA/knowledge
document_page_approval/models/document_page_history.py
DocumentPageHistory._compute_diff
def _compute_diff(self): """Shows a diff between this version and the previous version""" history = self.env['document.page.history'] for rec in self: domain = [ ('page_id', '=', rec.page_id.id), ('state', '=', 'approved')] if rec.approved_date: domain.append(('approved_date', '<', rec.approved_date)) prev = history.search(domain, limit=1, order='approved_date DESC') if prev: rec.diff = self.getDiff(prev.id, rec.id) else: rec.diff = self.getDiff(False, rec.id)
python
def _compute_diff(self): """Shows a diff between this version and the previous version""" history = self.env['document.page.history'] for rec in self: domain = [ ('page_id', '=', rec.page_id.id), ('state', '=', 'approved')] if rec.approved_date: domain.append(('approved_date', '<', rec.approved_date)) prev = history.search(domain, limit=1, order='approved_date DESC') if prev: rec.diff = self.getDiff(prev.id, rec.id) else: rec.diff = self.getDiff(False, rec.id)
[ "def", "_compute_diff", "(", "self", ")", ":", "history", "=", "self", ".", "env", "[", "'document.page.history'", "]", "for", "rec", "in", "self", ":", "domain", "=", "[", "(", "'page_id'", ",", "'='", ",", "rec", ".", "page_id", ".", "id", ")", ",", "(", "'state'", ",", "'='", ",", "'approved'", ")", "]", "if", "rec", ".", "approved_date", ":", "domain", ".", "append", "(", "(", "'approved_date'", ",", "'<'", ",", "rec", ".", "approved_date", ")", ")", "prev", "=", "history", ".", "search", "(", "domain", ",", "limit", "=", "1", ",", "order", "=", "'approved_date DESC'", ")", "if", "prev", ":", "rec", ".", "diff", "=", "self", ".", "getDiff", "(", "prev", ".", "id", ",", "rec", ".", "id", ")", "else", ":", "rec", ".", "diff", "=", "self", ".", "getDiff", "(", "False", ",", "rec", ".", "id", ")" ]
Shows a diff between this version and the previous version
[ "Shows", "a", "diff", "between", "this", "version", "and", "the", "previous", "version" ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page_history.py#L173-L186
train
234,171
OCA/knowledge
document_url/wizard/document_url.py
AddUrlWizard.action_add_url
def action_add_url(self): """Adds the URL with the given name as an ir.attachment record.""" if not self.env.context.get('active_model'): return attachment_obj = self.env['ir.attachment'] for form in self: url = parse.urlparse(form.url) if not url.scheme: url = parse.urlparse('%s%s' % ('http://', form.url)) for active_id in self.env.context.get('active_ids', []): attachment = { 'name': form.name, 'type': 'url', 'url': url.geturl(), 'res_id': active_id, 'res_model': self.env.context['active_model'], } attachment_obj.create(attachment) return {'type': 'ir.actions.act_close_wizard_and_reload_view'}
python
def action_add_url(self): """Adds the URL with the given name as an ir.attachment record.""" if not self.env.context.get('active_model'): return attachment_obj = self.env['ir.attachment'] for form in self: url = parse.urlparse(form.url) if not url.scheme: url = parse.urlparse('%s%s' % ('http://', form.url)) for active_id in self.env.context.get('active_ids', []): attachment = { 'name': form.name, 'type': 'url', 'url': url.geturl(), 'res_id': active_id, 'res_model': self.env.context['active_model'], } attachment_obj.create(attachment) return {'type': 'ir.actions.act_close_wizard_and_reload_view'}
[ "def", "action_add_url", "(", "self", ")", ":", "if", "not", "self", ".", "env", ".", "context", ".", "get", "(", "'active_model'", ")", ":", "return", "attachment_obj", "=", "self", ".", "env", "[", "'ir.attachment'", "]", "for", "form", "in", "self", ":", "url", "=", "parse", ".", "urlparse", "(", "form", ".", "url", ")", "if", "not", "url", ".", "scheme", ":", "url", "=", "parse", ".", "urlparse", "(", "'%s%s'", "%", "(", "'http://'", ",", "form", ".", "url", ")", ")", "for", "active_id", "in", "self", ".", "env", ".", "context", ".", "get", "(", "'active_ids'", ",", "[", "]", ")", ":", "attachment", "=", "{", "'name'", ":", "form", ".", "name", ",", "'type'", ":", "'url'", ",", "'url'", ":", "url", ".", "geturl", "(", ")", ",", "'res_id'", ":", "active_id", ",", "'res_model'", ":", "self", ".", "env", ".", "context", "[", "'active_model'", "]", ",", "}", "attachment_obj", ".", "create", "(", "attachment", ")", "return", "{", "'type'", ":", "'ir.actions.act_close_wizard_and_reload_view'", "}" ]
Adds the URL with the given name as an ir.attachment record.
[ "Adds", "the", "URL", "with", "the", "given", "name", "as", "an", "ir", ".", "attachment", "record", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_url/wizard/document_url.py#L14-L32
train
234,172
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage._compute_is_approval_required
def _compute_is_approval_required(self): """Check if the document required approval based on his parents.""" for page in self: res = page.approval_required if page.parent_id: res = res or page.parent_id.is_approval_required page.is_approval_required = res
python
def _compute_is_approval_required(self): """Check if the document required approval based on his parents.""" for page in self: res = page.approval_required if page.parent_id: res = res or page.parent_id.is_approval_required page.is_approval_required = res
[ "def", "_compute_is_approval_required", "(", "self", ")", ":", "for", "page", "in", "self", ":", "res", "=", "page", ".", "approval_required", "if", "page", ".", "parent_id", ":", "res", "=", "res", "or", "page", ".", "parent_id", ".", "is_approval_required", "page", ".", "is_approval_required", "=", "res" ]
Check if the document required approval based on his parents.
[ "Check", "if", "the", "document", "required", "approval", "based", "on", "his", "parents", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L76-L82
train
234,173
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage._compute_approver_group_ids
def _compute_approver_group_ids(self): """Compute the approver groups based on his parents.""" for page in self: res = page.approver_gid if page.parent_id: res = res | page.parent_id.approver_group_ids page.approver_group_ids = res
python
def _compute_approver_group_ids(self): """Compute the approver groups based on his parents.""" for page in self: res = page.approver_gid if page.parent_id: res = res | page.parent_id.approver_group_ids page.approver_group_ids = res
[ "def", "_compute_approver_group_ids", "(", "self", ")", ":", "for", "page", "in", "self", ":", "res", "=", "page", ".", "approver_gid", "if", "page", ".", "parent_id", ":", "res", "=", "res", "|", "page", ".", "parent_id", ".", "approver_group_ids", "page", ".", "approver_group_ids", "=", "res" ]
Compute the approver groups based on his parents.
[ "Compute", "the", "approver", "groups", "based", "on", "his", "parents", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L86-L92
train
234,174
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage._compute_am_i_approver
def _compute_am_i_approver(self): """Check if the current user can approve changes to this page.""" for rec in self: rec.am_i_approver = rec.can_user_approve_this_page(self.env.user)
python
def _compute_am_i_approver(self): """Check if the current user can approve changes to this page.""" for rec in self: rec.am_i_approver = rec.can_user_approve_this_page(self.env.user)
[ "def", "_compute_am_i_approver", "(", "self", ")", ":", "for", "rec", "in", "self", ":", "rec", ".", "am_i_approver", "=", "rec", ".", "can_user_approve_this_page", "(", "self", ".", "env", ".", "user", ")" ]
Check if the current user can approve changes to this page.
[ "Check", "if", "the", "current", "user", "can", "approve", "changes", "to", "this", "page", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L96-L99
train
234,175
OCA/knowledge
document_page_approval/models/document_page.py
DocumentPage.can_user_approve_this_page
def can_user_approve_this_page(self, user): """Check if a user can approve this page.""" self.ensure_one() # if it's not required, anyone can approve if not self.is_approval_required: return True # if user belongs to 'Knowledge / Manager', he can approve anything if user.has_group('document_page.group_document_manager'): return True # to approve, user must have approver rights if not user.has_group( 'document_page_approval.group_document_approver_user'): return False # if there aren't any approver_groups_defined, user can approve if not self.approver_group_ids: return True # to approve, user must belong to any of the approver groups return len(user.groups_id & self.approver_group_ids) > 0
python
def can_user_approve_this_page(self, user): """Check if a user can approve this page.""" self.ensure_one() # if it's not required, anyone can approve if not self.is_approval_required: return True # if user belongs to 'Knowledge / Manager', he can approve anything if user.has_group('document_page.group_document_manager'): return True # to approve, user must have approver rights if not user.has_group( 'document_page_approval.group_document_approver_user'): return False # if there aren't any approver_groups_defined, user can approve if not self.approver_group_ids: return True # to approve, user must belong to any of the approver groups return len(user.groups_id & self.approver_group_ids) > 0
[ "def", "can_user_approve_this_page", "(", "self", ",", "user", ")", ":", "self", ".", "ensure_one", "(", ")", "# if it's not required, anyone can approve", "if", "not", "self", ".", "is_approval_required", ":", "return", "True", "# if user belongs to 'Knowledge / Manager', he can approve anything", "if", "user", ".", "has_group", "(", "'document_page.group_document_manager'", ")", ":", "return", "True", "# to approve, user must have approver rights", "if", "not", "user", ".", "has_group", "(", "'document_page_approval.group_document_approver_user'", ")", ":", "return", "False", "# if there aren't any approver_groups_defined, user can approve", "if", "not", "self", ".", "approver_group_ids", ":", "return", "True", "# to approve, user must belong to any of the approver groups", "return", "len", "(", "user", ".", "groups_id", "&", "self", ".", "approver_group_ids", ")", ">", "0" ]
Check if a user can approve this page.
[ "Check", "if", "a", "user", "can", "approve", "this", "page", "." ]
77fa06019c989b56ce34839e9f6343577184223a
https://github.com/OCA/knowledge/blob/77fa06019c989b56ce34839e9f6343577184223a/document_page_approval/models/document_page.py#L102-L119
train
234,176
watchforstock/evohome-client
evohomeclient2/location.py
Location.status
def status(self): """Retrieves the location status.""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1/" "location/%s/status?includeTemperatureControlSystems=True" % self.locationId, headers=self.client._headers() # pylint: disable=protected-access ) response.raise_for_status() data = response.json() # Now feed into other elements for gw_data in data['gateways']: gateway = self.gateways[gw_data['gatewayId']] for sys in gw_data["temperatureControlSystems"]: system = gateway.control_systems[sys['systemId']] system.__dict__.update( {'systemModeStatus': sys['systemModeStatus'], 'activeFaults': sys['activeFaults']}) if 'dhw' in sys: system.hotwater.__dict__.update(sys['dhw']) for zone_data in sys["zones"]: zone = system.zones[zone_data['name']] zone.__dict__.update(zone_data) return data
python
def status(self): """Retrieves the location status.""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1/" "location/%s/status?includeTemperatureControlSystems=True" % self.locationId, headers=self.client._headers() # pylint: disable=protected-access ) response.raise_for_status() data = response.json() # Now feed into other elements for gw_data in data['gateways']: gateway = self.gateways[gw_data['gatewayId']] for sys in gw_data["temperatureControlSystems"]: system = gateway.control_systems[sys['systemId']] system.__dict__.update( {'systemModeStatus': sys['systemModeStatus'], 'activeFaults': sys['activeFaults']}) if 'dhw' in sys: system.hotwater.__dict__.update(sys['dhw']) for zone_data in sys["zones"]: zone = system.zones[zone_data['name']] zone.__dict__.update(zone_data) return data
[ "def", "status", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1/\"", "\"location/%s/status?includeTemperatureControlSystems=True\"", "%", "self", ".", "locationId", ",", "headers", "=", "self", ".", "client", ".", "_headers", "(", ")", "# pylint: disable=protected-access", ")", "response", ".", "raise_for_status", "(", ")", "data", "=", "response", ".", "json", "(", ")", "# Now feed into other elements", "for", "gw_data", "in", "data", "[", "'gateways'", "]", ":", "gateway", "=", "self", ".", "gateways", "[", "gw_data", "[", "'gatewayId'", "]", "]", "for", "sys", "in", "gw_data", "[", "\"temperatureControlSystems\"", "]", ":", "system", "=", "gateway", ".", "control_systems", "[", "sys", "[", "'systemId'", "]", "]", "system", ".", "__dict__", ".", "update", "(", "{", "'systemModeStatus'", ":", "sys", "[", "'systemModeStatus'", "]", ",", "'activeFaults'", ":", "sys", "[", "'activeFaults'", "]", "}", ")", "if", "'dhw'", "in", "sys", ":", "system", ".", "hotwater", ".", "__dict__", ".", "update", "(", "sys", "[", "'dhw'", "]", ")", "for", "zone_data", "in", "sys", "[", "\"zones\"", "]", ":", "zone", "=", "system", ".", "zones", "[", "zone_data", "[", "'name'", "]", "]", "zone", ".", "__dict__", ".", "update", "(", "zone_data", ")", "return", "data" ]
Retrieves the location status.
[ "Retrieves", "the", "location", "status", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/location.py#L26-L55
train
234,177
watchforstock/evohome-client
evohomeclient2/hotwater.py
HotWater.set_dhw_on
def set_dhw_on(self, until=None): """Sets the DHW on until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "On", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "On", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
python
def set_dhw_on(self, until=None): """Sets the DHW on until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "On", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "On", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
[ "def", "set_dhw_on", "(", "self", ",", "until", "=", "None", ")", ":", "if", "until", "is", "None", ":", "data", "=", "{", "\"Mode\"", ":", "\"PermanentOverride\"", ",", "\"State\"", ":", "\"On\"", ",", "\"UntilTime\"", ":", "None", "}", "else", ":", "data", "=", "{", "\"Mode\"", ":", "\"TemporaryOverride\"", ",", "\"State\"", ":", "\"On\"", ",", "\"UntilTime\"", ":", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "}", "self", ".", "_set_dhw", "(", "data", ")" ]
Sets the DHW on until a given time, or permanently.
[ "Sets", "the", "DHW", "on", "until", "a", "given", "time", "or", "permanently", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L34-L45
train
234,178
watchforstock/evohome-client
evohomeclient2/hotwater.py
HotWater.set_dhw_off
def set_dhw_off(self, until=None): """Sets the DHW off until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "Off", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "Off", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
python
def set_dhw_off(self, until=None): """Sets the DHW off until a given time, or permanently.""" if until is None: data = {"Mode": "PermanentOverride", "State": "Off", "UntilTime": None} else: data = {"Mode": "TemporaryOverride", "State": "Off", "UntilTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_dhw(data)
[ "def", "set_dhw_off", "(", "self", ",", "until", "=", "None", ")", ":", "if", "until", "is", "None", ":", "data", "=", "{", "\"Mode\"", ":", "\"PermanentOverride\"", ",", "\"State\"", ":", "\"Off\"", ",", "\"UntilTime\"", ":", "None", "}", "else", ":", "data", "=", "{", "\"Mode\"", ":", "\"TemporaryOverride\"", ",", "\"State\"", ":", "\"Off\"", ",", "\"UntilTime\"", ":", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "}", "self", ".", "_set_dhw", "(", "data", ")" ]
Sets the DHW off until a given time, or permanently.
[ "Sets", "the", "DHW", "off", "until", "a", "given", "time", "or", "permanently", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/hotwater.py#L47-L58
train
234,179
watchforstock/evohome-client
evohomeclient2/zone.py
ZoneBase.schedule
def schedule(self): """Gets the schedule for the given zone""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), headers=self.client._headers() # pylint: disable=no-member,protected-access ) response.raise_for_status() mapping = [ ('dailySchedules', 'DailySchedules'), ('dayOfWeek', 'DayOfWeek'), ('temperature', 'TargetTemperature'), ('timeOfDay', 'TimeOfDay'), ('switchpoints', 'Switchpoints'), ('dhwState', 'DhwState'), ] response_data = response.text for from_val, to_val in mapping: response_data = response_data.replace(from_val, to_val) data = json.loads(response_data) # change the day name string to a number offset (0 = Monday) for day_of_week, schedule in enumerate(data['DailySchedules']): schedule['DayOfWeek'] = day_of_week return data
python
def schedule(self): """Gets the schedule for the given zone""" response = requests.get( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), headers=self.client._headers() # pylint: disable=no-member,protected-access ) response.raise_for_status() mapping = [ ('dailySchedules', 'DailySchedules'), ('dayOfWeek', 'DayOfWeek'), ('temperature', 'TargetTemperature'), ('timeOfDay', 'TimeOfDay'), ('switchpoints', 'Switchpoints'), ('dhwState', 'DhwState'), ] response_data = response.text for from_val, to_val in mapping: response_data = response_data.replace(from_val, to_val) data = json.loads(response_data) # change the day name string to a number offset (0 = Monday) for day_of_week, schedule in enumerate(data['DailySchedules']): schedule['DayOfWeek'] = day_of_week return data
[ "def", "schedule", "(", "self", ")", ":", "response", "=", "requests", ".", "get", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1\"", "\"/%s/%s/schedule\"", "%", "(", "self", ".", "zone_type", ",", "self", ".", "zoneId", ")", ",", "headers", "=", "self", ".", "client", ".", "_headers", "(", ")", "# pylint: disable=no-member,protected-access", ")", "response", ".", "raise_for_status", "(", ")", "mapping", "=", "[", "(", "'dailySchedules'", ",", "'DailySchedules'", ")", ",", "(", "'dayOfWeek'", ",", "'DayOfWeek'", ")", ",", "(", "'temperature'", ",", "'TargetTemperature'", ")", ",", "(", "'timeOfDay'", ",", "'TimeOfDay'", ")", ",", "(", "'switchpoints'", ",", "'Switchpoints'", ")", ",", "(", "'dhwState'", ",", "'DhwState'", ")", ",", "]", "response_data", "=", "response", ".", "text", "for", "from_val", ",", "to_val", "in", "mapping", ":", "response_data", "=", "response_data", ".", "replace", "(", "from_val", ",", "to_val", ")", "data", "=", "json", ".", "loads", "(", "response_data", ")", "# change the day name string to a number offset (0 = Monday)", "for", "day_of_week", ",", "schedule", "in", "enumerate", "(", "data", "[", "'DailySchedules'", "]", ")", ":", "schedule", "[", "'DayOfWeek'", "]", "=", "day_of_week", "return", "data" ]
Gets the schedule for the given zone
[ "Gets", "the", "schedule", "for", "the", "given", "zone" ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L16-L42
train
234,180
watchforstock/evohome-client
evohomeclient2/zone.py
ZoneBase.set_schedule
def set_schedule(self, zone_info): """Sets the schedule for this zone""" # must only POST json, otherwise server API handler raises exceptions try: json.loads(zone_info) except ValueError as error: raise ValueError("zone_info must be valid JSON: ", error) headers = dict(self.client._headers()) # pylint: disable=protected-access headers['Content-Type'] = 'application/json' response = requests.put( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), data=zone_info, headers=headers ) response.raise_for_status() return response.json()
python
def set_schedule(self, zone_info): """Sets the schedule for this zone""" # must only POST json, otherwise server API handler raises exceptions try: json.loads(zone_info) except ValueError as error: raise ValueError("zone_info must be valid JSON: ", error) headers = dict(self.client._headers()) # pylint: disable=protected-access headers['Content-Type'] = 'application/json' response = requests.put( "https://tccna.honeywell.com/WebAPI/emea/api/v1" "/%s/%s/schedule" % (self.zone_type, self.zoneId), data=zone_info, headers=headers ) response.raise_for_status() return response.json()
[ "def", "set_schedule", "(", "self", ",", "zone_info", ")", ":", "# must only POST json, otherwise server API handler raises exceptions", "try", ":", "json", ".", "loads", "(", "zone_info", ")", "except", "ValueError", "as", "error", ":", "raise", "ValueError", "(", "\"zone_info must be valid JSON: \"", ",", "error", ")", "headers", "=", "dict", "(", "self", ".", "client", ".", "_headers", "(", ")", ")", "# pylint: disable=protected-access", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", "response", "=", "requests", ".", "put", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1\"", "\"/%s/%s/schedule\"", "%", "(", "self", ".", "zone_type", ",", "self", ".", "zoneId", ")", ",", "data", "=", "zone_info", ",", "headers", "=", "headers", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")" ]
Sets the schedule for this zone
[ "Sets", "the", "schedule", "for", "this", "zone" ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/zone.py#L44-L63
train
234,181
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.temperatures
def temperatures(self, force_refresh=False): """Retrieve the current details for each zone. Returns a generator.""" self._populate_full_data(force_refresh) for device in self.full_data['devices']: set_point = 0 status = "" if 'heatSetpoint' in device['thermostat']['changeableValues']: set_point = float( device['thermostat']['changeableValues']["heatSetpoint"]["value"]) status = device['thermostat']['changeableValues']["heatSetpoint"]["status"] else: status = device['thermostat']['changeableValues']['status'] yield {'thermostat': device['thermostatModelType'], 'id': device['deviceID'], 'name': device['name'], 'temp': float(device['thermostat']['indoorTemperature']), 'setpoint': set_point, 'status': status, 'mode': device['thermostat']['changeableValues']['mode']}
python
def temperatures(self, force_refresh=False): """Retrieve the current details for each zone. Returns a generator.""" self._populate_full_data(force_refresh) for device in self.full_data['devices']: set_point = 0 status = "" if 'heatSetpoint' in device['thermostat']['changeableValues']: set_point = float( device['thermostat']['changeableValues']["heatSetpoint"]["value"]) status = device['thermostat']['changeableValues']["heatSetpoint"]["status"] else: status = device['thermostat']['changeableValues']['status'] yield {'thermostat': device['thermostatModelType'], 'id': device['deviceID'], 'name': device['name'], 'temp': float(device['thermostat']['indoorTemperature']), 'setpoint': set_point, 'status': status, 'mode': device['thermostat']['changeableValues']['mode']}
[ "def", "temperatures", "(", "self", ",", "force_refresh", "=", "False", ")", ":", "self", ".", "_populate_full_data", "(", "force_refresh", ")", "for", "device", "in", "self", ".", "full_data", "[", "'devices'", "]", ":", "set_point", "=", "0", "status", "=", "\"\"", "if", "'heatSetpoint'", "in", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", ":", "set_point", "=", "float", "(", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "\"heatSetpoint\"", "]", "[", "\"value\"", "]", ")", "status", "=", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "\"heatSetpoint\"", "]", "[", "\"status\"", "]", "else", ":", "status", "=", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "'status'", "]", "yield", "{", "'thermostat'", ":", "device", "[", "'thermostatModelType'", "]", ",", "'id'", ":", "device", "[", "'deviceID'", "]", ",", "'name'", ":", "device", "[", "'name'", "]", ",", "'temp'", ":", "float", "(", "device", "[", "'thermostat'", "]", "[", "'indoorTemperature'", "]", ")", ",", "'setpoint'", ":", "set_point", ",", "'status'", ":", "status", ",", "'mode'", ":", "device", "[", "'thermostat'", "]", "[", "'changeableValues'", "]", "[", "'mode'", "]", "}" ]
Retrieve the current details for each zone. Returns a generator.
[ "Retrieve", "the", "current", "details", "for", "each", "zone", ".", "Returns", "a", "generator", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L115-L133
train
234,182
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.get_modes
def get_modes(self, zone): """Returns the set of modes the device can be assigned.""" self._populate_full_data() device = self._get_device(zone) return device['thermostat']['allowedModes']
python
def get_modes(self, zone): """Returns the set of modes the device can be assigned.""" self._populate_full_data() device = self._get_device(zone) return device['thermostat']['allowedModes']
[ "def", "get_modes", "(", "self", ",", "zone", ")", ":", "self", ".", "_populate_full_data", "(", ")", "device", "=", "self", ".", "_get_device", "(", "zone", ")", "return", "device", "[", "'thermostat'", "]", "[", "'allowedModes'", "]" ]
Returns the set of modes the device can be assigned.
[ "Returns", "the", "set", "of", "modes", "the", "device", "can", "be", "assigned", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L135-L139
train
234,183
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.set_temperature
def set_temperature(self, zone, temperature, until=None): """Sets the temperature of the given zone.""" if until is None: data = {"Value": temperature, "Status": "Hold", "NextTime": None} else: data = {"Value": temperature, "Status": "Temporary", "NextTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_heat_setpoint(zone, data)
python
def set_temperature(self, zone, temperature, until=None): """Sets the temperature of the given zone.""" if until is None: data = {"Value": temperature, "Status": "Hold", "NextTime": None} else: data = {"Value": temperature, "Status": "Temporary", "NextTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')} self._set_heat_setpoint(zone, data)
[ "def", "set_temperature", "(", "self", ",", "zone", ",", "temperature", ",", "until", "=", "None", ")", ":", "if", "until", "is", "None", ":", "data", "=", "{", "\"Value\"", ":", "temperature", ",", "\"Status\"", ":", "\"Hold\"", ",", "\"NextTime\"", ":", "None", "}", "else", ":", "data", "=", "{", "\"Value\"", ":", "temperature", ",", "\"Status\"", ":", "\"Temporary\"", ",", "\"NextTime\"", ":", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "}", "self", ".", "_set_heat_setpoint", "(", "zone", ",", "data", ")" ]
Sets the temperature of the given zone.
[ "Sets", "the", "temperature", "of", "the", "given", "zone", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L266-L275
train
234,184
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient._set_dhw
def _set_dhw(self, status="Scheduled", mode=None, next_time=None): """Set DHW to On, Off or Auto, either indefinitely, or until a specified time. """ data = {"Status": status, "Mode": mode, "NextTime": next_time, "SpecialModes": None, "HeatSetpoint": None, "CoolSetpoint": None} self._populate_full_data() dhw_zone = self._get_dhw_zone() if dhw_zone is None: raise Exception('No DHW zone reported from API') url = (self.hostname + "/WebAPI/api/devices" "/%s/thermostat/changeableValues" % dhw_zone) response = self._do_request('put', url, json.dumps(data)) task_id = self._get_task_id(response) while self._get_task_status(task_id) != 'Succeeded': time.sleep(1)
python
def _set_dhw(self, status="Scheduled", mode=None, next_time=None): """Set DHW to On, Off or Auto, either indefinitely, or until a specified time. """ data = {"Status": status, "Mode": mode, "NextTime": next_time, "SpecialModes": None, "HeatSetpoint": None, "CoolSetpoint": None} self._populate_full_data() dhw_zone = self._get_dhw_zone() if dhw_zone is None: raise Exception('No DHW zone reported from API') url = (self.hostname + "/WebAPI/api/devices" "/%s/thermostat/changeableValues" % dhw_zone) response = self._do_request('put', url, json.dumps(data)) task_id = self._get_task_id(response) while self._get_task_status(task_id) != 'Succeeded': time.sleep(1)
[ "def", "_set_dhw", "(", "self", ",", "status", "=", "\"Scheduled\"", ",", "mode", "=", "None", ",", "next_time", "=", "None", ")", ":", "data", "=", "{", "\"Status\"", ":", "status", ",", "\"Mode\"", ":", "mode", ",", "\"NextTime\"", ":", "next_time", ",", "\"SpecialModes\"", ":", "None", ",", "\"HeatSetpoint\"", ":", "None", ",", "\"CoolSetpoint\"", ":", "None", "}", "self", ".", "_populate_full_data", "(", ")", "dhw_zone", "=", "self", ".", "_get_dhw_zone", "(", ")", "if", "dhw_zone", "is", "None", ":", "raise", "Exception", "(", "'No DHW zone reported from API'", ")", "url", "=", "(", "self", ".", "hostname", "+", "\"/WebAPI/api/devices\"", "\"/%s/thermostat/changeableValues\"", "%", "dhw_zone", ")", "response", "=", "self", ".", "_do_request", "(", "'put'", ",", "url", ",", "json", ".", "dumps", "(", "data", ")", ")", "task_id", "=", "self", ".", "_get_task_id", "(", "response", ")", "while", "self", ".", "_get_task_status", "(", "task_id", ")", "!=", "'Succeeded'", ":", "time", ".", "sleep", "(", "1", ")" ]
Set DHW to On, Off or Auto, either indefinitely, or until a specified time.
[ "Set", "DHW", "to", "On", "Off", "or", "Auto", "either", "indefinitely", "or", "until", "a", "specified", "time", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L288-L311
train
234,185
watchforstock/evohome-client
evohomeclient/__init__.py
EvohomeClient.set_dhw_on
def set_dhw_on(self, until=None): """Set DHW to on, either indefinitely, or until a specified time. When On, the DHW controller will work to keep its target temperature at/above its target temperature. After the specified time, it will revert to its scheduled behaviour. """ time_until = None if until is None else until.strftime( '%Y-%m-%dT%H:%M:%SZ') self._set_dhw(status="Hold", mode="DHWOn", next_time=time_until)
python
def set_dhw_on(self, until=None): """Set DHW to on, either indefinitely, or until a specified time. When On, the DHW controller will work to keep its target temperature at/above its target temperature. After the specified time, it will revert to its scheduled behaviour. """ time_until = None if until is None else until.strftime( '%Y-%m-%dT%H:%M:%SZ') self._set_dhw(status="Hold", mode="DHWOn", next_time=time_until)
[ "def", "set_dhw_on", "(", "self", ",", "until", "=", "None", ")", ":", "time_until", "=", "None", "if", "until", "is", "None", "else", "until", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%SZ'", ")", "self", ".", "_set_dhw", "(", "status", "=", "\"Hold\"", ",", "mode", "=", "\"DHWOn\"", ",", "next_time", "=", "time_until", ")" ]
Set DHW to on, either indefinitely, or until a specified time. When On, the DHW controller will work to keep its target temperature at/above its target temperature. After the specified time, it will revert to its scheduled behaviour.
[ "Set", "DHW", "to", "on", "either", "indefinitely", "or", "until", "a", "specified", "time", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient/__init__.py#L313-L324
train
234,186
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient._headers
def _headers(self): """Ensure the Authorization Header has a valid Access Token.""" if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return {'Accept': HEADER_ACCEPT, 'Authorization': 'bearer ' + self.access_token}
python
def _headers(self): """Ensure the Authorization Header has a valid Access Token.""" if not self.access_token or not self.access_token_expires: self._basic_login() elif datetime.now() > self.access_token_expires - timedelta(seconds=30): self._basic_login() return {'Accept': HEADER_ACCEPT, 'Authorization': 'bearer ' + self.access_token}
[ "def", "_headers", "(", "self", ")", ":", "if", "not", "self", ".", "access_token", "or", "not", "self", ".", "access_token_expires", ":", "self", ".", "_basic_login", "(", ")", "elif", "datetime", ".", "now", "(", ")", ">", "self", ".", "access_token_expires", "-", "timedelta", "(", "seconds", "=", "30", ")", ":", "self", ".", "_basic_login", "(", ")", "return", "{", "'Accept'", ":", "HEADER_ACCEPT", ",", "'Authorization'", ":", "'bearer '", "+", "self", ".", "access_token", "}" ]
Ensure the Authorization Header has a valid Access Token.
[ "Ensure", "the", "Authorization", "Header", "has", "a", "valid", "Access", "Token", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L84-L93
train
234,187
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient._basic_login
def _basic_login(self): """Obtain a new access token from the vendor. First, try using the refresh_token, if one is available, otherwise authenticate using the user credentials. """ _LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...") self.access_token = self.access_token_expires = None if self.refresh_token: _LOGGER.debug("Trying refresh_token...") credentials = {'grant_type': "refresh_token", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous", 'refresh_token': self.refresh_token} try: self._obtain_access_token(credentials) except (requests.HTTPError, KeyError, ValueError): _LOGGER.warning( "Invalid refresh_token, will try user credentials.") self.refresh_token = None if not self.refresh_token: _LOGGER.debug("Trying user credentials...") credentials = {'grant_type': "password", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous " "EMEA-V1-Get-Current-User-Account", 'Username': self.username, 'Password': self.password} self._obtain_access_token(credentials) _LOGGER.debug("refresh_token = %s", self.refresh_token) _LOGGER.debug("access_token = %s", self.access_token) _LOGGER.debug("access_token_expires = %s", self.access_token_expires.strftime("%Y-%m-%d %H:%M:%S"))
python
def _basic_login(self): """Obtain a new access token from the vendor. First, try using the refresh_token, if one is available, otherwise authenticate using the user credentials. """ _LOGGER.debug("No/Expired/Invalid access_token, re-authenticating...") self.access_token = self.access_token_expires = None if self.refresh_token: _LOGGER.debug("Trying refresh_token...") credentials = {'grant_type': "refresh_token", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous", 'refresh_token': self.refresh_token} try: self._obtain_access_token(credentials) except (requests.HTTPError, KeyError, ValueError): _LOGGER.warning( "Invalid refresh_token, will try user credentials.") self.refresh_token = None if not self.refresh_token: _LOGGER.debug("Trying user credentials...") credentials = {'grant_type': "password", 'scope': "EMEA-V1-Basic EMEA-V1-Anonymous " "EMEA-V1-Get-Current-User-Account", 'Username': self.username, 'Password': self.password} self._obtain_access_token(credentials) _LOGGER.debug("refresh_token = %s", self.refresh_token) _LOGGER.debug("access_token = %s", self.access_token) _LOGGER.debug("access_token_expires = %s", self.access_token_expires.strftime("%Y-%m-%d %H:%M:%S"))
[ "def", "_basic_login", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"No/Expired/Invalid access_token, re-authenticating...\"", ")", "self", ".", "access_token", "=", "self", ".", "access_token_expires", "=", "None", "if", "self", ".", "refresh_token", ":", "_LOGGER", ".", "debug", "(", "\"Trying refresh_token...\"", ")", "credentials", "=", "{", "'grant_type'", ":", "\"refresh_token\"", ",", "'scope'", ":", "\"EMEA-V1-Basic EMEA-V1-Anonymous\"", ",", "'refresh_token'", ":", "self", ".", "refresh_token", "}", "try", ":", "self", ".", "_obtain_access_token", "(", "credentials", ")", "except", "(", "requests", ".", "HTTPError", ",", "KeyError", ",", "ValueError", ")", ":", "_LOGGER", ".", "warning", "(", "\"Invalid refresh_token, will try user credentials.\"", ")", "self", ".", "refresh_token", "=", "None", "if", "not", "self", ".", "refresh_token", ":", "_LOGGER", ".", "debug", "(", "\"Trying user credentials...\"", ")", "credentials", "=", "{", "'grant_type'", ":", "\"password\"", ",", "'scope'", ":", "\"EMEA-V1-Basic EMEA-V1-Anonymous \"", "\"EMEA-V1-Get-Current-User-Account\"", ",", "'Username'", ":", "self", ".", "username", ",", "'Password'", ":", "self", ".", "password", "}", "self", ".", "_obtain_access_token", "(", "credentials", ")", "_LOGGER", ".", "debug", "(", "\"refresh_token = %s\"", ",", "self", ".", "refresh_token", ")", "_LOGGER", ".", "debug", "(", "\"access_token = %s\"", ",", "self", ".", "access_token", ")", "_LOGGER", ".", "debug", "(", "\"access_token_expires = %s\"", ",", "self", ".", "access_token_expires", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", ")" ]
Obtain a new access token from the vendor. First, try using the refresh_token, if one is available, otherwise authenticate using the user credentials.
[ "Obtain", "a", "new", "access", "token", "from", "the", "vendor", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L95-L130
train
234,188
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.user_account
def user_account(self): """Return the user account information.""" self.account_info = None url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount' response = requests.get(url, headers=self._headers()) response.raise_for_status() self.account_info = response.json() return self.account_info
python
def user_account(self): """Return the user account information.""" self.account_info = None url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount' response = requests.get(url, headers=self._headers()) response.raise_for_status() self.account_info = response.json() return self.account_info
[ "def", "user_account", "(", "self", ")", ":", "self", ".", "account_info", "=", "None", "url", "=", "'https://tccna.honeywell.com/WebAPI/emea/api/v1/userAccount'", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "self", ".", "account_info", "=", "response", ".", "json", "(", ")", "return", "self", ".", "account_info" ]
Return the user account information.
[ "Return", "the", "user", "account", "information", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L192-L202
train
234,189
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.installation
def installation(self): """Return the details of the installation.""" self.locations = [] url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/installationInfo?userId=%s" "&includeTemperatureControlSystems=True" % self.account_info['userId']) response = requests.get(url, headers=self._headers()) response.raise_for_status() self.installation_info = response.json() self.system_id = (self.installation_info[0]['gateways'][0] ['temperatureControlSystems'][0]['systemId']) for loc_data in self.installation_info: self.locations.append(Location(self, loc_data)) return self.installation_info
python
def installation(self): """Return the details of the installation.""" self.locations = [] url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/installationInfo?userId=%s" "&includeTemperatureControlSystems=True" % self.account_info['userId']) response = requests.get(url, headers=self._headers()) response.raise_for_status() self.installation_info = response.json() self.system_id = (self.installation_info[0]['gateways'][0] ['temperatureControlSystems'][0]['systemId']) for loc_data in self.installation_info: self.locations.append(Location(self, loc_data)) return self.installation_info
[ "def", "installation", "(", "self", ")", ":", "self", ".", "locations", "=", "[", "]", "url", "=", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1/location\"", "\"/installationInfo?userId=%s\"", "\"&includeTemperatureControlSystems=True\"", "%", "self", ".", "account_info", "[", "'userId'", "]", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "self", ".", "installation_info", "=", "response", ".", "json", "(", ")", "self", ".", "system_id", "=", "(", "self", ".", "installation_info", "[", "0", "]", "[", "'gateways'", "]", "[", "0", "]", "[", "'temperatureControlSystems'", "]", "[", "0", "]", "[", "'systemId'", "]", ")", "for", "loc_data", "in", "self", ".", "installation_info", ":", "self", ".", "locations", ".", "append", "(", "Location", "(", "self", ",", "loc_data", ")", ")", "return", "self", ".", "installation_info" ]
Return the details of the installation.
[ "Return", "the", "details", "of", "the", "installation", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L204-L223
train
234,190
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.full_installation
def full_installation(self, location=None): """Return the full details of the installation.""" url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self._get_location(location)) response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
python
def full_installation(self, location=None): """Return the full details of the installation.""" url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location" "/%s/installationInfo?includeTemperatureControlSystems=True" % self._get_location(location)) response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
[ "def", "full_installation", "(", "self", ",", "location", "=", "None", ")", ":", "url", "=", "(", "\"https://tccna.honeywell.com/WebAPI/emea/api/v1/location\"", "\"/%s/installationInfo?includeTemperatureControlSystems=True\"", "%", "self", ".", "_get_location", "(", "location", ")", ")", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")" ]
Return the full details of the installation.
[ "Return", "the", "full", "details", "of", "the", "installation", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L225-L234
train
234,191
watchforstock/evohome-client
evohomeclient2/__init__.py
EvohomeClient.gateway
def gateway(self): """Return the detail of the gateway.""" url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
python
def gateway(self): """Return the detail of the gateway.""" url = 'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway' response = requests.get(url, headers=self._headers()) response.raise_for_status() return response.json()
[ "def", "gateway", "(", "self", ")", ":", "url", "=", "'https://tccna.honeywell.com/WebAPI/emea/api/v1/gateway'", "response", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "self", ".", "_headers", "(", ")", ")", "response", ".", "raise_for_status", "(", ")", "return", "response", ".", "json", "(", ")" ]
Return the detail of the gateway.
[ "Return", "the", "detail", "of", "the", "gateway", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L236-L243
train
234,192
watchforstock/evohome-client
evohomeclient2/controlsystem.py
ControlSystem.temperatures
def temperatures(self): """Return a generator with the details of each zone.""" self.location.status() if self.hotwater: yield { 'thermostat': 'DOMESTIC_HOT_WATER', 'id': self.hotwater.dhwId, 'name': '', 'temp': self.hotwater.temperatureStatus['temperature'], # pylint: disable=no-member 'setpoint': '' } for zone in self._zones: zone_info = { 'thermostat': 'EMEA_ZONE', 'id': zone.zoneId, 'name': zone.name, 'temp': None, 'setpoint': zone.setpointStatus['targetHeatTemperature'] } if zone.temperatureStatus['isAvailable']: zone_info['temp'] = zone.temperatureStatus['temperature'] yield zone_info
python
def temperatures(self): """Return a generator with the details of each zone.""" self.location.status() if self.hotwater: yield { 'thermostat': 'DOMESTIC_HOT_WATER', 'id': self.hotwater.dhwId, 'name': '', 'temp': self.hotwater.temperatureStatus['temperature'], # pylint: disable=no-member 'setpoint': '' } for zone in self._zones: zone_info = { 'thermostat': 'EMEA_ZONE', 'id': zone.zoneId, 'name': zone.name, 'temp': None, 'setpoint': zone.setpointStatus['targetHeatTemperature'] } if zone.temperatureStatus['isAvailable']: zone_info['temp'] = zone.temperatureStatus['temperature'] yield zone_info
[ "def", "temperatures", "(", "self", ")", ":", "self", ".", "location", ".", "status", "(", ")", "if", "self", ".", "hotwater", ":", "yield", "{", "'thermostat'", ":", "'DOMESTIC_HOT_WATER'", ",", "'id'", ":", "self", ".", "hotwater", ".", "dhwId", ",", "'name'", ":", "''", ",", "'temp'", ":", "self", ".", "hotwater", ".", "temperatureStatus", "[", "'temperature'", "]", ",", "# pylint: disable=no-member", "'setpoint'", ":", "''", "}", "for", "zone", "in", "self", ".", "_zones", ":", "zone_info", "=", "{", "'thermostat'", ":", "'EMEA_ZONE'", ",", "'id'", ":", "zone", ".", "zoneId", ",", "'name'", ":", "zone", ".", "name", ",", "'temp'", ":", "None", ",", "'setpoint'", ":", "zone", ".", "setpointStatus", "[", "'targetHeatTemperature'", "]", "}", "if", "zone", ".", "temperatureStatus", "[", "'isAvailable'", "]", ":", "zone_info", "[", "'temp'", "]", "=", "zone", ".", "temperatureStatus", "[", "'temperature'", "]", "yield", "zone_info" ]
Return a generator with the details of each zone.
[ "Return", "a", "generator", "with", "the", "details", "of", "each", "zone", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L92-L116
train
234,193
watchforstock/evohome-client
evohomeclient2/controlsystem.py
ControlSystem.zone_schedules_backup
def zone_schedules_backup(self, filename): """Backup all zones on control system to the given file.""" _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...", self.systemId, self.location.name) schedules = {} if self.hotwater: _LOGGER.info("Retrieving DHW schedule: %s...", self.hotwater.zoneId) schedule = self.hotwater.schedule() schedules[self.hotwater.zoneId] = { 'name': 'Domestic Hot Water', 'schedule': schedule} for zone in self._zones: zone_id = zone.zoneId name = zone.name _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name) schedule = zone.schedule() schedules[zone_id] = {'name': name, 'schedule': schedule} schedule_db = json.dumps(schedules, indent=4) _LOGGER.info("Writing to backup file: %s...", filename) with open(filename, 'w') as file_output: file_output.write(schedule_db) _LOGGER.info("Backup completed.")
python
def zone_schedules_backup(self, filename): """Backup all zones on control system to the given file.""" _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...", self.systemId, self.location.name) schedules = {} if self.hotwater: _LOGGER.info("Retrieving DHW schedule: %s...", self.hotwater.zoneId) schedule = self.hotwater.schedule() schedules[self.hotwater.zoneId] = { 'name': 'Domestic Hot Water', 'schedule': schedule} for zone in self._zones: zone_id = zone.zoneId name = zone.name _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name) schedule = zone.schedule() schedules[zone_id] = {'name': name, 'schedule': schedule} schedule_db = json.dumps(schedules, indent=4) _LOGGER.info("Writing to backup file: %s...", filename) with open(filename, 'w') as file_output: file_output.write(schedule_db) _LOGGER.info("Backup completed.")
[ "def", "zone_schedules_backup", "(", "self", ",", "filename", ")", ":", "_LOGGER", ".", "info", "(", "\"Backing up schedules from ControlSystem: %s (%s)...\"", ",", "self", ".", "systemId", ",", "self", ".", "location", ".", "name", ")", "schedules", "=", "{", "}", "if", "self", ".", "hotwater", ":", "_LOGGER", ".", "info", "(", "\"Retrieving DHW schedule: %s...\"", ",", "self", ".", "hotwater", ".", "zoneId", ")", "schedule", "=", "self", ".", "hotwater", ".", "schedule", "(", ")", "schedules", "[", "self", ".", "hotwater", ".", "zoneId", "]", "=", "{", "'name'", ":", "'Domestic Hot Water'", ",", "'schedule'", ":", "schedule", "}", "for", "zone", "in", "self", ".", "_zones", ":", "zone_id", "=", "zone", ".", "zoneId", "name", "=", "zone", ".", "name", "_LOGGER", ".", "info", "(", "\"Retrieving Zone schedule: %s - %s\"", ",", "zone_id", ",", "name", ")", "schedule", "=", "zone", ".", "schedule", "(", ")", "schedules", "[", "zone_id", "]", "=", "{", "'name'", ":", "name", ",", "'schedule'", ":", "schedule", "}", "schedule_db", "=", "json", ".", "dumps", "(", "schedules", ",", "indent", "=", "4", ")", "_LOGGER", ".", "info", "(", "\"Writing to backup file: %s...\"", ",", "filename", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "file_output", ":", "file_output", ".", "write", "(", "schedule_db", ")", "_LOGGER", ".", "info", "(", "\"Backup completed.\"", ")" ]
Backup all zones on control system to the given file.
[ "Backup", "all", "zones", "on", "control", "system", "to", "the", "given", "file", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L118-L149
train
234,194
watchforstock/evohome-client
evohomeclient2/controlsystem.py
ControlSystem.zone_schedules_restore
def zone_schedules_restore(self, filename): """Restore all zones on control system from the given file.""" _LOGGER.info("Restoring schedules to ControlSystem %s (%s)...", self.systemId, self.location) _LOGGER.info("Reading from backup file: %s...", filename) with open(filename, 'r') as file_input: schedule_db = file_input.read() schedules = json.loads(schedule_db) for zone_id, zone_schedule in schedules.items(): name = zone_schedule['name'] zone_info = zone_schedule['schedule'] _LOGGER.info("Restoring schedule for: %s - %s...", zone_id, name) if self.hotwater and self.hotwater.zoneId == zone_id: self.hotwater.set_schedule(json.dumps(zone_info)) else: self.zones_by_id[zone_id].set_schedule( json.dumps(zone_info)) _LOGGER.info("Restore completed.")
python
def zone_schedules_restore(self, filename): """Restore all zones on control system from the given file.""" _LOGGER.info("Restoring schedules to ControlSystem %s (%s)...", self.systemId, self.location) _LOGGER.info("Reading from backup file: %s...", filename) with open(filename, 'r') as file_input: schedule_db = file_input.read() schedules = json.loads(schedule_db) for zone_id, zone_schedule in schedules.items(): name = zone_schedule['name'] zone_info = zone_schedule['schedule'] _LOGGER.info("Restoring schedule for: %s - %s...", zone_id, name) if self.hotwater and self.hotwater.zoneId == zone_id: self.hotwater.set_schedule(json.dumps(zone_info)) else: self.zones_by_id[zone_id].set_schedule( json.dumps(zone_info)) _LOGGER.info("Restore completed.")
[ "def", "zone_schedules_restore", "(", "self", ",", "filename", ")", ":", "_LOGGER", ".", "info", "(", "\"Restoring schedules to ControlSystem %s (%s)...\"", ",", "self", ".", "systemId", ",", "self", ".", "location", ")", "_LOGGER", ".", "info", "(", "\"Reading from backup file: %s...\"", ",", "filename", ")", "with", "open", "(", "filename", ",", "'r'", ")", "as", "file_input", ":", "schedule_db", "=", "file_input", ".", "read", "(", ")", "schedules", "=", "json", ".", "loads", "(", "schedule_db", ")", "for", "zone_id", ",", "zone_schedule", "in", "schedules", ".", "items", "(", ")", ":", "name", "=", "zone_schedule", "[", "'name'", "]", "zone_info", "=", "zone_schedule", "[", "'schedule'", "]", "_LOGGER", ".", "info", "(", "\"Restoring schedule for: %s - %s...\"", ",", "zone_id", ",", "name", ")", "if", "self", ".", "hotwater", "and", "self", ".", "hotwater", ".", "zoneId", "==", "zone_id", ":", "self", ".", "hotwater", ".", "set_schedule", "(", "json", ".", "dumps", "(", "zone_info", ")", ")", "else", ":", "self", ".", "zones_by_id", "[", "zone_id", "]", ".", "set_schedule", "(", "json", ".", "dumps", "(", "zone_info", ")", ")", "_LOGGER", ".", "info", "(", "\"Restore completed.\"", ")" ]
Restore all zones on control system from the given file.
[ "Restore", "all", "zones", "on", "control", "system", "from", "the", "given", "file", "." ]
f1cb9273e97946d79c0651f00a218abbf7ada53a
https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/controlsystem.py#L151-L174
train
234,195
softlayer/softlayer-python
SoftLayer/CLI/order/item_list.py
cli
def cli(env, package_keyname, keyword, category): """List package items used for ordering. The item keyNames listed can be used with `slcli order place` to specify the items that are being ordered in the package. .. Note:: Items with a numbered category, like disk0 or gpu0, can be included multiple times in an order to match how many of the item you want to order. :: # List all items in the VSI package slcli order item-list CLOUD_SERVER # List Ubuntu OSes from the os category of the Bare Metal package slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu """ table = formatting.Table(COLUMNS) manager = ordering.OrderingManager(env.client) _filter = {'items': {}} if keyword: _filter['items']['description'] = {'operation': '*= %s' % keyword} if category: _filter['items']['categories'] = {'categoryCode': {'operation': '_= %s' % category}} items = manager.list_items(package_keyname, filter=_filter) sorted_items = sort_items(items) categories = sorted_items.keys() for catname in sorted(categories): for item in sorted_items[catname]: table.add_row([catname, item['keyName'], item['description'], get_price(item)]) env.fout(table)
python
def cli(env, package_keyname, keyword, category): """List package items used for ordering. The item keyNames listed can be used with `slcli order place` to specify the items that are being ordered in the package. .. Note:: Items with a numbered category, like disk0 or gpu0, can be included multiple times in an order to match how many of the item you want to order. :: # List all items in the VSI package slcli order item-list CLOUD_SERVER # List Ubuntu OSes from the os category of the Bare Metal package slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu """ table = formatting.Table(COLUMNS) manager = ordering.OrderingManager(env.client) _filter = {'items': {}} if keyword: _filter['items']['description'] = {'operation': '*= %s' % keyword} if category: _filter['items']['categories'] = {'categoryCode': {'operation': '_= %s' % category}} items = manager.list_items(package_keyname, filter=_filter) sorted_items = sort_items(items) categories = sorted_items.keys() for catname in sorted(categories): for item in sorted_items[catname]: table.add_row([catname, item['keyName'], item['description'], get_price(item)]) env.fout(table)
[ "def", "cli", "(", "env", ",", "package_keyname", ",", "keyword", ",", "category", ")", ":", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "manager", "=", "ordering", ".", "OrderingManager", "(", "env", ".", "client", ")", "_filter", "=", "{", "'items'", ":", "{", "}", "}", "if", "keyword", ":", "_filter", "[", "'items'", "]", "[", "'description'", "]", "=", "{", "'operation'", ":", "'*= %s'", "%", "keyword", "}", "if", "category", ":", "_filter", "[", "'items'", "]", "[", "'categories'", "]", "=", "{", "'categoryCode'", ":", "{", "'operation'", ":", "'_= %s'", "%", "category", "}", "}", "items", "=", "manager", ".", "list_items", "(", "package_keyname", ",", "filter", "=", "_filter", ")", "sorted_items", "=", "sort_items", "(", "items", ")", "categories", "=", "sorted_items", ".", "keys", "(", ")", "for", "catname", "in", "sorted", "(", "categories", ")", ":", "for", "item", "in", "sorted_items", "[", "catname", "]", ":", "table", ".", "add_row", "(", "[", "catname", ",", "item", "[", "'keyName'", "]", ",", "item", "[", "'description'", "]", ",", "get_price", "(", "item", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List package items used for ordering. The item keyNames listed can be used with `slcli order place` to specify the items that are being ordered in the package. .. Note:: Items with a numbered category, like disk0 or gpu0, can be included multiple times in an order to match how many of the item you want to order. :: # List all items in the VSI package slcli order item-list CLOUD_SERVER # List Ubuntu OSes from the os category of the Bare Metal package slcli order item-list BARE_METAL_SERVER --category os --keyword ubuntu
[ "List", "package", "items", "used", "for", "ordering", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/item_list.py#L18-L53
train
234,196
softlayer/softlayer-python
SoftLayer/CLI/order/item_list.py
sort_items
def sort_items(items): """sorts the items into a dictionary of categories, with a list of items""" sorted_items = {} for item in items: category = lookup(item, 'itemCategory', 'categoryCode') if sorted_items.get(category) is None: sorted_items[category] = [] sorted_items[category].append(item) return sorted_items
python
def sort_items(items): """sorts the items into a dictionary of categories, with a list of items""" sorted_items = {} for item in items: category = lookup(item, 'itemCategory', 'categoryCode') if sorted_items.get(category) is None: sorted_items[category] = [] sorted_items[category].append(item) return sorted_items
[ "def", "sort_items", "(", "items", ")", ":", "sorted_items", "=", "{", "}", "for", "item", "in", "items", ":", "category", "=", "lookup", "(", "item", ",", "'itemCategory'", ",", "'categoryCode'", ")", "if", "sorted_items", ".", "get", "(", "category", ")", "is", "None", ":", "sorted_items", "[", "category", "]", "=", "[", "]", "sorted_items", "[", "category", "]", ".", "append", "(", "item", ")", "return", "sorted_items" ]
sorts the items into a dictionary of categories, with a list of items
[ "sorts", "the", "items", "into", "a", "dictionary", "of", "categories", "with", "a", "list", "of", "items" ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/order/item_list.py#L56-L66
train
234,197
softlayer/softlayer-python
SoftLayer/CLI/vlan/list.py
cli
def cli(env, sortby, datacenter, number, name, limit): """List VLANs.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby vlans = mgr.list_vlans(datacenter=datacenter, vlan_number=number, name=name, limit=limit) for vlan in vlans: table.add_row([ vlan['id'], vlan['vlanNumber'], vlan.get('name') or formatting.blank(), 'Yes' if vlan['firewallInterfaces'] else 'No', utils.lookup(vlan, 'primaryRouter', 'datacenter', 'name'), vlan['hardwareCount'], vlan['virtualGuestCount'], vlan['totalPrimaryIpAddressCount'], ]) env.fout(table)
python
def cli(env, sortby, datacenter, number, name, limit): """List VLANs.""" mgr = SoftLayer.NetworkManager(env.client) table = formatting.Table(COLUMNS) table.sortby = sortby vlans = mgr.list_vlans(datacenter=datacenter, vlan_number=number, name=name, limit=limit) for vlan in vlans: table.add_row([ vlan['id'], vlan['vlanNumber'], vlan.get('name') or formatting.blank(), 'Yes' if vlan['firewallInterfaces'] else 'No', utils.lookup(vlan, 'primaryRouter', 'datacenter', 'name'), vlan['hardwareCount'], vlan['virtualGuestCount'], vlan['totalPrimaryIpAddressCount'], ]) env.fout(table)
[ "def", "cli", "(", "env", ",", "sortby", ",", "datacenter", ",", "number", ",", "name", ",", "limit", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "table", "=", "formatting", ".", "Table", "(", "COLUMNS", ")", "table", ".", "sortby", "=", "sortby", "vlans", "=", "mgr", ".", "list_vlans", "(", "datacenter", "=", "datacenter", ",", "vlan_number", "=", "number", ",", "name", "=", "name", ",", "limit", "=", "limit", ")", "for", "vlan", "in", "vlans", ":", "table", ".", "add_row", "(", "[", "vlan", "[", "'id'", "]", ",", "vlan", "[", "'vlanNumber'", "]", ",", "vlan", ".", "get", "(", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "'Yes'", "if", "vlan", "[", "'firewallInterfaces'", "]", "else", "'No'", ",", "utils", ".", "lookup", "(", "vlan", ",", "'primaryRouter'", ",", "'datacenter'", ",", "'name'", ")", ",", "vlan", "[", "'hardwareCount'", "]", ",", "vlan", "[", "'virtualGuestCount'", "]", ",", "vlan", "[", "'totalPrimaryIpAddressCount'", "]", ",", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List VLANs.
[ "List", "VLANs", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/vlan/list.py#L34-L58
train
234,198
softlayer/softlayer-python
SoftLayer/CLI/nas/list.py
cli
def cli(env): """List NAS accounts.""" account = env.client['Account'] nas_accounts = account.getNasNetworkStorage( mask='eventCount,serviceResource[datacenter.name]') table = formatting.Table(['id', 'datacenter', 'size', 'server']) for nas_account in nas_accounts: table.add_row([ nas_account['id'], utils.lookup(nas_account, 'serviceResource', 'datacenter', 'name') or formatting.blank(), formatting.FormattedItem( nas_account.get('capacityGb', formatting.blank()), "%dGB" % nas_account.get('capacityGb', 0)), nas_account.get('serviceResourceBackendIpAddress', formatting.blank())]) env.fout(table)
python
def cli(env): """List NAS accounts.""" account = env.client['Account'] nas_accounts = account.getNasNetworkStorage( mask='eventCount,serviceResource[datacenter.name]') table = formatting.Table(['id', 'datacenter', 'size', 'server']) for nas_account in nas_accounts: table.add_row([ nas_account['id'], utils.lookup(nas_account, 'serviceResource', 'datacenter', 'name') or formatting.blank(), formatting.FormattedItem( nas_account.get('capacityGb', formatting.blank()), "%dGB" % nas_account.get('capacityGb', 0)), nas_account.get('serviceResourceBackendIpAddress', formatting.blank())]) env.fout(table)
[ "def", "cli", "(", "env", ")", ":", "account", "=", "env", ".", "client", "[", "'Account'", "]", "nas_accounts", "=", "account", ".", "getNasNetworkStorage", "(", "mask", "=", "'eventCount,serviceResource[datacenter.name]'", ")", "table", "=", "formatting", ".", "Table", "(", "[", "'id'", ",", "'datacenter'", ",", "'size'", ",", "'server'", "]", ")", "for", "nas_account", "in", "nas_accounts", ":", "table", ".", "add_row", "(", "[", "nas_account", "[", "'id'", "]", ",", "utils", ".", "lookup", "(", "nas_account", ",", "'serviceResource'", ",", "'datacenter'", ",", "'name'", ")", "or", "formatting", ".", "blank", "(", ")", ",", "formatting", ".", "FormattedItem", "(", "nas_account", ".", "get", "(", "'capacityGb'", ",", "formatting", ".", "blank", "(", ")", ")", ",", "\"%dGB\"", "%", "nas_account", ".", "get", "(", "'capacityGb'", ",", "0", ")", ")", ",", "nas_account", ".", "get", "(", "'serviceResourceBackendIpAddress'", ",", "formatting", ".", "blank", "(", ")", ")", "]", ")", "env", ".", "fout", "(", "table", ")" ]
List NAS accounts.
[ "List", "NAS", "accounts", "." ]
9f181be08cc3668353b05a6de0cb324f52cff6fa
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/nas/list.py#L13-L36
train
234,199